@veltdev/sdk-dev 5.0.2-beta.92 → 5.0.2-beta.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/velt.js CHANGED
@@ -1,4 +1,4 @@
1
- var SNIPPYLY_VERSION = '5.0.2-beta.92';
1
+ var SNIPPYLY_VERSION = '5.0.2-beta.93';
2
2
  Promise.allSettled||(Promise.allSettled=function(t){return Promise.all(t.map(function(r){return Promise.resolve(r).then(function(e){return{status:"fulfilled",value:e}}).catch(function(e){return{status:"rejected",reason:e}})}))});
3
3
 
4
4
  var lOe=Object.create;var a6=Object.defineProperty,cOe=Object.defineProperties,sOe=Object.getOwnPropertyDescriptor,dOe=Object.getOwnPropertyDescriptors,vOe=Object.getOwnPropertyNames,i6=Object.getOwnPropertySymbols,Xte=Object.getPrototypeOf,CB=Object.prototype.hasOwnProperty,Qte=Object.prototype.propertyIsEnumerable,mOe=Reflect.get;var Jte=(n,o,r)=>o in n?a6(n,o,{enumerable:!0,configurable:!0,writable:!0,value:r}):n[o]=r,h=(n,o)=>{for(var r in o||={})CB.call(o,r)&&Jte(n,r,o[r]);if(i6)for(var r of i6(o))Qte.call(o,r)&&Jte(n,r,o[r]);return n},y=(n,o)=>cOe(n,dOe(o));var Uh=(n,o)=>{var r={};for(var e in n)CB.call(n,e)&&o.indexOf(e)<0&&(r[e]=n[e]);if(n!=null&&i6)for(var e of i6(n))o.indexOf(e)<0&&Qte.call(n,e)&&(r[e]=n[e]);return r};var gOe=(n,o)=>()=>(o||n((o={exports:{}}).exports,o),o.exports),l6=(n,o)=>{for(var r in o)a6(n,r,{get:o[r],enumerable:!0})},uOe=(n,o,r,e)=>{if(o&&typeof o=="object"||typeof o=="function")for(let t of vOe(o))!CB.call(n,t)&&t!==r&&a6(n,t,{get:()=>o[t],enumerable:!(e=sOe(o,t))||e.enumerable});return n};var ene=(n,o,r)=>(r=n!=null?lOe(Xte(n)):{},uOe(o||!n||!n.__esModule?a6(r,"default",{value:n,enumerable:!0}):r,n));var Vh=(n,o,r)=>mOe(Xte(n),r,o);var X=(n,o,r)=>new Promise((e,t)=>{var i=c=>{try{l(r.next(c))}catch(d){t(d)}},a=c=>{try{l(r.throw(c))}catch(d){t(d)}},l=c=>c.done?e(c.value):Promise.resolve(c.value).then(i,a);l((r=r.apply(n,o)).next())});var fte=gOe((Yki,hte)=>{"use strict";var Nt={};Nt.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)};Nt.localCName=Nt.generateIdentifier();Nt.splitLines=function(n){return n.trim().split(`
@@ -405,7 +405,7 @@ This typically indicates that your device does not have a healthy Internet conne
405
405
  </radialGradient>
406
406
  </defs>
407
407
  </svg>
408
- `},o.GIF_PATHS={CAT_JAM:"https://firebasestorage.googleapis.com/v0/b/snippyly-sdk-external/o/emojis%2Fcatjam.gif?alt=media&token=9868b4ec-0031-4751-bb2e-47bf0f9d9583"},o.\u0275fac=function(t){return new(t||o)(K(Ve),K(k),K($d))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vn=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u){this.analyticsService=e,this.authService=t,this.configService=i,this.coreActionsService=a,this.databaseService=l,this.docService=c,this.loggingService=d,this.commonDbService=m,this.usersService=u,this.db=null,this.internalUserContacts$=new _e([]),this.userGlobalContact$=new _e(!1),this.userGroupContact$=new _e(null),this.users$=new _e([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.documentPaths=null,this.userAccessFields$=new _e({}),this.userOrganizationContacts$=new _e([]),this.userFolderContacts$=new _e([]),this.userDocumentContacts$=new _e([]),this.userOrganizationGroups$=new _e([]),this.onContactSelectedSubject$=new at,this.documentAccessType=null,this.atHereEnabled$=new _e(!1),this.atHereLabel$=new _e("here"),this.atHereDescription$=new _e(null),this.contactListScopeForOrganizationUsers$=new _e([bo.ALL]),this.customUserContacts$=new _e(null),this.customUserContactsConfig$=new _e({merge:!1}),this.currentOrganizationUserIAM$=new _e(null),this.userContacts$=new _e([]),this.userSnippylyIdContacts$=new _e(null),this.usersByOrganizationId$=new _e({}),this.temporaryUserIds$=new _e([]),this.usersByOrganizationIdAndDocumentId$=new _e({}),this.usersByOrganizationIdAndFolderId$=new _e({}),this.userById$=new _e({}),this.searchUsersSubject$=new at,this.searchUsersDebounceTime=300,this.pendingSearchPromises=new Map,this.authService.setContactService(this),this.usersService.setContactService(this),this.authService.getUser$().pipe(Se(_=>this.docService.getDocumentPaths$().pipe(ln(I=>{this.documentPaths=I}),ue(()=>_)))).subscribe(_=>X(this,null,function*(){if(this.user=_,_&&this.documentPaths)if(!_?.organizationId)this.getLoggedInUsers$().subscribe(),this.getUserContactsFromDb$(),yield this.migrateLoggedInUserFromEmailToUserIdPath(_),this.setLoggedInUser(_),yield this.moveGlobalContactUserFromEmailToUserIdPath(_),this.updateUserInGlobalContactsIfAvailable(_),_?.groupId&&(yield this.migrateGroupContactsFromEmailToUserIdPath(_?.groupId)),this.checkToSetLoggedInUserInGroupContacts();else{let I=this.userPermissionService?.getCurrentUserPermissions(),A=this.documentPaths.folderId,M=!0;A&&I?.[_?.userId]?.folders?.[A]?.errorCode===mr.PERMISSION_DENIED&&(M=!1),this.getOrganizationContactsFromDb$(),M&&this.getFolderContactsFromDb$(),this.getDocumentContactsFromDb$(),this.getOrganizationGroupsFromDb$(),this.getTemporaryUsers()}else this.getUserContactSubscription?.unsubscribe(),this.getUserContactSubscription=void 0,this.getLoggedInUsersSubscription?.unsubscribe(),this.getLoggedInUsersSubscription=void 0,this.getOrganizationContactsSubscription?.unsubscribe(),this.getOrganizationContactsSubscription=void 0,this.getFolderContactsSubscription?.unsubscribe(),this.getFolderContactsSubscription=void 0,this.getDocumentContactsSubscription?.unsubscribe(),this.getDocumentContactsSubscription=void 0,this.getOrganizationGroupsSubscription?.unsubscribe(),this.getOrganizationGroupsSubscription=void 0}),_=>{this.loggingService.catch("Error in ContactService constructor getUser$: ",_)}),this.databaseService.getDb().pipe(Ge(_=>!!_),ut(1)).subscribe(_=>{_&&(this.db=_)},_=>{this.loggingService.catch("Error in ContactService constructor getDb: ",_)}),this.getOrganizationGroups$().subscribe(_=>{this.authService.setOrganizationUserGroups(_)}),gn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([_,I,A])=>{I?A?.merge?this.userContacts$.next([..._||[],...I||[]]):this.userContacts$.next(I||[]):this.userContacts$.next(_||[])}),this.getUserContacts$().subscribe(_=>{try{_?.forEach(I=>{let A=I?.userSnippylyId||cd(this.configService.getApiKey(),I.userId);A&&this.userSnippylyIdContacts$.next(y(h({},this.userSnippylyIdContacts$.value),{[A]:I}))})}catch{}})}setCommentService(e){try{this.commentService=e}catch(t){this.loggingService.catch("Error in ContactService setCommentService: ",t)}}setUserPermissionService(e){try{this.userPermissionService=e}catch(t){this.loggingService.catch("Error in ContactService setUserPermissionService: ",t)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ContactService","color: green;");try{this.documentPaths=null,this.usersByOrganizationId$.next({}),this.temporaryUserIds$.next([]),this.usersByOrganizationIdAndFolderId$.next({}),this.usersByOrganizationIdAndDocumentId$.next({}),this.userById$.next({}),this.userOrganizationContacts$.next([]),this.userFolderContacts$.next([]),this.userDocumentContacts$.next([]),this.userOrganizationGroups$.next([]),this.userContacts$.next([]),this.userSnippylyIdContacts$.next(null),this.userGlobalContact$.next(!1),this.userGroupContact$.next(null),this.users$.next([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.currentOrganizationUserIAM$.next(null)}catch(e){this.loggingService.catch("Error in ContactService clearCache: ",e)}}setDocumentAccessType(e){try{this.documentAccessType=e}catch(t){this.loggingService.catch("Error in ContactService setDocumentAccessType: ",t)}}checkIfUserGlobalContact(e){return X(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0}});if(Object.keys(t??{}).length>0)return!0}if(e?.email&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0)return!0}return!1}catch(t){return this.loggingService.catch("Error in ContactService isUserGlobalContact: ",t),!1}})}setLoggedInUser(e){try{e?.userId&&this.documentPaths?.logins&&(this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(y(h({},e),{contacts:void 0})))}),this.setLoggedInUserPrivateContacts(e,e?.contacts))}catch(t){this.loggingService.catch("Error in ContactService setLoggedInUser: ",t)}}migrateLoggedInUserFromEmailToUserIdPath(e){return X(this,null,function*(){try{if(e?.email&&this.documentPaths?.logins){let t=yield this.commonDbService?.getData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let i=t;if(i){if(i?.contacts){let a={};Object.keys(i?.contacts??{})?.forEach(l=>{let c=i.contacts[l];if(c?.userId){let d=It(c?.userId);a[d]=c}}),i.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))}),yield this.commonDbService.deleteData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}})}}}}catch(t){this.loggingService.catch("Error in ContactService migrateLoggedInUserFromEmailToUserIdPath: ",t)}})}addGlobalContact(e){try{e?.userId&&this.documentPaths?.globalContacts&&this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(e))})}catch(t){this.loggingService.catch("Error in ContactService addGlobalContact: ",t)}}getUserAccessFields(){return JSON.parse(JSON.stringify(this.userAccessFields$.value))}getUserAccessFieldsByUserId(e){return this.getUserAccessFields()?.[e]}setUserAccessFields(e){try{let t=this.getUserAccessFields();e.forEach(a=>{t[a.user.userId]=a.accessFields||[]});let i=this.authService.getUser()?.userId;if(i&&t?.[i]?.length){let a=this.userPermissionService?.getCurrentUserPermissions();a&&(a[i]||(a[i]={}),a[i].context={accessFields:t[i]},this.userPermissionService?.setCurrentUserPermissions(a))}this.userAccessFields$.next(JSON.parse(JSON.stringify(t)))}catch(t){this.loggingService.catch("Error in ContactService setUserAccessFields: ",t)}}updateUserInGlobalContactsIfAvailable(e){return X(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts&&(yield this.checkIfUserGlobalContact(e))){let i=new ra;i.userId=e?.userId,i.userSnippylyId=e?.userSnippylyId,i.email=e?.email,i.name=e?.name,i.photoUrl=e?.photoUrl,this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))})}}catch(t){this.loggingService.catch("Error in ContactService updateUserInGlobalContactsIfAvailable: ",t)}})}moveGlobalContactUserFromEmailToUserIdPath(e){return X(this,null,function*(){try{if(e?.email&&e?.userId&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let i=t;i&&(yield this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))}),yield this.commonDbService.deleteData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}}))}}}catch(t){this.loggingService.catch("Error in ContactService removeUserFromGlobalContactsByEmail: ",t)}})}setLoggedInUserPrivateContacts(e,t){try{if(e?.userId&&this.documentPaths?.logins){let i,a=t?.filter(c=>c?.visibility!=="group"),l=!1;this.authService.getUserOptions()&&(l=!!this.authService.getUserOptions()?.replaceContacts||!!this.authService.getUserOptions()?.replacePrivateContacts),a?.length?(i={},a?.forEach(c=>{if(c?.userId){let d=It(c?.userId);i[d]=c}}),l?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))}):this.commonDbService.updateData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))})):l&&this.commonDbService.deleteData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0}})}}catch(i){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",i)}}migrateGroupContactsFromEmailToUserIdPath(e){return X(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e){let t=yield this.commonDbService?.getData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}});t&&Object.keys(t??{}).forEach(i=>X(this,null,function*(){let a=t[i];a?.email&&a?.userId&&It(a?.email)===i&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:i,skipFirestore:!0}}),yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:It(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}))}))}}catch(t){this.loggingService.catch("Error in ContactService migrateGroupContacts: ",t)}})}checkToSetLoggedInUserInGroupContacts(){return X(this,null,function*(){try{this.user?.groupId&&this.user?.userId&&((yield this.checkIfUserGlobalContact(this.user))||this.docService.getDocumentIam$().pipe(ut(1)).subscribe(t=>X(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let i=!1,a=this.docService.getDocumentAccessType(t);if(!a||a===Hr.PUBLIC)i=!0;else if(a===Hr.RESTRICTED){let l=It(this.user?.userId);if(t?.users?.[l]&&(i=!0),this.user?.email){let c=It(this.user?.email);t?.users?.[c]&&(i=!0)}}if(i){let l=new Is;l.email=this.user.email,l.visibility="group",l.name=this.user.name,l.photoUrl=this.user.photoUrl,l.userId=this.user.userId,(this.authService.getUserOptions()?.replaceContacts||this.authService.getUserOptions()?.replaceGroupContacts)&&(yield this.removeGroupContacts(this.user?.groupId)),this.setLoggedInUserGroupContacts(this.user?.groupId,[l]),this.user?.contacts&&this.user?.groupId&&this.setLoggedInUserGroupContacts(this.user?.groupId,this.user?.contacts)}}})))}catch(e){this.loggingService.catch("Error in ContactService checkToSetLoggedInUserInGroupContacts: ",e)}})}setLoggedInUserGroupContacts(e,t){try{let i=t?.filter(a=>a?.visibility==="group");i?.length&&i.forEach(a=>X(this,null,function*(){if(a?.userId&&e&&this.documentPaths?.groupContacts){if(this.configService?.getSF()&&(yield this.checkIfUserGlobalContact(a)))return;yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:It(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}),a?.email&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:It(a?.email),skipFirestore:!0}}))}}))}catch(i){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",i)}}removeGroupContacts(e){return X(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e)return this.commonDbService.deleteData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}})}catch(t){this.loggingService.catch("Error in ContactService removeGroupContacts: ",t)}})}mergeUserContacts(){try{let e=[];this.userPersonalContacts&&e.push(...this.userPersonalContacts),this.userGroupContacts&&e.push(...this.userGroupContacts),this.userGlobalContacts&&e.push(...this.userGlobalContacts);let t={};e.forEach(i=>{i?.userId?(!i?.email||!t[i.email])&&(t[i.userId]=i):i?.email&&(!i?.userId||!t[i.userId])&&(t[i.email]=i)}),e=Object.values(t??{}),this.internalUserContacts$.next(e)}catch(e){this.loggingService.catch("Error in ContactService mergeUserContacts: ",e)}}getInternalUserContacts(){return this.internalUserContacts$.value}getInternalUserContacts$(){return this.internalUserContacts$.asObservable()}getUserContacts$(e){try{let{organizationId:t,documentId:i,veltFolderId:a}=e||{};return t&&i?gn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$(),this.temporaryUserIds$]).pipe(ue(([l,c,d,m,u,_,I,A])=>{let M={},V=!1;_&&!_?.merge&&(V=!0);let q=Ie=>I.some(he=>Ie.includes(he)),ae=q([bo.ALL,bo.ORGANIZATION])?Object.keys(l?.[t]||{}):[],ye=a?q([bo.ALL,bo.FOLDER])?Object.keys(c?.[t]?.[a]||{}):[]:[],ie=q([bo.ALL,bo.DOCUMENT])?Object.keys(d?.[t]?.[i]||{}):[];if([...ae,...ye||[],...ie,...A].forEach(Ie=>{let he=m?.[Ie];he&&(M[Ie]=he)}),u){let{merge:Ie,options:he}=_||{},{organizationId:Te,documentId:Oe,folderId:Pe}=he||{},$e=Pe?Lr(Pe):void 0;(!Te||Te===t)&&(!Oe||Oe===i)&&(!$e||$e===a)&&(Ie||(M={}),u.forEach(ze=>{ze?.userId&&(M[ze.userId]=ze)}))}return Object.values(M??{})})):this.userContacts$.asObservable().pipe(ue(l=>l))}catch(t){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",t),ce([])}}getUserContactsBySnippylyId$(){return this.userSnippylyIdContacts$.asObservable()}getUserBySnippylyId(e){return this.userSnippylyIdContacts$.value?.[e]}getAtHereLabel(){return this.atHereLabel$.asObservable()}getAtHereDescription(){return this.atHereDescription$.asObservable()}getUserContactsFromDb$(){this.getUserContactSubscription||(this.getUserContactSubscription=this.authService.getUser$().pipe(Ge(e=>!!e),Se(e=>this.docService.getDocumentPaths$().pipe(Ge(t=>!!t),ln(t=>{this.documentPaths=t}),ue(()=>e))),Se(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return ce();if(!this.documentPaths)return ce();let t=[];return t.push(this.commonDbService.dbListener({feature:"allGlobalContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ue(i=>i?.data),ln(i=>{i?(this.userGlobalContacts=Object.values(i??{}),this.userGlobalContacts?.find(a=>a.userId===this.user?.userId)?this.userGlobalContact$.next(!0):this.userGlobalContact$.next(!1)):(this.userGlobalContacts=[],this.userGlobalContact$.next(!1))}))),t.push(this.commonDbService.dbListener({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,groupId:e?.groupId}}).pipe(ue(i=>i?.data),ln(i=>{i?(this.userGroupContacts=Object.values(i??{}),this.userGroupContacts?.find(a=>a?.userId===this.user?.userId)?this.userGroupContact$.next(!0):this.userGroupContact$.next(!1)):(this.userGroupContacts=[],this.userGroupContact$.next(!1))}))),t.push(this.commonDbService.dbListener({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,userId:It(e?.userId)}}).pipe(ue(i=>i?.data),ln(i=>{i?this.userPersonalContacts=Object.values(i??{}):this.userPersonalContacts=[]}))),No(...t).pipe(zo(this.authService.getUser$().pipe(Ge(i=>!i))))})).subscribe(()=>{this.mergeUserContacts()},e=>{this.loggingService.catch("Error in ContactService getUserContacts$ subscription: ",e)}))}addUserContact(e){try{this.user?.organizationId||this.user?.groupId&&(e.visibility="group",this.setLoggedInUserGroupContacts(this.user?.groupId,[e]))}catch(t){this.loggingService.catch("Error in ContactService addUserContact: ",t)}}isUserGlobalContact$(){return this.userGlobalContact$.asObservable().pipe(_t(Kt))}isUserGlobalContact(){return this.userGlobalContact$.value}isUserGroupContact$(){return this.userGroupContact$.asObservable()}isUserGroupContact(){return this.userGroupContact$.value}getLoggedInUsers$(){return this.getLoggedInUsersSubscription||(this.getLoggedInUsersSubscription=this.authService.getUser$().pipe(Se(e=>e?this.documentPaths?e?.userId&&this.documentPaths?.logins?this.commonDbService.dbListener({feature:"allLogins",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ue(t=>t?.data),ln(t=>{t?this.users=Object.values(t??{}):this.users=[]})):(this.users=[],ce()):ce():ce())).subscribe(()=>{this.users$.next(this.users)},e=>{this.loggingService.catch("Error in ContactService getLoggedInUsers$ subscription: ",e)})),this.users$.asObservable()}getUsersMap$(){return this.authService.getUser$().pipe(Se(e=>e?.organizationId?this.userById$.pipe(ue(t=>{let i={};return Object.values(t||{}).forEach(a=>{a?.userSnippylyId&&(i[a?.userSnippylyId]=a)}),i})):this.users$.pipe(ue(t=>{let i={};return t.forEach(a=>{i[a.userSnippylyId]=a}),i}))))}getUserByEmail$(e){return this.users$.pipe(ue(t=>t.find(i=>i.email===e)))}getUserByEmail(e){return this.users?.find(t=>t.email===e)}getContactByEmail(e){return this.getInternalUserContacts().find(t=>t.email===e)}getUserByUserId$(e){return this.users$.pipe(ue(t=>t.find(i=>i.userId===e)))}getUserGroupContacts(){return this.userGroupContacts}getTemporaryUsers(){try{let e=this.authService.getUser();this.docService.getOrganizationConfig$().pipe(Ge(t=>!!t),ue(t=>t?.organizationId)).subscribe(t=>X(this,null,function*(){if(t&&e){let i=((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[ft("expiresAt",">",new Date().getTime())]}}))??[]).filter(a=>a?.userId!==e?.userId);if(i?.length){let a=i.map(m=>m?.userId),l=lt(),c=ks.GET_TEMPORARY_USERS;this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:l,moduleName:c,methodName:vi.GET_TEMPORARY_USERS,source:"internal",payload:{userIds:a}});let d=yield this.usersService.resolveUsers({userIds:a,uniqueId:l,moduleName:c});if(d){let m={};Object.entries(d).forEach(([_,I])=>{m[_]=I}),this.userById$.next(h(h({},this.userById$.value),m));let u=new Set([...this.temporaryUserIds$.value,...Object.keys(m)]);this.temporaryUserIds$.next(Array.from(u))}}}}))}catch(e){this.loggingService.catch("Error in ContactService getTemporaryUsers: ",e)}}searchUsers(e){return X(this,null,function*(){try{if(!e||typeof e!="string"||!e.trim())return[];let t=e.trim();return this.searchUsersDebounced$||(this.searchUsersDebounced$=this.searchUsersSubject$.pipe(Qr(this.searchUsersDebounceTime),_t(),Se(i=>co(this.performSearch(i)).pipe(ue(a=>({searchText:i,results:a})),Xn(a=>(this.loggingService.catch("Error in ContactService performSearch: ",a),ce({searchText:i,results:[]})))))),this.searchUsersDebounced$.subscribe({next:({searchText:i,results:a})=>{Array.from(this.pendingSearchPromises.keys()).forEach(d=>{if(d!==i){let m=this.pendingSearchPromises.get(d);m&&(m.forEach(({resolve:u})=>u([])),this.pendingSearchPromises.delete(d))}});let c=this.pendingSearchPromises.get(i);c&&(c.forEach(({resolve:d})=>d(a)),this.pendingSearchPromises.delete(i))},error:i=>{this.pendingSearchPromises.forEach(a=>{a.forEach(({reject:l})=>l(i))}),this.pendingSearchPromises.clear()}})),new Promise((i,a)=>{this.pendingSearchPromises.has(t)||this.pendingSearchPromises.set(t,[]),this.pendingSearchPromises.get(t).push({resolve:i,reject:a}),this.searchUsersSubject$.next(t)})}catch(t){return this.loggingService.catch("Error in ContactService searchUsers: ",t),[]}})}performSearch(e){return X(this,null,function*(){try{let t=this.docService.getOrganizationConfig()?.organizationId;if(!t)return[];let i=this.documentPaths?.veltFolderId,a=this.docService.getDocumentIds().map(q=>q?.documentId),l=e.toLowerCase().trim(),c=l+"\uF8FF",d=[],m=a?.filter(q=>!!q)||[],u=m.length>0,_=!!i;if(u){let q=[];for(let ye=0;ye<m.length;ye+=20)q.push(m.slice(ye,ye+20));q.forEach(ye=>{let ie=[ft("documentIds","array-contains-any",ye),ft("viewerDocumentIds","array-contains-any",ye)],ge=[ft("organizationIds","array-contains-any",[t]),ft("viewerOrganizationIds","array-contains-any",[t]),...ie];_&&ge.push(ft("folderIds","array-contains-any",[i]),ft("viewerFolderIds","array-contains-any",[i])),d.push(this.commonDbService.queryData({feature:"allDocumentUsers",properties:{organizationId:t,isCollection:!0,useCollectionGroup:!1,useQuery:!0,firestoreQuery:[yr(q0(...ge),ft("user.name_lowercase",">=",l),ft("user.name_lowercase","<",c)),hm(10)]}}).catch(()=>[])),d.push(this.commonDbService.queryData({feature:"allDocumentUsers",properties:{organizationId:t,isCollection:!0,useCollectionGroup:!1,useQuery:!0,firestoreQuery:[yr(q0(...ge),ft("user.email_lowercase",">=",l),ft("user.email_lowercase","<",c)),hm(10)]}}).catch(()=>[]))})}let I=yield Promise.all(d),A=[];I.forEach(q=>{q&&Array.isArray(q)?q.forEach(ae=>{ae&&ae.user&&ae.user.userId&&A.push(ae)}):q&&typeof q=="object"&&Object.values(q).forEach(ye=>{ye&&ye.user&&ye.user.userId&&A.push(ye)})});let M=new Map;A.forEach(q=>{let ae=q.user?.userId;ae&&!M.has(ae)&&M.set(ae,q)});let V=Array.from(M.values());return this.setResolvedUsers(V,!0),V}catch(t){return this.loggingService.catch("Error in ContactService performSearch: ",t),[]}})}setResolvedUsers(e,t=!1){try{if(e?.length){let i=[],a=[],l=[],c=this.docService.getOrganizationConfig()?.organizationId,d=this.documentPaths?.veltFolderId,m=this.docService.getDocumentIds().map(I=>I?.documentId);e.forEach(I=>{this.userById$.value[I?.user?.userId]||(c&&I?.organizationIds?.includes(c)&&!i.find(A=>A?.user?.userId===I?.user?.userId)&&i.push(I),d&&I?.folderIds?.includes(d)&&!a.find(A=>A?.user?.userId===I?.user?.userId)&&a.push(I),m?.some(A=>I?.documentIds?.includes(A))&&!l.find(A=>A?.user?.userId===I?.user?.userId)&&l.push(I))}),i?.length&&this.setUserOrganizationContacts(i,c,t),a?.length&&this.setUserFolderContacts(a,t),l?.length&&this.setUserDocumentContacts(l,t);let _=[...i,...a,...l].filter((I,A,M)=>A===M.findIndex(V=>V.user.userId===I.user.userId));_?.length&&(this.setUserAccessFields(_),this.mergeOrganizationAndDocumentContacts())}}catch(i){this.loggingService.catch("Error in ContactService setResolvedUsers: ",i)}}getOrganizationContactsFromDb$(){try{this.getOrganizationContactsSubscription||(this.getOrganizationContactsSubscription=this.authService.getUser$().pipe(Se(e=>e?.organizationId?ce(e).pipe(Se(t=>this.docService.getOrganizationConfig$().pipe(Ge(i=>!!i),ue(()=>t))),Se(t=>this.usersService.getResolveOrganizationUsers$().pipe(Ge(i=>i),ue(()=>t))),Se(t=>{let i=this.docService.getOrganizationConfig()?.organizationId;return this.setUserOrganizationContacts([],i),t?i?this.commonDbService.dbListener({feature:"allOrganizationUsers",properties:{organizationId:i,isCollection:!0,useQuery:!0,firestoreQuery:[yr(q0(ft("organizationIds","array-contains-any",[i]),ft("viewerOrganizationIds","array-contains-any",[i]))),uo("id"),...this.commentService?.getPaginatedContactList()?[hm(10)]:[]]}}).pipe(ue(a=>a?.data),Se(a=>this.commentService?.getPaginatedContactList()&&!Object.values(a??{}).find(l=>l?.user?.userId===this.authService.getUser()?.userId)?co(this.commonDbService.queryData({feature:"allOrganizationUsers",properties:{organizationId:i,isCollection:!0,useQuery:!0,firestoreQuery:[yr(q0(ft("organizationIds","array-contains-any",[i]),ft("viewerOrganizationIds","array-contains-any",[i])),ft("user.userId","==",this.authService.getUser()?.userId))]}})).pipe(ue(l=>{if(l&&l.length>0){let c=l[0],d=c?.user?.userId||c?.id;if(d&&a){let m=It(d);return y(h({},a),{[m]:c})}}return a})):ce(a)),ue(a=>{if(a){typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null);let l=Object.values(a??{});this.setUserAccessFields(l),this.setUserOrganizationContacts(l,i)}else this.setUserOrganizationContacts([],i)})):ce():ce()}),Se(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),ce()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(Se(e=>e?ce(e).pipe(Se(t=>this.docService.getOrganizationConfig$().pipe(Ge(i=>!!i),ue(()=>t))),Se(t=>this.usersService.getResolveFolderUsers$().pipe(Ge(i=>i),ue(()=>t))),Se(t=>{let i=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!t)return ce();if(!this.commonDbService.shouldUseFirestore())return ce();if(!this.documentPaths?.veltFolderId)return ce();let a=ce([]);return a=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:i,folderId:this.documentPaths?.veltFolderId,isCollection:!0,useQuery:!0,firestoreQuery:[yr(q0(ft("folderIds","array-contains-any",[this.documentPaths?.veltFolderId]),ft("viewerFolderIds","array-contains-any",[this.documentPaths?.veltFolderId]))),uo("id"),...this.commentService?.getPaginatedContactList()?[hm(10)]:[]]}}).pipe(ue(l=>l?.data)),a.pipe(ue(l=>{if(l){typeof l=="object"&&(l?.undefined&&delete l.undefined,l?.null&&delete l.null);let c=Object.values(l??{});this.setUserAccessFields(c),this.setUserFolderContacts(c)}else this.setUserFolderContacts([])}))}),Se(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),ce()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(Se(e=>e?ce(e).pipe(Se(t=>this.docService.getDocumentPaths$().pipe(Ge(i=>!!i),ln(i=>{this.documentPaths=i}),ue(()=>t))),Se(t=>this.usersService.getResolveDocumentUsers$().pipe(Ge(i=>i),ue(()=>t))),Se(t=>(this.setUserDocumentContacts([]),t?this.documentPaths?this.docService.getDocumentIds$().pipe(Se(i=>{let a=i?.length>0?i.map(m=>m.documentId):[this.documentPaths?.documentId??""];if(a.some(m=>!m)||!this.documentPaths)return ce();let l=ce([]),c={isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(c.documentId=a?.length?a[0]:void 0,c.organizationId=this.documentPaths?.organizationId);let d=[];for(let m=0;m<a.length;m+=N.LISTENER_BATCH_SIZE)d.push(a.slice(m,m+N.LISTENER_BATCH_SIZE));return l=gn(d.map(m=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:y(h({},c),{firestoreQuery:[yr(q0(ft("documentIds","array-contains-any",m),ft("viewerDocumentIds","array-contains-any",m))),uo("id"),...this.commentService?.getPaginatedContactList()?[hm(10)]:[]]})}).pipe(la()))).pipe(ue(m=>Na(m)?.data)),l.pipe(ue(m=>{if(m){typeof m=="object"&&(m?.undefined&&delete m.undefined,m?.null&&delete m.null);let u=Object.values(m??{});this.setUserAccessFields(u),this.setUserDocumentContacts(u)}else this.setUserDocumentContacts([])}))})):ce():ce())),Se(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),ce()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getDocumentContactsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationContacts(e,t,i=!0){try{let a=e.find(c=>c.user.userId===this.user?.userId);a&&this.setCurrentOrganizationUserIAM(a);let l=e.map(c=>c.user)?.filter(c=>!this.userOrganizationContacts$.value.find(d=>d.userId===c.userId));if(this.userOrganizationContacts$.next([...this.userOrganizationContacts$.value,...l]),i&&this.usersService.setUserByIds(l),t){let c={};c[t]={};let d={};e.forEach(u=>{c[t][u.user.userId]=u,d[u.user.userId]=u.user}),this.userById$.next(h(h({},this.userById$.value),d));let m=this.usersByOrganizationId$.value?.[t];m&&(c[t]=h(h({},m),c[t])),this.usersByOrganizationId$.next(y(h({},this.usersByOrganizationId$.value),{[t]:c[t]}))}else this.usersByOrganizationId$.next({})}catch(a){this.loggingService.catch("Error in ContactService setUserOrganizationContacts: ",a)}}getUserOrganizationContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(Se(()=>this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.ORGANIZATION])?this.userOrganizationContacts$.asObservable():ce([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.ORGANIZATION])?this.userOrganizationContacts$.value:[]}setUserFolderContacts(e,t=!0){try{let i=e?.map(d=>d?.user)?.filter(d=>!this.userFolderContacts$.value.find(m=>m.userId===d.userId));this.userFolderContacts$.next([...this.userFolderContacts$.value,...i]),t&&this.usersService.setUserByIds(i);let a=this.usersByOrganizationIdAndFolderId$.value||{},l=h({},a),c={};e?.forEach(d=>{let{organizationId:m}=d?.metadata||{};m&&(l[m]||(l[m]={}),d.folderIds?.forEach(u=>{l[m][u]||(l[m][u]={}),l[m][u]=y(h({},l[m][u]),{[d.user.userId]:d}),c[d.user.userId]=d.user}))}),this.userById$.next(h(h({},this.userById$.value),c)),this.usersByOrganizationIdAndFolderId$.next(l)}catch(i){this.loggingService.catch("Error in ContactService updateUserFolderContacts: ",i)}}getUserFolderContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(Se(()=>this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.FOLDER])?this.userFolderContacts$.asObservable():ce([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.FOLDER])?this.userFolderContacts$.value:[]}setUserDocumentContacts(e,t=!0){try{let i=e?.map(d=>d?.user)?.filter(d=>!this.userDocumentContacts$.value.find(m=>m.userId===d.userId));this.userDocumentContacts$.next([...this.userDocumentContacts$.value,...i]),t&&this.usersService.setUserByIds(i);let a=this.usersByOrganizationIdAndDocumentId$.value||{},l=h({},a),c={};e?.forEach(d=>{let{organizationId:m}=d?.metadata||{};m&&(l[m]||(l[m]={}),d.documentIds?.forEach(u=>{l[m][u]||(l[m][u]={}),l[m][u]=y(h({},l[m][u]),{[d.user.userId]:d}),c[d.user.userId]=d.user}))}),this.userById$.next(h(h({},this.userById$.value),c)),this.usersByOrganizationIdAndDocumentId$.next(l)}catch(i){this.loggingService.catch("Error in ContactService updateUserDocumentContacts: ",i)}}getUserDocumentContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(Se(()=>this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.DOCUMENT])?this.userDocumentContacts$.asObservable():ce([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.DOCUMENT])?this.userDocumentContacts$.value:[]}setCurrentOrganizationUserIAM(e){try{this.currentOrganizationUserIAM$.next(JSON.parse(JSON.stringify(e)))}catch(t){this.loggingService.catch("Error in ContactService setCurrentOrganizationUserIAM: ",t)}}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable().pipe(_t(Kt))}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{this.mergeContactsDebounceTimer&&clearTimeout(this.mergeContactsDebounceTimer),this.mergeContactsDebounceTimer=setTimeout(()=>{this.executeMergeContacts()},200)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}executeMergeContacts(){try{let e=this.getContactListScopeForOrganizationUsers(),t=[];e.includes(bo.ALL)?t=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:e.includes(bo.ORGANIZATION)?t=[...this.getUserOrganizationContacts()]:e.includes(bo.FOLDER)?t=[...this.getUserFolderContacts()]:e.includes(bo.DOCUMENT)&&(t=[...this.getUserDocumentContacts()]);let i=[...new Map(t.filter(a=>a?.userId).map(a=>[a.userId,a])).values()];this.internalUserContacts$.next(i)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}getOrganizationGroupsFromDb$(){try{this.getOrganizationGroupsSubscription||(this.getOrganizationGroupsSubscription=this.authService.getUser$().pipe(Se(e=>e?.organizationId?ce(e).pipe(Se(t=>this.docService.getOrganizationConfig$().pipe(Ge(i=>!!i),ue(()=>t))),Se(t=>{if(this.setUserOrganizationGroups([]),!t)return ce();let i=this.docService.getOrganizationConfig(),a=i?.organizationId,l=i?.clientOrganizationId??"";if(!a)return ce();let c=t.userId??"";return co(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:l})??Promise.resolve({})).pipe(Se(d=>c&&l&&d?.[c]?.organization?.[l]?.errorCode===mr.PERMISSION_DENIED?ce():this.commonDbService.dbListener({feature:"allOrganizationGroups",properties:{organizationId:a,isCollection:!0}}).pipe(ue(m=>m?.data),ue(m=>{m?(typeof m=="object"&&(m?.undefined&&delete m.undefined,m?.null&&delete m.null),this.setUserOrganizationGroups(Object.values(m??{}))):this.setUserOrganizationGroups([])}))))})):(this.setUserOrganizationGroups([]),ce()))).subscribe(()=>{},e=>{this.loggingService.catch("Error in ContactService getOrganizationGroupsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationGroups(e){try{this.userOrganizationGroups$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setUserOrganizationGroups: ",t)}}onContactSelected(e){try{if(e?.userId){let t=!!this.getUserDocumentContacts().find(a=>a.userId===e.userId),i=!!this.getUserOrganizationContacts().find(a=>a.userId===e.userId);switch(this.documentAccessType){case Hr.RESTRICTED:if(!t){let a={contact:e,isOrganizationContact:i,isDocumentContact:t,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(a)}break}}else{let t={contact:e,isOrganizationContact:!1,isDocumentContact:!1,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(t)}}catch(t){this.loggingService.catch("Error in ContactService onContactSelected: ",t)}}onContactSelected$(){return this.onContactSelectedSubject$.asObservable()}getOrganizationGroups$(){return this.getContactListScopeForOrganizationUsers$().pipe(Se(()=>this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():ce([])))}enableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{atHereEnabled:!0}}),this.atHereEnabled$.value===!0)return;this.atHereEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ContactService enableAtHere: ",e)}}setAtHereLabel(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{atHereLabel:e}}),e&&this.atHereLabel$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setAtHereLabel: ",t)}}setAtHereDescription(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{atHereDescription:e}}),e&&this.atHereDescription$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setAtHereDescription: ",t)}}disableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{atHereEnabled:!1}}),this.atHereEnabled$.value===!1)return;this.atHereEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ContactService disableAtHere: ",e)}}getAtHereEnabled$(){return this.getContactListScopeForOrganizationUsers$().pipe(Se(()=>this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.DOCUMENT])?this.atHereEnabled$.asObservable():ce(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.DOCUMENT])?this.atHereEnabled$.value:!1}updateContactListScopeForOrganizationUsers(e){try{this.contactListScopeForOrganizationUsers$.next(e)}catch(t){this.loggingService.catch("Error in ContactService updateContactListScopeForOrganizationUsers: ",t)}}getContactListScopeForOrganizationUsers$(){return this.contactListScopeForOrganizationUsers$.asObservable()}getContactListScopeForOrganizationUsers(){return this.contactListScopeForOrganizationUsers$.value}checkContactListScopeForOrganizationUsers(e){return this.getContactListScopeForOrganizationUsers().some(t=>e.includes(t))}updateContactList(e,t){return X(this,null,function*(){try{this.analyticsService.trackEvent(Y.Events.Contact.UPDATE_CONTACT_LIST_TRIGGERED,{contactsCount:e?.length,config:t}),this.usersService.setUserByIds(e),this.customUserContacts$.next(e),this.customUserContactsConfig$.next(t)}catch(i){this.loggingService.catch("Error in CommentService updateContactList: ",i)}})}convert(e){try{if(e?.options){let{documentId:t,organizationId:i}=this.docService.getServerId(e?.options);e.options=y(h({},e?.options),{documentId:t,organizationId:i})}return this}catch(t){return this.loggingService.catch("Error in ContactService convert: ",t),this}}getContactList$(){try{return this.authService.getUser$().pipe(Se(e=>e?gn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(ue(([t,i,a,l,c])=>{let d={};d.organizationUsers=t?.map(u=>this.convertToClientUser(u)),d.folderUsers=i?.map(u=>this.convertToClientUser(u)),d.documentUsers=a?.map(u=>this.convertToClientUser(u)),d.updatedContactList=c?.map(u=>this.convertToClientUser(u));let m=[];return l?.forEach(u=>{let _=this.convertToClientUserGroup(u,d.organizationUsers||[]);_&&m.push(_)}),d.userGroups=m,d}),_t(Kt)):ce(null)),Xn(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),ce(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),ce(null)}}convertToClientUserGroup(e,t){try{let i={groupId:e?.metadata?.clientGroupId,groupName:e?.metadata?.groupName,users:[]},a={};return t?.forEach(l=>{if(l?.userId){let c=It(l.userId);a[c]=l}}),Object.keys(e?.users??{}).forEach(l=>{a[l]&&i.users?.push(a[l])}),i}catch(i){return this.loggingService.catch("Error in ContactService convertToClientUserGroup: ",i),null}}convertToClientUser(e){try{return e&&(e=JSON.parse(JSON.stringify(e)),e?.clientGroupId&&(e.groupId=e.clientGroupId,delete e.clientGroupId),e?.clientOrganizationId&&(e.organizationId=e.clientOrganizationId,delete e.clientOrganizationId),e?.userSnippylyId&&delete e.userSnippylyId),e}catch(t){return this.loggingService.catch("Error in ContactService convertToClientUser: ",t),e}}getCustomUserContacts(){return this.customUserContacts$.value}getCustomUserContacts$(){return this.customUserContacts$.asObservable()}getCustomUserContactsConfig(){return this.customUserContactsConfig$.value}getCustomUserContactsConfig$(){return this.customUserContactsConfig$.asObservable()}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(qe),K(Ft),K(nr),K($n),K(st),K(k),K(yn),K(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Vn=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m){this.analyticsService=e,this.authService=t,this.contactService=i,this.databaseService=a,this.docService=l,this.configService=c,this.loggingService=d,this.commonDbService=m,this.documentIAM$=new _e(null),this.workspaceIAM$=new _e(null),this.roles$=new _e([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(Ge(u=>!!u),ut(1)).subscribe(u=>{u&&(this.getUser(),this.getDocumentPaths())},u=>{this.loggingService.catch("Error in CommentService getDb subscription: ",u)}),this.getRole$().pipe(ut(1)).subscribe(u=>{this.authService?.getUser()&&!u&&this.analyticsService.trackEvent(Y.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(u=>{u?.accessType&&this.contactService.setDocumentAccessType(u.accessType)})}catch(u){this.loggingService.catch("Error in IamService constructor: ",u)}}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(Ge(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(Ge(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 AN;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(Xn(e=>ce(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(ue(e=>!!e),_t())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(ue(e=>e?.length?e:N.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(ue(e=>e?.features),Se(e=>this.getRole$().pipe(ue(t=>(t===Uo.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(Se(()=>this.documentIAM$.pipe(Ge(t=>!!t),Se(()=>this.workspaceIAM$.pipe(ue(()=>e===this.getRole()))))))}catch(t){return this.loggingService.catch("Error in IamService hasRole$: ",t),ce(!1)}}getRole$(){try{return this.authService.getUser$().pipe(Se(()=>this.configService.getSF$()),Se(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():ce(null)),Se(()=>this.configService.getSF()?this.documentIAM$.pipe(Ge(e=>!!e),_t(Kt)):ce(null)),Se(()=>this.workspaceIAM$.pipe(_t(Kt))),ue(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),ce(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return Uo.ADMIN;if(!e)return this.user?.isAdmin?Uo.ADMIN:Uo.COMMENTER;let t=null,i;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?Hr.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||Hr.PUBLIC:null){case Hr.PUBLIC:i=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),i||(i=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=i?.role?.name||Uo.COMMENTER;break;case Hr.RESTRICTED:i=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),i||(i=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=i?.role?.name||null;break;default:break}return t}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(ue(e=>e===Uo.ADMIN),_t())}isUserAdmin(){try{return this.getRole()===Uo.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,t){try{if(e||t){let i;return e&&(i=this.documentIAM$.value?.users?.[It(e)]),!i&&t&&(i=this.documentIAM$.value?.users?.[It(t)]),i}else return}catch(i){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",i)}}getUserFromWorkspaceIAM(e,t){try{if(e||t){let i;return e&&(i=this.workspaceIAM$.value?.users?.[It(e)]),!i&&t&&(i=this.workspaceIAM$.value?.users?.[It(t)]),i}else return}catch(i){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",i)}}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(qe),K(vn),K($n),K(st),K(Ft),K(k),K(yn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var hS="public",Ia=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_){this.authService=e,this.docService=t,this.loggingService=i,this.commonDbService=a,this.usersService=l,this.commentUtilsService=c,this.coreActionsService=d,this.functions=m,this.configService=u,this.contactService=_,this.currentUserPermissions$=new _e(null),this.permissionsCache$=new _e(null),this.permissionProvider$=new _e(null),this.requestKeyedPermissionsCache=new Map,this.inFlightPermissionsRequests=new Map,this.permissionsCacheGeneration=0,this.REVOKE_DELAY_MS=3e3,this.pendingRevokeRequests=new Map,this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="";try{this.docService.setUserPermissionService(this),this.authService.setUserPermissionService(this),this.commentUtilsService.setUserPermissionService(this),this.contactService.setUserPermissionService(this)}catch(I){this.loggingService.catch("Error in UserPermissionService constructor:",I)}}ngOnDestroy(){try{this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(e){this.loggingService.catch("Error in UserPermissionService ngOnDestroy:",e)}}collectRevokeRequest(e,t,i,a,l,c){try{return e.find(m=>m.resourceId===i&&m.type===a&&m.organizationId===l&&m.userId===c)?(t.push({userId:c,resourceId:i,organizationId:l,type:a,hasAccess:!1}),e.filter(m=>!(m.resourceId===i&&m.type===a&&m.organizationId===l&&m.userId===c))):e}catch(d){return this.loggingService.catch("Error in UsersPermissionService collectRevokeRequest:",d),e}}hasUserContextAccess({userId:e,accessFields:t}){try{if(!this.getIsContextEnabled()||t.includes(N.DEFAULT_VELT_CONTEXT))return!0;let i=this.contactService.getUserAccessFieldsByUserId(e);return i?t.every(a=>i.includes(a)):!0}catch(i){return this.loggingService.catch("Error in UserPermissionService hasUserContextAccess:",i),!1}}organizationDetails(e){return X(this,null,function*(){try{let t=yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{organizationId:e,suppressError:!0}});return t&&t?.errorCode?{errorCode:mr.PERMISSION_DENIED,error:!0}:t&&!t?.metadata?{errorCode:mr.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(t){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",t),{errorCode:mr.SOMETHING_WENT_WRONG,error:!0}}})}documentDetails(i){return X(this,arguments,function*({documentId:e,organizationId:t}){try{let a=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:t,suppressError:!0}});if(a&&a?.errorCode)return{errorCode:mr.PERMISSION_DENIED,error:!0};if(a&&!a?.metadata)return{errorCode:mr.DOES_NOT_EXIST,error:!0};let l=this.docService.getDocumentMetadata(e)??{};this.docService.setDocumentMetadata(e,h(h({},l),a?.metadata??{}));let c,d=a?.metadata?.veltFolderId;if(d)try{c=(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:d,organizationId:t}}))?.folderIamConfig?.accessType}catch(m){this.loggingService.catch("Error fetching folder accessType for document:",m)}return c||(c=a?.docIamConfig?.accessType),{error:!1,accessType:c}}catch(a){return this.loggingService.catch("Error in UserPermissionService documentDetails:",a),{errorCode:mr.SOMETHING_WENT_WRONG,error:!0}}})}folderDetails(i){return X(this,arguments,function*({folderId:e,organizationId:t}){try{let a=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:t,suppressError:!0}});return a&&a?.errorCode?{errorCode:mr.PERMISSION_DENIED,error:!0}:a&&!a?.metadata?{errorCode:mr.DOES_NOT_EXIST,error:!0}:{error:!1,accessType:a?.folderIamConfig?.accessType}}catch(a){return this.loggingService.catch("Error in UserPermissionService folderDetails:",a),{errorCode:mr.SOMETHING_WENT_WRONG,error:!0}}})}getUserPermissions(e){return X(this,null,function*(){let t=this.permissionsCacheGeneration;try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getUserPermissions]",void 0,void 0,!0),{};let i=this.authService.getUser()?.userId,a=this.extractResourceIds(e);if(!a.clientOrganizationId||!a.organizationId)return this.loggingService.catch("Client organization id or organization id not set during getUserPermissions",void 0,void 0,!0),{};let l=yield this.validateResources(a),[c,d]=yield this.fetchUserPermissionsFromDB(a),m=this.authService.getUser()?.userId;if(i!==m)return{};let u=this.buildPermissionsResponse(a,l,c,d);if(Object.keys(u).length>0){if(!e)this.setCurrentUserPermissions(u);else if(this.permissionsCacheGeneration===t){let _=this.buildPermissionsCacheKey(e);_!==null&&this.requestKeyedPermissionsCache.set(_,JSON.parse(JSON.stringify(u)))}}return u}catch(i){return this.loggingService.catch("Error in UserPermissionService getUserPermissions:",i),{}}})}getUserPermissionsFromCacheOrFetch(e){return X(this,null,function*(){try{if(!e)return yield this.getUserPermissions(e);let t=this.buildPermissionsCacheKey(e);if(t===null)return yield this.getUserPermissions(e);let i=this.permissionsCacheGeneration,a=this.requestKeyedPermissionsCache.get(t);if(a)return JSON.parse(JSON.stringify(a));let l=this.inFlightPermissionsRequests.get(t);if(l){let m=yield l;return this.permissionsCacheGeneration!==i?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(m))}let c=this.getUserPermissions(e);this.inFlightPermissionsRequests.set(t,c),c.finally(()=>{this.inFlightPermissionsRequests.get(t)===c&&this.inFlightPermissionsRequests.delete(t)}).catch(()=>{});let d=yield c;return this.permissionsCacheGeneration!==i?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(d))}catch(t){return this.loggingService.catch("Error in UserPermissionService getUserPermissionsFromCacheOrFetch:",t),{}}})}clearRequestKeyedPermissionsCache(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService clearRequestKeyedPermissionsCache:",e)}}invalidateAllPermissionsState(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService invalidateAllPermissionsState:",e)}}buildPermissionsCacheKey(e){try{let t={};return Object.keys(e).sort().forEach(i=>{let a=e[i];a!==void 0&&(t[i]=Array.isArray(a)?[...a].sort():a)}),t.__userId=this.authService.getUser()?.userId??null,JSON.stringify(t)}catch(t){return this.loggingService.catch("Error in UserPermissionService buildPermissionsCacheKey:",t),null}}extractResourceIds(e){let t=this.docService.getDocumentPaths(),i=this.docService.getDocumentIds();if(e){let c=e.organizationId??t?.clientOrganizationId;return{folderIds:e.folderIds??[],documentIds:e.documentIds??[],clientOrganizationId:c,organizationId:c?ba(c):void 0}}let a=t?.clientOrganizationId;return{folderIds:t?.folderId?[t.folderId]:[],documentIds:i.map(c=>c.clientDocumentId),clientOrganizationId:a,organizationId:a?ba(a):void 0}}validateResources(e){return X(this,null,function*(){let{folderIds:t,documentIds:i,organizationId:a,clientOrganizationId:l}=e,c=[],d=[],m=t.length>0||i.length>0;a&&!m&&(c.push(this.organizationDetails(a)),d.push({id:l??"",type:"organization"})),t.forEach(A=>{c.push(this.folderDetails({folderId:Lr(A),organizationId:a??""})),d.push({id:A,type:"folder"})}),i.forEach(A=>{c.push(this.documentDetails({documentId:mi(A),organizationId:a??""})),d.push({id:A,type:"document"})});let[u,_]=yield Promise.all([Promise.allSettled(c),this.getDefaultDocumentAccessType()]),I=this.processValidationResults(u,d);return y(h({},this.suppressResolverGrantedFailures(I,l)),{defaultDocumentAccessType:_})})}suppressResolverGrantedFailures(e,t){try{let i=this.authService.getUser()?.userId;if(!i)return e;let a=this.getPermissionsCache()??[];if(a.length===0)return e;let l=(u,_,I)=>a.some(A=>A?.userId===i&&A?.resourceId===u&&A?.type===_&&(!I||A?.organizationId===I)&&A?.hasAccess===!0),c=e.failedDocumentIds.filter(u=>!(u.errorCode===mr.PERMISSION_DENIED&&l(u.id,bi.DOCUMENT,t))),d=e.failedFolderIds.filter(u=>!(u.errorCode===mr.PERMISSION_DENIED&&l(u.id,bi.FOLDER,t))),m=e.failedOrganizationId;return m&&m.errorCode===mr.PERMISSION_DENIED&&t&&l(t,bi.ORGANIZATION,t)&&(m=void 0),{failedFolderIds:d,failedDocumentIds:c,failedOrganizationId:m,folderAccessTypes:e.folderAccessTypes,documentAccessTypes:e.documentAccessTypes}}catch(i){return this.loggingService.catch("Error in UserPermissionService suppressResolverGrantedFailures:",i),e}}getDefaultDocumentAccessType(){return X(this,null,function*(){try{return(yield this.commonDbService?.getData({feature:"apiKeyMetadata",properties:{}}))?.defaultDocumentAccessType}catch(e){this.loggingService.catch("Error fetching defaultDocumentAccessType:",e);return}})}processValidationResults(e,t){let i=[],a=[],l,c={},d={};for(let m=0;m<e.length;m++){let u=e[m],_=t[m];if(u.status==="rejected"||u.status==="fulfilled"&&u.value.error){let A=u.status==="fulfilled"?u.value.errorCode??mr.SOMETHING_WENT_WRONG:mr.SOMETHING_WENT_WRONG,M={id:_.id,errorCode:A};switch(_.type){case"organization":if(l=M,A===mr.DOES_NOT_EXIST)throw new Error(`Organization with id '${_.id}' does not exist`);break;case"folder":i.push(M);break;case"document":a.push(M);break}}else if(u.status==="fulfilled")switch(_.type){case"folder":u.value.accessType&&(c[_.id]=u.value.accessType);break;case"document":u.value.accessType&&(d[_.id]=u.value.accessType);break}}return{failedFolderIds:i,failedDocumentIds:a,failedOrganizationId:l,folderAccessTypes:c,documentAccessTypes:d}}fetchUserPermissionsFromDB(e){return X(this,null,function*(){let{folderIds:t,documentIds:i,organizationId:a}=e,l=[this.authService.getUser()?.userId??""],c=[...t.map(u=>Lr(u)),...i.map(u=>mi(u)),a??""],[d,m]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:l,organizationId:a}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:l,organizationId:a,resourceIds:c})]);return[d.status==="fulfilled"?d.value:[],m.status==="fulfilled"?m.value:[]]})}buildPermissionsResponse(e,t,i,a){let{folderIds:l,documentIds:c,clientOrganizationId:d,organizationId:m}=e,{failedFolderIds:u,failedDocumentIds:_,failedOrganizationId:I}=t,A={};return this.processRegularUserPermissions(A,i,l,c,d??"",m??"",u,_,I,t.folderAccessTypes,t.documentAccessTypes,t.defaultDocumentAccessType),this.ensureCurrentUserFailuresRecorded(A,d??"",u,_,I,t.folderAccessTypes,t.documentAccessTypes,t.defaultDocumentAccessType),this.processTemporaryUserPermissions(A,a),this.processContextPermissions(A),A}processContextPermissions(e){try{let t=this.authService.getUser()?.userId;if(t){let i=this.contactService.getUserAccessFieldsByUserId(t);i?.length&&(e[t]||(e[t]={}),e[t].context={accessFields:i})}}catch(t){this.loggingService.catch("Error in UserPermissionService processContextPermissions:",t);return}}processRegularUserPermissions(e,t,i,a,l,c,d,m,u,_,I,A){for(let M of t)for(let V of M)V?.user?.userId&&(e[V.user.userId]=y(h({},i.length&&{folders:this.buildFolderPermissions(i,V,d,_,A)}),{documents:this.buildDocumentPermissions(a,V,m,I,A),organization:{[l]:this.buildOrganizationPermission(c,V,u)}}))}ensureCurrentUserFailuresRecorded(e,t,i,a,l,c,d,m){try{let u=this.authService.getUser()?.userId;if(!u)return;let _=!!l&&!!t,I=(i?.length??0)>0,A=(a?.length??0)>0;if(!_&&!I&&!A)return;if(e[u]||(e[u]={}),_&&(e[u].organization||(e[u].organization={}),e[u].organization[t]||(e[u].organization[t]={error:this.getErrorMessage(l.errorCode,"organization"),errorCode:l.errorCode})),I){e[u].folders||(e[u].folders={});for(let M of i)e[u].folders[M.id]||(e[u].folders[M.id]=h({error:this.getErrorMessage(M.errorCode,"folder"),errorCode:M.errorCode},M.errorCode===mr.PERMISSION_DENIED&&{accessType:c[M.id]??m??hS}))}if(A){e[u].documents||(e[u].documents={});for(let M of a)e[u].documents[M.id]||(e[u].documents[M.id]=h({error:this.getErrorMessage(M.errorCode,"document"),errorCode:M.errorCode},M.errorCode===mr.PERMISSION_DENIED&&{accessType:d[M.id]??m??hS}))}}catch(u){this.loggingService.catch("Error in UserPermissionService ensureCurrentUserFailuresRecorded:",u)}}getErrorMessage(e,t){try{switch(this.loggingService.log(`Error in UserPermissionService getErrorMessage: ${e} ${t}`),e){case mr.DOES_NOT_EXIST:return`${t} does not exist`;case mr.PERMISSION_DENIED:return`User does not have access to ${t}`;case mr.SOMETHING_WENT_WRONG:return"Something went wrong";default:return"Something went wrong"}}catch(i){return this.loggingService.catch("Error in UserPermissionService getErrorMessage:",i),"Something went wrong"}}buildFolderPermissions(e,t,i,a,l){return e.reduce((c,d)=>{let m=i.find(u=>u.id===d);return m?c[d]=h({error:this.getErrorMessage(m.errorCode,"folder"),errorCode:m.errorCode},m.errorCode===mr.PERMISSION_DENIED&&{accessType:a[d]??l??hS}):c[d]={accessRole:t.viewerFolderIds?.includes(Lr(d))?Yc.VIEWER:Yc.EDITOR,accessType:a[d]??l??hS},c},{})}buildDocumentPermissions(e,t,i,a,l){return e.reduce((c,d)=>{let m=i.find(u=>u.id===d);return m?c[d]=h({error:this.getErrorMessage(m.errorCode,"document"),errorCode:m.errorCode},m.errorCode===mr.PERMISSION_DENIED&&{accessType:a[d]??l??hS}):c[d]={accessRole:t.viewerDocumentIds?.includes(mi(d))?Yc.VIEWER:Yc.EDITOR,accessType:a[d]??l??hS},c},{})}buildOrganizationPermission(e,t,i){return i?{error:this.getErrorMessage(i.errorCode,"organization"),errorCode:i.errorCode}:{accessRole:t.viewerOrganizationIds?.includes(e)?Yc.VIEWER:Yc.EDITOR}}processTemporaryUserPermissions(e,t){for(let i of t)if(i?.userId)switch(this.ensureUserPermissionStructure(e,i.userId),i.type){case"folder":this.addTemporaryFolderPermission(e,i);break;case"document":this.addTemporaryDocumentPermission(e,i);break;case"organization":this.addTemporaryOrganizationPermission(e,i);break}}ensureUserPermissionStructure(e,t){e[t]||(e[t]={})}addTemporaryFolderPermission(e,t){let{userId:i,resourceId:a,role:l,expiresAt:c}=t;e[i].folders||(e[i].folders={}),e[i].folders[a]={accessRole:l??Yc.EDITOR,expiresAt:c}}addTemporaryDocumentPermission(e,t){let{userId:i,resourceId:a,role:l,expiresAt:c}=t;e[i].documents||(e[i].documents={}),e[i].documents[a]={accessRole:l??Yc.EDITOR,expiresAt:c}}addTemporaryOrganizationPermission(e,t){let{userId:i,resourceId:a,role:l,expiresAt:c}=t;e[i].organization||(e[i].organization={}),e[i].organization[a]={accessRole:l??Yc.EDITOR,expiresAt:c}}hasEditAccess({organizationId:e,folderId:t,documentId:i}){try{let a=!0,l=this.getCurrentUserPermissionsWithServerIds(),c=this.authService.getUser()?.userId??"";return l&&(e&&typeof e=="string"&&l?.[c]?.organization?.[e]&&(l?.[c]?.organization?.[e]?.accessRole===Yc.VIEWER||l?.[c]?.organization?.[e]?.errorCode===mr.PERMISSION_DENIED)&&(a=!1),t&&typeof t=="string"&&l?.[c]?.folders?.[t]&&(l?.[c]?.folders?.[t]?.accessRole===Yc.VIEWER||l?.[c]?.folders?.[t]?.errorCode===mr.PERMISSION_DENIED)&&(a=!1),i&&typeof i=="string"&&l?.[c]?.documents?.[i]&&(l?.[c]?.documents?.[i]?.accessRole===Yc.VIEWER||l?.[c]?.documents?.[i]?.errorCode===mr.PERMISSION_DENIED)&&(a=!1)),a}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(_t(Kt))}getCurrentUserPermissions(){return this.currentUserPermissions$.value}refactorPermissionsWithServerIds(e){try{let t=JSON.parse(JSON.stringify(e??{})),i=this.authService.getUser()?.userId??"";if(t?.[i]){let a=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(t?.[i]?.organization?.[a]){let l=ba(a);t[i].organization&&(t[i].organization[l]=t[i].organization[a],delete t[i].organization[a])}t?.[i]?.folders&&(t[i].folders=Object.fromEntries(Object.entries(t?.[i]?.folders??{}).map(([l,c])=>[Lr(l),c]))),t?.[i]?.documents&&(t[i].documents=Object.fromEntries(Object.entries(t?.[i]?.documents??{}).map(([l,c])=>[mi(l),c])))}return t}catch(t){return this.loggingService.catch("Error in UsersPermissionService refactorPermissionsWithServerIds:",t),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(ue(e=>this.refactorPermissionsWithServerIds(e)),_t(Kt))}getCurrentUserPermissionsWithServerIds(){return this.refactorPermissionsWithServerIds(this.currentUserPermissions$.value)}setCurrentUserPermissions(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCurrentUserPermissions","color: green;");let t=null;e&&(t=JSON.parse(JSON.stringify(e))),this.currentUserPermissions$.next(t)}catch(t){this.loggingService.catch("Error in UsersPermissionService setCurrentUserPermissions:",t)}}getIsContextEnabled(){return this.loggingService.log("%c[WB] Calling FUNCTION: getIsContextEnabled","color: green;"),this.permissionProvider$.value?.isContextEnabled??!1}setPermissionProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setPermissionProvider","color: green;"),this.permissionProvider$.next(e)}catch(t){this.loggingService.catch("Error in UsersPermissionService setPermissionProvider:",t)}}get isRevokeAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===s1.DOCUMENT_UNSET)??!1}get isRevokeAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===s1.USER_LOGOUT)??!1}get isRevokeOrganizationAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===s1.USER_LOGOUT&&e.revokeOrganizationAccess)??!1}get isRevokeOrganizationAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===s1.DOCUMENT_UNSET&&e.revokeOrganizationAccess)??!1}getPermissionProviderRetryConfig(){return this.permissionProvider$.value?.retryConfig??{retryCount:0,retryDelay:0}}revokeAccessOnUserLogout(){return X(this,null,function*(){let e=lt();try{if(this.isRevokeAccessOnUserLogoutEnabled){let t=[],i=this.authService.getUser()?.userId??"";if((this.getPermissionsCache()??[]).forEach(l=>{l.userId===i&&l.hasAccess&&(l.type===bi.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&t.push(y(h({},l),{hasAccess:!1})):t.push(y(h({},l),{hasAccess:!1})))}),t.length>0){this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_FORMED,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:t}}),this.setPermissionsCache([]),this.clearRequestKeyedPermissionsCache(),this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_TRIGGERED,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:t}});let l=yield this.revokeAccess({requests:t,userId:this.authService.getUser()?.userId??""});l.success?this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:l,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:l,success:!1,statusCode:500}}})}}}catch(t){this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{error:t}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnUserLogout:",t)}})}getRevokeKey(e){try{return`${e.userId}_${e.resourceId}_${e.type}_${e.organizationId}`}catch(t){return this.loggingService.catch("Error in UsersPermissionService getRevokeKey:",t),""}}cancelPendingRevokes(e){try{e.forEach(t=>{let i=this.getRevokeKey({userId:t.userId,resourceId:t.resource.id,type:t.resource.type,organizationId:t.resource.organizationId});this.pendingRevokeRequests.has(i)&&this.pendingRevokeRequests.delete(i)}),this.pendingRevokeRequests.size===0&&this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(t){this.loggingService.catch("Error in UsersPermissionService cancelPendingRevokes:",t)}}flushPendingRevokes(){return X(this,null,function*(){let e=this.pendingRevokeUniqueId,t=this.pendingRevokeUserId;try{let i=Array.from(this.pendingRevokeRequests.values());if(this.pendingRevokeRequests.clear(),this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="",i.length===0)return;let a=this.getPermissionsCache()??[];i.forEach(d=>{a=a.filter(m=>!(m.resourceId===d.resourceId&&m.type===d.type&&m.organizationId===d.organizationId&&m.userId===d.userId))}),this.setPermissionsCache(a);let l=this.docService.getDocContext(),c=yield this.revokeAccess({requests:i,userId:t,currentContext:l});c.success?this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:c,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:c,success:!1,statusCode:500}}})}catch(i){this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:i}}),this.loggingService.catch("Error in UsersPermissionService flushPendingRevokes:",i)}})}revokeAccessOnDocumentUnset(a){return X(this,arguments,function*({documentIds:e,folderId:t,context:i}){let l=lt();try{if(this.isRevokeAccessOnDocumentUnsetEnabled){let c=[],d=this.docService.getOrganizationConfig()?.clientOrganizationId??"",m=this.authService.getUser()?.userId??"",u=this.getPermissionsCache()??[];e.forEach(_=>{u=this.collectRevokeRequest(u,c,_.clientDocumentId,bi.DOCUMENT,d,m)}),t&&(u=this.collectRevokeRequest(u,c,t,bi.FOLDER,d,m)),d&&this.isRevokeOrganizationAccessOnDocumentUnsetEnabled&&(u=this.collectRevokeRequest(u,c,d,bi.ORGANIZATION,d,m)),i&&this.getIsContextEnabled()&&cF({input:i}).forEach(I=>{let A=JSON.stringify(I.access);u=this.collectRevokeRequest(u,c,A,bi.CONTEXT,d,m)}),this.setPermissionsCache(u),c.length>0&&(this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_FORMED,timestamp:new Date().getTime(),uniqueId:l,methodName:no.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:c}}),this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_TRIGGERED,timestamp:new Date().getTime(),uniqueId:l,methodName:no.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:c}}),c.forEach(_=>{this.pendingRevokeRequests.set(this.getRevokeKey(_),_)}),this.pendingRevokeUniqueId=l,this.pendingRevokeUserId=m,this.pendingRevokeTimeoutId&&clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=setTimeout(()=>this.flushPendingRevokes(),this.REVOKE_DELAY_MS))}}catch(c){this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:no.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:c}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnDocumentUnset:",c)}})}getAccess(i){return X(this,arguments,function*({requests:e,userId:t}){let a=Yr(this.functions,Zr({url:On?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield wl({methodName:"getAccess",data:{type:"getAccess",data:e,metadata:{retryConfig:this.getPermissionProviderRetryConfig()}},getSdkProxy:a,userId:t})})}revokeAccess(a){return X(this,arguments,function*({requests:e,userId:t,currentContext:i}){let l=Yr(this.functions,Zr({url:On?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield wl({methodName:"revokeAccess",data:{type:"revokeAccess",data:e,metadata:h({retryConfig:this.getPermissionProviderRetryConfig()},i?.access&&{currentContext:i})},getSdkProxy:l,userId:t})})}onResourceAccessRequired(c){return X(this,arguments,function*({requests:e,uniqueId:t,methodName:i,userId:a,fromCache:l=!0}){try{if(!e?.length)return;let d=[],m=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&l&&(e.forEach(u=>{let _=m?.find(I=>I.resourceId===u.resource.id&&I.type===u.resource.type&&I.userId===u.userId&&I.organizationId===u.resource.organizationId);_&&d.push(_)}),d.length>0&&(e=e.filter(u=>!d.find(_=>_.resourceId===u.resource.id&&_.type===u.resource.type&&_.userId===u.userId&&_.organizationId===u.resource.organizationId)))),e.length>0){this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:t,methodName:i,source:"internal",payload:{requests:e,fromCache:l}});let u=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??a??""});return this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_RESULT,timestamp:new Date().getTime(),uniqueId:t,methodName:i,source:"internal",payload:{result:u}}),u?.success&&u?.data?.length&&(this.setPermissionsCache([...m,...u.data]),u.data=[...d,...u.data]),u}else if(d.length>0)return this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_RESULT_FROM_CACHE,timestamp:new Date().getTime(),methodName:i,source:"internal",uniqueId:t,payload:{results:{data:d,success:!0,statusCode:200}}}),{data:d,success:!0,statusCode:200};return}catch(d){this.loggingService.catch("Error in UsersPermissionService onResourceAccessRequired:",d),this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_ERROR,timestamp:new Date().getTime(),methodName:i,source:"internal",uniqueId:t,payload:{error:d,requests:e,fromCache:l}});return}})}getPermissionsCache(){return this.forceRefreshPermissions()?[]:this.permissionsCache$.getValue()}forceRefreshPermissions(){return this.getPermissionProvider()?.forceRefresh??!1}setPermissionsCache(e){try{let t=new Map;e.forEach(a=>{let l=`${a.userId}_${a.resourceId}_${a.organizationId}_${a.type}`;t.set(l,a)});let i=JSON.parse(JSON.stringify(Array.from(t.values())));this.permissionsCache$.next(i)}catch(t){this.loggingService.catch("Error in UsersPermissionService setPermissionsCache:",t)}}isPermissionProviderAvailable(){try{return!!this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService isPermissionProviderAvailable:",e),!1}}getPermissionProvider(){try{return this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService getPermissionProvider:",e),null}}getPermissionProvider$(){return this.permissionProvider$.asObservable()}};o.\u0275fac=function(t){return new(t||o)(K(qe),K(st),K(k),K(yn),K(An),K(Cm),K(nr),K(Do),K(Ft),K(vn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var zi=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A){this.afAuth=e,this.analyticsService=t,this.authService=i,this.configService=a,this.databaseService=l,this.commonDbService=c,this.docService=d,this.domService=m,this.emojiService=u,this.iamService=_,this.loggingService=I,this.userPermissionService=A,this.documentPaths=null,this.reactionAnnotationById$=new _e({}),this.customReactions$=new _e({}),this.commentService=null,this.darkMode$=new _e(null),this.loggingService.log("%c[WB] Creating CLASS: ReactionService","color: blue;"),this.analyticsService.setReactionService(this),this.authService.setReactionService(this),this.databaseService.getDb().pipe(Ge(M=>!!M),ut(1)).subscribe(M=>{M&&this.getAllReactionAnnotations(void 0,void 0,!0).subscribe()},M=>{this.loggingService.catch("Error in ReactionService getDb subscription: ",M)})}setCommentService(e){this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;");try{this.commentService=e}catch(t){this.loggingService.catch("Error in ReactionService setCommentService: ",t)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ReactionService","color: green;");try{this.reactionAnnotationById$.next({}),this.customReactions$.next({}),this.documentPaths=null}catch(e){this.loggingService.catch("Error in ReactionService clearCache: ",e)}}getAllReactionAnnotations(e,t,i,a,l){this.loggingService.log("%c[WB] Calling FUNCTION: getAllReactionAnnotations","color: green;");let c,d;try{if(e&&(d=`${er(e)}`),t&&typeof t=="object"){let m=Oi(t);c=er(JSON.stringify(m))}}catch(m){this.loggingService.catch("Error in ReactionService getAllReactionAnnotations: ",m)}return _r(this.afAuth).pipe(Ge(m=>!!m),Se(m=>this.isFeatureAllowed({firebaseUser:m,annotations:[],filteredAnnotations:[]})),Se(m=>m.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(u=>(m.featureAllowed=u,m))):ce(m)),Se(m=>m.featureAllowed?ce(m).pipe(Se(u=>this.docService.getDocumentPaths$().pipe(ue(_=>(this.documentPaths=_,u.documentPaths=_,u)))),Se(u=>d?this.getDataFromDocumentIds([d]).pipe(ue(_=>(u.annotations=_||[],h({},u)))):this.docService.getDocumentIds$().pipe(Se(_=>{let I=_?.length>0?_.map(A=>A.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(I).pipe(ue(A=>(u.annotations=A||[],h({},u))))}))),Se(u=>this.docService.getLocation$().pipe(ue(_=>(u.location=_,u)))),Se(u=>this.docService.getLocations$().pipe(ue(_=>(u.customLocations=_,u)))),ue(u=>{if(u.filteredAnnotations=[],d&&!c)return u.filteredAnnotations=u.annotations?.slice(),u;{let _=[];return c?_.push(c):(_.push(u?.location?.locationId),_.push(...Object.values(u?.customLocations||[]).map(I=>I.locationId))),u.filteredAnnotations=this.filterAnnotationsByLocationIds(u?.annotations,_),u}}),Se(u=>i?ce(u):u?.annotations?.length?this.domService.onWindowResize$().pipe(ue(()=>u)):ce(u)),Se(u=>i?ce(u):ce(u)),ue(u=>u),Se(u=>u?.filteredAnnotations?ce(u?.filteredAnnotations||[]):ce([]))):ce([])),_t(Kt))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})),Se(t=>this.authService.getUser$().pipe(ue(i=>y(h({},t),{user:i})))),Se(t=>Ao(t.config,t.user,je.REACTION)?ce(y(h({},t),{featureAllowed:!0})):(this.loggingService.warn("Reaction feature is not allowed."),ce(y(h({},t),{featureAllowed:!1})))),_t((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t,filters:i}=e;if(t?.some(d=>!d)||!this.documentPaths)return ce([]);let a=this.docService.getDocumentPaths()?.veltFolderId,l=ce([]),c={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(c.documentId=t?.length?t[0]:void 0,c.organizationId=this.documentPaths?.organizationId),this.userPermissionService?.getIsContextEnabled()){let d=[N.DEFAULT_VELT_CONTEXT,...this.docService.getProcessedDocContext()],m=[];for(let u=0;u<(d?.length??0);u+=N.LISTENER_CONTEXT_BATCH_SIZE)m.push(d?.slice(u,u+N.LISTENER_CONTEXT_BATCH_SIZE)??[]);l=gn(m.map(u=>this.commonDbService.dbListener({feature:"allReactions",properties:y(h({},c),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",t),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[],...u?.length?[ft("context.accessFields","array-contains-any",u)]:[])]})}).pipe(la()))).pipe(ue(u=>Na(u)))}else{let d=[];for(let m=0;m<(t?.length??0);m+=N.LISTENER_BATCH_SIZE)d.push(t?.slice(m,m+N.LISTENER_BATCH_SIZE)??[]);l=gn(d.map(m=>this.commonDbService.dbListener({feature:"allReactions",properties:y(h({},c),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",m),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[])]})}).pipe(la()))).pipe(ue(m=>Na(m)))}return l.pipe(ue(d=>({data:d?.data,operation:d?.operation})),ue(({data:d,operation:m})=>{let u=[];return d&&(u=Object.values(d??{}).filter(_=>typeof _=="object")),u?.forEach(_=>{this.sanitizeReactionAnnotation(_)}),{data:u,operation:m}}),ue(({data:d,operation:m})=>{if(!t)return{data:d,documentMap:{},operation:m};let u=d.reduce((_,I)=>{let A=I.metadata?.documentId;return A&&(_[A]||(_[A]=[]),_[A].push(I)),_},{});return{data:d,documentMap:u,operation:m}}),ue(({data:d,documentMap:m,operation:u})=>{if(!i)if(u?.type==="removed"){if(u?.ids?.length){let _=this.reactionAnnotationById$.value;u?.ids?.forEach(I=>{delete _?.[I]}),this.reactionAnnotationById$.next(_)}}else Object.entries(m??{}).forEach(([_,I])=>{this.setReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:_,annotations:I})});return d}),Xn(d=>(this.loggingService.catch("Error in ReactionService getDataFromDocumentId: ",d),ce([]))))}else return ce([])}setReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:i,queryHash:a}){try{if(t){e||(e=N.NO_ORGANIZATION_ID),a||(a=N.DEFAULT_QUERY_HASH);let l={};i?.forEach(d=>{d?.annotationId&&(l[d?.annotationId]=d)});let c=h(h({},this.reactionAnnotationById$.value),l);this.reactionAnnotationById$.next(c)}}catch(l){this.loggingService.catch("Error in ReactionService setReactionAnnotationsByOrganizationIdAndDocumentId:",l)}}getReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let i={};return Object.values(this.reactionAnnotationById$.value??{}).forEach(a=>{a?.metadata?.documentId==t&&a?.metadata?.organizationId==e&&(i[a?.annotationId]=a)}),Object.values(i)}catch(i){return this.loggingService.catch("Error in ReactionService getReactionAnnotationsByOrganizationIdAndDocumentId:",i),[]}}getLocations$(){return this.docService.getLocation$().pipe(Se(e=>this.docService.getLocations$().pipe(ue(t=>({location:e,locations:t})))),ue(e=>{let t=[];return t.push(e?.location?.locationId),t.push(...Object.values(e.locations||[]).map(i=>i.locationId)),t||[]}))}filterAnnotationsByLocationIds(e,t){try{return e.filter(i=>t.includes(i.locationId))}catch(i){return this.loggingService.catch("Error in ReactionService filterAnnotationsByLocations:",i),[]}}getAnnotationById(e,t){try{let i=this.reactionAnnotationById$.value?.[e];if(i){let{documentId:a,organizationId:l}=t||{};if(a&&i.metadata?.documentId!==a||l&&i.metadata?.organizationId!==l)return}return i}catch(i){this.loggingService.catch("Error in ReactionService getAnnotationById: ",i);return}}getBaseMetadataFromReactionAnnotationId(e){try{let t=this.reactionAnnotationById$.value?.[e];return t?t.metadata:void 0}catch(t){this.loggingService.catch("Error in ReactionService getBaseMetadataFromReactionAnnotationId: ",t);return}}getReactionAnnotationByAnnotationId(e,t){try{return this.reactionAnnotationById$.pipe(ue(()=>this.getAnnotationById(e,t)),Se(i=>i?ce(i):ce(i)))}catch(i){return this.loggingService.catch("Error in ReactionService getReactionAnnotationByAnnotationId: ",i),ce(void 0)}}getReactionAnnotationsBySectionId(e){try{return this.reactionAnnotationById$.pipe(Se(t=>this.docService.getDocumentPaths$().pipe(ue(i=>({documentPaths:i,sectionId:e,reactionAnnotationsMap:t})))),Se(t=>{let i=nl(e,["id","data-id"]);if(i){let a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.genarateLocationId(a);return this.docService.getLocations$().pipe(ue(c=>{let m=Object.values(c||{}).find(u=>u.locationId===l||a?.id&&u.location.id===a.id);return y(h({},t),{additionalLocation:m,locationOnElement:!!a})}))}}return ce(y(h({},t),{additionalLocation:null,element:i}))}),Se(t=>t?.locationOnElement?ce(t):this.docService.getLocation$().pipe(ue(i=>y(h({},t),{location:i})))),ue(({documentPaths:t,location:i,additionalLocation:a,locationOnElement:l,element:c})=>{let d=null,m=this.docService.getAdditionalDocumentIdFromElement(c),u=m?this.docService.generateDocumentId(m):t?.documentId,_=t?.organizationId;if(u){let I=this.getReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:_,documentId:u});if(I){d=[];for(let A of I)A?.targetElementId===e&&(l?a&&_0({location:a?.location,locationId:a?.locationId},{location:A.location,locationId:A.locationId})&&d.push(A):i?_0({location:i?.location,locationId:i?.locationId},{location:A.location,locationId:A.locationId})&&d.push(A):A?.locationId||d.push(A))}}return d}))}catch(t){return this.loggingService.catch("Error in ReactionService getReactionAnnotationsBySectionId: ",t),ce(null)}}addOrUpdateReaction(e,t,i,a,l,c,d,m){return X(this,null,function*(){try{let u=t?.map(_=>this.getAnnotationById(_)).find(_=>_?.icon===e);if(u){if(!d||d==="delete")return yield this.updateUserInReaction(u)}else if(!d||d==="add")return yield this.addReaction(void 0,e,i,a,l,c,m)}catch(u){this.loggingService.catch("Error in ReactionService addOrUpdateReaction: ",u)}})}addReaction(e,t,i,a,l,c,d){return X(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: addReaction","color: green;");try{let m=this.authService.getUser();if(m)if(m.isReadOnly||m.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add reactions.");else{let u=new jN;if(u.from=m,u.lastUpdated=this.timestamp,u.reactions=[],u.reactions.push({from:m,lastUpdated:this.timestamp}),a&&(u.targetElementId=a),l){u.commentAnnotationId=l;let _=this.commentService?.getAnnotationById(l);if(_?.context?.access&&_?.context?.accessFields){if(!this.userPermissionService?.hasUserContextAccess({userId:m.userId,accessFields:_.context.accessFields})){this.loggingService.catch("User does not have context access to add reaction annotation.",void 0,void 0,!0);return}u.context={access:_.context.access,accessFields:_.context.accessFields}}}if(this.setLocationToReactionAnnotation(u),u.pageInfo=ro(),u.pageInfo&&(u.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth),t)if(u.icon=t,c)u.iconUrl=c?.url,u.iconEmoji=c?.emoji;else{let _=this.customReactions$.value;if(_){let I=_[t];I?.url&&(u.iconUrl=I?.url),I?.emoji&&(u.iconEmoji=I?.emoji)}}return i&&(u.location={},u.location=h({},i),u.locationId=this.docService.genarateLocationId(u.location)),yield this.saveReactionToDb(u)}}catch(m){this.loggingService.catch("Error in ReactionService addReaction: ",m)}})}setLocationToReactionAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location);try{let i;e.targetElement?.xpath?i=this.domService.getElementFromXPath(e.targetElement.xpath):e.targetElementId&&(i=nl(e.targetElementId,["id","data-id"]));let a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.addLocation({location:a,source:"internal"});l?.[0]&&(e.locationId=l[0].locationId,e.location=l[0].location)}}catch{}}catch(t){this.loggingService.catch("Error in ReactionService setLocationToReactionAnnotation:",t)}}getElementForReactionAnnotation(e){try{let t;return e.targetElementId&&(t=nl(e.targetElementId,["id","data-id"])),t}catch(t){return this.loggingService.catch("Error in ReactionService getElementForReactionAnnotation: ",t),null}}saveReactionToDb(e){return X(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: saveReactionToDb","color: green;");try{if(this.authService.getUser()){let t=yield this.docService.getDocumentPaths$().pipe(Ge(a=>!!a),ut(1)).toPromise();if(!t)throw new Error("Document paths not found.");if(this.documentPaths=t,this.loggingService.log(this.documentPaths),!(yield this.databaseService.getDb().pipe(Ge(a=>!!a),ut(1)).toPromise()))throw new Error("Database not found.");if(this.documentPaths?.reaction){if(e.annotationId=this.commonDbService.generateDocumentId(),e.pageInfo,!e?.metadata?.documentId){e?.metadata||(e.metadata={});let m=this.getElementForReactionAnnotation(e),u=this.docService.getBaseMetadata("reaction",{commentAnnotationId:e.commentAnnotationId,element:m});e.metadata=h(h({},e?.metadata),u)}let a=JSON.parse(JSON.stringify(e));a.position=null;let{documentId:l,organizationId:c}=this.getDocumentIdAndOrganizationIdFromReactionAnnotation(e),d=e.commentAnnotationId?void 0:{annotationData:a,actionType:"add",notificationSource:"reaction"};return yield this.commonDbService.setData({feature:"reaction",properties:{id:e.annotationId,documentId:l,organizationId:c},data:a,extraData:d}),a}else return}}catch(t){this.loggingService.catch("Error in ReactionService saveReactionToDb: ",t)}})}getDocumentIdAndOrganizationIdFromReactionAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in ReactionService getDocumentIdAndOrganizationIdFromReactionAnnotation: ",t),{}}}updateUserInReaction(e){return X(this,null,function*(){try{let t=this.authService.getUser();if(t)return e?.reactions||(e.reactions=[]),e?.reactions?.find(a=>a?.from?.userId===t?.userId)?e.reactions=e?.reactions?.filter(a=>a?.from?.userId!==t?.userId):e.reactions.push({from:t,lastUpdated:this.timestamp}),e.reactions.length?yield this.updateReaction(e):yield this.deleteReactionPinAnnotation(e?.annotationId),e}catch(t){this.loggingService.catch("Error in ReactionService updateUserInReaction: ",t)}})}removeUserFromReaction(e){this.loggingService.log("%c[WB] Calling FUNCTION: removeUserFromReaction","color: green;");try{let t=this.authService.getUser();t&&(e?.reactions||(e.reactions=[]),e.reactions=e?.reactions?.filter(i=>i?.from?.userId!==t?.userId),this.updateReaction(e))}catch(t){this.loggingService.catch("Error in ReactionService removeUserFromReaction: ",t)}}updateReaction(e,t,i){return X(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateReaction","color: green;");try{if(this.authService.getUser()){if(e?.targetElement?.xpath){let d=this.domService.getXPath(e.targetElement.xpath);if(d){let m=d.iterateNext();m&&(Kr(m)||(e.targetElement=null))}}let a=JSON.parse(JSON.stringify(e));if(a.position=null,a.lastUpdated=this.timestamp,!a?.metadata?.documentId){a?.metadata||(a.metadata={});let d=this.docService.getBaseMetadata("reaction",{commentAnnotationId:e.commentAnnotationId});a.metadata=h(h({},a?.metadata),d)}let{documentId:l,organizationId:c}=a?.metadata||{};return i?yield this.commonDbService.updateData({feature:"reaction",properties:{id:e.annotationId,documentId:l,organizationId:c},data:JSON.parse(JSON.stringify(a))}):yield this.commonDbService.setData({feature:"reaction",properties:{id:e.annotationId,documentId:l,organizationId:c},data:JSON.parse(JSON.stringify(a))}),a}}catch(a){this.loggingService.catch("Error in ReactionService updateReaction: ",a)}})}deleteReactionPinAnnotation(e,t){return X(this,null,function*(){try{let i=this.getAnnotationById(e),{documentId:a,organizationId:l}=this.getDocumentIdAndOrganizationIdFromReactionAnnotation(i),c=i&&!i.commentAnnotationId?{annotationData:i,actionType:"delete",notificationSource:"reaction"}:void 0;yield this.commonDbService.deleteData({feature:"reaction",properties:{id:e,documentId:a,organizationId:l},extraData:c})}catch(i){this.loggingService.catch("Error in ReactionService deleteReactionPinAnnotation: ",i)}})}setCustomReactions(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCustomReactions","color: green;"),this.customReactions$.next(e),this.emojiService.setEmojiList(e)}catch(t){this.loggingService.catch("Error in ReactionService setCustomReactions: ",t)}}enableDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDarkMode","color: green;"),this.darkMode$.value===!0)return;this.darkMode$.next(!0)}catch(e){this.loggingService.catch("Error in ReactionService enableDarkMode: ",e)}}disableDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDarkMode","color: green;"),this.darkMode$.value===!1)return;this.darkMode$.next(!1)}catch(e){this.loggingService.catch("Error in ReactionService disableDarkMode: ",e)}}getDarkMode(){return this.darkMode$.value}getDarkMode$(){return this.darkMode$.asObservable()}sanitizeReactionAnnotation(e){try{e&&(e.iconUrl&&(e.iconUrl=this.domService.sanitizeHtml(e.iconUrl)),e.iconEmoji&&(e.iconEmoji=this.domService.sanitizeHtml(e.iconEmoji)),e.icon&&(e.icon=this.domService.sanitizeHtml(e.icon)))}catch(t){this.loggingService.catch("Error in ReactionService sanitizeReactionAnnotation: ",t)}}get timestamp(){return this.commonDbService.getServerTimestamp()}getReactionAnnotationForClient(e){try{let t=["isReactionResolverUsed","pageInfo","from","involvedUserIds","position"],i=JSON.parse(JSON.stringify(e)),a={};return Object.keys(i).forEach(l=>{t.includes(l)||(l==="reactions"?a.fromUsers=i[l]:a[l]=i[l])}),a}catch(t){return this.loggingService.catch("Error in ReactionService getReactionAnnotationForClient: ",t),e}}};o.\u0275fac=function(t){return new(t||o)(K(eo),K(ct),K(qe),K(Ft),K($n),K(yn),K(st),K(Ve),K(Sm),K(Vn),K(k),K(Ia))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Rg={user:"componentConfigSignal.appState.user",isUserAdmin:"componentConfigSignal.appState.isUserAdmin",isKnownUser:"componentConfigSignal.appState.isKnownUser",repliesUniqueUsers:"componentConfigSignal.appState.repliesUniqueUsers",annotation:"componentConfigSignal.data.annotation",annotations:"componentConfigSignal.data.annotations",allAnnotations:"componentConfigSignal.data.allAnnotations",ghostComment:"componentConfigSignal.data.ghostComment",selectedFiles:"parentLocalUIState.selectedFiles",invalidSelectedFiles:"parentLocalUIState.invalidSelectedFiles",selectedAttachments:"parentLocalUIState.selectedAttachments",editComment:"parentLocalUIState.editComment",editCommentIndex:"parentLocalUIState.editCommentIndex",assignTo:"componentConfigSignal.data.assignTo",selectedUserContacts:"componentConfigSignal.data.selectedUserContacts",localRecordedData:"parentLocalUIState.localRecordedData",customList:"componentConfigSignal.data.customList",toOrganizationUserGroup:"componentConfigSignal.data.toOrganizationUserGroup",taggedUserContacts:"componentConfigSignal.data.taggedUserContacts",taggedGroups:"componentConfigSignal.data.taggedGroups",attachmentsToDelete:"parentLocalUIState.attachmentsToDelete",customChipData:"componentConfigSignal.data.customChipData",selectedCustomChipSet:"componentConfigSignal.data.selectedCustomChipSet",currentDialogView:"componentConfigSignal.data.currentDialogView",sidebarMode:"parentLocalUIState.sidebarMode",inboxMode:"parentLocalUIState.inboxMode",dialogMode:"parentLocalUIState.dialogMode",inlineCommentMode:"parentLocalUIState.inlineCommentMode",inlineCommentSectionMode:"parentLocalUIState.inlineCommentSectionMode",focusedThreadMode:"parentLocalUIState.focusedThreadMode",isFocusedThreadEnabled:"parentLocalUIState.isFocusedThreadEnabled",pageModeComposer:"parentLocalUIState.pageModeComposer",darkMode:"parentLocalUIState.darkMode",variant:"parentLocalUIState.variant",disabled:"parentLocalUIState.disabled",commentPinSelected:"parentLocalUIState.commentPinSelected",fullExpanded:"parentLocalUIState.fullExpanded",commentDialogSelected:"parentLocalUIState.commentDialogSelected",readOnly:"parentLocalUIState.readOnly",dialogShadowDOM:"parentLocalUIState.dialogShadowDOM",locationVersion:"parentLocalUIState.locationVersion",composerPosition:"parentLocalUIState.composerPosition",dialogOpenedInSidebar:"parentLocalUIState.dialogOpenedInSidebar",expandOnSelection:"parentLocalUIState.expandOnSelection",selectedVisibility:"parentLocalUIState.selectedVisibility",selectedVisibilityUsers:"parentLocalUIState.selectedVisibilityUsers",containerComponentId:"componentConfigSignal.uiState.containerComponentId",isPrivateComment:"componentConfigSignal.uiState.isPrivateComment",assignToMenuOpened:"parentLocalUIState.assignToMenuOpened",showGhostCommentMessage:"componentConfigSignal.uiState.showGhostCommentMessage",showReplies:"componentConfigSignal.uiState.showReplies",collapsedComments:"componentConfigSignal.uiState.collapsedComments",showAllComments:"componentConfigSignal.uiState.showAllComments",composerContent:"parentLocalUIState.composerContent",composerContentHTML:"parentLocalUIState.composerContentHTML",composerInOpenState:"parentLocalUIState.composerInOpenState",composerMode:"componentConfigSignal.uiState.composerMode",multiThreadAnnotationId:"componentConfigSignal.uiState.multiThreadAnnotationId",maxReplyAvatars:"componentConfigSignal.uiState.maxReplyAvatars",showSuggestionModeActions:"componentConfigSignal.uiState.showSuggestionModeActions",uploadingAttachments:"componentConfigSignal.uiState.uploadingAttachments",playVideoInFullScreen:"componentConfigSignal.uiState.playVideoInFullScreen",commentDialogUniqueId:"componentConfigSignal.uiState.commentDialogUniqueId",recorderInitConfig:"componentConfigSignal.uiState.recorderInitConfig",isInputFocused:"componentConfigSignal.uiState.isInputFocused",showCommentButtons:"componentConfigSignal.uiState.showCommentButtons",isAutocompleteDropdownOpen:"componentConfigSignal.uiState.isAutocompleteDropdownOpen",bottomSheetMode:"componentConfigSignal.uiState.bottomSheetMode",commentComposerMode:"componentConfigSignal.uiState.commentComposerMode",shouldScrollToBottom:"componentConfigSignal.uiState.shouldScrollToBottom",deviceType:"componentConfigSignal.uiState.deviceType",showReplyComposer:"componentConfigSignal.uiState.showReplyComposer",reactionToolOpenIndex:"componentConfigSignal.uiState.reactionToolOpenIndex",openDropdownIndexValue:"componentConfigSignal.uiState.openDropdownIndexValue",hasReactionsByCommentId:"componentConfigSignal.uiState.hasReactionsByCommentId",newComment:"parentLocalUIState.composerContent",newCommentHTML:"parentLocalUIState.composerContentHTML",canResolveAnnotation:"componentConfigSignal.featureState.canResolveAnnotation",canUnresolveAnnotation:"componentConfigSignal.featureState.canUnresolveAnnotation",dialogSelectedByKnownUser:"componentConfigSignal.featureState.dialogSelectedByKnownUser",resolveStatusAccessAdminOnly:"componentConfigSignal.featureState.resolveStatusAccessAdminOnly",enableResolve:"componentConfigSignal.featureState.enableResolve",isPlanExpired:"componentConfigSignal.featureState.isPlanExpired",moderatorMode:"componentConfigSignal.featureState.moderatorMode",enableAutoCategorize:"componentConfigSignal.featureState.enableAutoCategorize",suggestionMode:"componentConfigSignal.featureState.suggestionMode",commentAcceptedStatus:"componentConfigSignal.featureState.commentAcceptedStatus",commentRejectedStatus:"componentConfigSignal.featureState.commentRejectedStatus",enableSignInButton:"componentConfigSignal.featureState.enableSignInButton",enableUpgradeButton:"componentConfigSignal.featureState.enableUpgradeButton",enableGhostCommentsMessage:"componentConfigSignal.featureState.enableGhostCommentsMessage",replyAvatars:"componentConfigSignal.featureState.replyAvatars",userMentions:"componentConfigSignal.featureState.userMentions",recordingSummaryEnabled:"componentConfigSignal.featureState.recordingSummaryEnabled",enableAttachment:"componentConfigSignal.featureState.enableAttachment",allowedFileTypes:"componentConfigSignal.featureState.allowedFileTypes",allowedRecordings:"componentConfigSignal.featureState.allowedRecordings",screenSharingSupported:"componentConfigSignal.featureState.screenSharingSupported",enterKeyToSubmit:"componentConfigSignal.featureState.enterKeyToSubmit",deleteOnBackspace:"componentConfigSignal.featureState.deleteOnBackspace",showScreenSizeInfo:"componentConfigSignal.uiState.showScreenSizeInfo",enableReactions:"componentConfigSignal.featureState.enableReactions",isInsidePdfViewer:"componentConfigSignal.featureState.isInsidePdfViewer",sidebarButtonOnCommentDialogVisible:"componentConfigSignal.uiState.sidebarButtonOnCommentDialogVisible",enableStatus:"componentConfigSignal.featureState.enableStatus",customStatusesShown:"componentConfigSignal.featureState.customStatusesShown",statusOptions:"componentConfigSignal.featureState.statusOptions",enablePriority:"componentConfigSignal.featureState.enablePriority",visibilityOptions:"componentConfigSignal.featureState.visibilityOptions",priorityOptions:"componentConfigSignal.featureState.priorityOptions",enableAssignment:"componentConfigSignal.featureState.enableAssignment",enableNotifications:"componentConfigSignal.featureState.enableNotifications",enableEdit:"componentConfigSignal.featureState.enableEdit",enableDelete:"componentConfigSignal.featureState.enableDelete",enablePrivateMode:"componentConfigSignal.featureState.enablePrivateMode",deleteThreadWithFirstComment:"componentConfigSignal.featureState.deleteThreadWithFirstComment",seenByUsers:"componentConfigSignal.featureState.seenByUsers",allowAssignment:"componentConfigSignal.featureState.enableAssignment",allowToggleNotification:"componentConfigSignal.featureState.enableNotifications",allowEdit:"componentConfigSignal.featureState.enableEdit",allowChangeCommentAccessMode:"componentConfigSignal.featureState.enablePrivateMode",notificationEnabled:"notificationEnabled",mainCommentId:"componentConfigSignal.data.annotation.comments.0.commentId",commentObj:"commentObj",commentIndex:"commentIndex",userContact:"selectorItem.contact",comment:"commentObj",commentAnnotation:"componentConfigSignal.data.annotation",commentAnnotations:"componentConfigSignal.data.annotations",context:"parentLocalUIState.context",focusedAnnotation:"focusedAnnotation",notification:"notification",unreadNotificationsForYou:"componentConfigSignal.data.unreadNotificationsForYou",notificationsPanelVisible:"componentConfigSignal.uiState.notificationsPanelVisible",notificationsForYouInSession:"componentConfigSignal.data.notificationsForYouInSession",notificationsInSession:"componentConfigSignal.data.notificationsInSession",notificationsByUserMap:"componentConfigSignal.data.notificationsByUserMap",notificationsByDocumentId:"componentConfigSignal.data.notificationsByDocumentId",notificationsByDate:"componentConfigSignal.data.notificationsByDate",currentDocumentName:"componentConfigSignal.data.currentDocumentName",settingsConfig:"componentConfigSignal.data.settingsConfig",settingsSelectedOption:"componentConfigSignal.data.settingsSelectedOption",selectedTab:"componentConfigSignal.uiState.selectedTab",tabConfig:"componentConfigSignal.uiState.tabConfig",TABS:"componentConfigSignal.uiState.TABS",tabPage:"componentConfigSignal.uiState.tabPage",pageSize:"componentConfigSignal.uiState.pageSize",panelOpenMode:"componentConfigSignal.uiState.panelOpenMode",settingsOpen:"componentConfigSignal.uiState.settingsOpen",settingsAccordionExpanded:"componentConfigSignal.uiState.settingsAccordionExpanded",settingsMutedAll:"componentConfigSignal.uiState.settingsMutedAll",settingsItemRecentlyClosed:"componentConfigSignal.uiState.settingsItemRecentlyClosed",settingsLayout:"componentConfigSignal.uiState.settingsLayout",tabCount:"componentConfigSignal.uiState.tabCount",usersExpanded:"componentConfigSignal.uiState.usersExpanded",documentExpanded:"componentConfigSignal.uiState.documentExpanded",shadowDom:"componentConfigSignal.uiState.shadowDom",settingsEnabled:"componentConfigSignal.featureState.settingsEnabled",selectedMinimalFilterDropdownOption:"selectedMinimalFilterDropdownOption",appliedFiltersCount:"appliedFiltersCount",filteredCommentAnnotationsCount:"filteredCommentAnnotationsCount",unreadCommentAnnotationCount:"unreadCommentAnnotationCount",isEnabled:"componentConfigSignal.featureState.isEnabled",allActivities:"componentConfigSignal.data.allActivities",filteredActivities:"componentConfigSignal.data.filteredActivities",groupedActivities:"componentConfigSignal.data.groupedActivities",virtualScrollItems:"componentConfigSignal.data.virtualScrollItems",activeFilter:"componentConfigSignal.data.activeFilter",availableFilters:"componentConfigSignal.data.availableFilters",isOpen:"componentConfigSignal.uiState.isOpen",expandedGroups:"componentConfigSignal.uiState.expandedGroups",defaultVisibleCount:"componentConfigSignal.uiState.defaultVisibleCount",filterDropdownOpen:"componentConfigSignal.uiState.filterDropdownOpen",activity:"activityRecord",activityRecord:"activityRecord",dateGroup:"dateGroup",filter:"filterOption",filterOption:"filterOption",isActive:"isActive",isExpanded:"isExpanded",remainingCount:"remainingCount",showAdder:"componentConfigSignal.uiState.showAdder",commentToolEnabled:"componentConfigSignal.uiState.commentToolEnabled",isUserAllowed:"componentConfigSignal.uiState.isUserAllowed",enableTextComments:"componentConfigSignal.uiState.enableTextComments",rewriterEnabled:"componentConfigSignal.uiState.rewriterEnabled",rewriterDefaultUIEnabled:"componentConfigSignal.uiState.rewriterDefaultUIEnabled",selectedWordsCount:"componentConfigSignal.data.selectedWordsCount",selectedCharactersCount:"componentConfigSignal.data.selectedCharactersCount",allowedElementIds:"componentConfigSignal.data.allowedElementIds",contextId:"componentConfigSignal.data.contextId",position:"componentConfigSignal.data.position",MIN_ALLOWED_WORDS_COUNT:"componentConfigSignal.uiState.MIN_ALLOWED_WORDS_COUNT",MIN_ALLOWED_CHARACTERS_COUNT:"componentConfigSignal.uiState.MIN_ALLOWED_CHARACTERS_COUNT",MAX_ALLOWED_CHARACTERS_COUNT:"componentConfigSignal.uiState.MAX_ALLOWED_CHARACTERS_COUNT",filteredAnnotations:"componentConfigSignal.data.filteredAnnotations",multiThreadCommentAnnotation:"componentConfigSignal.data.multiThreadCommentAnnotation",nonDraftCommentsCount:"componentConfigSignal.data.nonDraftCommentsCount",commentPinType:"componentConfigSignal.uiState.commentPinType",hideMultiThreadAnnotationComposer:"componentConfigSignal.uiState.hideMultiThreadAnnotationComposer",dialogVariant:"componentConfigSignal.uiState.dialogVariant",minimalFilter:"componentConfigSignal.uiState.minimalFilter",minimalFilterDropdownOpen:"componentConfigSignal.uiState.minimalFilterDropdownOpen",minimalActionsDropdownOpen:"componentConfigSignal.uiState.minimalActionsDropdownOpen",noCommentsFoundForAppliedFilters:"componentConfigSignal.uiState.noCommentsFoundForAppliedFilters",noCommentsFound:"componentConfigSignal.uiState.noCommentsFound",isSelected:"isSelected",composerCommentAnnotation:"componentConfigSignal.data.composerCommentAnnotation",statuses:"componentConfigSignal.data.statuses",skeletonLoading:"componentConfigSignal.uiState.skeletonLoading",filterState:"componentConfigSignal.uiState.filterState",sortState:"componentConfigSignal.uiState.sortState",isResolvedCommentsOnDomFilterSelected:"componentConfigSignal.uiState.isResolvedCommentsOnDomFilterSelected",resolvedCommentsOnDom:"componentConfigSignal.uiState.resolvedCommentsOnDom",selectedAnnotationsMap:"componentConfigSignal.uiState.selectedAnnotationsMap",selectedAnnotationsLocationMap:"componentConfigSignal.uiState.selectedAnnotationsLocationMap",composerVariant:"parentLocalUIState.composerVariant",multiThread:"parentLocalUIState.multiThread",commentPlaceholder:"parentLocalUIState.commentPlaceholder",replyPlaceholder:"parentLocalUIState.replyPlaceholder",composerPlaceholder:"parentLocalUIState.composerPlaceholder",editPlaceholder:"parentLocalUIState.editPlaceholder",editCommentPlaceholder:"parentLocalUIState.editCommentPlaceholder",editReplyPlaceholder:"parentLocalUIState.editReplyPlaceholder",targetElementId:"parentLocalUIState.targetElementId",folderId:"parentLocalUIState.folderId",veltFolderId:"parentLocalUIState.veltFolderId",clientDocumentId:"parentLocalUIState.clientDocumentId",documentId:"parentLocalUIState.documentId",locationId:"parentLocalUIState.locationId",contextOptions:"parentLocalUIState.contextOptions",messageTruncation:"parentLocalUIState.messageTruncation",messageTruncationLines:"parentLocalUIState.messageTruncationLines",unresolvedAnnotationsCount:"componentConfigSignal.data.unresolvedAnnotationsCount",unreadCount:"componentConfigSignal.data.unreadCount",commentBubbleTargetPinHover:"parentLocalUIState.commentBubbleTargetPinHover",openDialog:"parentLocalUIState.openDialog",showAvatar:"parentLocalUIState.showAvatar",commentCountType:"parentLocalUIState.commentCountType"},DWe=["user","annotation","annotations","allAnnotations","userContact","comment","commentAnnotation","commentAnnotations","recorderInitConfig","ghostComment","editComment","assignTo","customChipData","currentDialogView","context","focusedAnnotation","notification","selectedMinimalFilterDropdownOption","unreadNotificationsForYou","notificationsForYouInSession","notificationsInSession","notificationsByUserMap","notificationsByDocumentId","notificationsByDate","settingsConfig","settingsSelectedOption","settingsAccordionExpanded","tabConfig","tabPage","TABS","allActivities","filteredActivities","groupedActivities","virtualScrollItems","availableFilters","expandedGroups","activity","activityRecord","dateGroup","filter","filterOption","position","allowedElementIds","filteredAnnotations","multiThreadCommentAnnotation","composerCommentAnnotation","statuses","filterState","sortState","selectedAnnotationsMap","selectedAnnotationsLocationMap","contextOptions"],T=(()=>{let _DynamicDataService=class _DynamicDataService{constructor(n,o,r,e,t,i){this.authService=n,this.commentService=o,this.loggingService=r,this.injector=e,this.docService=t,this.configService=i,this.subscriptions=[],this.commonData$=new _e({}),this.evaluateConditionTriggered=new Ue,this.conditionRegex=/\{(.*?)\}/g,this.extractedProps={},this.condition="",this.dataComponentConfigSignal=De({});try{this.subscriptions.push(this.authService.getUser$().subscribe(a=>{this.commonData$.next(y(h({},this.commonData$.value),{user:a}))})),this.subscriptions.push(this.commentService.getUnreadCommentAnnotationCountOnCurrentDocument$().subscribe(a=>{this.commonData$.next(y(h({},this.commonData$.value),{unreadCommentAnnotationCount:a?.count||0}))})),this.subscriptions.push(this.commentService.getUnreadCommentCountOnCurrentDocument$().subscribe(a=>{this.commonData$.next(y(h({},this.commonData$.value),{unreadCommentCount:a?.count||0}))})),this.subscriptions.push(this.docService.getUIState$().subscribe(a=>{this.commonData$.next(h(h({},this.commonData$.value),a))})),this.subscriptions.push(this.getCommonData().subscribe(a=>{this.dataComponentConfigSignal.update(l=>(l=h(h({},l),a),l)),this.executeConditionalClasses()})),this.subscriptions.push(this.evaluateConditionTriggered.subscribe(a=>{this.extractedProps=a.extractedProps,this.evaluateCondition(a.className,a.elementRef,a.condition)}))}catch(a){this.loggingService.catch("Error in DynamicDataService constructor: ",a)}}ngOnDestroy(){try{this.subscriptions.forEach(n=>n.unsubscribe())}catch(n){this.loggingService.catch("Error in DynamicDataService ngOnDestroy: ",n)}}getCommonData(){return this.commonData$.asObservable()}getModifiedPathBasedOnCondition(n,o){try{return Object.keys(o).forEach(r=>{o[r].path=this.modifyPathBasedOnCondition(r,n)}),o}catch(r){this.loggingService.catch("Error in DynamicDataService getModifiedPathBasedOnCondition: ",r)}}getComputedValues(n,o,r,e,t,i){try{Object.keys(r).forEach(a=>{let l;if(vo(n)?l=oe(()=>Il(n(),r[a].path)):l=oe(()=>Il(n,r[a].path)),vo(l()))xn(()=>{try{let c=l()();r[a].value=c,this.evaluateConditionTriggered.emit({extractedProps:r,className:e,elementRef:t,condition:i})}catch{}},{injector:this.injector});else{let c=l();r[a].value=c,this.evaluateConditionTriggered.emit({extractedProps:r,className:e,elementRef:t,condition:i})}})}catch(a){this.loggingService.catch("Error in DynamicDataService getComputedValues: ",a)}}modifyPathBasedOnCondition(n,o){try{let r=n.match(/^([^\.\[]+)/),e=r?r[1]:n,t=n.slice(e.length);if(Rg[n])return Rg[n];if(["commentDialogOptionsDropdownConfigSignal","commentDialogStatusDropdownConfigSignal"].includes(e)&&t.startsWith(".")){let a=t.slice(1),l=a.match(/^([^\.\[]+)/),c=l?l[1]:a,d=a.slice(c.length);return Rg[c]?Rg[c]+d:"componentConfigSignal."+a}if(e&&o&&typeof o=="function"){let a=o();if(a&&e in a){let c=n.match(/\[(.*?)\]/);if(c&&c[1]){let d=c[1];if(d.includes(".")){let m=d.split(".")[0];if(Rg[m]){let u=d.replace(m,Rg[m]);return n.replace(`[${d}]`,`[${u}]`)}return m&&a&&m in a?n:n.replace(`[${d}]`,`[componentConfigSignal.${d}]`)}}return n}let l=a?.componentConfigSignal;if(l&&typeof l=="function"){let c=l();if(c&&e in c)return"componentConfigSignal."+n}}return Rg[e]?DWe.includes(e)?Rg[e]+t:Rg[e]:"componentConfigSignal."+n}catch(r){return this.loggingService.catch("Error in DynamicDataService modifyPathBasedOnCondition: ",r),n}}applyConditionalClasses(n,o){try{this.elementRef=n,this.data=o}catch(r){this.loggingService.catch("Error in DynamicDataService applyConditionalClasses: ",r)}}executeConditionalClasses(){try{let n=this.getHostElementAttributes(this.elementRef),r=[...Object.keys(n).filter(e=>e.startsWith("velt-class-")).map(e=>({name:e,value:n[e]}))];if(n["velt-class"]){let e=n["velt-class"],t=/'([^']+)':\s*([^,]+)(?:,|$)/g,i=[],a=0,l=100,c;for(;(c=t.exec(e))!==null;){if(a++>l){this.loggingService.catch("Too many class definitions detected.");break}if(c.length<3)continue;let[,d,m]=c;!d||!m||d.split(" ").forEach(u=>{u.trim()&&i.push({name:`velt-class-${u.trim()}`,value:m.trim()})})}r=[...r,...i]}this.data&&typeof this.data=="object"&&Object.keys(this.data).forEach(e=>{this.updateDataComponentConfigSignal(e,this.data[e])}),r.forEach(e=>{let t=e.name.replace("velt-class-","");this.condition=e.value,this.condition&&(this.extractProps(),this.extractedProps=this.getModifiedPathBasedOnCondition(this.dataComponentConfigSignal,this.extractedProps),this.getComputedValues(this.dataComponentConfigSignal,this.evaluateCondition,this.extractedProps,t,this.elementRef,e.value))})}catch(n){this.loggingService.catch("Error in DynamicDataService applyConditionalClasses: ",n)}}updateDataComponentConfigSignal(n,o){try{n==="dataComponentConfigSignal"?this.dataComponentConfigSignal.set(o):this.dataComponentConfigSignal.update(r=>y(h({},r),{[n]:o}))}catch(r){this.loggingService.catch("Error in DataComponent updateDataComponentConfigSignal: ",r)}}extractProps(){try{this.extractedProps={},this.conditionRegex.lastIndex=0;let n;for(;(n=this.conditionRegex.exec(this.condition))!==null;){let o=n[1];this.extractedProps[o]={value:null,path:null,isDynamicPath:this.hasDynamicParts(o)}}}catch(n){this.loggingService.catch("Error in DynamicDataService extractProps: ",n)}}hasDynamicParts(n){try{let o=/\[[^\]'"]*[^\]'"]\]/.test(n),r=/\[[^[\]]*[\.\[][^[\]]*\]/.test(n);return o||r}catch(o){return this.loggingService.catch("Error checking for dynamic path: ",o),!1}}evaluateCondition(n,o,r){try{if(r){let e=this.extractedProps,t=r.replace(this.conditionRegex,(l,c)=>{let d=e[c];if(d&&d.value!==void 0){let m=d.value;return typeof m=="string"?`'${m}'`:typeof m=="boolean"||typeof m=="number"?String(m):m===null?"null":typeof m=="object"?m?"true":"false":String(m)}return"false"}),i=this.sanitizeCondition(t),a=this.safeEval(i);return n&&o&&(a?this.setHostElementClasses(o,n):this.removeHostElementClasses(o,n)),a}return!1}catch(e){return this.loggingService.catch("Error in IfComponent evaluateCondition: ",e),!1}}sanitizeCondition(n){try{return n.replace(/[^a-zA-Z0-9\s\+\-\*\/\%\(\)\!\=\<\>\|\&\.\[\]\{\},'"]/g,"")}catch(o){return this.loggingService.catch("Error in IfComponent sanitizeCondition: ",o),""}}safeEval(expression){try{if(this.configService.getSafeEval()){let n=this.tokenize(expression.trim());return this.evaluateTokens(n)}else return eval(expression)}catch(n){return this.loggingService.catch("safeEval error",n),!1}}tokenize(n){try{if(!n||n.trim()==="")return[];let o=[],r=0;for(;r<n.length;){let e=n[r];if(/\s/.test(e)){r++;continue}if(e==='"'||e==="'"){let t=e,i="";for(r++;r<n.length;)if(n[r]==="\\"&&r+1<n.length)i+=n[r+1],r+=2;else if(n[r]===t){r++;break}else i+=n[r],r++;o.push({type:"string",value:i});continue}if(e==="("){o.push({type:"lparen",value:"("}),r++;continue}if(e===")"){o.push({type:"rparen",value:")"}),r++;continue}if(r<n.length-2&&n.substring(r,r+3)==="==="){o.push({type:"operator",value:"===",precedence:4}),r+=3;continue}if(r<n.length-2&&n.substring(r,r+3)==="!=="){o.push({type:"operator",value:"!==",precedence:4}),r+=3;continue}if(r<n.length-1&&n.substring(r,r+2)==="&&"){o.push({type:"operator",value:"&&",precedence:2}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="||"){o.push({type:"operator",value:"||",precedence:1}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="<="){o.push({type:"operator",value:"<=",precedence:4}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)===">="){o.push({type:"operator",value:">=",precedence:4}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="=="){o.push({type:"operator",value:"==",precedence:4}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="!="){o.push({type:"operator",value:"!=",precedence:4}),r+=2;continue}if(e==="!"){o.push({type:"unary",value:"!",precedence:5}),r++;continue}if(e==="<"){o.push({type:"operator",value:"<",precedence:4}),r++;continue}if(e===">"){o.push({type:"operator",value:">",precedence:4}),r++;continue}if(/[a-zA-Z0-9._]/.test(e)){let t="";for(;r<n.length&&/[a-zA-Z0-9._]/.test(n[r]);)t+=n[r],r++;/^-?\d+(\.\d+)?$/.test(t)?o.push({type:"number",value:parseFloat(t)}):t==="true"||t==="false"?o.push({type:"boolean",value:t==="true"}):t==="null"?o.push({type:"null",value:null}):t==="undefined"?o.push({type:"undefined",value:void 0}):o.push({type:"identifier",value:t});continue}r++}return o}catch(o){return this.loggingService.catch("tokenize error",o),[]}}evaluateTokens(n){try{if(!n||n.length===0)return!1;let o=this.infixToPostfix(n);return this.evaluatePostfix(o)}catch(o){return this.loggingService.catch("evaluateTokens error",o),!1}}infixToPostfix(n){try{let o=[],r=[];for(let e of n)if(e.type==="string"||e.type==="number"||e.type==="boolean"||e.type==="null"||e.type==="undefined"||e.type==="identifier")o.push(e);else if(e.type==="unary")r.push(e);else if(e.type==="operator"){for(;r.length>0;){let t=r[r.length-1];if(t.type==="lparen"||t.precedence!==void 0&&t.precedence<e.precedence)break;o.push(r.pop())}r.push(e)}else if(e.type==="lparen")r.push(e);else if(e.type==="rparen"){for(;r.length>0&&r[r.length-1].type!=="lparen";)o.push(r.pop());r.length>0&&r.pop()}for(;r.length>0;){let e=r.pop();e.type!=="lparen"&&e.type!=="rparen"&&o.push(e)}return o}catch(o){return this.loggingService.catch("infixToPostfix error",o),[]}}evaluatePostfix(n){try{let o=[];for(let r of n)if(r.type==="string"||r.type==="number"||r.type==="boolean"||r.type==="null"||r.type==="undefined"||r.type==="identifier")o.push(r.value);else if(r.type==="unary"){if(o.length>=1){let e=o.pop();r.value==="!"&&o.push(!this.isTruthy(e))}}else if(r.type==="operator"&&o.length>=2){let e=o.pop(),t=o.pop();r.value==="&&"?o.push(this.isTruthy(t)&&this.isTruthy(e)):r.value==="||"?o.push(this.isTruthy(t)||this.isTruthy(e)):o.push(this.compare(t,e,r.value))}return o.length===1?this.isTruthy(o[0]):!1}catch(o){return this.loggingService.catch("evaluatePostfix error",o),!1}}parseValue(n){try{let o=n.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.substring(1,o.length-1):/^-?\d+(\.\d+)?$/.test(o)?parseFloat(o):o==="true"?!0:o==="false"?!1:o==="null"?null:o==="undefined"?void 0:o}catch(o){return this.loggingService.catch("parseValue error",o),n}}compare(n,o,r){try{switch(r){case"===":return n===o;case"!==":return n!==o;case"==":return n==o;case"!=":return n!=o;case"<":return n<o;case">":return n>o;case"<=":return n<=o;case">=":return n>=o;default:return!1}}catch(e){return this.loggingService.catch("compare error",e),!1}}isTruthy(n){try{return n==null||n===""||n==="false"?!1:n==="true"?!0:typeof n=="number"?n!==0:!!n}catch(o){return this.loggingService.catch("isTruthy error",o),!1}}getHostElementAttributes(n){try{let o=n,r={};for(let e of o.attributes)r[e.name]=e.value;return r}catch{return{}}}setHostElementClasses(n,o){try{n.classList.add(o)}catch{}}removeHostElementClasses(n,o){try{n.classList.remove(o)}catch{}}};_DynamicDataService.\u0275fac=function(o){return new(o||_DynamicDataService)(K(qe),K(Re),K(k),K(Dt),K(st),K(Ft))},_DynamicDataService.\u0275prov=Ae({token:_DynamicDataService,factory:_DynamicDataService.\u0275fac,providedIn:"root"});let DynamicDataService=_DynamicDataService;return DynamicDataService})();var me=(()=>{let o=class o{set veltIf(e){try{e&&this.setIfCondition(e)}catch(t){this._loggingService.catch("Error in BaseComponent set veltIf:",t)}}constructor(e,t,i){this._elementRef=e,this._dynamicDataService=t,this._loggingService=i,this.componentConfigSignal=De({}),this.veltElement=!0,this.conditionSignal=De(null)}initializeComponentConfigSignal(e){try{this.componentConfigSignal.set(e)}catch(t){this._loggingService.catch("Error in BaseComponent initializeComponentConfigSignal:",t)}}ngOnInit(){try{this._dynamicDataService.applyConditionalClasses(this._elementRef?.nativeElement,{componentConfigSignal:this.componentConfigSignal})}catch(e){this._loggingService.catch("Error in BaseComponent ngOnInit:",e)}}ngOnDestroy(){}setIfCondition(e){try{this.conditionSignal.set(e)}catch(t){this._loggingService.catch("Error in BaseComponent setIfCondition:",t)}}};o.\u0275fac=function(t){return new(t||o)(x(Q),x(T),x(k))},o.\u0275cmp=O({type:o,selectors:[["app-base"]],hostVars:1,hostBindings:function(t,i){t&2&&w("data-velt-element",i.veltElement)},inputs:{componentConfigSignal:"componentConfigSignal",template:"template",wireframe:"wireframe",veltIf:"veltIf"},standalone:!1,decls:0,vars:0,template:function(t,i){},encapsulation:2});let n=o;return n})();var yt=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.configService=t,this.darkMode$=new _e(!1)}setDarkMode(e){try{let t=document.documentElement;if(!t)return;e?t.setAttribute(N.ATTRIBUTES.VELT_THEME,"dark"):t.removeAttribute(N.ATTRIBUTES.VELT_THEME),this.darkMode$.next(e)}catch(t){this.loggingService.catch("Error in theme service setDarkMode: ",t)}}getDarkMode$(){return this.darkMode$.asObservable()}updateListenerOnConfigChange(){try{this.configService.getConfig$().subscribe(e=>{if(e&&e.usePrefersColorScheme){this.enablePrefersColorScheme();return}this.disablePrefersColorScheme()})}catch(e){this.loggingService.catch("Error in theme service updateListenerOnConfigChange: ",e)}}enablePrefersColorScheme(){try{if(this.disablePrefersColorScheme(),!window.matchMedia)return;this.darkModeQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.setDarkMode(this.darkModeQuery.matches),this.darkModeQueryListener=e=>{this.setDarkMode(e.matches)},this.darkModeQuery.addEventListener("change",this.darkModeQueryListener)}catch(e){this.loggingService.catch("Error in theme service enablePrefersColorScheme: ",e)}}disablePrefersColorScheme(){try{this.darkModeQuery&&this.darkModeQueryListener&&this.darkModeQuery.removeEventListener("change",this.darkModeQueryListener)}catch(e){this.loggingService.catch("Error in theme service disablePrefersColorScheme: ",e)}}};o.\u0275fac=function(t){return new(t||o)(K(k),K(Ft))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var At=(()=>{let o=class o extends me{onDarkModeChange(){return this.darkModeSubject$.asObservable()}constructor(e,t,i,a,l,c,d){super(e,c,d),this._elementRef=e,this._themeService=t,this._changeDetector=i,this._featureService=a,this._componentDarkModeObservable=l,this._componentDarkMode=null,this._globalDarkMode=!1,this._featureDarkMode=!1,this._themeSubscriptions=[],this._darkMode=!1,this.darkMode=!1,this.darkModeSubject$=new _e(!1);try{this._themeSubscriptions.push(this._themeService.getDarkMode$().subscribe(m=>{this._globalDarkMode=m,this.setDarkMode()})),this._featureService&&(this._featureService instanceof Re?this._themeSubscriptions.push(this._featureService.getCommentContainerDarkMode().subscribe(m=>{this._featureDarkMode=m,this.setDarkMode()})):this._featureService instanceof zi&&this._themeSubscriptions.push(this._featureService.getDarkMode$().subscribe(m=>{m!==null&&(this._featureDarkMode=m),this.setDarkMode()}))),this._componentDarkModeObservable&&this._componentDarkModeObservable instanceof Vt&&this._themeSubscriptions.push(this._componentDarkModeObservable.subscribe(m=>{this._componentDarkMode=m,this.setDarkMode()}))}catch{}}ngOnInit(){super.ngOnInit()}ngOnChanges(e){try{if(e._darkMode){let t=e._darkMode.currentValue;typeof t=="string"&&(t=t==="true"),this._componentDarkMode=t,this.setDarkMode()}}catch{}}setComponentDarkMode(e){try{this._componentDarkMode=e,this.setDarkMode()}catch{}}setDarkMode(){try{this._componentDarkMode===null?this._featureDarkMode?this.darkMode=!0:this.darkMode=!!this._globalDarkMode:this.darkMode=!!this._componentDarkMode,this.darkMode?this._elementRef.nativeElement.hasAttribute("dark")||this._elementRef.nativeElement.setAttribute("dark",""):this._elementRef.nativeElement.hasAttribute("dark")&&this._elementRef.nativeElement.removeAttribute("dark"),this.darkModeSubject$.next(this.darkMode),this._changeDetector&&this._changeDetector.markForCheck()}catch{}}ngOnDestroy(){try{super.ngOnDestroy(),this._themeSubscriptions.forEach(e=>{e.unsubscribe()})}catch{}}};o.\u0275fac=function(t){return new(t||o)(x(Q),x(yt),x(tn),x("FeatureService",8),x(Vt),x(T),x(k))},o.\u0275cmp=O({type:o,selectors:[["app-themed"]],inputs:{_darkMode:[0,"darkMode","_darkMode"]},standalone:!1,features:[P,Qe],decls:0,vars:0,template:function(t,i){},encapsulation:2,changeDetection:0});let n=o;return n})();var Xe=(()=>{let o=class o{constructor(e){this.loggingService=e,this.wireframeMap=new _e(new Map);try{this.loggingService.log("%c[WB] Creating CLASS: WireframeService","color: blue;")}catch(t){this.loggingService.catch("Error in WireframeService constructor: ",t)}}setWireframe(e,t){try{let i=this.wireframeMap.value,a=i.get(e),l=t.children.length>0||t.innerHTML?.trim()?.length>0,c=a&&(a.children.length>0||a.innerHTML?.trim()?.length>0);(!a||l&&!c)&&(i.set(e,t),this.wireframeMap.next(i))}catch(i){this.loggingService.catch("Error in WireframeService setWireframe: ",i)}}setWireframeMap(e){try{let t=this.wireframeMap.value;e.forEach((i,a)=>{let l=t.get(a),c=i.children.length>0||i.innerHTML?.trim()?.length>0,d=l&&(l.children.length>0||l.innerHTML?.trim()?.length>0);(!l||c&&!d)&&t.set(a,i)}),this.wireframeMap.next(t)}catch(t){this.loggingService.catch("Error in WireframeService setWireframeMap: ",t)}}getWireframe(e,t=!0){try{let i=this.wireframeMap.value,a=i.get(e);if(!a&&t){let l=e?.split("---")[0];l&&(a=i.get(l))}return a&&(a?.children?.length>0||a?.innerHTML?.trim()?.length>0)?a:void 0}catch(i){this.loggingService.catch("Error in WireframeService getWireframe: ",i);return}}getConditionElement(e,t=!0){try{let i=this.wireframeMap.value,a=i.get(e);if(!a&&t){let l=e?.split("---")[0];l&&(a=i.get(l))}return a}catch(i){this.loggingService.catch("Error in WireframeService getConditionElement: ",i);return}}getWireframe$(e,t=!0){return this.wireframeMap.asObservable().pipe(ue(i=>this.getWireframe(e,t)))}setChildren(e){try{this.wireframeMap.next(e)}catch(t){this.loggingService.catch("Error in WireframeService setChildren: ",t)}}getWireframeMap(){return this.wireframeMap.value}};o.\u0275fac=function(t){return new(t||o)(K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Lbe=n=>({componentConfigSignal:n}),OWe=(n,o)=>({condition:n,data:o}),AWe=(n,o,r,e,t)=>({template:n,context:o,componentName:"velt-confirm-dialog-wireframe",variant:r,setIfCondition:e,componentElementRef:t});function MWe(n,o){if(n&1&&(C(0),D(1,"app-confirm-dialog-title",5)(2,"app-confirm-dialog-message",5),f(3,"div",6),D(4,"app-confirm-dialog-reject",5)(5,"app-confirm-dialog-approve",5),S(),b()),n&2){let r=s(3);v(),g("componentConfigSignal",r.componentConfigSignal),v(),g("componentConfigSignal",r.componentConfigSignal),v(2),g("componentConfigSignal",r.componentConfigSignal),v(),g("componentConfigSignal",r.componentConfigSignal)}}function PWe(n,o){if(n&1&&(C(0),p(1,MWe,6,4,"ng-container",4),b()),n&2){let r=s().ngIf,e=s();v(),g("veltDynamicTemplate",j(3,AWe,e.template,J(1,Lbe,e.componentConfigSignal),r==null?null:r.variant,e.setIfCondition.bind(e),e.elementRef))}}function RWe(n,o){if(n&1&&(C(0),p(1,PWe,2,9,"ng-container",3),b()),n&2){let r=s();v(),g("veltIf",E(3,OWe,r.conditionSignal(),J(1,Lbe,r.componentConfigSignal)))}}var al=(()=>{let o=class o extends At{constructor(e,t,i,a,l,c,d){super(l,a,void 0,void 0,void 0,d,e),this.loggingService=e,this.dialogRef=t,this.wireframeService=i,this.themeService=a,this.elementRef=l,this.dynamicDataService=d,this.subscriptions=[],this.componentConfigSignal=De({title:"",message:"",yesButton:"",noButton:"",variant:"",type:"",closeDialog:this.closeDialog.bind(this)}),this.componentId="velt-confirm-dialog",this.veltElement=!0;try{c&&(this.componentConfigSignal.update(m=>(m=h(h({},m),c),m)),c?.darkMode&&[!0,!1].includes(c?.darkMode)&&super.setComponentDarkMode(c?.darkMode)),this.setZIndex()}catch(m){this.loggingService.catch("Error in ConfirmDialogComponent constructor: ",m)}}ngOnInit(){try{this.loggingService.log("%c[WB] Calling FUNCTION: ngOnInit","color: green;");let e="velt-confirm-dialog-wireframe";super.ngOnInit(),this.componentConfigSignal()?.variant&&(e+=`---${this.componentConfigSignal()?.variant}`),this.subscriptions.push(this.wireframeService.getWireframe$(e).subscribe(t=>{if(t){let i=document.createElement(t.tagName);i.innerHTML=t.innerHTML,this.template=i}}))}catch(e){this.loggingService.catch("Error in ConfirmDialogComponent OnInit: ",e)}}ngOnDestroy(){super.ngOnDestroy();try{this.subscriptions.forEach(e=>e.unsubscribe())}catch(e){this.loggingService.catch("Error in ConfirmDialogComponent OnDestroy: ",e)}}setZIndex(){try{if(this.dialogRef){let e=this.dialogRef._overlayRef;e&&(e.backdropElement&&(e.backdropElement.style.zIndex="2147483647"),e.hostElement&&(e.hostElement.style.zIndex="2147483647"))}}catch(e){this.loggingService.catch("Error in ConfirmDialogComponent setZIndex: ",e)}}closeDialog(e){try{this.dialogRef.close(e)}catch(t){this.loggingService.catch("Error in ConfirmDialogComponent closeDialog: ",t)}}get variantClass(){return NWe(this.componentConfigSignal()?.type)}};o.\u0275fac=function(t){return new(t||o)(x(k),x(ji),x(Xe),x(yt),x(Q),x(nd,8),x(T))},o.\u0275cmp=O({type:o,selectors:[["snippyly-confirm-dialog"]],hostVars:1,hostBindings:function(t,i){t&2&&w("data-velt-element",i.veltElement)},standalone:!1,features:[B([T]),P],decls:3,vars:6,consts:[["floatingConfirmationRef",""],[1,"velt-confirm-dialog",3,"ngClass","snippylyOverlay","snippylyOverlayZIndex","snippylyOverlayBackdropZIndex"],[4,"ngIf"],[4,"veltIf"],[4,"veltDynamicTemplate"],[3,"componentConfigSignal"],["mat-dialog-actions","",1,"velt-confirm-dialog-actions"]],template:function(t,i){if(t&1&&(f(0,"div",1,0),p(2,RWe,2,6,"ng-container",2),S()),t&2){let a=Ee(1);g("ngClass",i.variantClass)("snippylyOverlay",a)("snippylyOverlayZIndex",1200)("snippylyOverlayBackdropZIndex",1100),w("data-testid",i.componentId),v(2),g("ngIf",i.componentConfigSignal())}},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}body.velt-pin-dragging[_ngcontent-%COMP%] iframe[_ngcontent-%COMP%]{pointer-events:none!important}[_nghost-%COMP%] *[_ngcontent-%COMP%]{outline:0}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent)}[dark][_nghost-%COMP%]{--velt-green: var(--velt-dark-mode-green);--velt-magenta: var(--velt-dark-mode-magenta);--velt-amber: var(--velt-dark-mode-amber);--velt-purple: var(--velt-dark-mode-purple);--velt-cyan: var(--velt-dark-mode-cyan);--velt-orange: var(--velt-dark-mode-orange);--velt-black: var(--velt-dark-mode-black);--velt-white: var(--velt-dark-mode-white);--velt-gray: var(--velt-dark-mode-gray);--velt-error: var(--velt-dark-mode-error);--velt-error-hover: var(--velt-dark-mode-error-hover);--velt-error-foreground: var(--velt-dark-mode-error-foreground);--velt-error-light: var(--velt-dark-mode-error-light);--velt-error-transparent: var(--velt-dark-mode-error-transparent);--velt-warning: var(--velt-dark-mode-warning);--velt-warning-hover: var(--velt-dark-mode-warning-hover);--velt-warning-foreground: var(--velt-dark-mode-warning-foreground);--velt-warning-light: var(--velt-dark-mode-warning-light);--velt-warning-transparent: var(--velt-dark-mode-warning-transparent);--velt-success: var(--velt-dark-mode-success);--velt-success-hover: var(--velt-dark-mode-success-hover);--velt-success-foreground: var(--velt-dark-mode-success-foreground);--velt-success-light: var(--velt-dark-mode-success-light);--velt-success-transparent: var(--velt-dark-mode-success-transparent);--velt-accent: var(--velt-dark-mode-accent);--velt-accent-text: var(--velt-dark-mode-accent-text);--velt-accent-hover: var(--velt-dark-mode-accent-hover);--velt-accent-foreground: var(--velt-dark-mode-accent-foreground);--velt-accent-light: var(--velt-dark-mode-accent-light);--velt-accent-transparent: var(--velt-dark-mode-accent-transparent);--velt-text-0: var(--velt-dark-mode-text-0);--velt-text-1: var(--velt-dark-mode-text-1);--velt-text-2: var(--velt-dark-mode-text-2);--velt-text-3: var(--velt-dark-mode-text-3);--velt-text-4: var(--velt-dark-mode-text-4);--velt-text-5: var(--velt-dark-mode-text-5);--velt-text-6: var(--velt-dark-mode-text-6);--velt-text-7: var(--velt-dark-mode-text-7);--velt-text-8: var(--velt-dark-mode-text-8);--velt-text-9: var(--velt-dark-mode-text-9);--velt-text-10: var(--velt-dark-mode-text-10);--velt-text-11: var(--velt-dark-mode-text-11);--velt-text-12: var(--velt-dark-mode-text-12);--velt-background-0: var(--velt-dark-mode-background-0);--velt-background-1: var(--velt-dark-mode-background-1);--velt-background-2: var(--velt-dark-mode-background-2);--velt-background-3: var(--velt-dark-mode-background-3);--velt-background-4: var(--velt-dark-mode-background-4);--velt-background-5: var(--velt-dark-mode-background-5);--velt-background-6: var(--velt-dark-mode-background-6);--velt-background-7: var(--velt-dark-mode-background-7);--velt-background-8: var(--velt-dark-mode-background-8);--velt-background-9: var(--velt-dark-mode-background-9);--velt-background-10: var(--velt-dark-mode-background-10);--velt-border-0: var(--velt-dark-mode-border-0);--velt-border-1: var(--velt-dark-mode-border-1);--velt-border-2: var(--velt-dark-mode-border-2);--velt-border-3: var(--velt-dark-mode-border-3);--velt-border-4: var(--velt-dark-mode-border-4);--velt-border-5: var(--velt-dark-mode-border-5);--velt-border-6: var(--velt-dark-mode-border-6);--velt-border-7: var(--velt-dark-mode-border-7);--velt-border-8: var(--velt-dark-mode-border-8);--velt-border-9: var(--velt-dark-mode-border-9);--velt-border-10: var(--velt-dark-mode-border-10);--velt-background-transparent: var(--velt-dark-mode-background-transparent);--velt-border-transparent: var(--velt-dark-mode-border-transparent);--velt-animation-transparent: var(--velt-dark-mode-animation-transparent)}.velt-confirm-dialog[_ngcontent-%COMP%]{width:455px;padding:40px;display:block;box-sizing:border-box;background-color:var(--velt-background-0)}.velt-confirm-dialog-actions[_ngcontent-%COMP%]{justify-content:space-between;gap:var(--velt-spacing-md);min-height:auto} .velt-mat-dialog-container mat-dialog-container .mat-mdc-dialog-surface.mdc-dialog__surface:has(snippyly-confirm-dialog){border-radius:var(--velt-border-radius-xl);padding:0}@media (max-width: 768px){.velt-confirm-dialog[_ngcontent-%COMP%]{width:auto;max-width:455px;padding:24px}}"],changeDetection:0});let n=o;return n})();function NWe(n){return n?`velt-confirm-dialog--${n}`:""}var mn=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A,M,V,q,ae,ye,ie,ge){this.afAuth=e,this.analyticsService=t,this.authService=i,this.configService=a,this.commonDbService=l,this.commonDbUtilsService=c,this.commentUtilsService=d,this.commentAnnotationsResolverService=m,this.notificationResolverService=u,this.databaseService=_,this.docService=I,this.domService=A,this.iamService=M,this.loggingService=V,this.notificationUtilsService=q,this.usersService=ae,this.functions=ye,this.userPermissionService=ie,this.coreActionsService=ge,this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new _e([]),this.rawNotificationsByIdMap$=new _e(new Map),this.processedNotifications$=new _e([]),this.userNotificationsFromServer$=new _e(null),this.readNotificationsOnForYouTab$=new _e(!1),this.currentDocumentOnly$=new _e(!1),this.notificationViews$=new _e({}),this.notificationsByIdMap$=new _e(new Map),this.historyPanelVisible$=new _e(!1),this.notificationsForYou$=new _e(null),this.notificationsByDocumentIdMap$=new _e(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new _e(null),this.maxNotificationDays$=new _e(15),this.tabConfig$=new _e({people:{enable:!1}}),this.settingsConfig$=new _e(null),this.setSettingsConfigByOrganization$=new _e(!1),this.muteAllNotifications$=new _e(!1),this.enableSettings$=new _e(!1),this.selfNotifications$=new _e(!1),this.settingsInitialConfig$=new _e([{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 _e(!1);try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(Ge(Ie=>!!Ie),ut(1)).subscribe(Ie=>{if(Ie){this.db=Ie;try{let he=this.configService.getProxyConfig(),Te=On.firebaseNotificationsDatabaseURL;he?.v1DbHost&&Te&&(Te=KN(Te,he.v1DbHost)),this.notificationsDb=D_(void 0,Te),he?.v1DbHost&&Te&&this.databaseService.lockDatabaseHost(this.notificationsDb)}catch(he){this.loggingService.catch("Error initializing notifications DB, using default: ",he),this.notificationsDb=Ie}this.getDocumentIds(),this.subscribeGetNotificationsForYou()}},Ie=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",Ie)}),this.authService.getUser$().subscribe(Ie=>{Ie?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(he=>{this.notificationsByDocumentIdSubscription[he]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(Ie=>{if(Ie){let he=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(Ie||{}).forEach(Te=>{let Oe=he?.[Te]?.notifications;Oe?.length&&Oe.forEach(Pe=>{this.notificationUtilsService.mergeLocationWithNotification({notification:Pe},Ie)?.notification})}),this.notificationsByDocumentIdMap$.next(he)}})}catch(Ie){this.loggingService.catch("Error in NotificationService constructor: ",Ie)}}setDBConfigDataToInitialConfig(e){try{let t=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(e||{}).forEach(([i,a])=>{t[i]=a}),this.settingsConfig$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",t)}}getInitialConfigFromDB(e){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let t=++this.settingsConfigGeneration,i=It(this.authService.getUser()?.userId??""),a=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:this.getSettingsConfigByOrganization()?void 0:e?.documentId,organizationId:e?.organizationId??this.docService.getOrganizationConfig()?.organizationId,userId:i}});if(t!==this.settingsConfigGeneration)return;if(a?.notificationsConfig)this.setDBConfigDataToInitialConfig(a?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let l={};this.settingsInitialConfig$.getValue().forEach(d=>{if(d.enable){let m=d?.values?.find(u=>u.id===d.default);l[d.id]=m||d?.values?.[0]||{id:"NONE",name:"None"}}});let c={};Object.keys(l).forEach(d=>{c[d]=l[d].id}),yield this.updateSettingsConfigToDb(c)}}catch(t){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",t)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let e=It(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(Ge(t=>t===!0),Se(()=>gn([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe(Ge(([t,i,a])=>(i||!!t)&&!!a?.organizationId),Se(([t,i,a])=>co(this.getInitialConfigFromDB(t)).pipe(Se(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:i?void 0:t?.documentId,organizationId:t?.organizationId??a?.organizationId,userId:e}}).pipe(ue(l=>{l?.data?.notificationsConfig&&!sr(l?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(l?.data?.notificationsConfig)})))))))).subscribe()}catch(e){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",e)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.setUserNotificationsFromServer(null),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.next(null)}catch(e){this.loggingService.catch("Error in NotificationService resetCacheData: ",e)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",e)}}setCommentService(e){try{this.commentService=e}catch(t){this.loggingService.catch("Error in NotificationService setCommentService: ",t)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.selfNotifications$.pipe(Se(()=>this.getCurrentDocumentOnly$().pipe(Se(e=>e?this.docService.getDocumentPaths$().pipe(ue(t=>{})):ce(void 0)))),ln(()=>{this.notificationsByDocumentIdMap$.next(null)}),Se(()=>this.getDocumentIdsByLastNotificationTimestamp().pipe(Fr(),ue(([e,t])=>{let i=e?.map(m=>m.documentId),a=t?.map(m=>m.documentId),l=i?.filter(m=>!a?.includes(m)),c=a?.map(m=>({documentId:m,timestamp:t?.find(u=>u.documentId===m)?.timestamp})).filter(m=>!i?.includes(m.documentId)),d=a?.map(m=>{let u=t?.find(_=>_.documentId===m)?.timestamp;return{documentId:m,timestamp:u}}).filter(m=>{let u=e?.find(_=>_.documentId===m.documentId)?.timestamp;return u&&m.timestamp&&u!==m.timestamp});c?.length&&this.fetchNotificationsForDocumentIds(c),d?.length&&this.fetchNotificationsForDocumentIds(d,1),l?.forEach(m=>{this.removeNotificationsForDocumentId(m)}),t&&!t?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))})))).subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService getDocumentIds: ",e)}}getDocumentIdsByLastNotificationTimestamp(e=15){try{return this.authService.getUser$().pipe(Se(t=>this.docService.getOrganizationConfig$().pipe(ue(i=>{let a=null,l=this.configService.getApiKey(),c=i?.organizationId||t?.organizationId,d=i?.clientOrganizationId||t?.clientOrganizationId||"";return l&&c&&(a=new bm({apiKey:l,organizationId:c})),{user:t,documentPaths:a,clientOrganizationId:d}}))),Se(t=>{let{user:i,documentPaths:a,clientOrganizationId:l}=t;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return ce(null);if(i&&a?.organizationNotificationsLastNotificationTimestamp){let c=new Date,d=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;c.setDate(c.getDate()-d);let m=c.getTime(),u=[yr(ft("timestamp",">=",m),...this.getCurrentDocumentOnly()&&this.docService.getDocumentPaths()?.documentId?[ft("metadata.documentId","==",this.docService.getDocumentPaths()?.documentId)]:[])];this.getCurrentDocumentOnly()||(u.push(uo("timestamp","desc")),u.push(hm(e)));let _=i?.userId??"";return co(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:l})??Promise.resolve({})).pipe(Se(I=>_&&l&&I?.[_]?.organization?.[l]?.errorCode===mr.PERMISSION_DENIED?ce(null):this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:a?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:u}}).pipe(ue(A=>A?.data),ue(A=>{let M=[];return Object.keys(A||{}).forEach(V=>{let q=this.commonDbService.shouldUseFirestore()?A[V]?.timestamp??0:A[V],ae=this.commonDbService.shouldUseFirestore()?A[V]?.deletedNotification??!1:!1;if(ae&&ae.id&&ae?.timestamp===q){let ye=ae.id,ie=A[V]?.metadata?.documentId,ge=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),Ie=ge?.[ie]??{documentMetadata:null,notifications:[]},he=Ie.notifications??[],Te=he?.findIndex(Oe=>Oe.id===ye);Te!==-1&&(he.splice(Te,1),this.notificationsByDocumentIdMap$.next(y(h({},ge),{[ie]:y(h({},Ie),{notifications:he})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById(ye)&&this.notificationResolverService.deleteNotification(ye,this.docService.getDocumentPaths()?.clientOrganizationId??"")}M.push({documentId:V,timestamp:q})}),M}),Xn(A=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",A),ce([]))))))}return ce(null)}))}catch(t){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",t),ce([])}}resolveAndUpdateDocumentNotifications(e,t){try{Object.keys(e).forEach(i=>{let a=e[i]?.documentMetadata||this.docService.getAllDocumentMetadataMap()?.[i]||{},l;if(t==="user")l=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:e[i]?.notifications||[]});else if(t==="notification"){let c=e[i]?.notifications?.reduce((m,u)=>(m[u.notificationId]=u,m),{}),d=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:c});l=Object.values(d??{})}else{let c=e[i]?.notifications?.reduce((m,u)=>(m[u.notificationId]=u,m),{}),d=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:c});l=Object.values(d??{})}l.forEach(c=>{c.notification=this.getClientNotificationObject(c)}),this.setNotificationForDocumentIdInCache(i,a,l)})}catch(i){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",i)}}resolveAndMergeUserNotifications(e,t,i=!1){try{let a=e;if(i&&t==="comment"){let u=this.getUserNotificationsFromServer()??[],_=new Set(e.map(I=>I.notificationId));a=u.filter(I=>_.has(I.notificationId)).concat(e.filter(I=>!u.some(A=>A.notificationId===I.notificationId)))}let l=a.reduce((u,_)=>(u[_.notificationId]=_,u),{}),c;if(t==="user"){let u=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:l});c=Object.values(u??{})}else if(t==="notification"){let u=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:l});c=Object.values(u??{})}else{let u=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:l});c=Object.values(u??{})}c.forEach(u=>{u.notification=this.getClientNotificationObject(u)});let d=this.getUserNotificationsFromServer()??[],m=new Map(d.map(u=>[u.notificationId,u]));c.forEach(u=>{m.set(u.notificationId,u)}),this.setUserNotificationsFromServer(Array.from(m.values()))}catch(a){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",a)}}fetchNotificationsForDocumentIds(e,t=15){return X(this,null,function*(){try{if(e?.length){let i=Yr(this.functions,Zr({url:On.cloudFunction.getNotificationsForDocuments,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"";if(!a)return[];let l=this.getStartAtTimestamp(),c={};if(e.forEach(ie=>{if(ie?.documentId){let ge=this.getAllowedDocumentMetadataByDocumentId(ie.documentId);ge&&(c[ie.documentId]=ge)}}),this.userPermissionService?.isPermissionProviderAvailable())try{let ie=[];if(e.forEach(Oe=>{this.docService.getDocumentMetadata(Oe.documentId)||ie.push(Oe.documentId)}),ie.length){let Oe=this.authService.getUser(),Pe=Yr(this.functions,Zr({url:On?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let $e=yield wl({methodName:"getDocumentMetadataFromIds",data:{type:"getDocumentMetadataFromIds",metadata:{organizationId:Oe?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:ie},getSdkProxy:Pe,userId:Oe?.userId??""});if($e?.data?.length){let ze={};$e.data.forEach(We=>{We?.documentId&&(ze[We.documentId]=We)}),this.docService.setAllDocumentMetadata(h(h({},this.docService.getAllDocumentMetadataMap()),ze))}}catch($e){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",$e)}}let ge=[],Ie=[];e.forEach(Oe=>{let Pe=this.docService.getDocumentMetadata(Oe.documentId);Pe?.clientDocumentId?ge.push({userId:this.authService.getUser()?.userId??"",resource:{id:Pe.clientDocumentId,type:bi.DOCUMENT,source:no.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""}}):Ie.push(Oe.documentId)}),Ie.length&&(e=e.filter(Oe=>!Ie.includes(Oe.documentId)));let he=lt();this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:he,methodName:no.GET_NOTIFICATIONS,source:"internal",payload:{requests:ge}});let Te=yield this.userPermissionService?.onResourceAccessRequired({requests:ge,uniqueId:he,methodName:no.GET_NOTIFICATIONS});Te?.success&&Te?.data?.length?Te.data.forEach(Oe=>{!Oe.hasAccess&&Oe.resourceId&&(e=e.filter(Pe=>Pe.documentId!==mi(Oe.resourceId)))}):e=[]}catch(ie){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",ie),e=[]}if(!e.length)return this.notificationsByDocumentIdMap$.getValue()||(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),[];let d=this.userPermissionService?.getPermissionsCache()?.filter(ie=>ie.type===bi.CONTEXT),m={organizationId:a,documentIds:e.filter(ie=>!!ie.documentId&&!!ie.timestamp).map(ie=>({documentId:ie.documentId,timestamp:ie.timestamp??0})),timestamp:l,limitToLast:t,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:d,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},u=yield this.notificationUtilsService.handleNotificationEncryption({data:m}),_=yield i({veltData:u}),I=_?.data?.data?.veltData||{},A=_?.data?.data?.veltAdditionalData||{},M="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),V=yield u1(I,M),{userNotifications:q=[],userNotificationIdsInDocNotifications:ae=[],permissionResults:ye=[]}=yield u1(A,M);if(this.userPermissionService?.getIsContextEnabled()){let ie=[...this.userPermissionService?.getPermissionsCache()??[],...ye??[]];this.userPermissionService?.setPermissionsCache(ie)}if(V&&typeof V=="object"){let ie=this.usersService.userDataProviderAvailable(),ge=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),Ie=this.notificationResolverService.notificationDataProviderAvailable(),he=[],Te=[],Oe=[];Object.keys(V).forEach((ze,We)=>{let gr=V[ze].documentMetadata??this.docService.getAllDocumentMetadataMap()?.[ze];if(gr){let Et=this.allowedDocumentMetadataMap$.value||{};(!Et?.[ze]||!sr(Et?.[ze],gr))&&this.allowedDocumentMetadataMap$.next(y(h({},Et),{[ze]:gr}))}let nt=V[ze].notifications||[];nt.forEach(Et=>{ae.includes(Et.notificationId)&&!q.find(Je=>Je.notificationId===Et.notificationId)&&q.push(JSON.parse(JSON.stringify(Et))),Et.notification=this.getClientNotificationObject(Et)}),this.setNotificationForDocumentIdInCache(ze,gr,nt),ie&&(he.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:nt,shouldAwait:!0,forceResolve:!0})),he.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:q,shouldAwait:!0,forceResolve:!0}))),ge&&(Te.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:nt,shouldCommentAnnotationsResolverAwait:!0})),Te.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:q,shouldCommentAnnotationsResolverAwait:!0}))),Ie&&(Oe.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:nt,shouldNotificationResolverAwait:!0})),Oe.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:q,shouldNotificationResolverAwait:!0})))});let Pe=JSON.parse(JSON.stringify(q));this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...q]),(Ie||ie||ge)&&(()=>{let ze=Promise.resolve();if(Ie&&(ze=ze.then(()=>Promise.allSettled(Oe)).then(()=>{this.resolveAndUpdateDocumentNotifications(V,"notification"),this.resolveAndMergeUserNotifications(Pe,"notification")})),ie&&(ze=ze.then(()=>Promise.allSettled(he)).then(()=>{this.resolveAndUpdateDocumentNotifications(V,"user"),this.resolveAndMergeUserNotifications(Pe,"user")})),ge){let We=Ie||ie;ze=ze.then(()=>Promise.allSettled(Te)).then(()=>{this.resolveAndUpdateDocumentNotifications(V,"comment"),this.resolveAndMergeUserNotifications(Pe,"comment",We)})}return ze})().catch(ze=>{this.loggingService.catch("Error in NotificationService resolveChain: ",ze)})}}}catch(i){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",i),[]}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(e){try{let t=JSON.parse(JSON.stringify(e));t=t?.filter((i,a,l)=>a===l.findIndex(c=>c.notificationId===i.notificationId)),this.userNotificationsFromServer$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService setUserNotificationsFromServer: ",t)}}getUserNotificationsFromServer(){return this.userNotificationsFromServer$.getValue()}setNotificationForDocumentIdInCache(e,t,i,a){try{let l=this.docService.getOrganizationConfig()?.organizationId??"",c=this.docService.getOrganizationMetadata(l);t||(t=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),c||(c=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(l)||{})));let d=this.notificationsByDocumentIdMap$.getValue(),m=d?.[e]?.notifications||[],u=this.docService.getLocationMetadatas(),_=i?.map(M=>{let V=M?.notification;return V?(V.metadata&&(V.metadata.documentName=t?.documentName||V.metadata.documentName,V.metadata.organizationMetadata=c||V.metadata.organizationMetadata,V.metadata.documentMetadata=t||V.metadata.documentMetadata),u&&(V=this.notificationUtilsService.mergeLocationWithNotification({notification:V},u)?.notification),V):null})?.filter(M=>!!M)||[],I=new Map(m.map(M=>[M.id,M]));_.forEach(M=>{I.set(M.id,M)});let A=Array.from(I.values()).sort((M,V)=>(V.timestamp||0)-(M.timestamp||0));this.notificationsByDocumentIdMap$.next(y(h({},d),{[e]:{notifications:A,documentMetadata:t}}))}catch(l){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",l)}}removeNotificationsForDocumentId(e){try{this.notificationsByDocumentIdSubscription[e]&&this.notificationsByDocumentIdSubscription[e].unsubscribe();let t=this.notificationsByDocumentIdMap$.getValue();delete t?.[e],this.notificationsByDocumentIdMap$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",t)}}getStartAtTimestamp(){try{let e=new Date,t=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return e.setDate(e.getDate()-t),e.getTime()}catch(e){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",e),0}}getNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(Se(e=>ce(e).pipe(Ge(t=>!!t),ue(t=>{let i=this.usersService.userDataProviderAvailable(),a=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),l=this.notificationResolverService?.notificationDataProviderAvailable();if(l||i||a){let d=t?.reduce((m,u)=>(m[u.notificationId]=u,m),{});l&&(d=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:d||[]})),i&&(d=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:d||[]})),a&&(d=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:d||[]})),t=Object.values(d??{})}return t.forEach(d=>{d.notification=this.getClientNotificationObject(d)}),t.sort((d,m)=>m.timestamp-d.timestamp),t.map(d=>d.notification).filter(d=>!!d)}),Se(t=>{let i={data:t?.reduce((a,l)=>(a[l.id]={notification:l},a),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:i,feature:"allUserNotifications"}).pipe(ue(a=>Object.values(a?.data||{}).map(l=>l?.notification)))}))),Se(e=>{let t=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(t).pipe(ue(()=>e))}),Se(e=>this.allowedDocumentMetadataMap$.pipe(ue(()=>e))),ue(e=>(e?.length&&(e=e.map(t=>{if(t?.metadata){let i=this.docService.getOrganizationConfig()?.organizationId??"",a=this.getAllowedDocumentMetadataByDocumentId(t.metadata.documentId),l=this.docService.getOrganizationMetadata(i);a||(a=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),l||(l=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(i)||{}))),t.metadata.documentName=a?.documentName||t.metadata.documentName,t.metadata.organizationMetadata=l||t.metadata.organizationMetadata,t.metadata.documentMetadata=a||t.metadata.documentMetadata}return t})),e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(JSON.parse(JSON.stringify(e))):this.notificationsForYou$.next([]),ce(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),ce({})}}subscribeNotificationsData(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let i,a;try{if(e&&(a=er(e)),t&&typeof t=="object"){let l=Oi(t);i=er(JSON.stringify(l))}}catch(l){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",l)}return _r(this.afAuth).pipe(Ge(l=>!!l),Se(l=>this.isFeatureAllowed({firebaseUser:l})),Se(l=>l.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(c=>(l.featureAllowed=c,l))):ce(l)),Se(l=>!l.featureAllowed||l?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),ce([])):ce(l).pipe(Se(c=>this.docService.getDocumentPaths$().pipe(ue(d=>(this.documentPaths=d,c.documentPaths=d,c)))),Se(c=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})),Se(t=>this.authService.getUser$().pipe(ue(i=>y(h({},t),{user:i})))),Se(t=>Ao(t.config,t.user,je.NOTIFICATION)?ce(y(h({},t),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),ce(y(h({},t),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ge(t=>!!t),Se(t=>{if(this.db=t,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let i=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(i+=`/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=jr(this.db,`${e?i+"/"+N.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+N.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return x8(a).pipe(Xn(l=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",l),ce(null))),ue(l=>{let c=[],d=new Map;l?.raw&&(Object.keys(l?.raw||{}).forEach(u=>{let _=l?.raw[u];_?.id&&c.push(_)}),c.forEach(u=>{u.id&&d.set(u.id,u)})),this.notifications$.next(c),this.rawNotificationsByIdMap$.next(d);let m=[];l?.processed&&Object.keys(l?.processed||{}).forEach(u=>{let _=l?.processed[u];_?.id&&m.push(_)}),this.processedNotifications$.next(m),this.setNotificationsByIdMap()}))}else return ce(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let t=this.notificationViews$.getValue(),i;e?.email&&(i=It(e?.email));let a;e?.userId&&(a=It(e?.userId));let l=new Map;this.processedNotifications$.getValue().forEach(d=>{if(d.id&&d?.displayHeadlineMessageTemplate){let m=!1;(i&&d.notifyUsers?.[i]||a&&d.notifyUsers?.[a])&&(m=!0);let u={id:d.id,notificationSource:d.notificationSource,actionType:d.actionType,actionUser:d.actionUser,timestamp:d.timestamp,targetAnnotationId:d.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(d),displayBodyMessage:this.getNotificationBodyMessage(d),forYou:m,notificationSourceData:d.notificationSourceData},_=this.getRawNotificationById(u.id);if(_?.metadata&&(u.metadata={apiKey:_.metadata.apiKey,organizationId:_.metadata.organizationId,clientOrganizationId:_.metadata.clientOrganizationId,documentId:_.metadata.documentId,clientDocumentId:_.metadata.clientDocumentId,location:_?.location,locationId:_?.locationId}),u?.notificationSource==="comment"&&u?.targetAnnotationId){let I=this.commentService?.getAnnotationById(u.targetAnnotationId);I||_?.annotationData&&(I=_.annotationData),I&&(u.notificationSourceData=this.commentService?.getCommentAnnotationForClient(I))}l.set(d.id,u)}}),l.forEach((d,m)=>{d.isUnread=d?.actionUser?.userSnippylyId!==e?.userSnippylyId&&!t?.notification?.[m]?.views?.[e?.userSnippylyId],l.set(m,d)}),this.notificationsByIdMap$.next(l)}}catch(e){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",e)}}getClientNotificationObject({processed:e,raw:t,metadata:i,views:a,notification:l}){try{let c=this.authService.getUser(),d=l||e;if(d.id&&d?.displayHeadlineMessageTemplate&&c){let m=null;c?.email&&(m=It(c?.email));let u=null;c?.userId&&(u=It(c?.userId));let _=!1,I=!0;(m&&d.notifyUsers?.[m]||u&&d.notifyUsersByUserId?.[u])&&(_=!0),u&&a?.[u]&&(I=!1);let A={id:d.id};if(l?A=y(h(h({},A),l),{displayHeadlineMessage:this.getNotificationHeadlineMessage(l),displayBodyMessage:this.getNotificationBodyMessage(l),forYou:_,isUnread:I}):A={id:e.id,notificationSource:e.notificationSource,actionType:e.actionType,actionUser:e.actionUser,timestamp:e.timestamp,targetAnnotationId:e.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(e),displayBodyMessage:this.getNotificationBodyMessage(e),forYou:_,isUnread:I,metadata:i},A?.notificationSource==="comment"&&A?.targetAnnotationId){let M=this.commentService?.getAnnotationById(A.targetAnnotationId);M||l?.notificationSourceData&&(M=l?.notificationSourceData),M||t?.annotationData&&(M=t.annotationData),M&&(A.notificationSourceData=this.commentService?.getCommentAnnotationForClient(M))}return t?.targetAnnotationData?.isCommentResolverUsed&&(A.isCommentResolverUsed=t?.targetAnnotationData?.isCommentResolverUsed),l?.isNotificationResolverUsed&&(A.isNotificationResolverUsed=l.isNotificationResolverUsed),A}return}catch(c){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",c);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(ue(e=>e?Object.keys(e??{}).map(t=>{let i=e[t].notifications||[],a=i.filter(c=>c.isUnread).length,l=i.length>0&&i[0]?.timestamp||0;return{documentId:t,notifications:e[t]?.notifications,unreadNotificationsCount:a,latestNotificationTimestamp:l,documentMetadata:e[t]?.documentMetadata}}).filter(t=>t.notifications?.length>0).sort((t,i)=>i.latestNotificationTimestamp-t.latestNotificationTimestamp):null))}getAllNotifications$(){return this.getNotificationsByDocumentId$().pipe(ue(e=>{let t=null;return e?(t=[],e.forEach(i=>{i.notifications.forEach(a=>{t?.push(a)})}),t?.sort((i,a)=>a.timestamp-i.timestamp)):null}))}processNotificationData(e){try{let t=e?.annotationData?.metadata,i=this.docService.getOrganizationConfig()?.organizationId;e.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(t?.documentId)||{})),e.metadata||(e.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete e.metadata.locations,e.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(t?.documentId)||{})),e?.metadata?.documentMetadata?.clientDocumentId&&e?.metadata?.documentMetadata?.documentId&&(e.metadata.documentMetadata.documentId=e?.metadata?.documentMetadata?.clientDocumentId),delete e.metadata.documentMetadata.locations,e.metadata.organizationMetadata=JSON.parse(JSON.stringify(i?this.docService.getOrganizationMetadata(i)||{}:{})),e?.metadata?.organizationMetadata?.clientOrganizationId&&e?.metadata?.organizationMetadata?.organizationId&&(e.metadata.organizationMetadata.organizationId=e?.metadata?.organizationMetadata?.clientOrganizationId);let a=this.configService.getApiKey();e.metadata.apiKey=a,e.platform=this.configService.getSF()?"sf":"sdk",e.actionUser=this.authService.getUser();let l=t?.documentId?new bm({apiKey:a,documentId:t.documentId,organizationId:t?.organizationId}):this.docService.getDocumentPaths();e?.actionUser?.organizationId&&(e.metadata.organizationId=l?.organizationId||e.actionUser.organizationId,e.metadata.clientOrganizationId=l?.clientOrganizationId||e.actionUser.clientOrganizationId);let c=this.docService.getLocation();c&&(e.location=c?.location,e.locationId=c?.locationId),this.loggingService.log(`[NOTIFICATION] ${e?.notificationSource} ${e?.actionType}`,e);let d=this.commonDbService.getServerTimestamp(),m=this.notificationUtilsService.formatNotification(e,d);return JSON.parse(JSON.stringify(m))}catch(t){return this.loggingService.catch("Error in NotificationService processNotificationData: ",t),null}}updateNotificationDatabase(e){try{if(!this.notificationsDb)return;let t=jr(this.notificationsDb),i=this.processNotificationData(e);p8(t,JSON.parse(JSON.stringify(i)))}catch(t){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",t)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(e){return this.authService.getUser$().pipe(Se(t=>t?t.organizationId?this.getAllNotifications$().pipe(Se(i=>this.notificationsForYou$.pipe(ue(a=>{if(i||a){let l=new Map;return(!e?.type||["all","documents"].includes(e.type))&&(i||[]).forEach(c=>{c.id&&l.set(c.id,c)}),(!e?.type||["all","forYou"].includes(e.type))&&(a||[]).forEach(c=>{c.id&&!l.has(c.id)&&l.set(c.id,c)}),Array.from(l.values()).sort((c,d)=>(d.timestamp||0)-(c.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(ue(i=>Array.from(i.values())),ue(i=>i.sort((a,l)=>l.timestamp-a.timestamp)),Zh()):ce(null)),_t(Kt))}getRawNotificationById(e){try{return this.rawNotificationsByIdMap$.getValue()?.get(e)}catch(t){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",t);return}}setNotificationViews(e){try{this.notificationViews$.next(e),this.setNotificationsByIdMap()}catch(t){this.loggingService.catch("Error in NotificationService setNotificationViews: ",t)}}getNotificationHeadlineMessage(e){try{let t=this.authService.getUser();if(e?.displayHeadlineMessageTemplate&&e?.displayHeadlineMessageTemplateData){let i=e.displayHeadlineMessageTemplate,a=e.displayHeadlineMessageTemplateData,l=/\{(\w+)\}/g,c=i.replace(l,(d,m)=>(m==="actionUser"||m==="recipientUser")&&a[m]?t?.email&&a[m].email===t?.email||t?.userId&&a[m]?.userId===t?.userId?"You":a[m].name||a[m].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':a[m]?a[m]:d);return this.domService.sanitizeHtml(c)}return this.domService.sanitizeHtml(e.displayHeadlineMessageTemplate||"")}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",t),""}}getNotificationBodyMessage(e){try{if(e?.displayBodyMessageTemplate&&e?.displayBodyMessageTemplateData){let t=e?.displayBodyMessageTemplate;return e?.displayBodyMessageTemplateData&&e?.displayBodyMessageTemplateData?.users?.forEach(i=>{if(i?.userId){let a=this.usersService.getUserById(i?.userId);t=t?.replaceAll(`{{${i.userId}}}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>'),t=t?.replaceAll(`@User ${i.userId}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(t)}return this.domService.sanitizeHtml(e.displayBodyMessage||"")}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",t),""}}setHistoryPanelVisibility(e,t=!1,i=!1){try{e?document.querySelector(N.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(e):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${N.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(e),e?this.analyticsService.trackEvent(Y.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(Y.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${N.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(e=!1,t=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(N.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(Y.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(Y.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${N.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${N.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(e){return X(this,null,function*(){try{let t=JSON.parse(JSON.stringify(this.getUserNotificationsFromServer()??[]));if(e?.length){for(let c=0;c<e.length;c+=50){let m=e.slice(c,c+50).filter(I=>I?.id),u=m.map(I=>this.setNotificationAsRead({notification:I,userNotifications:JSON.parse(JSON.stringify(t))})),_=yield Promise.all(u);m.forEach((I,A)=>{let M=_[A];if(!M.some(q=>q.notificationId===I.id))t=t.filter(q=>q.notificationId!==I.id);else{let q=t.find(ye=>ye.notificationId===I.id),ae=M.find(ye=>ye.notificationId===I.id);q&&ae?.views&&(q.views=ae.views)}})}let a=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));e.forEach(c=>{let d=c.metadata?.documentId;if(d&&a?.[d]){let m=a?.[d]?.notifications||[],u=m.find(_=>_.id===c.id);u&&(u.isUnread=!1),a[d].notifications=m}}),this.notificationsByDocumentIdMap$.next(a),!sr(t,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(t)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",t)}})}setAllNotificationsAsRead(e){return X(this,null,function*(){try{if(e?.tabId==="for-you"){let t=this.notificationsForYou$.value||[];this.setNotificationsAsRead(t)}else this.getNotifications$().pipe(ut(1)).subscribe(t=>{t&&this.setNotificationsAsRead(t)})}catch(t){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",t)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(ue(e=>e?.filter(i=>i?.isUnread)?.length??null),Se(e=>this.getNotifications$().pipe(ue(t=>{let i=t?.filter(a=>a?.isUnread)?.length??null;return{forYou:e,all:i}}))))}catch(e){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",e),ce({forYou:null,all:null})}}setNotificationAsRead(i){return X(this,arguments,function*({notification:e,userNotifications:t}){try{let a=this.authService.getUser();if(a&&e?.id){let l=It(a?.userId),{metadata:c}=e;if(c){let{apiKey:d,organizationId:m,documentId:u}=c;if(d&&m&&u&&l){let _=yield this.commonDbService.getData({feature:"docNotification",properties:{id:e.id,organizationId:m,documentId:u,apiKey:d}});_?.notificationId&&(_?.views?.[l]||(_.views||(_.views={}),_.views[l]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:e.id,organizationId:m,documentId:u,apiKey:d},data:_})));let I=yield this.commonDbService.getData({feature:"userNotification",properties:{id:e.id,userId:l,documentId:u,organizationId:m}});if(I?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:e.id,userId:l,documentId:u,organizationId:m}}),t=t.filter(A=>A.notificationId!==e.id);else if(!I?.views?.[l]){I.views||(I.views={}),I.views[l]={timestamp:Date.now()};let A=t.find(M=>M.notificationId===e.id);A&&(A.views=I.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:e.id,userId:l,documentId:u,organizationId:m},data:I})}}}}}return t}catch(a){return this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",a),t}})}setMaxDays(e){try{e>0?this.maxNotificationDays$.next(e):this.maxNotificationDays$.next(15)}catch(t){this.loggingService.catch("Error in NotificationService setMaxDays: ",t)}}setTabConfig(e){try{e&&this.tabConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setTabConfig: ",t)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}enableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!0)return;this.currentDocumentOnly$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableCurrentDocumentOnly: ",e)}}disableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!1)return;this.currentDocumentOnly$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableCurrentDocumentOnly: ",e)}}getCurrentDocumentOnly$(){return this.currentDocumentOnly$.asObservable()}getCurrentDocumentOnly(){return this.currentDocumentOnly$.value}markNotificationAsReadById(e){return X(this,null,function*(){try{this.getNotifications$().pipe(ut(1)).subscribe(t=>{if(t){let i=t.filter(a=>a.id===e);this.setNotificationsAsRead(i)}})}catch(t){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",t)}})}getAllowedDocumentMetadataByDocumentId(e){try{return this.allowedDocumentMetadataMap$.value?.[e]||null}catch(t){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",t),null}}setSettingsConfig(e){try{this.enableSettings$.value&&this.settingsConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",t)}}setSettingsConfigWithDB(e){try{this.enableSettings$.value&&(this.settingsConfig$.next(e),this.updateSettingsConfigToDb())}catch(t){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",t)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",e)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSettings: ",e)}}enableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!0&&this.setSettingsConfigByOrganization$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSettingsConfigByOrganization: ",e)}}disableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!1&&this.setSettingsConfigByOrganization$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSettingsConfigByOrganization: ",e)}}getSettingsConfigByOrganization$(){return this.setSettingsConfigByOrganization$.asObservable()}getSettingsConfigByOrganization(){return this.setSettingsConfigByOrganization$.value}enableSelfNotifications(){try{this.selfNotifications$.value!==!0&&this.selfNotifications$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSelfNotifications: ",e)}}disableSelfNotifications(){try{this.selfNotifications$.value!==!1&&this.selfNotifications$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSelfNotifications: ",e)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSettings: ",e)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(e){try{let t=!1;if(e.forEach(i=>{["email","inbox"].includes(i.id)&&(t=!i.values?.every(a=>["ALL","NONE","MINE"].includes(a.id)))}),t){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",t)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(e){return X(this,null,function*(){try{let t=this.authService.getUser(),i=It(t?.userId??""),a=this.docService.getDocumentPaths(),l=this.docService.getOrganizationConfig(),c=a?.organizationId??l?.organizationId,d=a?.clientOrganizationId??l?.clientOrganizationId,m={apiKey:this.configService.getApiKey(),organizationId:c,documentId:a?.documentId,clientOrganizationId:d,clientDocumentId:a?.clientDocumentId,userId:i,clientUserId:this.authService.getUser()?.userId};i&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:d??t?.clientOrganizationId??"",user:{userId:t?.userId??""},notificationsConfig:e||this.settingsConfig$.getValue()}):a?.documentId&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:a?.documentId,userId:i},data:{id:a?.documentId,notificationsConfig:e||this.settingsConfig$.getValue(),metadata:m}})))}catch(t){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",t)}})}openNotificationsPanel(){try{this.notificationsPanelVisible$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService openNotificationsPanel: ",e)}}closeNotificationsPanel(){try{this.notificationsPanelVisible$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService closeNotificationsPanel: ",e)}}getNotificationsPanelVisible$(){return this.notificationsPanelVisible$.asObservable()}getNotificationsPanelVisible(){return this.notificationsPanelVisible$.value}};o.\u0275fac=function(t){return new(t||o)(K(eo),K(ct),K(qe),K(Ft),K(yn),K(vd),K(Cm),K(ol),K(_m),K($n),K(st),K(Ve),K(Vn),K(k),K(WL),K(An),K(Do),K(Ia),K(nr))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var uv=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A,M){this.analyticsService=e,this.configService=t,this.docService=i,this.databaseService=a,this.commonDbService=l,this.authService=c,this.domService=d,this.afAuth=m,this.iamService=u,this.dialog=_,this.loggingService=I,this.notificationService=A,this.userPermissionService=M,this.areaAnnotationById$=new _e({}),this.documentPaths=null,this.areaEnabled$=new _e(!0),this.allowedElementIds$=new _e([]),this.addAreaMode$=new _e(!1),this.loggingService.log("%c[WB] Creating CLASS: AreaService","color: blue;"),this.analyticsService.setAreaService(this),this.authService.setAreaService(this),this.databaseService.getDb().pipe(Ge(V=>!!V),ut(1)).subscribe(V=>{V&&this.getDocumentPaths()},V=>{this.loggingService.catch("Error in AreaService getDb subscription: ",V)}),this.domService.onWindowPointerMove$().subscribe(V=>{if(this.addAreaMode$.value){this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement);let q=this.domService.getBackgroundElement(V.clientX,V.clientY);q&&(this.isElementInsideAllowedElements(q)?eF(V.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement=q,this.domService.highlightElement(this.highlightElement,N.CURSOR.AREA_PIN)):this.domService.removeClassFromElement(document.body,"show-pin-cursor"))}},V=>{this.loggingService.catch("Error in AreaService onWindowPointerMove$ subscription: ",V)}),this.domService.onWindowKeyupEsc$().subscribe(V=>{this.addAreaMode$.value&&this.disableAddAreaMode()},V=>{this.loggingService.catch("Error in AreaService onWindowKeyupEsc$ subscription: ",V)}),this.domService.onDocumentClick$().subscribe(V=>{if(V&&this.addAreaMode$.value){if(V.preventDefault(),V.stopPropagation(),!eF(V.target)){let q=this.domService.getBackgroundElement(V.clientX,V.clientY);q&&this.isElementInsideAllowedElements(q)&&this.addArea(V)}this.disableAddAreaMode()}},V=>{this.loggingService.catch("Error in AreaService onDocumentClick$ subscription: ",V)}),this.addAreaMode$.subscribe(V=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),V?this.domService.addClassToElement(document.body,"snippyly-add-area-mode"):(this.domService.removeClassFromElement(document.body,"snippyly-add-area-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"))},V=>{this.loggingService.catch("Error in AreaService addAreaMode$ subscription: ",V)}),this.domService.onWindowKeyupBackspace$().subscribe(V=>{this.deleteAreaPinAnnotations("keyupBackspace")},V=>{this.loggingService.catch("Error in AreaService onWindowKeyupBackspace$ subscription: ",V)}),this.domService.onWindowKeyupDelete$().subscribe(V=>{this.deleteAreaPinAnnotations("keyupDelete")},V=>{this.loggingService.catch("Error in AreaService onWindowKeyupDelete$ subscription: ",V)})}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in AreaService","color: green;");try{this.areaAnnotationById$.next({}),this.areaEnabled$.next(!0),this.allowedElementIds$.next([]),this.addAreaMode$.next(!1),this.highlightElement=null}catch(e){this.loggingService.catch("Error in AreaService clearCache: ",e)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$()}setAllowedElementIds(e){this.allowedElementIds$.next(e||[])}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}getAllAreaAnnotations(e,t,i){this.loggingService.log("%c[WB] Calling FUNCTION: getAllAreaAnnotations","color: green;");let a,l;try{if(e&&(l=er(e)),t&&typeof t=="object"){let c=Oi(t);a=er(JSON.stringify(c))}}catch(c){this.loggingService.catch("Error in AreaService getAllAreaAnnotations: ",c)}return _r(this.afAuth).pipe(Ge(c=>!!c),Se(c=>this.isFeatureAllowed({firebaseUser:c,annotations:[],filteredAnnotations:[]})),Se(c=>c.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(d=>(c.featureAllowed=d,c))):ce(c)),Se(c=>c.featureAllowed?this.authService.isPlanExpired$().pipe(ue(d=>(c.featureAllowed=!d,c))):ce(c)),Se(c=>c.featureAllowed?ce(c).pipe(Se(d=>this.docService.getDocumentPaths$().pipe(ue(m=>(this.documentPaths=m,d.documentPaths=m,d)))),Se(d=>l?this.getDataFromDocumentIds([l]).pipe(ue(m=>(d.annotations=m||[],h({},d)))):this.docService.getDocumentIds$().pipe(Se(m=>{let u=m?.length>0?m.map(_=>_.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(u).pipe(ue(_=>(d.annotations=_||[],h({},d))))}))),Se(d=>this.docService.getLocation$().pipe(ue(m=>(d.location=m,d)))),Se(d=>this.docService.getLocations$().pipe(ue(m=>(d.customLocations=m,d)))),ue(d=>{if(d.filteredAnnotations=[],l&&!a)return d.filteredAnnotations=d.annotations?.slice(),d;{let m=[],u=[];return a?m.push(a):(m.push(d?.location?.locationId),m.push(...Object.values(d?.customLocations||[]).map(_=>_.locationId)),d?.location?.location?.id&&u.push(d?.location?.location?.id)),d.filteredAnnotations=this.filterAnnotationsByLocationIds(d?.annotations,m,u),d}}),Se(d=>i?ce(d):d?.annotations?.length?this.domService.onWindowResize$().pipe(ue(()=>d)):ce(d)),Se(d=>i?ce(d):d?.annotations?.length?this.domService.onDomChange$("AreaService getAllAreaAnnotations").pipe(ue(()=>d)):ce(d)),ue(d=>(d.filteredAnnotations=d.filteredAnnotations?.map(m=>{let u=Object.assign({},m);return u.areaProperties=this.calculateAreaAnnotationPosition(u),u}),d)),Se(d=>d?.filteredAnnotations?ce(d?.filteredAnnotations||[]):ce([])),Se(d=>{if(this.authService.isFeatureAllowed(je.COMMENT))return ce(d);{let m=d?.filter(u=>!u?.targetAnnotations?.filter(_=>_?.type===je.COMMENT)?.length);return ce(m)}})):ce([])),_t(Kt))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})),Se(t=>this.authService.getUser$().pipe(ue(i=>y(h({},t),{user:i})))),Se(t=>Ao(t.config,t.user,je.AREA)?ce(y(h({},t),{featureAllowed:!0})):(this.loggingService.warn("Area feature is not allowed."),ce(y(h({},t),{featureAllowed:!1})))),_t((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getDataFromDocuments(e){if(this.configService.getApiKey()){let{documentIds:t,filters:i}=e;if(t?.some(d=>!d)||!this.documentPaths)return ce([]);let a=this.docService.getDocumentPaths()?.veltFolderId,l=ce([]),c={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(c.documentId=t?.length?t[0]:void 0,c.organizationId=this.documentPaths?.organizationId),this.userPermissionService?.getIsContextEnabled()){let d=[N.DEFAULT_VELT_CONTEXT,...this.docService.getProcessedDocContext()],m=[];for(let u=0;u<(d?.length??0);u+=N.LISTENER_CONTEXT_BATCH_SIZE)m.push(d?.slice(u,u+N.LISTENER_CONTEXT_BATCH_SIZE)??[]);l=gn(m.map(u=>this.commonDbService.dbListener({feature:"allAreas",properties:y(h({},c),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",t),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[],...u?.length?[ft("context.accessFields","array-contains-any",u)]:[])]})}).pipe(la()))).pipe(ue(u=>Na(u)))}else{let d=[];for(let m=0;m<(t?.length??0);m+=N.LISTENER_BATCH_SIZE)d.push(t?.slice(m,m+N.LISTENER_BATCH_SIZE)??[]);l=gn(d.map(m=>this.commonDbService.dbListener({feature:"allAreas",properties:y(h({},c),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",m),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[])]})}).pipe(la()))).pipe(ue(m=>Na(m)))}return l.pipe(ue(({data:d,operation:m})=>{let u=[];return d&&(u=Object.values(d??{}).filter(_=>typeof _=="object")),{data:u,operation:m}}),ue(({data:d,operation:m})=>{if(!t)return{data:d,documentMap:{},operation:m};let u=d.reduce((_,I)=>{let A=I.metadata?.documentId;return A&&(_[A]||(_[A]=[]),_[A].push(I)),_},{});return{data:d,documentMap:u,operation:m}}),ue(({data:d,documentMap:m,operation:u})=>{if(!i)if(u?.type==="removed"){if(u?.ids?.length){let _=this.areaAnnotationById$.value;u?.ids?.forEach(I=>{delete _?.[I]}),this.areaAnnotationById$.next(_)}}else Object.entries(m??{}).forEach(([_,I])=>{this.setAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:_,annotations:I})});return d}))}else return ce([])}setAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:i,queryHash:a}){try{if(t){e||(e=N.NO_ORGANIZATION_ID),a||(a=N.DEFAULT_QUERY_HASH);let l={};i?.forEach(d=>{d?.annotationId&&(l[d?.annotationId]=d)});let c=h(h({},this.areaAnnotationById$.value),l);this.areaAnnotationById$.next(c)}}catch(l){this.loggingService.catch("Error in AreaService setAreaAnnotationsByOrganizationIdAndDocumentId:",l)}}getAnnotationById(e){try{return this.areaAnnotationById$.value?.[e]?this.areaAnnotationById$.value?.[e]:void 0}catch(t){this.loggingService.catch("Error in AreaService getAnnotationById: ",t);return}}filterAnnotationsByLocationIds(e,t,i){try{return e.filter(a=>t.includes(a.locationId)||i?.includes(a?.location?.id)||t?.find(l=>l==a?.location?.id)||i?.find(l=>l==a?.locationId+""))}catch(a){return this.loggingService.catch("Error in AreaService filterAnnotationsByLocations:",a),[]}}calculateAreaAnnotationPosition(e,t=!1){try{if(e.targetElements?.length){let i=e.targetElements[0],a=e.targetElements[1];if(i?.xpath&&a?.xpath||i?.anchor&&a?.anchor){let l=null,c=null;if(i?.anchor){let d=this.domService.resolveAnchorRecord(i.anchor);d?.element&&d?.element instanceof HTMLElement&&!Mo(d.element)&&this.domService.isElementVisible(d.element)&&Kr(d.element)&&(l=d.element)}else i?.xpath&&(l=this.domService.getElementFromXPath(i.xpath),l&&Mo(l)&&(l=null),this.domService.isXpathWithId(i.xpath)||(!l&&i.cfXpath&&(l=this.domService.getElementFromXPath(i.cfXpath),l&&Mo(l)&&(l=null)),!l&&i.fXpath&&(l=this.domService.getElementFromXPath(i.fXpath),l&&Mo(l)&&(l=null))));if(a?.anchor){let d=this.domService.resolveAnchorRecord(a.anchor);d?.element&&d?.element instanceof HTMLElement&&!Mo(d.element)&&this.domService.isElementVisible(d.element)&&Kr(d.element)&&(c=d.element)}else a?.xpath&&(c=this.domService.getElementFromXPath(a.xpath),c&&Mo(c)&&(c=null),this.domService.isXpathWithId(a.xpath)||(!c&&a.cfXpath&&(c=this.domService.getElementFromXPath(a.cfXpath),c&&Mo(c)&&(c=null)),!c&&a.fXpath&&(c=this.domService.getElementFromXPath(a.fXpath),c&&Mo(c)&&(c=null))));if(l&&c){let d=eZ(l,c);if(d){let m=l,u=c,_=m.getBoundingClientRect(),I=u.getBoundingClientRect(),A=t?_.width:m.offsetWidth||_.width,M=t?_.height:m.offsetHeight||_.height,V=t?I.width:u.offsetWidth||I.width,q=t?I.height:u.offsetHeight||I.height,ae={};A&&M&&(ae={top:M*i.topPercentage/100,left:A*i.leftPercentage/100});let ye={};V&&q&&(ye={top:q*a.topPercentage/100,left:V*a.leftPercentage/100});let ie=!t,ge=tZ(ae.left,ae.top,l,d,ie),Ie=tZ(ye.left,ye.top,c,d,ie),he,Te,Oe,Pe,$e={};ge.x>Ie.x?ge.y>Ie.y?(Pe={x:ge.x,y:ge.y},he={x:Ie.x,y:Ie.y},$e.handle1=Pe,$e.handle2=he):(Te={x:ge.x,y:ge.y},Oe={x:Ie.x,y:Ie.y},$e.handle1=Te,$e.handle2=Oe):ge.y>Ie.y?(Oe={x:ge.x,y:ge.y},Te={x:Ie.x,y:Ie.y},$e.handle1=Oe,$e.handle2=Te):(he={x:ge.x,y:ge.y},Pe={x:Ie.x,y:Ie.y},$e.handle1=he,$e.handle2=Pe);let ze={topLeft:he||{x:Oe?.x,y:Te?.y},bottomRight:Pe||{x:Te?.x,y:Oe?.y},topRight:Te||{x:Pe?.x,y:he?.y},bottomLeft:Oe||{x:he?.x,y:Pe?.y}};return $e.coordinates=ze,$e.targetElement=this.domService.getXPath(d),$e}}}}return}catch(i){this.loggingService.catch("Error in AreaService calculateAreaAnnotationPosition:",i);return}}addArea(e,t=[],i,a,l,c){this.loggingService.log("%c[WB] Calling FUNCTION: addArea","color: green;");try{let d=this.authService.getUser();if(d)if(d.isReadOnly||d.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add areas.");else{let m=new TN;a&&(m.annotationId=a),m.from=d,m.color=N.DEFAULT_ANNOTATION_COLOR,m.lastUpdated=this.timestamp,i&&(m.targetAnnotations=[i]),m.props=new ad;let u=this.domService.getCurrentWindowSizeValue();if(m.props.screenWidth=u.screenWidth,m.props.screenHeight=u.screenHeight,m.props.screenScrollHeight=u.screenScrollHeight,m.props.viewportWidth=window.innerWidth,m.props.viewportHeight=window.innerHeight,e||t?.length>0){let A=e?this.getPointsForAreaPinAnnotation(e):t;m.targetElements=[],A.forEach(M=>{m.targetElements.push(this.domService.getTargetElementForCursorPosition(e,void 0,void 0,void 0,void 0,!0,{clientX:M.x,clientY:M.y}))})}this.setLocationToAreaAnnotation(m),l&&(m.locationId=l.locationId,m.location=l.location),m.pageInfo=ro(),m.pageInfo&&(m.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth);let _=this.getElementForAreaAnnotation(m),I=this.docService.getBaseMetadata("area",{element:_});if(m?.metadata||(m.metadata={}),m.metadata=h(h({},m.metadata),I),c?.access&&c?.accessFields){if(!this.userPermissionService?.hasUserContextAccess({userId:d.userId,accessFields:c.accessFields})){this.loggingService.catch("User does not have context access to add area annotation.",void 0,void 0,!0);return}m.context={access:c.access,accessFields:c.accessFields}}return this.saveAreaToDb(m),m}return}catch(d){this.loggingService.catch("Error in AreaService addArea: ",d);return}}setLocationToAreaAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location)}catch(t){this.loggingService.catch("Error in AreaService setLocationToAreaAnnotation:",t)}}getElementForAreaAnnotation(e){try{let t,i,a;if(e.targetElements?.length){if(e.targetElements[0]?.anchor){let l=this.domService.resolveAnchorRecord(e.targetElements[0].anchor);l?.element&&this.domService.isElementVisible(l.element)&&Kr(l.element)&&(i=l.element)}else e.targetElements[0]?.xpath&&(i=this.domService.getElementFromXPath(e.targetElements[0].xpath));if(e.targetElements[1]?.anchor){let l=this.domService.resolveAnchorRecord(e.targetElements[1].anchor);l?.element&&this.domService.isElementVisible(l.element)&&Kr(l.element)&&(a=l.element)}else e.targetElements[1]?.xpath&&(a=this.domService.getElementFromXPath(e.targetElements[1].xpath))}return i&&a&&(t=eZ(i,a)),t}catch(t){return this.loggingService.catch("Error in AreaService getElementForAreaAnnotation: ",t),null}}saveAreaToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: saveAreaToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(je.AREA)&&gn([this.docService.getDocumentPaths$(),this.databaseService.getDb()]).pipe(Ge(([t,i])=>!!t&&!!i),ut(1),Se(([t,i])=>{if(this.documentPaths=t,this.documentPaths?.area){e.annotationId||(e.annotationId=this.commonDbService.generateDocumentId()),e.pageInfo&&(e.pageInfo.areaUrl=this.generateAreaUrl(e));let a=JSON.parse(JSON.stringify(e));if(a.position=null,!a?.metadata?.documentId){a?.metadata||(a.metadata={});let d=this.docService.getBaseMetadata("area");a.metadata=h(h({},a?.metadata),d)}this.domService.toggleAnnotationSelection(a),this.analyticsService.trackEvent(Y.Events.Area.AREA_ADDED,{annotationId:e.annotationId});let{documentId:l,organizationId:c}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);return this.commonDbService.setData({feature:"area",properties:{id:e.annotationId,documentId:l,organizationId:c},data:JSON.parse(JSON.stringify(a))})}else return ce(null)})).subscribe(()=>{},t=>{this.loggingService.catch("Error in AreaService saveAreaToDb subscription: ",t)})}catch(t){this.loggingService.catch("Error in AreaService saveAreaToDb: ",t)}}getDocumentIdAndOrganizationIdFromAreaAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in AreaService getDocumentIdAndOrganizationIdFromAreaAnnotation: ",t),{}}}updateArea(e,t=!1,i){try{i&&this.setLocationToAreaAnnotation(e),t&&this.updateNotificationsDatabase(e,EN.UPDATED),this.updateAreaToDb(e)}catch(a){this.loggingService.catch("Error in AreaService updateArea: ",a)}}updateAreaToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateAreaToDb","color: green;");try{if(this.domService.updateSelectedAnnotationInMap([e]),this.authService.getUser()&&this.authService.isFeatureAllowed(je.AREA)){let t=JSON.parse(JSON.stringify(e));if(t.position=null,!t?.metadata?.documentId){t?.metadata||(t.metadata={});let l=this.docService.getBaseMetadata("area");t.metadata=h(h({},t?.metadata),l)}let{documentId:i,organizationId:a}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);this.commonDbService.setData({feature:"area",properties:{id:e.annotationId,documentId:i,organizationId:a},data:JSON.parse(JSON.stringify(t))})}}catch(t){this.loggingService.catch("Error in AreaService updateAreaToDb: ",t)}}deleteAreaPinAnnotations(e){try{let t=this.domService.getSelectedAnnotationsMap(),i=this.authService.getUser(),a=[];Object.keys(t??{}).forEach(l=>X(this,null,function*(){let c=t[l];c.type==="area"&&i&&c.from&&(i?.isAdmin||c.from.userId===i.userId)&&a.push(c)})),a?.length&&(this.analyticsService.trackEvent(Y.Events.Area.AREA_DELETE_TRIGGERED,{triggerType:e,annotationId:a.map(l=>l.annotationId).join()}),this.dialog.open(al,{panelClass:"velt-mat-dialog-container",data:{title:"Delete area?",message:"This selected area will be deleted.",yesButton:"Delete",noButton:"Cancel",variant:"area"}}).afterClosed().pipe(ut(1)).subscribe(l=>{l&&(a.forEach(c=>X(this,null,function*(){yield this.deleteAreaPinAnnotation(c)})),setTimeout(()=>{document.querySelectorAll(`[${N.SNIPPYLY_HIGHLIGHT}]`).forEach(d=>{this.domService.removeHighlightFromElement(d)})},100))})),this.domService.resetSelectedAnnotationsMap(!0,"area")}catch(t){this.loggingService.catch("Error in AreaService deleteAreaPinAnnotations: ",t)}}getAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let i={};return Object.values(this.areaAnnotationById$.value??{}).forEach(a=>{a?.metadata?.documentId==t&&a?.metadata?.organizationId==e&&(i[a?.annotationId]=a)}),Object.values(i??{})}catch(i){return this.loggingService.catch("Error in AreaService getAreaAnnotationsByOrganizationIdAndDocumentId:",i),[]}}onDeleteTargetAnnotation(e,t){try{if(this.docService.getDocumentId()&&this.areaAnnotationById$.value){let a=Object.values(this.areaAnnotationById$.value||{}),l;t?l=a.find(c=>c?.annotationId===t):l=a.find(c=>c?.targetAnnotations?.find(d=>d?.annotationId===e)),l&&(l.targetAnnotations=l.targetAnnotations?.filter(c=>c?.annotationId!==e),l.targetAnnotations?.length?this.updateAreaToDb(l):this.deleteAreaPinAnnotation(l))}}catch(i){this.loggingService.catch("Error in AreaService onDeleteTargetAnnotation: ",i)}}deleteAreaPinAnnotation(e){if(this.authService.isFeatureAllowed(je.AREA)&&this.documentPaths?.area&&e?.annotationId){this.updateNotificationsDatabase(e,EN.DELETED),this.analyticsService.trackEvent(Y.Events.Area.AREA_DELETED,{annotationId:e.annotationId});let{documentId:t,organizationId:i}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);return this.commonDbService.deleteData({feature:"area",properties:{id:e.annotationId,documentId:t,organizationId:i}})}else return Promise.resolve()}enableArea(){try{this.areaEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in AreaService enableArea: ",e)}}disableArea(){try{this.areaEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in AreaService disableArea: ",e)}}getAreaEnabled$(){try{return this.areaEnabled$.asObservable()}catch(e){return this.loggingService.catch("Error in AreaService getAreaEnabled$: ",e),ce(!1)}}getAreaEnabled(){try{return this.areaEnabled$.value}catch(e){return this.loggingService.catch("Error in AreaService getAreaEnabled: ",e),!1}}enableAddAreaMode(){this.authService.isFeatureAllowed(je.AREA)?(this.analyticsService.trackEvent(Y.Events.Area.AREA_ADD_MODE_ENABLED),this.addAreaMode$.next(!0)):this.loggingService.catch("Error in AreaService enableAddAreaMode: ","Area feature is not enabled.")}disableAddAreaMode(){this.analyticsService.trackEvent(Y.Events.Area.AREA_ADD_MODE_DISABLED),this.addAreaMode$.next(!1)}addAreaModeChange(){return this.addAreaMode$.asObservable()}getPointsForAreaPinAnnotation(e){let t=[],i=e,a=i?.touches?.length?i.touches[0]?.clientX:i.clientX,l=i?.touches?.length?i.touches[0]?.clientY:i.clientY;return t.push({x:a,y:l}),t.push({x:a+100,y:l+100}),t}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(t){return this.loggingService.catch("Error in AreaService isElementInsideAllowedElements: ",t),!1}}updateNotificationsDatabase(e,t){try{let i={annotationData:e,actionType:t,notificationSource:"area"};this.notificationService.updateNotificationDatabase(i)}catch(i){this.loggingService.catch("Error in AreaService updateNotificationsDatabase: ",i)}}getAreaUrl(e){try{return e?.pageInfo?.areaUrl?e.pageInfo.areaUrl:(e?.pageInfo||(e.pageInfo=ro(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.areaUrl=this.generateAreaUrl(e),this.updateArea(e),e.pageInfo?.areaUrl)}catch(t){this.loggingService.catch("Error in AreaService getAreaUrl: ",t);return}}generateAreaUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(N.URL_PARAMS.TAG_ID),t.searchParams.append(N.URL_PARAMS.TAG_ID,e.annotationId),t.href}generateAreaAnnotationId(){return X(this,null,function*(){try{if(this.docService.getDocumentPaths()?.area){let t=this.commonDbService.generateDocumentId();return yield tp(10),t||""}else return""}catch(e){return this.loggingService.catch("Error in AreaService generateAreaAnnotationId: ",e),""}})}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(Ft),K(st),K($n),K(yn),K(qe),K(Ve),K(eo),K(Vn),K(Lo),K(k),K(mn),K(Ia))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ube=n=>{try{let o={USE_PROFILES:{svg:!0,svgFilters:!0},FORBID_ATTR:["onerror","onload","onclick","onmouseover","onmouseout","onmouseenter","onmouseleave","onmousemove","onmousedown","onmouseup","onwheel","onscroll","onkeydown","onkeyup","onkeypress","onfocus","onblur","onchange","onsubmit","on*"],FORBID_TAGS:["script","style","iframe","object","embed","form"]};return vS.sanitize(n,o)}catch(o){return it.catch("Error in File utils sanitizeSvg: ",o),""}},Vbe=n=>{try{return n.name.split(".").slice(0,-1).join(".")}catch(o){it.catch("Error in File utils getFileName: ",o);return}},IQ=n=>{try{return/(?:\.([^.]+))?$/.exec(n?.name)[1]}catch(o){it.catch("Error in File utils getFileExtension: ",o);return}},Bbe=(n,o)=>{try{let r=n.slice(0,-1,n.type);return new File([r],o+"."+IQ(n),{type:n.type})}catch(r){it.catch("Error in File utils updateFile: ",r);return}};var EQ={mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",wmv:"video/x-ms-wmv",flv:"video/x-flv",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",webm:"video/webm",mkv:"video/x-matroska",m4v:"video/x-m4v",m4a:"audio/x-m4a",aac:"audio/aac","3gp":"video/3gpp","3g2":"video/3gpp2",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",bmp:"image/bmp",svg:"image/svg+xml",webp:"image/webp",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",odt:"application/vnd.oasis.opendocument.text",ods:"application/vnd.oasis.opendocument.spreadsheet",zip:"application/zip",rar:"application/x-rar-compressed",txt:"text/plain",rtf:"application/rtf",html:"text/html",htm:"text/html",csv:"text/csv",ics:"text/calendar",vcf:"text/x-vcard",js:"application/javascript",css:"text/css",json:"application/json",xml:"application/xml",swf:"application/x-shockwave-flash"};var Pp=(()=>{let o=class o{constructor(e,t,i,a,l){this.authService=e,this.configService=t,this.coreActionsService=i,this.loggingService=a,this.attachmentResolverService=l,this.storage=VD();try{this.configService.getApiKey$().subscribe(c=>{this.apiKey=c}),this.authService.getFirebaseConfig$().subscribe(c=>{if(c&&c.firebaseOptions?.storageBucket){this.storage=VD(void 0,c?.firebaseOptions?.storageBucket);let d=this.configService.getProxyConfig();d?.storageHost&&(this.storage.host=d.storageHost)}},c=>{this.loggingService.catch("Error in StorageService constructor: ",c)})}catch(c){this.loggingService.catch("Error in StorageService constructor:",c)}}createAttachment({path:e,file:t}){try{let i=new o1;i.name=t.name;let a=Bbe(t,`${i.attachmentId}_${Vbe(t)}`),l=`${this.apiKey}/${e}/${a?.name}`;return i.bucketPath=l,i.size=t.size,i.type=IQ(t),i?.type&&(i.mimeType=EQ[i?.type]),i}catch(i){return this.loggingService.catch("Error in StorageService createAttachment: ",i),null}}sanitizeSvgFile(e){return X(this,null,function*(){if(e.type===EQ.svg)try{let t=yield e.text(),i=Ube(t);return new File([i],e.name,{type:e.type})}catch(t){return this.loggingService.catch("Error in StorageService sanitizeSvgFile: ",t),e}return e})}uploadAttachmentToStorage(l){return X(this,arguments,function*({attachment:e,file:t,resolve:i,reject:a}){try{let c=BD(this.storage,e.bucketPath),d=xY(c,t,{cacheControl:"public,max-age=3600"});d.on("state_changed",m=>{let u=m.bytesTransferred/m.totalBytes*100},m=>{a(m)},()=>{kY(d.snapshot.ref).then(m=>{e.url=m,i(e)})})}catch(c){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",c),a(c)}})}uploadToResolver(d){return X(this,arguments,function*({file:e,attachment:t,metadata:i,resolve:a,reject:l,scope:c}){try{i.attachmentId=t.attachmentId;let m={attachmentId:t.attachmentId,name:t.name,file:e,metadata:i,mimeType:t.mimeType},u=lt();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:xs.UPLOAD_TO_RESOLVER,source:"internal",payload:{attachment:m,eventType:ko.ATTACHMENT_ADD}});let _=yield this.attachmentResolverService.saveAttachment({attachment:m,eventType:ko.ATTACHMENT_ADD},u,c);_&&_.data?.url?(t.url=_.data?.url,a(t)):l(new Error("Failed to upload attachment to resolver"))}catch(m){this.loggingService.catch("Error in StorageService uploadToResolver: ",m),l(m)}})}uploadFile({path:e,file:t,useAttachmentResolver:i,metadata:a,attachmentScope:l}){return new Promise((c,d)=>X(this,null,function*(){try{if(!this.apiKey)throw new Error("API key not configured");let m=yield this.sanitizeSvgFile(t),u=this.createAttachment({path:e,file:m});if(!u)throw new Error("Attachment not created");i?this.uploadToResolver({file:m,attachment:u,metadata:a,resolve:c,reject:d,scope:l}):this.uploadAttachmentToStorage({attachment:u,file:m,resolve:c,reject:d})}catch(m){this.loggingService.catch("Error in StorageService uploadFile:",m),d(m)}}))}uploadChunk(e,t,i,a){return new Promise((l,c)=>{try{if(a?.useAttachmentResolver){let d=this.createAttachment({path:e,file:t});if(!d){c(new Error("Attachment not created for chunk upload"));return}this.uploadToResolver({file:t,attachment:d,metadata:a.metadata,resolve:m=>l(m.url),reject:c,scope:a.attachmentScope});return}if(this.apiKey){let d=`${this.apiKey}/${e}/${t.name}`,m=BD(this.storage,d),u=xY(m,t,{cacheControl:"public,max-age=3600"});u.on("state_changed",_=>{let I=_.bytesTransferred/_.totalBytes*100},_=>{c(_)},()=>{kY(u.snapshot.ref).then(_=>{l(_)}).catch(_=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${i}:`,_),c(_)})})}else{let d=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",d),c(d)}}catch(d){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${i}: `,d),c(d)}})}downloadAttachment(e){try{if(e.url){let t=new XMLHttpRequest;t.responseType="blob",t.onload=()=>{let i=t.response,a=document.createElement("a"),l=window.URL.createObjectURL(i);a.setAttribute("type","hidden"),a.setAttribute(N.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),a.classList.add("snippyly-overlay-panel"),a.href=l,e?.name&&(a.download=e?.name),document.body.appendChild(a);let c=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});a.dispatchEvent(c),window.URL.revokeObjectURL(l),a.remove()},t.onerror=()=>{window.open(e.url,"_blank")},t.open("GET",e.url),t.send()}}catch(t){this.loggingService.catch("Error in StorageService downloadAttachment: ",t)}}deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:i,attachmentScope:a}){return new Promise((l,c)=>{if(i){let d=lt();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:xs.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:e.attachmentId,metadata:t}}),this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:t},d,a).then(()=>{l(null)}).catch(m=>{c(m)})}else{let d=BD(this.storage,e.bucketPath);yY(d).then(()=>{l(null)}).catch(m=>{l(null)})}})}deleteFileFromPath(e){return new Promise((t,i)=>{let a=BD(this.storage,e);yY(a).then(()=>{t(null)}).catch(l=>{i(l)})})}};o.\u0275fac=function(t){return new(t||o)(K(qe),K(Ft),K(nr),K(k),K(es))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var po=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new _e(N.CommentAnnotationStatusMap),this._customPriorityMap=new _e(N.CommentAnnotationPriorityMap),this._customCategoryMap=new _e(N.CommentCategoryMap);try{let t=sessionStorage.getItem(N.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);t&&this._customPriorityMap.next(JSON.parse(t));let i=sessionStorage.getItem(N.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);i&&this._customStatusMap.next(JSON.parse(i));let a=sessionStorage.getItem(N.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);a&&this._customCategoryMap.next(JSON.parse(a))}catch(t){this.loggingService.catch("Error in CustomFilterService constructor: ",t)}}setCustomStatusFilters(e){try{if(e.length<2){this._customStatusMap.next(N.CommentAnnotationStatusMap),sessionStorage.setItem(N.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(N.CommentAnnotationStatusMap)),this.loggingService.catch("Custom status filters must have at least 2 filters");return}let t={};e.forEach(i=>{t[i.id]=i,i.type||(i.type="ongoing")}),this._customStatusMap.next(t),sessionStorage.setItem(N.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomStatusFilters: ",t)}}setCustomPriorityFilters(e){try{if(e.length<2){this._customPriorityMap.next(N.CommentAnnotationPriorityMap),sessionStorage.setItem(N.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(N.CommentAnnotationPriorityMap)),this.loggingService.catch("Custom priority filters must have at least 2 filters");return}let t={};e.forEach(i=>{t[i.id]=i}),this._customPriorityMap.next(t),sessionStorage.setItem(N.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomPriorityFilters: ",t)}}setCustomCategories(e){try{let t={};e.forEach(i=>{t[i.id]=i}),this._customCategoryMap.next(t),sessionStorage.setItem(N.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomCategories: ",t)}}get customStatusMap$(){return this._customStatusMap.asObservable()}get customPriorityMap$(){return this._customPriorityMap.asObservable()}get customCategoryMap$(){return this._customCategoryMap.asObservable()}get defaultStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([i,a])=>a.type==="default");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService defaultStatus: ",e)}return N.CommentAnnotationStatusMap.OPEN}get resolvedStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([i,a])=>a.type==="terminal");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService resolvedStatus: ",e)}return N.CommentAnnotationStatusMap.OPEN}get ongoingStatuses(){try{let t=Object.entries(this._customStatusMap.value).filter(([i,a])=>a.type==="ongoing");if(t)return t.map(i=>i[1])}catch(e){this.loggingService.catch("Error in CustomFilterService ongoingStatuses: ",e)}return[N.CommentAnnotationStatusMap.IN_PROGRESS]}convertLegacyAnnotationStatus(e){try{if(typeof e.status=="string"||e.status===void 0){let t=Object.entries(this._customStatusMap.value),i=t.find(([a,l])=>l.type==="default");switch(e.status){case"open":i&&(e.status=i[1]);break;case"inProgress":let a=t.find(([c,d])=>d.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let l=t.find(([c,d])=>d.type==="terminal");l&&(e.status=l[1]);break;default:i&&(e.status=i[1]);break}}return e}catch(t){return this.loggingService.catch("Error in CustomFilterService convertLegacyAnnotation: ",t),e}}convertLegacyPriority(e){try{typeof e.priority=="string"&&(e.priority=N.CommentAnnotationPriorityMap[e.priority])}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyPriority: ",t)}return e}convertLegacyCategory(e){try{if(e.commentCategories===void 0||e.commentCategories===null||!Array.isArray(e.commentCategories)||e.commentCategories.length===0)return e;typeof e.commentCategories[0]=="string"&&(e.commentCategories=e.commentCategories.map(t=>N.CommentCategoryMap[t]))}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",t)}return e}};o.\u0275fac=function(t){return new(t||o)(K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var jbe=(()=>{let o=class o{constructor(e,t){this.domService=e,this.loggingService=t,this.keyEventSubject$=new at;try{this.loggingService.log("%c[WB] Creating CLASS: HotkeyService","color: blue;"),this.keyEvent$=this.keyEventSubject$.asObservable().pipe(Zh()),this.domService.onWindowKeydown$().subscribe(i=>{this.keyEventSubject$.next(i)})}catch(i){this.loggingService.catch("Error in HotkeyService constructor: ",i)}}getKeyPressEvent(e,t={}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getKeyPressEvent","color: green;"),this.keyEvent$.pipe(Ge(i=>i?.key===e),Ge(i=>!(!!t?.includeCtrl!==i.ctrlKey||!!t?.includeAlt!==i.altKey||!!t?.includeShift!==i.shiftKey||!!t?.includeMeta!==i.metaKey)),Ge(()=>this.isNoInputFocused()))}catch(i){return this.loggingService.catch("Error in HotkeyService getKeyPressEvent: ",i),new Vt}}isNoInputFocused(){try{let e=document.activeElement;for(;e&&e?.tagName!=="BODY";){if(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e?.isContentEditable)return!1;e=e?.parentElement}return!0}catch(e){return this.loggingService.catch("Error in HotkeyService isNoInputFocused: ",e),!1}}};o.\u0275fac=function(t){return new(t||o)(K(Ve),K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();function LWe(n,o){n&1&&(se(),f(0,"svg",16),D(1,"rect",17)(2,"path",18)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function UWe(n,o){n&1&&(se(),f(0,"svg",16),D(1,"rect",22)(2,"path",23)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function VWe(n,o){if(n&1&&(C(0),f(1,"div",6)(2,"div",7),p(3,LWe,6,0,"svg",8)(4,UWe,6,0,"ng-template",null,1,Be),S(),f(6,"div",9),re(7),R(8,"translate"),D(9,"br"),re(10),R(11,"translate"),S(),f(12,"div",10)(13,"p"),re(14),R(15,"translate"),se(),f(16,"svg",11),D(17,"path",12)(18,"path",13)(19,"path",14)(20,"path",15),S(),re(21),R(22,"translate"),S(),St(),f(23,"p"),re(24),R(25,"translate"),S()()(),b()),n&2){let r=Ee(5),e=s();v(3),g("ngIf",e.darkMode)("ngIfElse",r),v(4),we(" ",F(8,7,"Allow mic permission to")),v(3),we("",F(11,9,"enable your audio")," "),v(4),we(" ",F(15,11,"1. Click the")," "),v(7),we(" ",F(22,13,"page info icon in your browser\u2019s address bar")," "),v(3),we(" ",F(25,15,"2. Turn on Microphone")," ")}}function BWe(n,o){n&1&&(se(),f(0,"svg",16),D(1,"rect",17)(2,"path",24)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function jWe(n,o){n&1&&(se(),f(0,"svg",16),D(1,"rect",22)(2,"path",25)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function $We(n,o){if(n&1&&(C(0),f(1,"div",6)(2,"div",7),p(3,BWe,6,0,"svg",8)(4,jWe,6,0,"ng-template",null,2,Be),S(),f(6,"div",9),re(7),R(8,"translate"),D(9,"br"),re(10),R(11,"translate"),S(),f(12,"div",10)(13,"p"),re(14),R(15,"translate"),se(),f(16,"svg",11),D(17,"path",12)(18,"path",13)(19,"path",14)(20,"path",15),S(),re(21),R(22,"translate"),S(),St(),f(23,"p"),re(24),R(25,"translate"),S()()(),b()),n&2){let r=Ee(5),e=s();v(3),g("ngIf",e.darkMode)("ngIfElse",r),v(4),we(" ",F(8,7,"Allow camera permission")),v(3),we("",F(11,9,"to enable your video")," "),v(4),we(" ",F(15,11,"1. Click the")," "),v(7),we(" ",F(22,13,"page info icon in your browser\u2019s address bar")," "),v(3),we(" ",F(25,15,"2. Turn on Camera")," ")}}var KL=(()=>{let o=class o{constructor(e,t,i,a,l){this.loggingService=e,this.themeService=t,this.elementRef=i,this.matDialogRef=a,this.data=l,this.veltElement=!0,this.darkMode=!0;try{this.loggingService.log("%c[WB] Creating CLASS: DevicePermissionDeniedDialogComponent","color: blue;"),this.type=this.data?.type,[!0,!1].includes(this.data?.darkMode)&&(this.darkMode=this.data?.darkMode)}catch(c){this.loggingService.catch("Error in DevicePermissionDeniedDialogComponent constructor: ",c)}}ngOnDestroy(){}};o.\u0275fac=function(t){return new(t||o)(x(k),x(yt),x(Q),x(ji,8),x(nd,8))},o.\u0275cmp=O({type:o,selectors:[["velt-device-permission-denied-dialog-internal"]],hostVars:1,hostBindings:function(t,i){t&2&&w("data-velt-element",i.veltElement)},inputs:{type:"type"},standalone:!1,decls:5,vars:5,consts:[["devicePermissionDialogRef",""],["defaultAudioIcon",""],["defaultVideoIcon",""],[1,"velt-device-permission-denied-dialog--container",3,"snippylyOverlay","snippylyOverlayZIndex"],[3,"ngSwitch"],[4,"ngSwitchCase"],[1,"velt-device-permission-denied-dialog"],[1,"velt-device-permission-denied-dialog--icon"],["width","61","height","60","viewBox","0 0 61 60","fill","none","xmlns","http://www.w3.org/2000/svg",4,"ngIf","ngIfElse"],[1,"velt-device-permission-denied-dialog--header"],[1,"velt-device-permission-denied-dialog--content"],["width","13","height","12","viewBox","0 0 13 12","fill","none","xmlns","http://www.w3.org/2000/svg",1,"velt-device-permission-denied-dialog--page-info-icon"],["d","M4.375 2.5C4.375 3.53553 3.53553 4.375 2.5 4.375C1.46447 4.375 0.625 3.53553 0.625 2.5C0.625 1.46447 1.46447 0.625 2.5 0.625C3.53553 0.625 4.375 1.46447 4.375 2.5Z","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["d","M5 2.5H12.5","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["d","M0 8.75H7.5","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["d","M11.875 8.75C11.875 9.78553 11.0355 10.625 10 10.625C8.96447 10.625 8.125 9.78553 8.125 8.75C8.125 7.71447 8.96447 6.875 10 6.875C11.0355 6.875 11.875 7.71447 11.875 8.75Z","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["width","61","height","60","viewBox","0 0 61 60","fill","none","xmlns","http://www.w3.org/2000/svg"],["x","0.5","y","4","width","56","height","56","rx","28","fill","white","fill-opacity","0.04"],["d","M23.5026 20.333C23.5026 19.0069 24.0294 17.7352 24.9671 16.7975C25.9048 15.8598 27.1765 15.333 28.5026 15.333C29.8287 15.333 31.1005 15.8598 32.0381 16.7975C32.9758 17.7352 33.5026 19.0069 33.5026 20.333V28.6663C33.5027 29.1599 33.4297 29.6508 33.2859 30.123M29.9526 33.4563C29.2054 33.6828 28.4155 33.7311 27.6463 33.5973C26.8771 33.4636 26.1499 33.1516 25.5229 32.6863C24.8959 32.2211 24.3866 31.6154 24.0358 30.9179C23.685 30.2204 23.5024 29.4504 23.5026 28.6697V27.003M16.8359 28.6663C16.8356 30.7719 17.405 32.8383 18.484 34.6465C19.5629 36.4546 21.111 37.9371 22.9642 38.9366C24.8174 39.9362 26.9066 40.4156 29.0102 40.324C31.1137 40.2324 33.1533 39.5732 34.9126 38.4163M38.2459 35.083C39.5023 33.1791 40.1701 30.9474 40.1659 28.6663M21.8359 46.9997H35.1693M28.5026 40.333V46.9997","stroke","white","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["d","M13.5 17L43.5 47","stroke","currentColor","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["x","36.5","width","24","height","24","rx","12","fill","currentColor"],["d","M48.5 18.99V19M48.5 14V5","stroke","white","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["x","0.5","y","4","width","56","height","56","rx","28","fill","black","fill-opacity","0.04"],["d","M23.5026 20.333C23.5026 19.0069 24.0294 17.7352 24.9671 16.7975C25.9048 15.8598 27.1765 15.333 28.5026 15.333C29.8287 15.333 31.1005 15.8598 32.0381 16.7975C32.9758 17.7352 33.5026 19.0069 33.5026 20.333V28.6663C33.5027 29.1599 33.4297 29.6508 33.2859 30.123M29.9526 33.4563C29.2054 33.6828 28.4155 33.7311 27.6463 33.5973C26.8771 33.4636 26.1499 33.1516 25.5229 32.6863C24.8959 32.2211 24.3866 31.6154 24.0358 30.9179C23.685 30.2204 23.5024 29.4504 23.5026 28.6697V27.003M16.8359 28.6663C16.8356 30.7719 17.405 32.8383 18.484 34.6465C19.5629 36.4546 21.111 37.9371 22.9642 38.9366C24.8174 39.9362 26.9066 40.4156 29.0102 40.324C31.1137 40.2324 33.1533 39.5732 34.9126 38.4163M38.2459 35.083C39.5023 33.1791 40.1701 30.9474 40.1659 28.6663M21.8359 46.9997H35.1693M28.5026 40.333V46.9997","stroke","black","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["d","M42.375 39.2135C42.7034 39.1007 42.9883 38.8881 43.19 38.6054C43.3917 38.3227 43.5001 37.9841 43.5 37.6369V26.3635C43.4998 26.0795 43.4271 25.8003 43.2888 25.5523C43.1504 25.3043 42.9509 25.0958 42.7093 24.9465C42.4677 24.7973 42.192 24.7122 41.9083 24.6994C41.6246 24.6867 41.3424 24.7466 41.0883 24.8735L33.5 28.6669V30.3335V25.3333C33.5 24.4493 33.1488 23.6014 32.5237 22.9763C31.8986 22.3512 31.0507 22 30.1667 22H25.1667M33.5 37V38.6667C33.5 39.5507 33.1488 40.3986 32.5237 41.0237C31.8986 41.6488 31.0507 42 30.1667 42H16.8333C15.9493 42 15.1014 41.6488 14.4763 41.0237C13.8512 40.3986 13.5 39.5507 13.5 38.6667V25.3333C13.5 24.4493 13.8512 23.6014 14.4763 22.9763C15.1014 22.3512 15.9493 22 16.8333 22H18.5","stroke","white","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["d","M42.375 39.2135C42.7034 39.1007 42.9883 38.8881 43.19 38.6054C43.3917 38.3227 43.5001 37.9841 43.5 37.6369V26.3635C43.4998 26.0795 43.4271 25.8003 43.2888 25.5523C43.1504 25.3043 42.9509 25.0958 42.7093 24.9465C42.4677 24.7973 42.192 24.7122 41.9083 24.6994C41.6246 24.6867 41.3424 24.7466 41.0883 24.8735L33.5 28.6669V30.3335V25.3333C33.5 24.4493 33.1488 23.6014 32.5237 22.9763C31.8986 22.3512 31.0507 22 30.1667 22H25.1667M33.5 37V38.6667C33.5 39.5507 33.1488 40.3986 32.5237 41.0237C31.8986 41.6488 31.0507 42 30.1667 42H16.8333C15.9493 42 15.1014 41.6488 14.4763 41.0237C13.8512 40.3986 13.5 39.5507 13.5 38.6667V25.3333C13.5 24.4493 13.8512 23.6014 14.4763 22.9763C15.1014 22.3512 15.9493 22 16.8333 22H18.5","stroke","currentColor","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"]],template:function(t,i){if(t&1&&(f(0,"div",3,0),C(2,4),p(3,VWe,26,17,"ng-container",5)(4,$We,26,17,"ng-container",5),b(),S()),t&2){let a=Ee(1);g("snippylyOverlay",a)("snippylyOverlayZIndex",3e3),v(2),g("ngSwitch",i.type),v(),g("ngSwitchCase","audio"),v(),g("ngSwitchCase","video")}},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}body.velt-pin-dragging[_ngcontent-%COMP%] iframe[_ngcontent-%COMP%]{pointer-events:none!important}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent)}[dark][_nghost-%COMP%]{--velt-green: var(--velt-dark-mode-green);--velt-magenta: var(--velt-dark-mode-magenta);--velt-amber: var(--velt-dark-mode-amber);--velt-purple: var(--velt-dark-mode-purple);--velt-cyan: var(--velt-dark-mode-cyan);--velt-orange: var(--velt-dark-mode-orange);--velt-black: var(--velt-dark-mode-black);--velt-white: var(--velt-dark-mode-white);--velt-gray: var(--velt-dark-mode-gray);--velt-error: var(--velt-dark-mode-error);--velt-error-hover: var(--velt-dark-mode-error-hover);--velt-error-foreground: var(--velt-dark-mode-error-foreground);--velt-error-light: var(--velt-dark-mode-error-light);--velt-error-transparent: var(--velt-dark-mode-error-transparent);--velt-warning: var(--velt-dark-mode-warning);--velt-warning-hover: var(--velt-dark-mode-warning-hover);--velt-warning-foreground: var(--velt-dark-mode-warning-foreground);--velt-warning-light: var(--velt-dark-mode-warning-light);--velt-warning-transparent: var(--velt-dark-mode-warning-transparent);--velt-success: var(--velt-dark-mode-success);--velt-success-hover: var(--velt-dark-mode-success-hover);--velt-success-foreground: var(--velt-dark-mode-success-foreground);--velt-success-light: var(--velt-dark-mode-success-light);--velt-success-transparent: var(--velt-dark-mode-success-transparent);--velt-accent: var(--velt-dark-mode-accent);--velt-accent-text: var(--velt-dark-mode-accent-text);--velt-accent-hover: var(--velt-dark-mode-accent-hover);--velt-accent-foreground: var(--velt-dark-mode-accent-foreground);--velt-accent-light: var(--velt-dark-mode-accent-light);--velt-accent-transparent: var(--velt-dark-mode-accent-transparent);--velt-text-0: var(--velt-dark-mode-text-0);--velt-text-1: var(--velt-dark-mode-text-1);--velt-text-2: var(--velt-dark-mode-text-2);--velt-text-3: var(--velt-dark-mode-text-3);--velt-text-4: var(--velt-dark-mode-text-4);--velt-text-5: var(--velt-dark-mode-text-5);--velt-text-6: var(--velt-dark-mode-text-6);--velt-text-7: var(--velt-dark-mode-text-7);--velt-text-8: var(--velt-dark-mode-text-8);--velt-text-9: var(--velt-dark-mode-text-9);--velt-text-10: var(--velt-dark-mode-text-10);--velt-text-11: var(--velt-dark-mode-text-11);--velt-text-12: var(--velt-dark-mode-text-12);--velt-background-0: var(--velt-dark-mode-background-0);--velt-background-1: var(--velt-dark-mode-background-1);--velt-background-2: var(--velt-dark-mode-background-2);--velt-background-3: var(--velt-dark-mode-background-3);--velt-background-4: var(--velt-dark-mode-background-4);--velt-background-5: var(--velt-dark-mode-background-5);--velt-background-6: var(--velt-dark-mode-background-6);--velt-background-7: var(--velt-dark-mode-background-7);--velt-background-8: var(--velt-dark-mode-background-8);--velt-background-9: var(--velt-dark-mode-background-9);--velt-background-10: var(--velt-dark-mode-background-10);--velt-border-0: var(--velt-dark-mode-border-0);--velt-border-1: var(--velt-dark-mode-border-1);--velt-border-2: var(--velt-dark-mode-border-2);--velt-border-3: var(--velt-dark-mode-border-3);--velt-border-4: var(--velt-dark-mode-border-4);--velt-border-5: var(--velt-dark-mode-border-5);--velt-border-6: var(--velt-dark-mode-border-6);--velt-border-7: var(--velt-dark-mode-border-7);--velt-border-8: var(--velt-dark-mode-border-8);--velt-border-9: var(--velt-dark-mode-border-9);--velt-border-10: var(--velt-dark-mode-border-10);--velt-background-transparent: var(--velt-dark-mode-background-transparent);--velt-border-transparent: var(--velt-dark-mode-border-transparent);--velt-animation-transparent: var(--velt-dark-mode-animation-transparent)} .velt-mat-dialog-container.velt-device-permission-denied-dialog--panel mat-dialog-container .mat-mdc-dialog-surface.mdc-dialog__surface{padding:0;background-color:transparent;box-shadow:none;overflow:unset}.velt-device-permission-denied-dialog[_ngcontent-%COMP%]{display:flex;flex-direction:column;gap:var(--velt-spacing-lg);align-items:center;justify-content:center;padding:4rem;box-sizing:border-box;word-break:break-word;max-width:600px;max-height:400px;text-align:center;background-color:var(--velt-background-0);border-radius:var(--velt-border-radius-2xl);box-shadow:0 calc((4rem + 0px) * var(--velt-base-rem-unit)) calc((4rem + 0px) * var(--velt-base-rem-unit)) calc((-3rem + 0px) * var(--velt-base-rem-unit)) #1f2f461f}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--icon[_ngcontent-%COMP%]{color:var(--velt-error)}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--header[_ngcontent-%COMP%]{font-size:var(--velt-font-size-lg);font-weight:600;line-height:36px;letter-spacing:-.02em;text-align:center;color:var(--velt-text-0)}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--content[_ngcontent-%COMP%]{font-size:var(--velt-font-size-sm);font-weight:400;line-height:21px;text-align:center;color:var(--velt-text-0)}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--content[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--page-info-icon[_ngcontent-%COMP%]{margin-left:var(--velt-spacing-sm);margin-right:var(--velt-spacing-sm);color:var(--velt-error)}"],changeDetection:0});let n=o;return n})();var ym=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.matDialog=t,this.audioPermissionState$=new _e(null),this.videoPermissionState$=new _e(null);try{this.loggingService.log("%c[WB] Creating CLASS: DevicePermissionService","color: blue;"),this.checkPermissions()}catch(i){this.loggingService.catch("Error in DevicePermissionService constructor: ",i)}}checkPermissions(){try{this.loggingService.log("%c[WB] Calling DevicePermissionService FUNCTION: checkPermissions","color: green;"),new hr().browserName!=="Firefox"&&(navigator.permissions.query({name:"microphone"}).then(t=>{this.audioPermissionState$.next(t.state),t.onchange=()=>{this.audioPermissionState$.next(t.state)}}).catch(t=>{}),navigator.permissions.query({name:"camera"}).then(t=>{this.videoPermissionState$.next(t.state),t.onchange=()=>{this.videoPermissionState$.next(t.state)}}).catch(t=>{}))}catch(e){this.loggingService.catch("Error in DevicePermissionService checkPermissions: ",e)}}getPermissionState$(e){try{switch(this.loggingService.log("%c[WB] Calling DevicePermissionService FUNCTION: getPermissionState$","color: green;"),e){case"audio":return this.getAudioPermissionState$();case"video":return this.getVideoPermissionState$();default:return ce(null)}}catch(t){return this.loggingService.catch("Error in DevicePermissionService getPermissionState$: ",t),ce(null)}}getAudioPermissionState$(){return this.audioPermissionState$.asObservable()}getVideoPermissionState$(){return this.videoPermissionState$.asObservable()}openDevicePermissionDeniedDialog(e,t){try{this.loggingService.log("%c[WB] Calling DevicePermissionService FUNCTION: openDevicePermissionDeniedDialog","color: green;"),this.matDialog.open(KL,{panelClass:["velt-device-permission-denied-dialog--panel","velt-mat-dialog-container"],backdropClass:["velt-device-permission-denied-dialog--backdrop","s-background-blur-1"],data:h({type:e},t||{})})}catch(i){this.loggingService.catch("Error in DevicePermissionService openDevicePermissionDeniedDialog: ",i)}}};o.\u0275fac=function(t){return new(t||o)(K(k),K(Lo))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var GWe=()=>["video","screen"];function HWe(n,o){if(n&1&&D(0,"app-recording-preview-steps-dialog-video",4),n&2){let r=s(2);g("componentConfigSignal",r.componentConfigSignal)}}function zWe(n,o){if(n&1&&D(0,"app-recording-preview-steps-dialog-audio",4),n&2){let r=s(2);g("componentConfigSignal",r.componentConfigSignal)}}function WWe(n,o){if(n&1&&(C(0),f(1,"div",2,0),p(3,HWe,1,1,"app-recording-preview-steps-dialog-video",3)(4,zWe,1,1,"app-recording-preview-steps-dialog-audio",3),S(),b()),n&2){let r=o.ngIf,e=Ee(2),t=s();v(),g("snippylyOverlay",e)("snippylyOverlayZIndex",2e3),w("aria-label","Recording preview - "+r.type+" mode")("data-testid",t.componentId),v(2),g("ngIf",xt(6,GWe).includes(r.type)),v(),g("ngIf",r.type==="audio")}}var ZL=(()=>{let o=class o{constructor(e,t,i,a,l,c,d){this.loggingService=e,this.recorderService=t,this.dialog=i,this.devicePermissionService=a,this.dialogRef=l,this.elementRef=c,this.data=d,this.darkMode=!1,this.shadowDom=!0,this.startCountdownFrom=3,this.defaultMediaSourceOptions=lv(),this.recordingCountdownEnabled=!1,this.subscriptions=[],this.veltElement=!0,this.componentId="velt-recording-preview-steps-dialog",this.componentConfigSignal=De({closeDialog:this.closeDialog.bind(this),startCountdown:this.startCountdown.bind(this),toggleAudio:this.toggleAudio.bind(this),toggleVideo:this.toggleVideo.bind(this),toggleSettings:this.toggleSettings.bind(this),cancelCountdown:this.cancelCountdown.bind(this),updateMediaConfig:this.updateMediaConfig.bind(this),handleOverlayClick:this.handleOverlayClick.bind(this),countdownStarted:!1,mediaConfig:{audio:{enabled:!1},video:{enabled:!1}},mediaState:{audio:{enabled:!1},video:{enabled:!1}},type:"video",countdown:this.startCountdownFrom,mediaStream:void 0,isSettingsOpen:!1,darkMode:this.darkMode,shadowDom:this.shadowDom,isExplicitShadowDom:!1});try{this.devicePermissionService.getPermissionState$("video").subscribe(m=>{this.componentConfigSignal.update(u=>(u=y(h({},u),{mediaState:y(h({},u.mediaState),{video:{enabled:m!=="denied"}})}),u))}),this.devicePermissionService.getPermissionState$("audio").subscribe(m=>{this.componentConfigSignal.update(u=>(u=y(h({},u),{mediaState:y(h({},u.mediaState),{audio:{enabled:m!=="denied"}})}),u))}),this.subscriptions.push(this.recorderService.getRecordingCountdownEnabled$().subscribe(m=>{this.recordingCountdownEnabled=m})),this.subscriptions.push(this.recorderService.getRecordingMicEnabled$().subscribe(m=>{m!==null&&(m?this.toggleAudioOn():this.toggleAudioOff())})),d&&(d.type&&this.componentConfigSignal.update(m=>(m=y(h({},m),{type:d.type}),m)),d.recordingCountdown!==void 0&&(this.recordingCountdownEnabled=!!d.recordingCountdown),d.mediaConfig&&(d.mediaConfig?.audio?.enabled&&!d.mediaConfig?.audio?.deviceId&&(d.mediaConfig.audio.deviceId=this.defaultMediaSourceOptions?.selectedAudioDevice?.deviceId),d.mediaConfig?.video?.enabled&&!d.mediaConfig?.video?.deviceId&&(d.mediaConfig.video.deviceId=this.defaultMediaSourceOptions?.selectedVideoDevice?.deviceId),d?.darkMode?this.elementRef.nativeElement.setAttribute("dark",""):this.elementRef.nativeElement.removeAttribute("dark"),this.componentConfigSignal.update(m=>(m=y(h({},m),{shadowDom:d?.shadowDom!==!1,isExplicitShadowDom:!!d?.isExplicitShadowDom,darkMode:d.darkMode||!1}),m)),this.updateMediaConfig(d.mediaConfig)))}catch(m){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent constructor: ",m)}}ngOnInit(){try{this.setupA11yAttributes(),this.componentConfigSignal().type==="screen"&&this.subscriptions.push(this.recorderService.getScreenStream$().subscribe(e=>{e&&e.active&&e.getVideoTracks().some(t=>t.readyState==="live")&&this.componentConfigSignal.update(t=>(t=h({},t),t.mediaConfig.screen={enabled:!0,stream:e},t))}))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngOnInit:",e)}}setupA11yAttributes(){try{let e=this.elementRef.nativeElement;e.setAttribute("data-testid",this.componentId+"-container"),e.setAttribute("role","dialog"),e.setAttribute("aria-label","Recording preview steps dialog")}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent setupA11yAttributes:",e)}}ngOnChanges(e){try{e&&Object.keys(e).forEach(t=>{this.componentConfigSignal.update(i=>(i=y(h({},i),{[t]:e[t].currentValue}),i))})}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngOnChanges: ",t)}}ngAfterViewInit(){try{this.dialogRef.addPanelClass("snippyly-recording-preview-steps-dialog"),this.dialogRef.disableClose=!0}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngAfterViewInit: ",e)}}toggleSettings(e){try{e.stopPropagation(),this.componentConfigSignal.update(t=>(t=y(h({},t),{isSettingsOpen:!t.isSettingsOpen}),t))}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleSettings: ",t)}}toggleAudio(){try{this.componentConfigSignal().mediaConfig.audio||this.componentConfigSignal.update(i=>(i=y(h({},i),{mediaConfig:y(h({},i.mediaConfig),{audio:{enabled:!0}})}),i));let e=!this.componentConfigSignal().mediaConfig.audio?.enabled;this.componentConfigSignal.update(i=>(i=y(h({},i),{mediaConfig:y(h({},i.mediaConfig),{audio:{enabled:e}})}),i));let t=this.componentConfigSignal().mediaStream?.getAudioTracks()[0];t?t.enabled=e:e&&(this.componentConfigSignal.update(i=>(i=y(h({},i),{mediaConfig:y(h({},i.mediaConfig),{audio:y(h({},i.mediaConfig.audio),{deviceId:this.defaultMediaSourceOptions?.selectedAudioDevice?.deviceId})})}),i)),this.updateMediaConfig(this.componentConfigSignal().mediaConfig))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleAudio: ",e)}}toggleAudioOn(){try{this.componentConfigSignal.update(t=>(t=y(h({},t),{mediaConfig:y(h({},t.mediaConfig),{audio:{enabled:!0}})}),t));let e=this.componentConfigSignal().mediaStream?.getAudioTracks()[0];e?e.enabled=!0:(this.componentConfigSignal.update(t=>(t=y(h({},t),{mediaConfig:y(h({},t.mediaConfig),{audio:y(h({},t.mediaConfig.audio),{deviceId:this.defaultMediaSourceOptions?.selectedAudioDevice?.deviceId})})}),t)),this.updateMediaConfig(this.componentConfigSignal().mediaConfig))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleAudioOn: ",e)}}toggleAudioOff(){try{this.componentConfigSignal.update(t=>(t=y(h({},t),{mediaConfig:y(h({},t.mediaConfig),{audio:{enabled:!1}})}),t));let e=this.componentConfigSignal().mediaStream?.getAudioTracks()[0];e&&(e.enabled=!1)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleAudioOn: ",e)}}toggleVideo(){try{this.componentConfigSignal.update(e=>(e=h({},e),e.mediaConfig.video||(e.mediaConfig.video={enabled:!0}),e.mediaConfig.video.enabled=!e.mediaConfig.video.enabled,e.mediaConfig.video.deviceId=this.defaultMediaSourceOptions?.selectedVideoDevice?.deviceId,e)),this.updateMediaConfig(this.componentConfigSignal().mediaConfig)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleVideo: ",e)}}updateMediaConfig(e){try{this.stopMediaStream(),this.getMediaStream(e)}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent updateMediaConfig: ",t)}}getMediaStream(e){try{if(!navigator.mediaDevices){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream: ","No media devices");return}if(!navigator.mediaDevices.getUserMedia){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream: ","No getUserMedia");return}if(e.audio?.enabled||e.video?.enabled){let t=$be(e);navigator.mediaDevices.getUserMedia(t).then(i=>{this.componentConfigSignal.update(a=>(a=y(h({},a),{mediaConfig:e,mediaStream:i}),a))}).catch(i=>{this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream catch: ",i)})}else this.componentConfigSignal.update(t=>(t=y(h({},t),{mediaStream:void 0,mediaConfig:e}),t))}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream: ",t)}}stopMediaStream(){try{this.componentConfigSignal.update(e=>(e=h({},e),e.mediaStream?.getTracks().forEach(t=>{t.stop()}),e.mediaStream=void 0,e))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent stopMediaStream: ",e)}}startCountdown(){return X(this,null,function*(){try{let t=new hr().getBrowserName()==="Firefox",i=null;if(t&&this.componentConfigSignal().type==="screen")try{let a=this.componentConfigSignal().mediaConfig,l=$be(a);Object.keys(l).length>0&&(i=yield navigator.mediaDevices.getUserMedia(l))}catch(a){this.loggingService.catch("Error getting Firefox user media stream:",a),i=null}if(this.componentConfigSignal().type==="screen"){if(!this.componentConfigSignal().mediaConfig.screen?.stream)try{let l=yield navigator.mediaDevices.getDisplayMedia({video:!0,audio:!0});this.componentConfigSignal.update(c=>(c=h({},c),c.mediaConfig.screen={enabled:!0,stream:l},c))}catch(l){this.loggingService.catch("Error getting screen media stream:",l),this.cancelCountdown();return}this.componentConfigSignal.update(l=>(l=h({},l),i&&(l.mediaConfig.audio?.enabled&&(l.mediaConfig.audio.stream=i),l.mediaConfig.video?.enabled&&(l.mediaConfig.video.stream=i)),l)),this.componentConfigSignal().mediaConfig.screen?.stream?.getTracks().forEach(l=>{l&&(l.onended=()=>{this.cancelCountdown()})})}this.recordingCountdownEnabled?(this.componentConfigSignal.update(a=>(a=y(h({},a),{countdownStarted:!0}),a)),this.countdownInterval=setInterval(()=>{this.componentConfigSignal().countdown>1?this.componentConfigSignal.update(a=>(a=y(h({},a),{countdown:a.countdown-1}),a)):this.closeDialog(this.componentConfigSignal().mediaConfig)},1e3)):this.closeDialog(this.componentConfigSignal().mediaConfig)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent startCountdown: ",e)}})}cancelCountdown(){try{if(this.componentConfigSignal.update(e=>(e=y(h({},e),{countdownStarted:!1,countdown:this.startCountdownFrom}),e)),this.clearInterval(),this.componentConfigSignal().type==="screen"){let e=this.componentConfigSignal().mediaConfig.screen?.stream;e&&e.getTracks().forEach(t=>{t.stop()}),this.componentConfigSignal.update(t=>(t=h({},t),t.mediaConfig.screen=void 0,t))}}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent cancelCountdown: ",e)}}closeDialog(e){return X(this,null,function*(){try{this.clearInterval(),e||(this.stopMediaStream(),this.componentConfigSignal.update(t=>(t=h({},t),t.mediaConfig&&(t.mediaConfig.screen?.stream&&(t.mediaConfig.screen.stream.getTracks().forEach(i=>i.stop()),t.mediaConfig.screen.stream=void 0),t.mediaConfig.audio?.stream&&(t.mediaConfig.audio.stream.getTracks().forEach(i=>i.stop()),t.mediaConfig.audio.stream=void 0),t.mediaConfig.video?.stream&&(t.mediaConfig.video.stream.getTracks().forEach(i=>i.stop()),t.mediaConfig.video.stream=void 0)),t))),this.dialogRef.close(e)}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent closeDialog: ",t)}})}handleOverlayClick(e){try{this.componentConfigSignal.update(t=>(t=y(h({},t),{isSettingsOpen:!1}),t)),e.stopPropagation()}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent handleOverlayClick: ",t)}}clearInterval(){try{this.countdownInterval&&(clearInterval(this.countdownInterval),this.countdownInterval=void 0)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent clearInterval: ",e)}}ngOnDestroy(){try{this.clearInterval(),this.stopMediaStream(),this.subscriptions.forEach(e=>{e?.unsubscribe()})}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngOnDestroy: ",e)}}};o.\u0275fac=function(t){return new(t||o)(x(k),x(Un),x(Lo),x(ym),x(ji),x(Q),x(nd,8))},o.\u0275cmp=O({type:o,selectors:[["snippyly-recording-preview-steps-dialog"]],hostVars:1,hostBindings:function(t,i){t&2&&w("data-velt-element",i.veltElement)},inputs:{darkMode:"darkMode",shadowDom:"shadowDom"},standalone:!1,features:[Qe],decls:1,vars:1,consts:[["recordingPreviewDialogRef",""],[4,"ngIf"],["role","dialog","aria-modal","true",3,"snippylyOverlay","snippylyOverlayZIndex"],[3,"componentConfigSignal",4,"ngIf"],[3,"componentConfigSignal"]],template:function(t,i){t&1&&p(0,WWe,5,7,"ng-container",1),t&2&&g("ngIf",i.componentConfigSignal())},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}body.velt-pin-dragging[_ngcontent-%COMP%] iframe[_ngcontent-%COMP%]{pointer-events:none!important}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent)}[dark][_nghost-%COMP%]{--velt-green: var(--velt-dark-mode-green);--velt-magenta: var(--velt-dark-mode-magenta);--velt-amber: var(--velt-dark-mode-amber);--velt-purple: var(--velt-dark-mode-purple);--velt-cyan: var(--velt-dark-mode-cyan);--velt-orange: var(--velt-dark-mode-orange);--velt-black: var(--velt-dark-mode-black);--velt-white: var(--velt-dark-mode-white);--velt-gray: var(--velt-dark-mode-gray);--velt-error: var(--velt-dark-mode-error);--velt-error-hover: var(--velt-dark-mode-error-hover);--velt-error-foreground: var(--velt-dark-mode-error-foreground);--velt-error-light: var(--velt-dark-mode-error-light);--velt-error-transparent: var(--velt-dark-mode-error-transparent);--velt-warning: var(--velt-dark-mode-warning);--velt-warning-hover: var(--velt-dark-mode-warning-hover);--velt-warning-foreground: var(--velt-dark-mode-warning-foreground);--velt-warning-light: var(--velt-dark-mode-warning-light);--velt-warning-transparent: var(--velt-dark-mode-warning-transparent);--velt-success: var(--velt-dark-mode-success);--velt-success-hover: var(--velt-dark-mode-success-hover);--velt-success-foreground: var(--velt-dark-mode-success-foreground);--velt-success-light: var(--velt-dark-mode-success-light);--velt-success-transparent: var(--velt-dark-mode-success-transparent);--velt-accent: var(--velt-dark-mode-accent);--velt-accent-text: var(--velt-dark-mode-accent-text);--velt-accent-hover: var(--velt-dark-mode-accent-hover);--velt-accent-foreground: var(--velt-dark-mode-accent-foreground);--velt-accent-light: var(--velt-dark-mode-accent-light);--velt-accent-transparent: var(--velt-dark-mode-accent-transparent);--velt-text-0: var(--velt-dark-mode-text-0);--velt-text-1: var(--velt-dark-mode-text-1);--velt-text-2: var(--velt-dark-mode-text-2);--velt-text-3: var(--velt-dark-mode-text-3);--velt-text-4: var(--velt-dark-mode-text-4);--velt-text-5: var(--velt-dark-mode-text-5);--velt-text-6: var(--velt-dark-mode-text-6);--velt-text-7: var(--velt-dark-mode-text-7);--velt-text-8: var(--velt-dark-mode-text-8);--velt-text-9: var(--velt-dark-mode-text-9);--velt-text-10: var(--velt-dark-mode-text-10);--velt-text-11: var(--velt-dark-mode-text-11);--velt-text-12: var(--velt-dark-mode-text-12);--velt-background-0: var(--velt-dark-mode-background-0);--velt-background-1: var(--velt-dark-mode-background-1);--velt-background-2: var(--velt-dark-mode-background-2);--velt-background-3: var(--velt-dark-mode-background-3);--velt-background-4: var(--velt-dark-mode-background-4);--velt-background-5: var(--velt-dark-mode-background-5);--velt-background-6: var(--velt-dark-mode-background-6);--velt-background-7: var(--velt-dark-mode-background-7);--velt-background-8: var(--velt-dark-mode-background-8);--velt-background-9: var(--velt-dark-mode-background-9);--velt-background-10: var(--velt-dark-mode-background-10);--velt-border-0: var(--velt-dark-mode-border-0);--velt-border-1: var(--velt-dark-mode-border-1);--velt-border-2: var(--velt-dark-mode-border-2);--velt-border-3: var(--velt-dark-mode-border-3);--velt-border-4: var(--velt-dark-mode-border-4);--velt-border-5: var(--velt-dark-mode-border-5);--velt-border-6: var(--velt-dark-mode-border-6);--velt-border-7: var(--velt-dark-mode-border-7);--velt-border-8: var(--velt-dark-mode-border-8);--velt-border-9: var(--velt-dark-mode-border-9);--velt-border-10: var(--velt-dark-mode-border-10);--velt-background-transparent: var(--velt-dark-mode-background-transparent);--velt-border-transparent: var(--velt-dark-mode-border-transparent);--velt-animation-transparent: var(--velt-dark-mode-animation-transparent)} .velt-mat-dialog-container.snippyly-recording-preview-steps-dialog{max-width:none} .velt-mat-dialog-container.snippyly-recording-preview-steps-dialog mat-dialog-container .mat-mdc-dialog-surface.mdc-dialog__surface{background:transparent;padding:0;margin:0;border-radius:var(--velt-border-radius-lg)}"],changeDetection:0});let n=o;return n})();function $be(n){try{let o={};return n.audio?.enabled&&(o.audio={deviceId:n.audio.deviceId?{exact:n.audio.deviceId}:void 0}),n.video?.enabled&&(o.video={deviceId:n.video.deviceId?{exact:n.video.deviceId}:void 0}),o}catch{return{}}}var oc=(()=>{let o=class o{constructor(e){this.loggingService=e,this.isPipActive$=new _e(!1),this.pipStopRecordingTriggered$=new _e(!1),this.pipPauseRecordingTriggered$=new _e(!1),this.pictureInPicture$=new _e(!1),this.pipClearRecordingTriggered$=new _e(!1)}getPipClearRecordingTriggered$(){return this.pipClearRecordingTriggered$.asObservable()}resetPipClearRecordingTriggered(){this.pipClearRecordingTriggered$.next(!1)}openPictureInPicture(e,t){return X(this,null,function*(){try{if(!this.isPictureInPictureEnabled()||!e||document.pictureInPictureElement||window.documentPictureInPicture?.window)return;if("documentPictureInPicture"in window){yield this.createDocumentPip(e,t);return}if(document.pictureInPictureEnabled){let i=yield this.findVideoElement();if(!i){this.loggingService.warn("No video element found for Picture-in-Picture");return}yield i.requestPictureInPicture(),this.isPipActive$.next(!0);return}}catch(i){this.loggingService.catch("Error in PipService openPictureInPicture:",i)}})}createDocumentPip(e,t){return X(this,null,function*(){try{let i=window.documentPictureInPicture;this.pipWindow=yield i.requestWindow({width:320,height:288}),yield this.addStylesToPip(),yield this.createControlPanelInPip(e,t),this.pipWindow?.addEventListener("unload",()=>{try{this.isPipActive$.next(!1),this.pipWindow=void 0}catch(a){this.loggingService.catch("Error in PipService createDocumentPip unload:",a)}}),this.isPipActive$.next(!0)}catch{this.isPipActive$.next(!1),this.pipWindow=void 0}})}addStylesToPip(){return X(this,null,function*(){try{if(!this.pipWindow)return;this.pipWindow.document.body.style.margin="0",this.pipWindow.document.body.style.padding="0",this.pipWindow.document.body.style.backgroundColor="#000",this.pipWindow.document.body.style.display="flex",this.pipWindow.document.body.style.alignItems="center",this.pipWindow.document.body.style.justifyContent="center"}catch(e){this.loggingService.catch("Error in PipService copyStylesToPip:",e)}})}createControlPanelInPip(e,t){return X(this,null,function*(){if(this.pipWindow)try{let i=this.pipWindow.document.createElement("div");i.style.cssText=`
408
+ `},o.GIF_PATHS={CAT_JAM:"https://firebasestorage.googleapis.com/v0/b/snippyly-sdk-external/o/emojis%2Fcatjam.gif?alt=media&token=9868b4ec-0031-4751-bb2e-47bf0f9d9583"},o.\u0275fac=function(t){return new(t||o)(K(Ve),K(k),K($d))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var vn=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u){this.analyticsService=e,this.authService=t,this.configService=i,this.coreActionsService=a,this.databaseService=l,this.docService=c,this.loggingService=d,this.commonDbService=m,this.usersService=u,this.db=null,this.internalUserContacts$=new _e([]),this.userGlobalContact$=new _e(!1),this.userGroupContact$=new _e(null),this.users$=new _e([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.documentPaths=null,this.userAccessFields$=new _e({}),this.userOrganizationContacts$=new _e([]),this.userFolderContacts$=new _e([]),this.userDocumentContacts$=new _e([]),this.userOrganizationGroups$=new _e([]),this.onContactSelectedSubject$=new at,this.documentAccessType=null,this.atHereEnabled$=new _e(!1),this.atHereLabel$=new _e("here"),this.atHereDescription$=new _e(null),this.contactListScopeForOrganizationUsers$=new _e([bo.ALL]),this.customUserContacts$=new _e(null),this.customUserContactsConfig$=new _e({merge:!1}),this.currentOrganizationUserIAM$=new _e(null),this.userContacts$=new _e([]),this.userSnippylyIdContacts$=new _e(null),this.usersByOrganizationId$=new _e({}),this.temporaryUserIds$=new _e([]),this.usersByOrganizationIdAndDocumentId$=new _e({}),this.usersByOrganizationIdAndFolderId$=new _e({}),this.userById$=new _e({}),this.searchUsersSubject$=new at,this.searchUsersDebounceTime=300,this.pendingSearchPromises=new Map,this.authService.setContactService(this),this.usersService.setContactService(this),this.authService.getUser$().pipe(Se(_=>this.docService.getDocumentPaths$().pipe(ln(I=>{this.documentPaths=I}),ue(()=>_)))).subscribe(_=>X(this,null,function*(){if(this.user=_,_&&this.documentPaths)if(!_?.organizationId)this.getLoggedInUsers$().subscribe(),this.getUserContactsFromDb$(),yield this.migrateLoggedInUserFromEmailToUserIdPath(_),this.setLoggedInUser(_),yield this.moveGlobalContactUserFromEmailToUserIdPath(_),this.updateUserInGlobalContactsIfAvailable(_),_?.groupId&&(yield this.migrateGroupContactsFromEmailToUserIdPath(_?.groupId)),this.checkToSetLoggedInUserInGroupContacts();else{let I=this.userPermissionService?.getCurrentUserPermissions(),A=this.documentPaths.folderId,M=!0;A&&I?.[_?.userId]?.folders?.[A]?.errorCode===mr.PERMISSION_DENIED&&(M=!1),this.getOrganizationContactsFromDb$(),M&&this.getFolderContactsFromDb$(),this.getDocumentContactsFromDb$(),this.getOrganizationGroupsFromDb$(),this.getTemporaryUsers()}else this.getUserContactSubscription?.unsubscribe(),this.getUserContactSubscription=void 0,this.getLoggedInUsersSubscription?.unsubscribe(),this.getLoggedInUsersSubscription=void 0,this.getOrganizationContactsSubscription?.unsubscribe(),this.getOrganizationContactsSubscription=void 0,this.getFolderContactsSubscription?.unsubscribe(),this.getFolderContactsSubscription=void 0,this.getDocumentContactsSubscription?.unsubscribe(),this.getDocumentContactsSubscription=void 0,this.getOrganizationGroupsSubscription?.unsubscribe(),this.getOrganizationGroupsSubscription=void 0}),_=>{this.loggingService.catch("Error in ContactService constructor getUser$: ",_)}),this.databaseService.getDb().pipe(Ge(_=>!!_),ut(1)).subscribe(_=>{_&&(this.db=_)},_=>{this.loggingService.catch("Error in ContactService constructor getDb: ",_)}),this.getOrganizationGroups$().subscribe(_=>{this.authService.setOrganizationUserGroups(_)}),gn([this.getInternalUserContacts$(),this.getCustomUserContacts$(),this.getCustomUserContactsConfig$()]).subscribe(([_,I,A])=>{I?A?.merge?this.userContacts$.next([..._||[],...I||[]]):this.userContacts$.next(I||[]):this.userContacts$.next(_||[])}),this.getUserContacts$().subscribe(_=>{try{_?.forEach(I=>{let A=I?.userSnippylyId||cd(this.configService.getApiKey(),I.userId);A&&this.userSnippylyIdContacts$.next(y(h({},this.userSnippylyIdContacts$.value),{[A]:I}))})}catch{}})}setCommentService(e){try{this.commentService=e}catch(t){this.loggingService.catch("Error in ContactService setCommentService: ",t)}}setUserPermissionService(e){try{this.userPermissionService=e}catch(t){this.loggingService.catch("Error in ContactService setUserPermissionService: ",t)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ContactService","color: green;");try{this.documentPaths=null,this.usersByOrganizationId$.next({}),this.temporaryUserIds$.next([]),this.usersByOrganizationIdAndFolderId$.next({}),this.usersByOrganizationIdAndDocumentId$.next({}),this.userById$.next({}),this.userOrganizationContacts$.next([]),this.userFolderContacts$.next([]),this.userDocumentContacts$.next([]),this.userOrganizationGroups$.next([]),this.userContacts$.next([]),this.userSnippylyIdContacts$.next(null),this.userGlobalContact$.next(!1),this.userGroupContact$.next(null),this.users$.next([]),this.userPersonalContacts=[],this.userGroupContacts=[],this.userGlobalContacts=[],this.users=[],this.currentOrganizationUserIAM$.next(null)}catch(e){this.loggingService.catch("Error in ContactService clearCache: ",e)}}setDocumentAccessType(e){try{this.documentAccessType=e}catch(t){this.loggingService.catch("Error in ContactService setDocumentAccessType: ",t)}}checkIfUserGlobalContact(e){return X(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0}});if(Object.keys(t??{}).length>0)return!0}if(e?.email&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0)return!0}return!1}catch(t){return this.loggingService.catch("Error in ContactService isUserGlobalContact: ",t),!1}})}setLoggedInUser(e){try{e?.userId&&this.documentPaths?.logins&&(this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(y(h({},e),{contacts:void 0})))}),this.setLoggedInUserPrivateContacts(e,e?.contacts))}catch(t){this.loggingService.catch("Error in ContactService setLoggedInUser: ",t)}}migrateLoggedInUserFromEmailToUserIdPath(e){return X(this,null,function*(){try{if(e?.email&&this.documentPaths?.logins){let t=yield this.commonDbService?.getData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let i=t;if(i){if(i?.contacts){let a={};Object.keys(i?.contacts??{})?.forEach(l=>{let c=i.contacts[l];if(c?.userId){let d=It(c?.userId);a[d]=c}}),i.contacts=a}yield this.commonDbService.updateData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))}),yield this.commonDbService.deleteData({feature:"logins",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}})}}}}catch(t){this.loggingService.catch("Error in ContactService migrateLoggedInUserFromEmailToUserIdPath: ",t)}})}addGlobalContact(e){try{e?.userId&&this.documentPaths?.globalContacts&&this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(e))})}catch(t){this.loggingService.catch("Error in ContactService addGlobalContact: ",t)}}getUserAccessFields(){return JSON.parse(JSON.stringify(this.userAccessFields$.value))}getUserAccessFieldsByUserId(e){return this.getUserAccessFields()?.[e]}setUserAccessFields(e){try{let t=this.getUserAccessFields();e.forEach(a=>{t[a.user.userId]=a.accessFields||[]});let i=this.authService.getUser()?.userId;if(i&&t?.[i]?.length){let a=this.userPermissionService?.getCurrentUserPermissions();a&&(a[i]||(a[i]={}),a[i].context={accessFields:t[i]},this.userPermissionService?.setCurrentUserPermissions(a))}this.userAccessFields$.next(JSON.parse(JSON.stringify(t)))}catch(t){this.loggingService.catch("Error in ContactService setUserAccessFields: ",t)}}updateUserInGlobalContactsIfAvailable(e){return X(this,null,function*(){try{if(e?.userId&&this.documentPaths?.globalContacts&&(yield this.checkIfUserGlobalContact(e))){let i=new ra;i.userId=e?.userId,i.userSnippylyId=e?.userSnippylyId,i.email=e?.email,i.name=e?.name,i.photoUrl=e?.photoUrl,this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))})}}catch(t){this.loggingService.catch("Error in ContactService updateUserInGlobalContactsIfAvailable: ",t)}})}moveGlobalContactUserFromEmailToUserIdPath(e){return X(this,null,function*(){try{if(e?.email&&e?.userId&&this.documentPaths?.globalContacts){let t=yield this.commonDbService?.getData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}});if(Object.keys(t??{}).length>0){let i=t;i&&(yield this.commonDbService.updateData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))}),yield this.commonDbService.deleteData({feature:"globalContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.email),skipFirestore:!0}}))}}}catch(t){this.loggingService.catch("Error in ContactService removeUserFromGlobalContactsByEmail: ",t)}})}setLoggedInUserPrivateContacts(e,t){try{if(e?.userId&&this.documentPaths?.logins){let i,a=t?.filter(c=>c?.visibility!=="group"),l=!1;this.authService.getUserOptions()&&(l=!!this.authService.getUserOptions()?.replaceContacts||!!this.authService.getUserOptions()?.replacePrivateContacts),a?.length?(i={},a?.forEach(c=>{if(c?.userId){let d=It(c?.userId);i[d]=c}}),l?this.commonDbService.setData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))}):this.commonDbService.updateData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(i))})):l&&this.commonDbService.deleteData({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",userId:It(e?.userId),skipFirestore:!0}})}}catch(i){this.loggingService.catch("Error in ContactService setLoggedInUserPrivateContacts: ",i)}}migrateGroupContactsFromEmailToUserIdPath(e){return X(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e){let t=yield this.commonDbService?.getData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}});t&&Object.keys(t??{}).forEach(i=>X(this,null,function*(){let a=t[i];a?.email&&a?.userId&&It(a?.email)===i&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:i,skipFirestore:!0}}),yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:It(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}))}))}}catch(t){this.loggingService.catch("Error in ContactService migrateGroupContacts: ",t)}})}checkToSetLoggedInUserInGroupContacts(){return X(this,null,function*(){try{this.user?.groupId&&this.user?.userId&&((yield this.checkIfUserGlobalContact(this.user))||this.docService.getDocumentIam$().pipe(ut(1)).subscribe(t=>X(this,null,function*(){if(this.user?.groupId&&this.user?.userId){let i=!1,a=this.docService.getDocumentAccessType(t);if(!a||a===Hr.PUBLIC)i=!0;else if(a===Hr.RESTRICTED){let l=It(this.user?.userId);if(t?.users?.[l]&&(i=!0),this.user?.email){let c=It(this.user?.email);t?.users?.[c]&&(i=!0)}}if(i){let l=new Is;l.email=this.user.email,l.visibility="group",l.name=this.user.name,l.photoUrl=this.user.photoUrl,l.userId=this.user.userId,(this.authService.getUserOptions()?.replaceContacts||this.authService.getUserOptions()?.replaceGroupContacts)&&(yield this.removeGroupContacts(this.user?.groupId)),this.setLoggedInUserGroupContacts(this.user?.groupId,[l]),this.user?.contacts&&this.user?.groupId&&this.setLoggedInUserGroupContacts(this.user?.groupId,this.user?.contacts)}}})))}catch(e){this.loggingService.catch("Error in ContactService checkToSetLoggedInUserInGroupContacts: ",e)}})}setLoggedInUserGroupContacts(e,t){try{let i=t?.filter(a=>a?.visibility==="group");i?.length&&i.forEach(a=>X(this,null,function*(){if(a?.userId&&e&&this.documentPaths?.groupContacts){if(this.configService?.getSF()&&(yield this.checkIfUserGlobalContact(a)))return;yield this.commonDbService.updateData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:It(a?.userId),skipFirestore:!0},data:JSON.parse(JSON.stringify(a))}),a?.email&&(yield this.commonDbService.deleteData({feature:"groupContactsUser",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,userId:It(a?.email),skipFirestore:!0}}))}}))}catch(i){this.loggingService.catch("Error in ContactService setLoggedInUserGroupContacts: ",i)}}removeGroupContacts(e){return X(this,null,function*(){try{if(this.documentPaths?.groupContacts&&e)return this.commonDbService.deleteData({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",groupId:e,skipFirestore:!0}})}catch(t){this.loggingService.catch("Error in ContactService removeGroupContacts: ",t)}})}mergeUserContacts(){try{let e=[];this.userPersonalContacts&&e.push(...this.userPersonalContacts),this.userGroupContacts&&e.push(...this.userGroupContacts),this.userGlobalContacts&&e.push(...this.userGlobalContacts);let t={};e.forEach(i=>{i?.userId?(!i?.email||!t[i.email])&&(t[i.userId]=i):i?.email&&(!i?.userId||!t[i.userId])&&(t[i.email]=i)}),e=Object.values(t??{}),this.internalUserContacts$.next(e)}catch(e){this.loggingService.catch("Error in ContactService mergeUserContacts: ",e)}}getInternalUserContacts(){return this.internalUserContacts$.value}getInternalUserContacts$(){return this.internalUserContacts$.asObservable()}getUserContacts$(e){try{let{organizationId:t,documentId:i,veltFolderId:a}=e||{};return t&&i?gn([this.usersByOrganizationId$,this.usersByOrganizationIdAndFolderId$,this.usersByOrganizationIdAndDocumentId$,this.userById$,this.customUserContacts$,this.customUserContactsConfig$,this.getContactListScopeForOrganizationUsers$(),this.temporaryUserIds$]).pipe(ue(([l,c,d,m,u,_,I,A])=>{let M={},V=!1;_&&!_?.merge&&(V=!0);let q=Ie=>I.some(he=>Ie.includes(he)),ae=q([bo.ALL,bo.ORGANIZATION])?Object.keys(l?.[t]||{}):[],ye=a?q([bo.ALL,bo.FOLDER])?Object.keys(c?.[t]?.[a]||{}):[]:[],ie=q([bo.ALL,bo.DOCUMENT])?Object.keys(d?.[t]?.[i]||{}):[];if([...ae,...ye||[],...ie,...A].forEach(Ie=>{let he=m?.[Ie];he&&(M[Ie]=he)}),u){let{merge:Ie,options:he}=_||{},{organizationId:Te,documentId:Oe,folderId:Pe}=he||{},$e=Pe?Lr(Pe):void 0;(!Te||Te===t)&&(!Oe||Oe===i)&&(!$e||$e===a)&&(Ie||(M={}),u.forEach(ze=>{ze?.userId&&(M[ze.userId]=ze)}))}return Object.values(M??{})})):this.userContacts$.asObservable().pipe(ue(l=>l))}catch(t){return this.loggingService.catch("Error in ContactService getUserContacts$ metadata: ",t),ce([])}}getUserContactsBySnippylyId$(){return this.userSnippylyIdContacts$.asObservable()}getUserBySnippylyId(e){return this.userSnippylyIdContacts$.value?.[e]}getAtHereLabel(){return this.atHereLabel$.asObservable()}getAtHereDescription(){return this.atHereDescription$.asObservable()}getUserContactsFromDb$(){this.getUserContactSubscription||(this.getUserContactSubscription=this.authService.getUser$().pipe(Ge(e=>!!e),Se(e=>this.docService.getDocumentPaths$().pipe(Ge(t=>!!t),ln(t=>{this.documentPaths=t}),ue(()=>e))),Se(e=>{if(this.userGroupContacts=[],this.userPersonalContacts=[],!e)return ce();if(!this.documentPaths)return ce();let t=[];return t.push(this.commonDbService.dbListener({feature:"allGlobalContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ue(i=>i?.data),ln(i=>{i?(this.userGlobalContacts=Object.values(i??{}),this.userGlobalContacts?.find(a=>a.userId===this.user?.userId)?this.userGlobalContact$.next(!0):this.userGlobalContact$.next(!1)):(this.userGlobalContacts=[],this.userGlobalContact$.next(!1))}))),t.push(this.commonDbService.dbListener({feature:"groupContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,groupId:e?.groupId}}).pipe(ue(i=>i?.data),ln(i=>{i?(this.userGroupContacts=Object.values(i??{}),this.userGroupContacts?.find(a=>a?.userId===this.user?.userId)?this.userGroupContact$.next(!0):this.userGroupContact$.next(!1)):(this.userGroupContacts=[],this.userGroupContact$.next(!1))}))),t.push(this.commonDbService.dbListener({feature:"allLoginContacts",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,userId:It(e?.userId)}}).pipe(ue(i=>i?.data),ln(i=>{i?this.userPersonalContacts=Object.values(i??{}):this.userPersonalContacts=[]}))),No(...t).pipe(zo(this.authService.getUser$().pipe(Ge(i=>!i))))})).subscribe(()=>{this.mergeUserContacts()},e=>{this.loggingService.catch("Error in ContactService getUserContacts$ subscription: ",e)}))}addUserContact(e){try{this.user?.organizationId||this.user?.groupId&&(e.visibility="group",this.setLoggedInUserGroupContacts(this.user?.groupId,[e]))}catch(t){this.loggingService.catch("Error in ContactService addUserContact: ",t)}}isUserGlobalContact$(){return this.userGlobalContact$.asObservable().pipe(_t(Kt))}isUserGlobalContact(){return this.userGlobalContact$.value}isUserGroupContact$(){return this.userGroupContact$.asObservable()}isUserGroupContact(){return this.userGroupContact$.value}getLoggedInUsers$(){return this.getLoggedInUsersSubscription||(this.getLoggedInUsersSubscription=this.authService.getUser$().pipe(Se(e=>e?this.documentPaths?e?.userId&&this.documentPaths?.logins?this.commonDbService.dbListener({feature:"allLogins",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ue(t=>t?.data),ln(t=>{t?this.users=Object.values(t??{}):this.users=[]})):(this.users=[],ce()):ce():ce())).subscribe(()=>{this.users$.next(this.users)},e=>{this.loggingService.catch("Error in ContactService getLoggedInUsers$ subscription: ",e)})),this.users$.asObservable()}getUsersMap$(){return this.authService.getUser$().pipe(Se(e=>e?.organizationId?this.userById$.pipe(ue(t=>{let i={};return Object.values(t||{}).forEach(a=>{a?.userSnippylyId&&(i[a?.userSnippylyId]=a)}),i})):this.users$.pipe(ue(t=>{let i={};return t.forEach(a=>{i[a.userSnippylyId]=a}),i}))))}getUserByEmail$(e){return this.users$.pipe(ue(t=>t.find(i=>i.email===e)))}getUserByEmail(e){return this.users?.find(t=>t.email===e)}getContactByEmail(e){return this.getInternalUserContacts().find(t=>t.email===e)}getUserByUserId$(e){return this.users$.pipe(ue(t=>t.find(i=>i.userId===e)))}getUserGroupContacts(){return this.userGroupContacts}getTemporaryUsers(){try{let e=this.authService.getUser();this.docService.getOrganizationConfig$().pipe(Ge(t=>!!t),ue(t=>t?.organizationId)).subscribe(t=>X(this,null,function*(){if(t&&e){let i=((yield this.commonDbService?.queryData({feature:"allPermissionsUsers",properties:{organizationId:t,useCollectionGroup:!1,isCollection:!0,firestoreQuery:[ft("expiresAt",">",new Date().getTime())]}}))??[]).filter(a=>a?.userId!==e?.userId);if(i?.length){let a=i.map(m=>m?.userId),l=lt(),c=ks.GET_TEMPORARY_USERS;this.coreActionsService.triggerAction(tt.USER_RESOLVER,{event:Y.Events.Resolver.USER_RESOLUTION_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:l,moduleName:c,methodName:vi.GET_TEMPORARY_USERS,source:"internal",payload:{userIds:a}});let d=yield this.usersService.resolveUsers({userIds:a,uniqueId:l,moduleName:c});if(d){let m={};Object.entries(d).forEach(([_,I])=>{m[_]=I}),this.userById$.next(h(h({},this.userById$.value),m));let u=new Set([...this.temporaryUserIds$.value,...Object.keys(m)]);this.temporaryUserIds$.next(Array.from(u))}}}}))}catch(e){this.loggingService.catch("Error in ContactService getTemporaryUsers: ",e)}}searchUsers(e){return X(this,null,function*(){try{if(!e||typeof e!="string"||!e.trim())return[];let t=e.trim();return this.searchUsersDebounced$||(this.searchUsersDebounced$=this.searchUsersSubject$.pipe(Qr(this.searchUsersDebounceTime),_t(),Se(i=>co(this.performSearch(i)).pipe(ue(a=>({searchText:i,results:a})),Xn(a=>(this.loggingService.catch("Error in ContactService performSearch: ",a),ce({searchText:i,results:[]})))))),this.searchUsersDebounced$.subscribe({next:({searchText:i,results:a})=>{Array.from(this.pendingSearchPromises.keys()).forEach(d=>{if(d!==i){let m=this.pendingSearchPromises.get(d);m&&(m.forEach(({resolve:u})=>u([])),this.pendingSearchPromises.delete(d))}});let c=this.pendingSearchPromises.get(i);c&&(c.forEach(({resolve:d})=>d(a)),this.pendingSearchPromises.delete(i))},error:i=>{this.pendingSearchPromises.forEach(a=>{a.forEach(({reject:l})=>l(i))}),this.pendingSearchPromises.clear()}})),new Promise((i,a)=>{this.pendingSearchPromises.has(t)||this.pendingSearchPromises.set(t,[]),this.pendingSearchPromises.get(t).push({resolve:i,reject:a}),this.searchUsersSubject$.next(t)})}catch(t){return this.loggingService.catch("Error in ContactService searchUsers: ",t),[]}})}performSearch(e){return X(this,null,function*(){try{let t=this.docService.getOrganizationConfig()?.organizationId;if(!t)return[];let i=this.documentPaths?.veltFolderId,a=this.docService.getDocumentIds().map(q=>q?.documentId),l=e.toLowerCase().trim(),c=l+"\uF8FF",d=[],m=a?.filter(q=>!!q)||[],u=m.length>0,_=!!i;if(u){let q=[];for(let ye=0;ye<m.length;ye+=20)q.push(m.slice(ye,ye+20));q.forEach(ye=>{let ie=[ft("documentIds","array-contains-any",ye),ft("viewerDocumentIds","array-contains-any",ye)],ge=[ft("organizationIds","array-contains-any",[t]),ft("viewerOrganizationIds","array-contains-any",[t]),...ie];_&&ge.push(ft("folderIds","array-contains-any",[i]),ft("viewerFolderIds","array-contains-any",[i])),d.push(this.commonDbService.queryData({feature:"allDocumentUsers",properties:{organizationId:t,isCollection:!0,useCollectionGroup:!1,useQuery:!0,firestoreQuery:[yr(q0(...ge),ft("user.name_lowercase",">=",l),ft("user.name_lowercase","<",c)),hm(10)]}}).catch(()=>[])),d.push(this.commonDbService.queryData({feature:"allDocumentUsers",properties:{organizationId:t,isCollection:!0,useCollectionGroup:!1,useQuery:!0,firestoreQuery:[yr(q0(...ge),ft("user.email_lowercase",">=",l),ft("user.email_lowercase","<",c)),hm(10)]}}).catch(()=>[]))})}let I=yield Promise.all(d),A=[];I.forEach(q=>{q&&Array.isArray(q)?q.forEach(ae=>{ae&&ae.user&&ae.user.userId&&A.push(ae)}):q&&typeof q=="object"&&Object.values(q).forEach(ye=>{ye&&ye.user&&ye.user.userId&&A.push(ye)})});let M=new Map;A.forEach(q=>{let ae=q.user?.userId;ae&&!M.has(ae)&&M.set(ae,q)});let V=Array.from(M.values());return this.setResolvedUsers(V,!0),V}catch(t){return this.loggingService.catch("Error in ContactService performSearch: ",t),[]}})}setResolvedUsers(e,t=!1){try{if(e?.length){let i=[],a=[],l=[],c=this.docService.getOrganizationConfig()?.organizationId,d=this.documentPaths?.veltFolderId,m=this.docService.getDocumentIds().map(I=>I?.documentId);e.forEach(I=>{this.userById$.value[I?.user?.userId]||(c&&I?.organizationIds?.includes(c)&&!i.find(A=>A?.user?.userId===I?.user?.userId)&&i.push(I),d&&I?.folderIds?.includes(d)&&!a.find(A=>A?.user?.userId===I?.user?.userId)&&a.push(I),m?.some(A=>I?.documentIds?.includes(A))&&!l.find(A=>A?.user?.userId===I?.user?.userId)&&l.push(I))}),i?.length&&this.setUserOrganizationContacts(i,c,t),a?.length&&this.setUserFolderContacts(a,t),l?.length&&this.setUserDocumentContacts(l,t);let _=[...i,...a,...l].filter((I,A,M)=>A===M.findIndex(V=>V.user.userId===I.user.userId));_?.length&&(this.setUserAccessFields(_),this.mergeOrganizationAndDocumentContacts())}}catch(i){this.loggingService.catch("Error in ContactService setResolvedUsers: ",i)}}getOrganizationContactsFromDb$(){try{this.getOrganizationContactsSubscription||(this.getOrganizationContactsSubscription=this.authService.getUser$().pipe(Se(e=>e?.organizationId?ce(e).pipe(Se(t=>this.docService.getOrganizationConfig$().pipe(Ge(i=>!!i),ue(()=>t))),Se(t=>this.usersService.getResolveOrganizationUsers$().pipe(Ge(i=>i),ue(()=>t))),Se(t=>{let i=this.docService.getOrganizationConfig()?.organizationId;return this.setUserOrganizationContacts([],i),t?i?this.commonDbService.dbListener({feature:"allOrganizationUsers",properties:{organizationId:i,isCollection:!0,useQuery:!0,firestoreQuery:[yr(q0(ft("organizationIds","array-contains-any",[i]),ft("viewerOrganizationIds","array-contains-any",[i]))),uo("id"),...this.commentService?.getPaginatedContactList()?[hm(10)]:[]]}}).pipe(ue(a=>a?.data),Se(a=>this.commentService?.getPaginatedContactList()&&!Object.values(a??{}).find(l=>l?.user?.userId===this.authService.getUser()?.userId)?co(this.commonDbService.queryData({feature:"allOrganizationUsers",properties:{organizationId:i,isCollection:!0,useQuery:!0,firestoreQuery:[yr(q0(ft("organizationIds","array-contains-any",[i]),ft("viewerOrganizationIds","array-contains-any",[i])),ft("user.userId","==",this.authService.getUser()?.userId))]}})).pipe(ue(l=>{if(l&&l.length>0){let c=l[0],d=c?.user?.userId||c?.id;if(d&&a){let m=It(d);return y(h({},a),{[m]:c})}}return a})):ce(a)),ue(a=>{if(a){typeof a=="object"&&(a?.undefined&&delete a.undefined,a?.null&&delete a.null);let l=Object.values(a??{});this.setUserAccessFields(l),this.setUserOrganizationContacts(l,i)}else this.setUserOrganizationContacts([],i)})):ce():ce()}),Se(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserOrganizationContacts([]),ce()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getOrganizationContactsFromDb$ subscription: ",e)}))}catch{}}getFolderContactsFromDb$(){try{this.getFolderContactsSubscription||(this.getFolderContactsSubscription=this.authService.getUser$().pipe(Se(e=>e?ce(e).pipe(Se(t=>this.docService.getOrganizationConfig$().pipe(Ge(i=>!!i),ue(()=>t))),Se(t=>this.usersService.getResolveFolderUsers$().pipe(Ge(i=>i),ue(()=>t))),Se(t=>{let i=this.docService.getOrganizationConfig()?.organizationId;if(this.setUserFolderContacts([]),!t)return ce();if(!this.commonDbService.shouldUseFirestore())return ce();if(!this.documentPaths?.veltFolderId)return ce();let a=ce([]);return a=this.commonDbService.dbListener({feature:"allFolderUsers",properties:{organizationId:i,folderId:this.documentPaths?.veltFolderId,isCollection:!0,useQuery:!0,firestoreQuery:[yr(q0(ft("folderIds","array-contains-any",[this.documentPaths?.veltFolderId]),ft("viewerFolderIds","array-contains-any",[this.documentPaths?.veltFolderId]))),uo("id"),...this.commentService?.getPaginatedContactList()?[hm(10)]:[]]}}).pipe(ue(l=>l?.data)),a.pipe(ue(l=>{if(l){typeof l=="object"&&(l?.undefined&&delete l.undefined,l?.null&&delete l.null);let c=Object.values(l??{});this.setUserAccessFields(c),this.setUserFolderContacts(c)}else this.setUserFolderContacts([])}))}),Se(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserFolderContacts([]),ce()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getFolderContactsFromDb$ subscription: ",e)}))}catch{}}getDocumentContactsFromDb$(){try{this.getDocumentContactsSubscription||(this.getDocumentContactsSubscription=this.authService.getUser$().pipe(Se(e=>e?ce(e).pipe(Se(t=>this.docService.getDocumentPaths$().pipe(Ge(i=>!!i),ln(i=>{this.documentPaths=i}),ue(()=>t))),Se(t=>this.usersService.getResolveDocumentUsers$().pipe(Ge(i=>i),ue(()=>t))),Se(t=>(this.setUserDocumentContacts([]),t?this.documentPaths?this.docService.getDocumentIds$().pipe(Se(i=>{let a=i?.length>0?i.map(m=>m.documentId):[this.documentPaths?.documentId??""];if(a.some(m=>!m)||!this.documentPaths)return ce();let l=ce([]),c={isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(c.documentId=a?.length?a[0]:void 0,c.organizationId=this.documentPaths?.organizationId);let d=[];for(let m=0;m<a.length;m+=N.LISTENER_BATCH_SIZE)d.push(a.slice(m,m+N.LISTENER_BATCH_SIZE));return l=gn(d.map(m=>this.commonDbService.dbListener({feature:"allDocumentUsers",properties:y(h({},c),{firestoreQuery:[yr(q0(ft("documentIds","array-contains-any",m),ft("viewerDocumentIds","array-contains-any",m))),uo("id"),...this.commentService?.getPaginatedContactList()?[hm(10)]:[]]})}).pipe(la()))).pipe(ue(m=>Na(m)?.data)),l.pipe(ue(m=>{if(m){typeof m=="object"&&(m?.undefined&&delete m.undefined,m?.null&&delete m.null);let u=Object.values(m??{});this.setUserAccessFields(u),this.setUserDocumentContacts(u)}else this.setUserDocumentContacts([])}))})):ce():ce())),Se(()=>this.getContactListScopeForOrganizationUsers$())):(this.setUserDocumentContacts([]),ce()))).subscribe(()=>{this.mergeOrganizationAndDocumentContacts()},e=>{this.loggingService.catch("Error in ContactService getDocumentContactsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationContacts(e,t,i=!0){try{let a=e.find(c=>c.user.userId===this.user?.userId);a&&this.setCurrentOrganizationUserIAM(a);let l=e.map(c=>c.user)?.filter(c=>!this.userOrganizationContacts$.value.find(d=>d.userId===c.userId));if(this.userOrganizationContacts$.next([...this.userOrganizationContacts$.value,...l]),i&&this.usersService.setUserByIds(l),t){let c={};c[t]={};let d={};e.forEach(u=>{c[t][u.user.userId]=u,d[u.user.userId]=u.user}),this.userById$.next(h(h({},this.userById$.value),d));let m=this.usersByOrganizationId$.value?.[t];m&&(c[t]=h(h({},m),c[t])),this.usersByOrganizationId$.next(y(h({},this.usersByOrganizationId$.value),{[t]:c[t]}))}else this.usersByOrganizationId$.next({})}catch(a){this.loggingService.catch("Error in ContactService setUserOrganizationContacts: ",a)}}getUserOrganizationContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(Se(()=>this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.ORGANIZATION])?this.userOrganizationContacts$.asObservable():ce([])))}getUserOrganizationContacts(){return this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.ORGANIZATION])?this.userOrganizationContacts$.value:[]}setUserFolderContacts(e,t=!0){try{let i=e?.map(d=>d?.user)?.filter(d=>!this.userFolderContacts$.value.find(m=>m.userId===d.userId));this.userFolderContacts$.next([...this.userFolderContacts$.value,...i]),t&&this.usersService.setUserByIds(i);let a=this.usersByOrganizationIdAndFolderId$.value||{},l=h({},a),c={};e?.forEach(d=>{let{organizationId:m}=d?.metadata||{};m&&(l[m]||(l[m]={}),d.folderIds?.forEach(u=>{l[m][u]||(l[m][u]={}),l[m][u]=y(h({},l[m][u]),{[d.user.userId]:d}),c[d.user.userId]=d.user}))}),this.userById$.next(h(h({},this.userById$.value),c)),this.usersByOrganizationIdAndFolderId$.next(l)}catch(i){this.loggingService.catch("Error in ContactService updateUserFolderContacts: ",i)}}getUserFolderContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(Se(()=>this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.FOLDER])?this.userFolderContacts$.asObservable():ce([])))}getUserFolderContacts(){return this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.FOLDER])?this.userFolderContacts$.value:[]}setUserDocumentContacts(e,t=!0){try{let i=e?.map(d=>d?.user)?.filter(d=>!this.userDocumentContacts$.value.find(m=>m.userId===d.userId));this.userDocumentContacts$.next([...this.userDocumentContacts$.value,...i]),t&&this.usersService.setUserByIds(i);let a=this.usersByOrganizationIdAndDocumentId$.value||{},l=h({},a),c={};e?.forEach(d=>{let{organizationId:m}=d?.metadata||{};m&&(l[m]||(l[m]={}),d.documentIds?.forEach(u=>{l[m][u]||(l[m][u]={}),l[m][u]=y(h({},l[m][u]),{[d.user.userId]:d}),c[d.user.userId]=d.user}))}),this.userById$.next(h(h({},this.userById$.value),c)),this.usersByOrganizationIdAndDocumentId$.next(l)}catch(i){this.loggingService.catch("Error in ContactService updateUserDocumentContacts: ",i)}}getUserDocumentContacts$(){return this.getContactListScopeForOrganizationUsers$().pipe(Se(()=>this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.DOCUMENT])?this.userDocumentContacts$.asObservable():ce([])))}getUserDocumentContacts(){return this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.DOCUMENT])?this.userDocumentContacts$.value:[]}setCurrentOrganizationUserIAM(e){try{this.currentOrganizationUserIAM$.next(JSON.parse(JSON.stringify(e)))}catch(t){this.loggingService.catch("Error in ContactService setCurrentOrganizationUserIAM: ",t)}}getCurrentOrganizationUserIAM$(){return this.currentOrganizationUserIAM$.asObservable().pipe(_t(Kt))}getCurrentOrganizationUserIAM(){return this.currentOrganizationUserIAM$.value}mergeOrganizationAndDocumentContacts(){try{this.mergeContactsDebounceTimer&&clearTimeout(this.mergeContactsDebounceTimer),this.mergeContactsDebounceTimer=setTimeout(()=>{this.executeMergeContacts()},200)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}executeMergeContacts(){try{let e=this.getContactListScopeForOrganizationUsers(),t=[];e.includes(bo.ALL)?t=[...this.getUserOrganizationContacts(),...this.getUserFolderContacts(),...this.getUserDocumentContacts()]:e.includes(bo.ORGANIZATION)?t=[...this.getUserOrganizationContacts()]:e.includes(bo.FOLDER)?t=[...this.getUserFolderContacts()]:e.includes(bo.DOCUMENT)&&(t=[...this.getUserDocumentContacts()]);let i=[...new Map(t.filter(a=>a?.userId).map(a=>[a.userId,a])).values()];this.internalUserContacts$.next(i)}catch(e){this.loggingService.catch("Error in ContactService mergeOrganizationAndDocumentContacts: ",e)}}getOrganizationGroupsFromDb$(){try{this.getOrganizationGroupsSubscription||(this.getOrganizationGroupsSubscription=this.authService.getUser$().pipe(Se(e=>e?.organizationId?ce(e).pipe(Se(t=>this.docService.getOrganizationConfig$().pipe(Ge(i=>!!i),ue(()=>t))),Se(t=>{if(this.setUserOrganizationGroups([]),!t)return ce();let i=this.docService.getOrganizationConfig(),a=i?.organizationId,l=i?.clientOrganizationId??"";if(!a)return ce();let c=t.userId??"";return co(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:l})??Promise.resolve({})).pipe(Se(d=>c&&l&&d?.[c]?.organization?.[l]?.errorCode===mr.PERMISSION_DENIED?ce():this.commonDbService.dbListener({feature:"allOrganizationGroups",properties:{organizationId:a,isCollection:!0}}).pipe(ue(m=>m?.data),ue(m=>{m?(typeof m=="object"&&(m?.undefined&&delete m.undefined,m?.null&&delete m.null),this.setUserOrganizationGroups(Object.values(m??{}))):this.setUserOrganizationGroups([])}))))})):(this.setUserOrganizationGroups([]),ce()))).subscribe(()=>{},e=>{this.loggingService.catch("Error in ContactService getOrganizationGroupsFromDb$ subscription: ",e)}))}catch{}}setUserOrganizationGroups(e){try{this.userOrganizationGroups$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setUserOrganizationGroups: ",t)}}onContactSelected(e){try{if(e?.userId){let t=!!this.getUserDocumentContacts().find(a=>a.userId===e.userId),i=!!this.getUserOrganizationContacts().find(a=>a.userId===e.userId);switch(this.documentAccessType){case Hr.RESTRICTED:if(!t){let a={contact:e,isOrganizationContact:i,isDocumentContact:t,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(a)}break}}else{let t={contact:e,isOrganizationContact:!1,isDocumentContact:!1,documentAccessType:this.documentAccessType};this.onContactSelectedSubject$.next(t)}}catch(t){this.loggingService.catch("Error in ContactService onContactSelected: ",t)}}onContactSelected$(){return this.onContactSelectedSubject$.asObservable()}getOrganizationGroups$(){return this.getContactListScopeForOrganizationUsers$().pipe(Se(()=>this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.ORGANIZATION_USER_GROUP])?this.userOrganizationGroups$.asObservable():ce([])))}enableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{atHereEnabled:!0}}),this.atHereEnabled$.value===!0)return;this.atHereEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ContactService enableAtHere: ",e)}}setAtHereLabel(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{atHereLabel:e}}),e&&this.atHereLabel$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setAtHereLabel: ",t)}}setAtHereDescription(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{atHereDescription:e}}),e&&this.atHereDescription$.next(e)}catch(t){this.loggingService.catch("Error in ContactService setAtHereDescription: ",t)}}disableAtHere(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{atHereEnabled:!1}}),this.atHereEnabled$.value===!1)return;this.atHereEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ContactService disableAtHere: ",e)}}getAtHereEnabled$(){return this.getContactListScopeForOrganizationUsers$().pipe(Se(()=>this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.DOCUMENT])?this.atHereEnabled$.asObservable():ce(!1)))}getAtHereEnabled(){return this.checkContactListScopeForOrganizationUsers([bo.ALL,bo.DOCUMENT])?this.atHereEnabled$.value:!1}updateContactListScopeForOrganizationUsers(e){try{this.contactListScopeForOrganizationUsers$.next(e)}catch(t){this.loggingService.catch("Error in ContactService updateContactListScopeForOrganizationUsers: ",t)}}getContactListScopeForOrganizationUsers$(){return this.contactListScopeForOrganizationUsers$.asObservable()}getContactListScopeForOrganizationUsers(){return this.contactListScopeForOrganizationUsers$.value}checkContactListScopeForOrganizationUsers(e){return this.getContactListScopeForOrganizationUsers().some(t=>e.includes(t))}updateContactList(e,t){return X(this,null,function*(){try{this.analyticsService.trackEvent(Y.Events.Contact.UPDATE_CONTACT_LIST_TRIGGERED,{contactsCount:e?.length,config:t}),this.usersService.setUserByIds(e),this.customUserContacts$.next(e),this.customUserContactsConfig$.next(t)}catch(i){this.loggingService.catch("Error in CommentService updateContactList: ",i)}})}convert(e){try{if(e?.options){let{documentId:t,organizationId:i}=this.docService.getServerId(e?.options);e.options=y(h({},e?.options),{documentId:t,organizationId:i})}return this}catch(t){return this.loggingService.catch("Error in ContactService convert: ",t),this}}getContactList$(){try{return this.authService.getUser$().pipe(Se(e=>e?gn([this.userOrganizationContacts$.asObservable(),this.userFolderContacts$.asObservable(),this.userDocumentContacts$.asObservable(),this.userOrganizationGroups$.asObservable(),this.customUserContacts$.asObservable()]).pipe(ue(([t,i,a,l,c])=>{let d={};d.organizationUsers=t?.map(u=>this.convertToClientUser(u)),d.folderUsers=i?.map(u=>this.convertToClientUser(u)),d.documentUsers=a?.map(u=>this.convertToClientUser(u)),d.updatedContactList=c?.map(u=>this.convertToClientUser(u));let m=[];return l?.forEach(u=>{let _=this.convertToClientUserGroup(u,d.organizationUsers||[]);_&&m.push(_)}),d.userGroups=m,d}),_t(Kt)):ce(null)),Xn(e=>(this.loggingService.catch("Error in ContactService getContactList$: ",e),ce(null))))}catch(e){return this.loggingService.catch("Error in ContactService getContactList$: ",e),ce(null)}}convertToClientUserGroup(e,t){try{let i={groupId:e?.metadata?.clientGroupId,groupName:e?.metadata?.groupName,users:[]},a={};return t?.forEach(l=>{if(l?.userId){let c=It(l.userId);a[c]=l}}),Object.keys(e?.users??{}).forEach(l=>{a[l]&&i.users?.push(a[l])}),i}catch(i){return this.loggingService.catch("Error in ContactService convertToClientUserGroup: ",i),null}}convertToClientUser(e){try{return e&&(e=JSON.parse(JSON.stringify(e)),e?.clientGroupId&&(e.groupId=e.clientGroupId,delete e.clientGroupId),e?.clientOrganizationId&&(e.organizationId=e.clientOrganizationId,delete e.clientOrganizationId),e?.userSnippylyId&&delete e.userSnippylyId),e}catch(t){return this.loggingService.catch("Error in ContactService convertToClientUser: ",t),e}}getCustomUserContacts(){return this.customUserContacts$.value}getCustomUserContacts$(){return this.customUserContacts$.asObservable()}getCustomUserContactsConfig(){return this.customUserContactsConfig$.value}getCustomUserContactsConfig$(){return this.customUserContactsConfig$.asObservable()}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(qe),K(Ft),K(nr),K($n),K(st),K(k),K(yn),K(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Vn=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m){this.analyticsService=e,this.authService=t,this.contactService=i,this.databaseService=a,this.docService=l,this.configService=c,this.loggingService=d,this.commonDbService=m,this.documentIAM$=new _e(null),this.workspaceIAM$=new _e(null),this.roles$=new _e([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(Ge(u=>!!u),ut(1)).subscribe(u=>{u&&(this.getUser(),this.getDocumentPaths())},u=>{this.loggingService.catch("Error in CommentService getDb subscription: ",u)}),this.getRole$().pipe(ut(1)).subscribe(u=>{this.authService?.getUser()&&!u&&this.analyticsService.trackEvent(Y.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(u=>{u?.accessType&&this.contactService.setDocumentAccessType(u.accessType)})}catch(u){this.loggingService.catch("Error in IamService constructor: ",u)}}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(Ge(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(Ge(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 AN;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(Xn(e=>ce(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(ue(e=>!!e),_t())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(ue(e=>e?.length?e:N.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(ue(e=>e?.features),Se(e=>this.getRole$().pipe(ue(t=>(t===Uo.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(Se(()=>this.documentIAM$.pipe(Ge(t=>!!t),Se(()=>this.workspaceIAM$.pipe(ue(()=>e===this.getRole()))))))}catch(t){return this.loggingService.catch("Error in IamService hasRole$: ",t),ce(!1)}}getRole$(){try{return this.authService.getUser$().pipe(Se(()=>this.configService.getSF$()),Se(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():ce(null)),Se(()=>this.configService.getSF()?this.documentIAM$.pipe(Ge(e=>!!e),_t(Kt)):ce(null)),Se(()=>this.workspaceIAM$.pipe(_t(Kt))),ue(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),ce(null)}}getRole(){try{let e=this.configService.getSF();if(e&&this.contactService.isUserGlobalContact())return Uo.ADMIN;if(!e)return this.user?.isAdmin?Uo.ADMIN:Uo.COMMENTER;let t=null,i;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?Hr.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||Hr.PUBLIC:null){case Hr.PUBLIC:i=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),i||(i=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=i?.role?.name||Uo.COMMENTER;break;case Hr.RESTRICTED:i=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),i||(i=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=i?.role?.name||null;break;default:break}return t}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(ue(e=>e===Uo.ADMIN),_t())}isUserAdmin(){try{return this.getRole()===Uo.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,t){try{if(e||t){let i;return e&&(i=this.documentIAM$.value?.users?.[It(e)]),!i&&t&&(i=this.documentIAM$.value?.users?.[It(t)]),i}else return}catch(i){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",i)}}getUserFromWorkspaceIAM(e,t){try{if(e||t){let i;return e&&(i=this.workspaceIAM$.value?.users?.[It(e)]),!i&&t&&(i=this.workspaceIAM$.value?.users?.[It(t)]),i}else return}catch(i){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",i)}}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(qe),K(vn),K($n),K(st),K(Ft),K(k),K(yn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var hS="public",Ia=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_){this.authService=e,this.docService=t,this.loggingService=i,this.commonDbService=a,this.usersService=l,this.commentUtilsService=c,this.coreActionsService=d,this.functions=m,this.configService=u,this.contactService=_,this.currentUserPermissions$=new _e(null),this.permissionsCache$=new _e(null),this.permissionProvider$=new _e(null),this.requestKeyedPermissionsCache=new Map,this.inFlightPermissionsRequests=new Map,this.permissionsCacheGeneration=0,this.REVOKE_DELAY_MS=3e3,this.pendingRevokeRequests=new Map,this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="";try{this.docService.setUserPermissionService(this),this.authService.setUserPermissionService(this),this.commentUtilsService.setUserPermissionService(this),this.contactService.setUserPermissionService(this)}catch(I){this.loggingService.catch("Error in UserPermissionService constructor:",I)}}ngOnDestroy(){try{this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(e){this.loggingService.catch("Error in UserPermissionService ngOnDestroy:",e)}}collectRevokeRequest(e,t,i,a,l,c){try{return e.find(m=>m.resourceId===i&&m.type===a&&m.organizationId===l&&m.userId===c)?(t.push({userId:c,resourceId:i,organizationId:l,type:a,hasAccess:!1}),e.filter(m=>!(m.resourceId===i&&m.type===a&&m.organizationId===l&&m.userId===c))):e}catch(d){return this.loggingService.catch("Error in UsersPermissionService collectRevokeRequest:",d),e}}hasUserContextAccess({userId:e,accessFields:t}){try{if(!this.getIsContextEnabled()||t.includes(N.DEFAULT_VELT_CONTEXT))return!0;let i=this.contactService.getUserAccessFieldsByUserId(e);return i?t.every(a=>i.includes(a)):!0}catch(i){return this.loggingService.catch("Error in UserPermissionService hasUserContextAccess:",i),!1}}organizationDetails(e){return X(this,null,function*(){try{let t=yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{organizationId:e,suppressError:!0}});return t&&t?.errorCode?{errorCode:mr.PERMISSION_DENIED,error:!0}:t&&!t?.metadata?{errorCode:mr.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(t){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",t),{errorCode:mr.SOMETHING_WENT_WRONG,error:!0}}})}documentDetails(i){return X(this,arguments,function*({documentId:e,organizationId:t}){try{let a=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:t,suppressError:!0}});if(a&&a?.errorCode)return{errorCode:mr.PERMISSION_DENIED,error:!0};if(a&&!a?.metadata)return{errorCode:mr.DOES_NOT_EXIST,error:!0};let l=this.docService.getDocumentMetadata(e)??{};this.docService.setDocumentMetadata(e,h(h({},l),a?.metadata??{}));let c,d=a?.metadata?.veltFolderId;if(d)try{c=(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:d,organizationId:t}}))?.folderIamConfig?.accessType}catch(m){this.loggingService.catch("Error fetching folder accessType for document:",m)}return c||(c=a?.docIamConfig?.accessType),{error:!1,accessType:c}}catch(a){return this.loggingService.catch("Error in UserPermissionService documentDetails:",a),{errorCode:mr.SOMETHING_WENT_WRONG,error:!0}}})}folderDetails(i){return X(this,arguments,function*({folderId:e,organizationId:t}){try{let a=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:t,suppressError:!0}});return a&&a?.errorCode?{errorCode:mr.PERMISSION_DENIED,error:!0}:a&&!a?.metadata?{errorCode:mr.DOES_NOT_EXIST,error:!0}:{error:!1,accessType:a?.folderIamConfig?.accessType}}catch(a){return this.loggingService.catch("Error in UserPermissionService folderDetails:",a),{errorCode:mr.SOMETHING_WENT_WRONG,error:!0}}})}getUserPermissions(e){return X(this,null,function*(){let t=this.permissionsCacheGeneration;try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getUserPermissions]",void 0,void 0,!0),{};let i=this.authService.getUser()?.userId,a=this.extractResourceIds(e);if(!a.clientOrganizationId||!a.organizationId)return this.loggingService.catch("Client organization id or organization id not set during getUserPermissions",void 0,void 0,!0),{};let l=yield this.validateResources(a),[c,d]=yield this.fetchUserPermissionsFromDB(a),m=this.authService.getUser()?.userId;if(i!==m)return{};let u=this.buildPermissionsResponse(a,l,c,d);if(Object.keys(u).length>0){if(!e)this.setCurrentUserPermissions(u);else if(this.permissionsCacheGeneration===t){let _=this.buildPermissionsCacheKey(e);_!==null&&this.requestKeyedPermissionsCache.set(_,JSON.parse(JSON.stringify(u)))}}return u}catch(i){return this.loggingService.catch("Error in UserPermissionService getUserPermissions:",i),{}}})}getUserPermissionsFromCacheOrFetch(e){return X(this,null,function*(){try{if(!e)return yield this.getUserPermissions(e);let t=this.buildPermissionsCacheKey(e);if(t===null)return yield this.getUserPermissions(e);let i=this.permissionsCacheGeneration,a=this.requestKeyedPermissionsCache.get(t);if(a)return JSON.parse(JSON.stringify(a));let l=this.inFlightPermissionsRequests.get(t);if(l){let m=yield l;return this.permissionsCacheGeneration!==i?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(m))}let c=this.getUserPermissions(e);this.inFlightPermissionsRequests.set(t,c),c.finally(()=>{this.inFlightPermissionsRequests.get(t)===c&&this.inFlightPermissionsRequests.delete(t)}).catch(()=>{});let d=yield c;return this.permissionsCacheGeneration!==i?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(d))}catch(t){return this.loggingService.catch("Error in UserPermissionService getUserPermissionsFromCacheOrFetch:",t),{}}})}clearRequestKeyedPermissionsCache(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService clearRequestKeyedPermissionsCache:",e)}}invalidateAllPermissionsState(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService invalidateAllPermissionsState:",e)}}buildPermissionsCacheKey(e){try{let t={};return Object.keys(e).sort().forEach(i=>{let a=e[i];a!==void 0&&(t[i]=Array.isArray(a)?[...a].sort():a)}),t.__userId=this.authService.getUser()?.userId??null,JSON.stringify(t)}catch(t){return this.loggingService.catch("Error in UserPermissionService buildPermissionsCacheKey:",t),null}}extractResourceIds(e){let t=this.docService.getDocumentPaths(),i=this.docService.getDocumentIds();if(e){let c=e.organizationId??t?.clientOrganizationId;return{folderIds:e.folderIds??[],documentIds:e.documentIds??[],clientOrganizationId:c,organizationId:c?ba(c):void 0}}let a=t?.clientOrganizationId;return{folderIds:t?.folderId?[t.folderId]:[],documentIds:i.map(c=>c.clientDocumentId),clientOrganizationId:a,organizationId:a?ba(a):void 0}}validateResources(e){return X(this,null,function*(){let{folderIds:t,documentIds:i,organizationId:a,clientOrganizationId:l}=e,c=[],d=[],m=t.length>0||i.length>0;a&&!m&&(c.push(this.organizationDetails(a)),d.push({id:l??"",type:"organization"})),t.forEach(A=>{c.push(this.folderDetails({folderId:Lr(A),organizationId:a??""})),d.push({id:A,type:"folder"})}),i.forEach(A=>{c.push(this.documentDetails({documentId:mi(A),organizationId:a??""})),d.push({id:A,type:"document"})});let[u,_]=yield Promise.all([Promise.allSettled(c),this.getDefaultDocumentAccessType()]),I=this.processValidationResults(u,d);return y(h({},this.suppressResolverGrantedFailures(I,l)),{defaultDocumentAccessType:_})})}suppressResolverGrantedFailures(e,t){try{let i=this.authService.getUser()?.userId;if(!i)return e;let a=this.getPermissionsCache()??[];if(a.length===0)return e;let l=(u,_,I)=>a.some(A=>A?.userId===i&&A?.resourceId===u&&A?.type===_&&(!I||A?.organizationId===I)&&A?.hasAccess===!0),c=e.failedDocumentIds.filter(u=>!(u.errorCode===mr.PERMISSION_DENIED&&l(u.id,bi.DOCUMENT,t))),d=e.failedFolderIds.filter(u=>!(u.errorCode===mr.PERMISSION_DENIED&&l(u.id,bi.FOLDER,t))),m=e.failedOrganizationId;return m&&m.errorCode===mr.PERMISSION_DENIED&&t&&l(t,bi.ORGANIZATION,t)&&(m=void 0),{failedFolderIds:d,failedDocumentIds:c,failedOrganizationId:m,folderAccessTypes:e.folderAccessTypes,documentAccessTypes:e.documentAccessTypes}}catch(i){return this.loggingService.catch("Error in UserPermissionService suppressResolverGrantedFailures:",i),e}}getDefaultDocumentAccessType(){return X(this,null,function*(){try{return(yield this.commonDbService?.getData({feature:"apiKeyMetadata",properties:{}}))?.defaultDocumentAccessType}catch(e){this.loggingService.catch("Error fetching defaultDocumentAccessType:",e);return}})}processValidationResults(e,t){let i=[],a=[],l,c={},d={};for(let m=0;m<e.length;m++){let u=e[m],_=t[m];if(u.status==="rejected"||u.status==="fulfilled"&&u.value.error){let A=u.status==="fulfilled"?u.value.errorCode??mr.SOMETHING_WENT_WRONG:mr.SOMETHING_WENT_WRONG,M={id:_.id,errorCode:A};switch(_.type){case"organization":if(l=M,A===mr.DOES_NOT_EXIST)throw new Error(`Organization with id '${_.id}' does not exist`);break;case"folder":i.push(M);break;case"document":a.push(M);break}}else if(u.status==="fulfilled")switch(_.type){case"folder":u.value.accessType&&(c[_.id]=u.value.accessType);break;case"document":u.value.accessType&&(d[_.id]=u.value.accessType);break}}return{failedFolderIds:i,failedDocumentIds:a,failedOrganizationId:l,folderAccessTypes:c,documentAccessTypes:d}}fetchUserPermissionsFromDB(e){return X(this,null,function*(){let{folderIds:t,documentIds:i,organizationId:a}=e,l=[this.authService.getUser()?.userId??""],c=[...t.map(u=>Lr(u)),...i.map(u=>mi(u)),a??""],[d,m]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:l,organizationId:a}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:l,organizationId:a,resourceIds:c})]);return[d.status==="fulfilled"?d.value:[],m.status==="fulfilled"?m.value:[]]})}buildPermissionsResponse(e,t,i,a){let{folderIds:l,documentIds:c,clientOrganizationId:d,organizationId:m}=e,{failedFolderIds:u,failedDocumentIds:_,failedOrganizationId:I}=t,A={};return this.processRegularUserPermissions(A,i,l,c,d??"",m??"",u,_,I,t.folderAccessTypes,t.documentAccessTypes,t.defaultDocumentAccessType),this.ensureCurrentUserFailuresRecorded(A,d??"",u,_,I,t.folderAccessTypes,t.documentAccessTypes,t.defaultDocumentAccessType),this.processTemporaryUserPermissions(A,a),this.processContextPermissions(A),A}processContextPermissions(e){try{let t=this.authService.getUser()?.userId;if(t){let i=this.contactService.getUserAccessFieldsByUserId(t);i?.length&&(e[t]||(e[t]={}),e[t].context={accessFields:i})}}catch(t){this.loggingService.catch("Error in UserPermissionService processContextPermissions:",t);return}}processRegularUserPermissions(e,t,i,a,l,c,d,m,u,_,I,A){for(let M of t)for(let V of M)V?.user?.userId&&(e[V.user.userId]=y(h({},i.length&&{folders:this.buildFolderPermissions(i,V,d,_,A)}),{documents:this.buildDocumentPermissions(a,V,m,I,A),organization:{[l]:this.buildOrganizationPermission(c,V,u)}}))}ensureCurrentUserFailuresRecorded(e,t,i,a,l,c,d,m){try{let u=this.authService.getUser()?.userId;if(!u)return;let _=!!l&&!!t,I=(i?.length??0)>0,A=(a?.length??0)>0;if(!_&&!I&&!A)return;if(e[u]||(e[u]={}),_&&(e[u].organization||(e[u].organization={}),e[u].organization[t]||(e[u].organization[t]={error:this.getErrorMessage(l.errorCode,"organization"),errorCode:l.errorCode})),I){e[u].folders||(e[u].folders={});for(let M of i)e[u].folders[M.id]||(e[u].folders[M.id]=h({error:this.getErrorMessage(M.errorCode,"folder"),errorCode:M.errorCode},M.errorCode===mr.PERMISSION_DENIED&&{accessType:c[M.id]??m??hS}))}if(A){e[u].documents||(e[u].documents={});for(let M of a)e[u].documents[M.id]||(e[u].documents[M.id]=h({error:this.getErrorMessage(M.errorCode,"document"),errorCode:M.errorCode},M.errorCode===mr.PERMISSION_DENIED&&{accessType:d[M.id]??m??hS}))}}catch(u){this.loggingService.catch("Error in UserPermissionService ensureCurrentUserFailuresRecorded:",u)}}getErrorMessage(e,t){try{switch(this.loggingService.log(`Error in UserPermissionService getErrorMessage: ${e} ${t}`),e){case mr.DOES_NOT_EXIST:return`${t} does not exist`;case mr.PERMISSION_DENIED:return`User does not have access to ${t}`;case mr.SOMETHING_WENT_WRONG:return"Something went wrong";default:return"Something went wrong"}}catch(i){return this.loggingService.catch("Error in UserPermissionService getErrorMessage:",i),"Something went wrong"}}buildFolderPermissions(e,t,i,a,l){return e.reduce((c,d)=>{let m=i.find(u=>u.id===d);return m?c[d]=h({error:this.getErrorMessage(m.errorCode,"folder"),errorCode:m.errorCode},m.errorCode===mr.PERMISSION_DENIED&&{accessType:a[d]??l??hS}):c[d]={accessRole:t.viewerFolderIds?.includes(Lr(d))?Yc.VIEWER:Yc.EDITOR,accessType:a[d]??l??hS},c},{})}buildDocumentPermissions(e,t,i,a,l){return e.reduce((c,d)=>{let m=i.find(u=>u.id===d);return m?c[d]=h({error:this.getErrorMessage(m.errorCode,"document"),errorCode:m.errorCode},m.errorCode===mr.PERMISSION_DENIED&&{accessType:a[d]??l??hS}):c[d]={accessRole:t.viewerDocumentIds?.includes(mi(d))?Yc.VIEWER:Yc.EDITOR,accessType:a[d]??l??hS},c},{})}buildOrganizationPermission(e,t,i){return i?{error:this.getErrorMessage(i.errorCode,"organization"),errorCode:i.errorCode}:{accessRole:t.viewerOrganizationIds?.includes(e)?Yc.VIEWER:Yc.EDITOR}}processTemporaryUserPermissions(e,t){for(let i of t)if(i?.userId)switch(this.ensureUserPermissionStructure(e,i.userId),i.type){case"folder":this.addTemporaryFolderPermission(e,i);break;case"document":this.addTemporaryDocumentPermission(e,i);break;case"organization":this.addTemporaryOrganizationPermission(e,i);break}}ensureUserPermissionStructure(e,t){e[t]||(e[t]={})}addTemporaryFolderPermission(e,t){let{userId:i,resourceId:a,role:l,expiresAt:c}=t;e[i].folders||(e[i].folders={}),e[i].folders[a]={accessRole:l??Yc.EDITOR,expiresAt:c}}addTemporaryDocumentPermission(e,t){let{userId:i,resourceId:a,role:l,expiresAt:c}=t;e[i].documents||(e[i].documents={}),e[i].documents[a]={accessRole:l??Yc.EDITOR,expiresAt:c}}addTemporaryOrganizationPermission(e,t){let{userId:i,resourceId:a,role:l,expiresAt:c}=t;e[i].organization||(e[i].organization={}),e[i].organization[a]={accessRole:l??Yc.EDITOR,expiresAt:c}}hasEditAccess({organizationId:e,folderId:t,documentId:i}){try{let a=!0,l=this.getCurrentUserPermissionsWithServerIds(),c=this.authService.getUser()?.userId??"";return l&&(e&&typeof e=="string"&&l?.[c]?.organization?.[e]&&(l?.[c]?.organization?.[e]?.accessRole===Yc.VIEWER||l?.[c]?.organization?.[e]?.errorCode===mr.PERMISSION_DENIED)&&(a=!1),t&&typeof t=="string"&&l?.[c]?.folders?.[t]&&(l?.[c]?.folders?.[t]?.accessRole===Yc.VIEWER||l?.[c]?.folders?.[t]?.errorCode===mr.PERMISSION_DENIED)&&(a=!1),i&&typeof i=="string"&&l?.[c]?.documents?.[i]&&(l?.[c]?.documents?.[i]?.accessRole===Yc.VIEWER||l?.[c]?.documents?.[i]?.errorCode===mr.PERMISSION_DENIED)&&(a=!1)),a}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(_t(Kt))}getCurrentUserPermissions(){return this.currentUserPermissions$.value}refactorPermissionsWithServerIds(e){try{let t=JSON.parse(JSON.stringify(e??{})),i=this.authService.getUser()?.userId??"";if(t?.[i]){let a=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(t?.[i]?.organization?.[a]){let l=ba(a);t[i].organization&&(t[i].organization[l]=t[i].organization[a],delete t[i].organization[a])}t?.[i]?.folders&&(t[i].folders=Object.fromEntries(Object.entries(t?.[i]?.folders??{}).map(([l,c])=>[Lr(l),c]))),t?.[i]?.documents&&(t[i].documents=Object.fromEntries(Object.entries(t?.[i]?.documents??{}).map(([l,c])=>[mi(l),c])))}return t}catch(t){return this.loggingService.catch("Error in UsersPermissionService refactorPermissionsWithServerIds:",t),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(ue(e=>this.refactorPermissionsWithServerIds(e)),_t(Kt))}getCurrentUserPermissionsWithServerIds(){return this.refactorPermissionsWithServerIds(this.currentUserPermissions$.value)}setCurrentUserPermissions(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCurrentUserPermissions","color: green;");let t=null;e&&(t=JSON.parse(JSON.stringify(e))),this.currentUserPermissions$.next(t)}catch(t){this.loggingService.catch("Error in UsersPermissionService setCurrentUserPermissions:",t)}}getIsContextEnabled(){return this.loggingService.log("%c[WB] Calling FUNCTION: getIsContextEnabled","color: green;"),this.permissionProvider$.value?.isContextEnabled??!1}setPermissionProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setPermissionProvider","color: green;"),this.permissionProvider$.next(e)}catch(t){this.loggingService.catch("Error in UsersPermissionService setPermissionProvider:",t)}}get isRevokeAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===s1.DOCUMENT_UNSET)??!1}get isRevokeAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===s1.USER_LOGOUT)??!1}get isRevokeOrganizationAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===s1.USER_LOGOUT&&e.revokeOrganizationAccess)??!1}get isRevokeOrganizationAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===s1.DOCUMENT_UNSET&&e.revokeOrganizationAccess)??!1}getPermissionProviderRetryConfig(){return this.permissionProvider$.value?.retryConfig??{retryCount:0,retryDelay:0}}revokeAccessOnUserLogout(){return X(this,null,function*(){let e=lt();try{if(this.isRevokeAccessOnUserLogoutEnabled){let t=[],i=this.authService.getUser()?.userId??"";if((this.getPermissionsCache()??[]).forEach(l=>{l.userId===i&&l.hasAccess&&(l.type===bi.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&t.push(y(h({},l),{hasAccess:!1})):t.push(y(h({},l),{hasAccess:!1})))}),t.length>0){this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_FORMED,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:t}}),this.setPermissionsCache([]),this.clearRequestKeyedPermissionsCache(),this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_TRIGGERED,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:t}});let l=yield this.revokeAccess({requests:t,userId:this.authService.getUser()?.userId??""});l.success?this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:l,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:l,success:!1,statusCode:500}}})}}}catch(t){this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{error:t}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnUserLogout:",t)}})}getRevokeKey(e){try{return`${e.userId}_${e.resourceId}_${e.type}_${e.organizationId}`}catch(t){return this.loggingService.catch("Error in UsersPermissionService getRevokeKey:",t),""}}cancelPendingRevokes(e){try{e.forEach(t=>{let i=this.getRevokeKey({userId:t.userId,resourceId:t.resource.id,type:t.resource.type,organizationId:t.resource.organizationId});this.pendingRevokeRequests.has(i)&&this.pendingRevokeRequests.delete(i)}),this.pendingRevokeRequests.size===0&&this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(t){this.loggingService.catch("Error in UsersPermissionService cancelPendingRevokes:",t)}}flushPendingRevokes(){return X(this,null,function*(){let e=this.pendingRevokeUniqueId,t=this.pendingRevokeUserId;try{let i=Array.from(this.pendingRevokeRequests.values());if(this.pendingRevokeRequests.clear(),this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="",i.length===0)return;let a=this.getPermissionsCache()??[];i.forEach(d=>{a=a.filter(m=>!(m.resourceId===d.resourceId&&m.type===d.type&&m.organizationId===d.organizationId&&m.userId===d.userId))}),this.setPermissionsCache(a);let l=this.docService.getDocContext(),c=yield this.revokeAccess({requests:i,userId:t,currentContext:l});c.success?this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:c,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:c,success:!1,statusCode:500}}})}catch(i){this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:no.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:i}}),this.loggingService.catch("Error in UsersPermissionService flushPendingRevokes:",i)}})}revokeAccessOnDocumentUnset(a){return X(this,arguments,function*({documentIds:e,folderId:t,context:i}){let l=lt();try{if(this.isRevokeAccessOnDocumentUnsetEnabled){let c=[],d=this.docService.getOrganizationConfig()?.clientOrganizationId??"",m=this.authService.getUser()?.userId??"",u=this.getPermissionsCache()??[];e.forEach(_=>{u=this.collectRevokeRequest(u,c,_.clientDocumentId,bi.DOCUMENT,d,m)}),t&&(u=this.collectRevokeRequest(u,c,t,bi.FOLDER,d,m)),d&&this.isRevokeOrganizationAccessOnDocumentUnsetEnabled&&(u=this.collectRevokeRequest(u,c,d,bi.ORGANIZATION,d,m)),i&&this.getIsContextEnabled()&&cF({input:i}).forEach(I=>{let A=JSON.stringify(I.access);u=this.collectRevokeRequest(u,c,A,bi.CONTEXT,d,m)}),this.setPermissionsCache(u),c.length>0&&(this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_FORMED,timestamp:new Date().getTime(),uniqueId:l,methodName:no.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:c}}),this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_TRIGGERED,timestamp:new Date().getTime(),uniqueId:l,methodName:no.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:c}}),c.forEach(_=>{this.pendingRevokeRequests.set(this.getRevokeKey(_),_)}),this.pendingRevokeUniqueId=l,this.pendingRevokeUserId=m,this.pendingRevokeTimeoutId&&clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=setTimeout(()=>this.flushPendingRevokes(),this.REVOKE_DELAY_MS))}}catch(c){this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:l,methodName:no.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:c}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnDocumentUnset:",c)}})}getAccess(i){return X(this,arguments,function*({requests:e,userId:t}){let a=Yr(this.functions,Zr({url:On?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield wl({methodName:"getAccess",data:{type:"getAccess",data:e,metadata:{retryConfig:this.getPermissionProviderRetryConfig()}},getSdkProxy:a,userId:t})})}revokeAccess(a){return X(this,arguments,function*({requests:e,userId:t,currentContext:i}){let l=Yr(this.functions,Zr({url:On?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield wl({methodName:"revokeAccess",data:{type:"revokeAccess",data:e,metadata:h({retryConfig:this.getPermissionProviderRetryConfig()},i?.access&&{currentContext:i})},getSdkProxy:l,userId:t})})}onResourceAccessRequired(c){return X(this,arguments,function*({requests:e,uniqueId:t,methodName:i,userId:a,fromCache:l=!0}){try{if(!e?.length)return;let d=[],m=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&l&&(e.forEach(u=>{let _=m?.find(I=>I.resourceId===u.resource.id&&I.type===u.resource.type&&I.userId===u.userId&&I.organizationId===u.resource.organizationId);_&&d.push(_)}),d.length>0&&(e=e.filter(u=>!d.find(_=>_.resourceId===u.resource.id&&_.type===u.resource.type&&_.userId===u.userId&&_.organizationId===u.resource.organizationId)))),e.length>0){this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:t,methodName:i,source:"internal",payload:{requests:e,fromCache:l}});let u=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??a??""});return this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_RESULT,timestamp:new Date().getTime(),uniqueId:t,methodName:i,source:"internal",payload:{result:u}}),u?.success&&u?.data?.length&&(this.setPermissionsCache([...m,...u.data]),u.data=[...d,...u.data]),u}else if(d.length>0)return this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_RESULT_FROM_CACHE,timestamp:new Date().getTime(),methodName:i,source:"internal",uniqueId:t,payload:{results:{data:d,success:!0,statusCode:200}}}),{data:d,success:!0,statusCode:200};return}catch(d){this.loggingService.catch("Error in UsersPermissionService onResourceAccessRequired:",d),this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_ERROR,timestamp:new Date().getTime(),methodName:i,source:"internal",uniqueId:t,payload:{error:d,requests:e,fromCache:l}});return}})}getPermissionsCache(){return this.forceRefreshPermissions()?[]:this.permissionsCache$.getValue()}forceRefreshPermissions(){return this.getPermissionProvider()?.forceRefresh??!1}setPermissionsCache(e){try{let t=new Map;e.forEach(a=>{let l=`${a.userId}_${a.resourceId}_${a.organizationId}_${a.type}`;t.set(l,a)});let i=JSON.parse(JSON.stringify(Array.from(t.values())));this.permissionsCache$.next(i)}catch(t){this.loggingService.catch("Error in UsersPermissionService setPermissionsCache:",t)}}isPermissionProviderAvailable(){try{return!!this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService isPermissionProviderAvailable:",e),!1}}getPermissionProvider(){try{return this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService getPermissionProvider:",e),null}}getPermissionProvider$(){return this.permissionProvider$.asObservable()}};o.\u0275fac=function(t){return new(t||o)(K(qe),K(st),K(k),K(yn),K(An),K(Cm),K(nr),K(Do),K(Ft),K(vn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var zi=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A){this.afAuth=e,this.analyticsService=t,this.authService=i,this.configService=a,this.databaseService=l,this.commonDbService=c,this.docService=d,this.domService=m,this.emojiService=u,this.iamService=_,this.loggingService=I,this.userPermissionService=A,this.documentPaths=null,this.reactionAnnotationById$=new _e({}),this.customReactions$=new _e({}),this.commentService=null,this.darkMode$=new _e(null),this.loggingService.log("%c[WB] Creating CLASS: ReactionService","color: blue;"),this.analyticsService.setReactionService(this),this.authService.setReactionService(this),this.databaseService.getDb().pipe(Ge(M=>!!M),ut(1)).subscribe(M=>{M&&this.getAllReactionAnnotations(void 0,void 0,!0).subscribe()},M=>{this.loggingService.catch("Error in ReactionService getDb subscription: ",M)})}setCommentService(e){this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;");try{this.commentService=e}catch(t){this.loggingService.catch("Error in ReactionService setCommentService: ",t)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ReactionService","color: green;");try{this.reactionAnnotationById$.next({}),this.customReactions$.next({}),this.documentPaths=null}catch(e){this.loggingService.catch("Error in ReactionService clearCache: ",e)}}getAllReactionAnnotations(e,t,i,a,l){this.loggingService.log("%c[WB] Calling FUNCTION: getAllReactionAnnotations","color: green;");let c,d;try{if(e&&(d=`${er(e)}`),t&&typeof t=="object"){let m=Oi(t);c=er(JSON.stringify(m))}}catch(m){this.loggingService.catch("Error in ReactionService getAllReactionAnnotations: ",m)}return _r(this.afAuth).pipe(Ge(m=>!!m),Se(m=>this.isFeatureAllowed({firebaseUser:m,annotations:[],filteredAnnotations:[]})),Se(m=>m.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(u=>(m.featureAllowed=u,m))):ce(m)),Se(m=>m.featureAllowed?ce(m).pipe(Se(u=>this.docService.getDocumentPaths$().pipe(ue(_=>(this.documentPaths=_,u.documentPaths=_,u)))),Se(u=>d?this.getDataFromDocumentIds([d]).pipe(ue(_=>(u.annotations=_||[],h({},u)))):this.docService.getDocumentIds$().pipe(Se(_=>{let I=_?.length>0?_.map(A=>A.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(I).pipe(ue(A=>(u.annotations=A||[],h({},u))))}))),Se(u=>this.docService.getLocation$().pipe(ue(_=>(u.location=_,u)))),Se(u=>this.docService.getLocations$().pipe(ue(_=>(u.customLocations=_,u)))),ue(u=>{if(u.filteredAnnotations=[],d&&!c)return u.filteredAnnotations=u.annotations?.slice(),u;{let _=[];return c?_.push(c):(_.push(u?.location?.locationId),_.push(...Object.values(u?.customLocations||[]).map(I=>I.locationId))),u.filteredAnnotations=this.filterAnnotationsByLocationIds(u?.annotations,_),u}}),Se(u=>i?ce(u):u?.annotations?.length?this.domService.onWindowResize$().pipe(ue(()=>u)):ce(u)),Se(u=>i?ce(u):ce(u)),ue(u=>u),Se(u=>u?.filteredAnnotations?ce(u?.filteredAnnotations||[]):ce([]))):ce([])),_t(Kt))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})),Se(t=>this.authService.getUser$().pipe(ue(i=>y(h({},t),{user:i})))),Se(t=>Ao(t.config,t.user,je.REACTION)?ce(y(h({},t),{featureAllowed:!0})):(this.loggingService.warn("Reaction feature is not allowed."),ce(y(h({},t),{featureAllowed:!1})))),_t((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t,filters:i}=e;if(t?.some(d=>!d)||!this.documentPaths)return ce([]);let a=this.docService.getDocumentPaths()?.veltFolderId,l=ce([]),c={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(c.documentId=t?.length?t[0]:void 0,c.organizationId=this.documentPaths?.organizationId),this.userPermissionService?.getIsContextEnabled()){let d=[N.DEFAULT_VELT_CONTEXT,...this.docService.getProcessedDocContext()],m=[];for(let u=0;u<(d?.length??0);u+=N.LISTENER_CONTEXT_BATCH_SIZE)m.push(d?.slice(u,u+N.LISTENER_CONTEXT_BATCH_SIZE)??[]);l=gn(m.map(u=>this.commonDbService.dbListener({feature:"allReactions",properties:y(h({},c),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",t),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[],...u?.length?[ft("context.accessFields","array-contains-any",u)]:[])]})}).pipe(la()))).pipe(ue(u=>Na(u)))}else{let d=[];for(let m=0;m<(t?.length??0);m+=N.LISTENER_BATCH_SIZE)d.push(t?.slice(m,m+N.LISTENER_BATCH_SIZE)??[]);l=gn(d.map(m=>this.commonDbService.dbListener({feature:"allReactions",properties:y(h({},c),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",m),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[])]})}).pipe(la()))).pipe(ue(m=>Na(m)))}return l.pipe(ue(d=>({data:d?.data,operation:d?.operation})),ue(({data:d,operation:m})=>{let u=[];return d&&(u=Object.values(d??{}).filter(_=>typeof _=="object")),u?.forEach(_=>{this.sanitizeReactionAnnotation(_)}),{data:u,operation:m}}),ue(({data:d,operation:m})=>{if(!t)return{data:d,documentMap:{},operation:m};let u=d.reduce((_,I)=>{let A=I.metadata?.documentId;return A&&(_[A]||(_[A]=[]),_[A].push(I)),_},{});return{data:d,documentMap:u,operation:m}}),ue(({data:d,documentMap:m,operation:u})=>{if(!i)if(u?.type==="removed"){if(u?.ids?.length){let _=this.reactionAnnotationById$.value;u?.ids?.forEach(I=>{delete _?.[I]}),this.reactionAnnotationById$.next(_)}}else Object.entries(m??{}).forEach(([_,I])=>{this.setReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:_,annotations:I})});return d}),Xn(d=>(this.loggingService.catch("Error in ReactionService getDataFromDocumentId: ",d),ce([]))))}else return ce([])}setReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:i,queryHash:a}){try{if(t){e||(e=N.NO_ORGANIZATION_ID),a||(a=N.DEFAULT_QUERY_HASH);let l={};i?.forEach(d=>{d?.annotationId&&(l[d?.annotationId]=d)});let c=h(h({},this.reactionAnnotationById$.value),l);this.reactionAnnotationById$.next(c)}}catch(l){this.loggingService.catch("Error in ReactionService setReactionAnnotationsByOrganizationIdAndDocumentId:",l)}}getReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let i={};return Object.values(this.reactionAnnotationById$.value??{}).forEach(a=>{a?.metadata?.documentId==t&&a?.metadata?.organizationId==e&&(i[a?.annotationId]=a)}),Object.values(i)}catch(i){return this.loggingService.catch("Error in ReactionService getReactionAnnotationsByOrganizationIdAndDocumentId:",i),[]}}getLocations$(){return this.docService.getLocation$().pipe(Se(e=>this.docService.getLocations$().pipe(ue(t=>({location:e,locations:t})))),ue(e=>{let t=[];return t.push(e?.location?.locationId),t.push(...Object.values(e.locations||[]).map(i=>i.locationId)),t||[]}))}filterAnnotationsByLocationIds(e,t){try{return e.filter(i=>t.includes(i.locationId))}catch(i){return this.loggingService.catch("Error in ReactionService filterAnnotationsByLocations:",i),[]}}getAnnotationById(e,t){try{let i=this.reactionAnnotationById$.value?.[e];if(i){let{documentId:a,organizationId:l}=t||{};if(a&&i.metadata?.documentId!==a||l&&i.metadata?.organizationId!==l)return}return i}catch(i){this.loggingService.catch("Error in ReactionService getAnnotationById: ",i);return}}getBaseMetadataFromReactionAnnotationId(e){try{let t=this.reactionAnnotationById$.value?.[e];return t?t.metadata:void 0}catch(t){this.loggingService.catch("Error in ReactionService getBaseMetadataFromReactionAnnotationId: ",t);return}}getReactionAnnotationByAnnotationId(e,t){try{return this.reactionAnnotationById$.pipe(ue(()=>this.getAnnotationById(e,t)),Se(i=>i?ce(i):ce(i)))}catch(i){return this.loggingService.catch("Error in ReactionService getReactionAnnotationByAnnotationId: ",i),ce(void 0)}}getReactionAnnotationsBySectionId(e){try{return this.reactionAnnotationById$.pipe(Se(t=>this.docService.getDocumentPaths$().pipe(ue(i=>({documentPaths:i,sectionId:e,reactionAnnotationsMap:t})))),Se(t=>{let i=nl(e,["id","data-id"]);if(i){let a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.genarateLocationId(a);return this.docService.getLocations$().pipe(ue(c=>{let m=Object.values(c||{}).find(u=>u.locationId===l||a?.id&&u.location.id===a.id);return y(h({},t),{additionalLocation:m,locationOnElement:!!a})}))}}return ce(y(h({},t),{additionalLocation:null,element:i}))}),Se(t=>t?.locationOnElement?ce(t):this.docService.getLocation$().pipe(ue(i=>y(h({},t),{location:i})))),ue(({documentPaths:t,location:i,additionalLocation:a,locationOnElement:l,element:c})=>{let d=null,m=this.docService.getAdditionalDocumentIdFromElement(c),u=m?this.docService.generateDocumentId(m):t?.documentId,_=t?.organizationId;if(u){let I=this.getReactionAnnotationsByOrganizationIdAndDocumentId({organizationId:_,documentId:u});if(I){d=[];for(let A of I)A?.targetElementId===e&&(l?a&&_0({location:a?.location,locationId:a?.locationId},{location:A.location,locationId:A.locationId})&&d.push(A):i?_0({location:i?.location,locationId:i?.locationId},{location:A.location,locationId:A.locationId})&&d.push(A):A?.locationId||d.push(A))}}return d}))}catch(t){return this.loggingService.catch("Error in ReactionService getReactionAnnotationsBySectionId: ",t),ce(null)}}addOrUpdateReaction(e,t,i,a,l,c,d,m){return X(this,null,function*(){try{let u=t?.map(_=>this.getAnnotationById(_)).find(_=>_?.icon===e);if(u){if(!d||d==="delete")return yield this.updateUserInReaction(u)}else if(!d||d==="add")return yield this.addReaction(void 0,e,i,a,l,c,m)}catch(u){this.loggingService.catch("Error in ReactionService addOrUpdateReaction: ",u)}})}addReaction(e,t,i,a,l,c,d){return X(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: addReaction","color: green;");try{let m=this.authService.getUser();if(m)if(m.isReadOnly||m.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add reactions.");else{let u=new jN;if(u.from=m,u.lastUpdated=this.timestamp,u.reactions=[],u.reactions.push({from:m,lastUpdated:this.timestamp}),a&&(u.targetElementId=a),l){u.commentAnnotationId=l;let _=this.commentService?.getAnnotationById(l);if(_?.context?.accessFields){if(!this.userPermissionService?.hasUserContextAccess({userId:m.userId,accessFields:_.context.accessFields})){this.loggingService.catch("User does not have context access to add reaction annotation.",void 0,void 0,!0);return}u.context=y(h({},_.context.access?{access:_.context.access}:{}),{accessFields:_.context.accessFields})}}if(this.setLocationToReactionAnnotation(u),u.pageInfo=ro(),u.pageInfo&&(u.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth),t)if(u.icon=t,c)u.iconUrl=c?.url,u.iconEmoji=c?.emoji;else{let _=this.customReactions$.value;if(_){let I=_[t];I?.url&&(u.iconUrl=I?.url),I?.emoji&&(u.iconEmoji=I?.emoji)}}return i&&(u.location={},u.location=h({},i),u.locationId=this.docService.genarateLocationId(u.location)),yield this.saveReactionToDb(u)}}catch(m){this.loggingService.catch("Error in ReactionService addReaction: ",m)}})}setLocationToReactionAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location);try{let i;e.targetElement?.xpath?i=this.domService.getElementFromXPath(e.targetElement.xpath):e.targetElementId&&(i=nl(e.targetElementId,["id","data-id"]));let a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.addLocation({location:a,source:"internal"});l?.[0]&&(e.locationId=l[0].locationId,e.location=l[0].location)}}catch{}}catch(t){this.loggingService.catch("Error in ReactionService setLocationToReactionAnnotation:",t)}}getElementForReactionAnnotation(e){try{let t;return e.targetElementId&&(t=nl(e.targetElementId,["id","data-id"])),t}catch(t){return this.loggingService.catch("Error in ReactionService getElementForReactionAnnotation: ",t),null}}saveReactionToDb(e){return X(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: saveReactionToDb","color: green;");try{if(this.authService.getUser()){let t=yield this.docService.getDocumentPaths$().pipe(Ge(a=>!!a),ut(1)).toPromise();if(!t)throw new Error("Document paths not found.");if(this.documentPaths=t,this.loggingService.log(this.documentPaths),!(yield this.databaseService.getDb().pipe(Ge(a=>!!a),ut(1)).toPromise()))throw new Error("Database not found.");if(this.documentPaths?.reaction){if(e.annotationId=this.commonDbService.generateDocumentId(),e.pageInfo,!e?.metadata?.documentId){e?.metadata||(e.metadata={});let m=this.getElementForReactionAnnotation(e),u=this.docService.getBaseMetadata("reaction",{commentAnnotationId:e.commentAnnotationId,element:m});e.metadata=h(h({},e?.metadata),u)}let a=JSON.parse(JSON.stringify(e));a.position=null;let{documentId:l,organizationId:c}=this.getDocumentIdAndOrganizationIdFromReactionAnnotation(e),d=e.commentAnnotationId?void 0:{annotationData:a,actionType:"add",notificationSource:"reaction"};return yield this.commonDbService.setData({feature:"reaction",properties:{id:e.annotationId,documentId:l,organizationId:c},data:a,extraData:d}),a}else return}}catch(t){this.loggingService.catch("Error in ReactionService saveReactionToDb: ",t)}})}getDocumentIdAndOrganizationIdFromReactionAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in ReactionService getDocumentIdAndOrganizationIdFromReactionAnnotation: ",t),{}}}updateUserInReaction(e){return X(this,null,function*(){try{let t=this.authService.getUser();if(t)return e?.reactions||(e.reactions=[]),e?.reactions?.find(a=>a?.from?.userId===t?.userId)?e.reactions=e?.reactions?.filter(a=>a?.from?.userId!==t?.userId):e.reactions.push({from:t,lastUpdated:this.timestamp}),e.reactions.length?yield this.updateReaction(e):yield this.deleteReactionPinAnnotation(e?.annotationId),e}catch(t){this.loggingService.catch("Error in ReactionService updateUserInReaction: ",t)}})}removeUserFromReaction(e){this.loggingService.log("%c[WB] Calling FUNCTION: removeUserFromReaction","color: green;");try{let t=this.authService.getUser();t&&(e?.reactions||(e.reactions=[]),e.reactions=e?.reactions?.filter(i=>i?.from?.userId!==t?.userId),this.updateReaction(e))}catch(t){this.loggingService.catch("Error in ReactionService removeUserFromReaction: ",t)}}updateReaction(e,t,i){return X(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateReaction","color: green;");try{if(this.authService.getUser()){if(e?.targetElement?.xpath){let d=this.domService.getXPath(e.targetElement.xpath);if(d){let m=d.iterateNext();m&&(Kr(m)||(e.targetElement=null))}}let a=JSON.parse(JSON.stringify(e));if(a.position=null,a.lastUpdated=this.timestamp,!a?.metadata?.documentId){a?.metadata||(a.metadata={});let d=this.docService.getBaseMetadata("reaction",{commentAnnotationId:e.commentAnnotationId});a.metadata=h(h({},a?.metadata),d)}let{documentId:l,organizationId:c}=a?.metadata||{};return i?yield this.commonDbService.updateData({feature:"reaction",properties:{id:e.annotationId,documentId:l,organizationId:c},data:JSON.parse(JSON.stringify(a))}):yield this.commonDbService.setData({feature:"reaction",properties:{id:e.annotationId,documentId:l,organizationId:c},data:JSON.parse(JSON.stringify(a))}),a}}catch(a){this.loggingService.catch("Error in ReactionService updateReaction: ",a)}})}deleteReactionPinAnnotation(e,t){return X(this,null,function*(){try{let i=this.getAnnotationById(e),{documentId:a,organizationId:l}=this.getDocumentIdAndOrganizationIdFromReactionAnnotation(i),c=i&&!i.commentAnnotationId?{annotationData:i,actionType:"delete",notificationSource:"reaction"}:void 0;yield this.commonDbService.deleteData({feature:"reaction",properties:{id:e,documentId:a,organizationId:l},extraData:c})}catch(i){this.loggingService.catch("Error in ReactionService deleteReactionPinAnnotation: ",i)}})}setCustomReactions(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCustomReactions","color: green;"),this.customReactions$.next(e),this.emojiService.setEmojiList(e)}catch(t){this.loggingService.catch("Error in ReactionService setCustomReactions: ",t)}}enableDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDarkMode","color: green;"),this.darkMode$.value===!0)return;this.darkMode$.next(!0)}catch(e){this.loggingService.catch("Error in ReactionService enableDarkMode: ",e)}}disableDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDarkMode","color: green;"),this.darkMode$.value===!1)return;this.darkMode$.next(!1)}catch(e){this.loggingService.catch("Error in ReactionService disableDarkMode: ",e)}}getDarkMode(){return this.darkMode$.value}getDarkMode$(){return this.darkMode$.asObservable()}sanitizeReactionAnnotation(e){try{e&&(e.iconUrl&&(e.iconUrl=this.domService.sanitizeHtml(e.iconUrl)),e.iconEmoji&&(e.iconEmoji=this.domService.sanitizeHtml(e.iconEmoji)),e.icon&&(e.icon=this.domService.sanitizeHtml(e.icon)))}catch(t){this.loggingService.catch("Error in ReactionService sanitizeReactionAnnotation: ",t)}}get timestamp(){return this.commonDbService.getServerTimestamp()}getReactionAnnotationForClient(e){try{let t=["isReactionResolverUsed","pageInfo","from","involvedUserIds","position"],i=JSON.parse(JSON.stringify(e)),a={};return Object.keys(i).forEach(l=>{t.includes(l)||(l==="reactions"?a.fromUsers=i[l]:a[l]=i[l])}),a}catch(t){return this.loggingService.catch("Error in ReactionService getReactionAnnotationForClient: ",t),e}}};o.\u0275fac=function(t){return new(t||o)(K(eo),K(ct),K(qe),K(Ft),K($n),K(yn),K(st),K(Ve),K(Sm),K(Vn),K(k),K(Ia))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Rg={user:"componentConfigSignal.appState.user",isUserAdmin:"componentConfigSignal.appState.isUserAdmin",isKnownUser:"componentConfigSignal.appState.isKnownUser",repliesUniqueUsers:"componentConfigSignal.appState.repliesUniqueUsers",annotation:"componentConfigSignal.data.annotation",annotations:"componentConfigSignal.data.annotations",allAnnotations:"componentConfigSignal.data.allAnnotations",ghostComment:"componentConfigSignal.data.ghostComment",selectedFiles:"parentLocalUIState.selectedFiles",invalidSelectedFiles:"parentLocalUIState.invalidSelectedFiles",selectedAttachments:"parentLocalUIState.selectedAttachments",editComment:"parentLocalUIState.editComment",editCommentIndex:"parentLocalUIState.editCommentIndex",assignTo:"componentConfigSignal.data.assignTo",selectedUserContacts:"componentConfigSignal.data.selectedUserContacts",localRecordedData:"parentLocalUIState.localRecordedData",customList:"componentConfigSignal.data.customList",toOrganizationUserGroup:"componentConfigSignal.data.toOrganizationUserGroup",taggedUserContacts:"componentConfigSignal.data.taggedUserContacts",taggedGroups:"componentConfigSignal.data.taggedGroups",attachmentsToDelete:"parentLocalUIState.attachmentsToDelete",customChipData:"componentConfigSignal.data.customChipData",selectedCustomChipSet:"componentConfigSignal.data.selectedCustomChipSet",currentDialogView:"componentConfigSignal.data.currentDialogView",sidebarMode:"parentLocalUIState.sidebarMode",inboxMode:"parentLocalUIState.inboxMode",dialogMode:"parentLocalUIState.dialogMode",inlineCommentMode:"parentLocalUIState.inlineCommentMode",inlineCommentSectionMode:"parentLocalUIState.inlineCommentSectionMode",focusedThreadMode:"parentLocalUIState.focusedThreadMode",isFocusedThreadEnabled:"parentLocalUIState.isFocusedThreadEnabled",pageModeComposer:"parentLocalUIState.pageModeComposer",darkMode:"parentLocalUIState.darkMode",variant:"parentLocalUIState.variant",disabled:"parentLocalUIState.disabled",commentPinSelected:"parentLocalUIState.commentPinSelected",fullExpanded:"parentLocalUIState.fullExpanded",commentDialogSelected:"parentLocalUIState.commentDialogSelected",readOnly:"parentLocalUIState.readOnly",dialogShadowDOM:"parentLocalUIState.dialogShadowDOM",locationVersion:"parentLocalUIState.locationVersion",composerPosition:"parentLocalUIState.composerPosition",dialogOpenedInSidebar:"parentLocalUIState.dialogOpenedInSidebar",expandOnSelection:"parentLocalUIState.expandOnSelection",selectedVisibility:"parentLocalUIState.selectedVisibility",selectedVisibilityUsers:"parentLocalUIState.selectedVisibilityUsers",containerComponentId:"componentConfigSignal.uiState.containerComponentId",isPrivateComment:"componentConfigSignal.uiState.isPrivateComment",assignToMenuOpened:"parentLocalUIState.assignToMenuOpened",showGhostCommentMessage:"componentConfigSignal.uiState.showGhostCommentMessage",showReplies:"componentConfigSignal.uiState.showReplies",collapsedComments:"componentConfigSignal.uiState.collapsedComments",showAllComments:"componentConfigSignal.uiState.showAllComments",composerContent:"parentLocalUIState.composerContent",composerContentHTML:"parentLocalUIState.composerContentHTML",composerInOpenState:"parentLocalUIState.composerInOpenState",composerMode:"componentConfigSignal.uiState.composerMode",multiThreadAnnotationId:"componentConfigSignal.uiState.multiThreadAnnotationId",maxReplyAvatars:"componentConfigSignal.uiState.maxReplyAvatars",showSuggestionModeActions:"componentConfigSignal.uiState.showSuggestionModeActions",uploadingAttachments:"componentConfigSignal.uiState.uploadingAttachments",playVideoInFullScreen:"componentConfigSignal.uiState.playVideoInFullScreen",commentDialogUniqueId:"componentConfigSignal.uiState.commentDialogUniqueId",recorderInitConfig:"componentConfigSignal.uiState.recorderInitConfig",isInputFocused:"componentConfigSignal.uiState.isInputFocused",showCommentButtons:"componentConfigSignal.uiState.showCommentButtons",isAutocompleteDropdownOpen:"componentConfigSignal.uiState.isAutocompleteDropdownOpen",bottomSheetMode:"componentConfigSignal.uiState.bottomSheetMode",commentComposerMode:"componentConfigSignal.uiState.commentComposerMode",shouldScrollToBottom:"componentConfigSignal.uiState.shouldScrollToBottom",deviceType:"componentConfigSignal.uiState.deviceType",showReplyComposer:"componentConfigSignal.uiState.showReplyComposer",reactionToolOpenIndex:"componentConfigSignal.uiState.reactionToolOpenIndex",openDropdownIndexValue:"componentConfigSignal.uiState.openDropdownIndexValue",hasReactionsByCommentId:"componentConfigSignal.uiState.hasReactionsByCommentId",newComment:"parentLocalUIState.composerContent",newCommentHTML:"parentLocalUIState.composerContentHTML",canResolveAnnotation:"componentConfigSignal.featureState.canResolveAnnotation",canUnresolveAnnotation:"componentConfigSignal.featureState.canUnresolveAnnotation",dialogSelectedByKnownUser:"componentConfigSignal.featureState.dialogSelectedByKnownUser",resolveStatusAccessAdminOnly:"componentConfigSignal.featureState.resolveStatusAccessAdminOnly",enableResolve:"componentConfigSignal.featureState.enableResolve",isPlanExpired:"componentConfigSignal.featureState.isPlanExpired",moderatorMode:"componentConfigSignal.featureState.moderatorMode",enableAutoCategorize:"componentConfigSignal.featureState.enableAutoCategorize",suggestionMode:"componentConfigSignal.featureState.suggestionMode",commentAcceptedStatus:"componentConfigSignal.featureState.commentAcceptedStatus",commentRejectedStatus:"componentConfigSignal.featureState.commentRejectedStatus",enableSignInButton:"componentConfigSignal.featureState.enableSignInButton",enableUpgradeButton:"componentConfigSignal.featureState.enableUpgradeButton",enableGhostCommentsMessage:"componentConfigSignal.featureState.enableGhostCommentsMessage",replyAvatars:"componentConfigSignal.featureState.replyAvatars",userMentions:"componentConfigSignal.featureState.userMentions",recordingSummaryEnabled:"componentConfigSignal.featureState.recordingSummaryEnabled",enableAttachment:"componentConfigSignal.featureState.enableAttachment",allowedFileTypes:"componentConfigSignal.featureState.allowedFileTypes",allowedRecordings:"componentConfigSignal.featureState.allowedRecordings",screenSharingSupported:"componentConfigSignal.featureState.screenSharingSupported",enterKeyToSubmit:"componentConfigSignal.featureState.enterKeyToSubmit",deleteOnBackspace:"componentConfigSignal.featureState.deleteOnBackspace",showScreenSizeInfo:"componentConfigSignal.uiState.showScreenSizeInfo",enableReactions:"componentConfigSignal.featureState.enableReactions",isInsidePdfViewer:"componentConfigSignal.featureState.isInsidePdfViewer",sidebarButtonOnCommentDialogVisible:"componentConfigSignal.uiState.sidebarButtonOnCommentDialogVisible",enableStatus:"componentConfigSignal.featureState.enableStatus",customStatusesShown:"componentConfigSignal.featureState.customStatusesShown",statusOptions:"componentConfigSignal.featureState.statusOptions",enablePriority:"componentConfigSignal.featureState.enablePriority",visibilityOptions:"componentConfigSignal.featureState.visibilityOptions",priorityOptions:"componentConfigSignal.featureState.priorityOptions",enableAssignment:"componentConfigSignal.featureState.enableAssignment",enableNotifications:"componentConfigSignal.featureState.enableNotifications",enableEdit:"componentConfigSignal.featureState.enableEdit",enableDelete:"componentConfigSignal.featureState.enableDelete",enablePrivateMode:"componentConfigSignal.featureState.enablePrivateMode",deleteThreadWithFirstComment:"componentConfigSignal.featureState.deleteThreadWithFirstComment",seenByUsers:"componentConfigSignal.featureState.seenByUsers",allowAssignment:"componentConfigSignal.featureState.enableAssignment",allowToggleNotification:"componentConfigSignal.featureState.enableNotifications",allowEdit:"componentConfigSignal.featureState.enableEdit",allowChangeCommentAccessMode:"componentConfigSignal.featureState.enablePrivateMode",notificationEnabled:"notificationEnabled",mainCommentId:"componentConfigSignal.data.annotation.comments.0.commentId",commentObj:"commentObj",commentIndex:"commentIndex",userContact:"selectorItem.contact",comment:"commentObj",commentAnnotation:"componentConfigSignal.data.annotation",commentAnnotations:"componentConfigSignal.data.annotations",context:"parentLocalUIState.context",focusedAnnotation:"focusedAnnotation",notification:"notification",unreadNotificationsForYou:"componentConfigSignal.data.unreadNotificationsForYou",notificationsPanelVisible:"componentConfigSignal.uiState.notificationsPanelVisible",notificationsForYouInSession:"componentConfigSignal.data.notificationsForYouInSession",notificationsInSession:"componentConfigSignal.data.notificationsInSession",notificationsByUserMap:"componentConfigSignal.data.notificationsByUserMap",notificationsByDocumentId:"componentConfigSignal.data.notificationsByDocumentId",notificationsByDate:"componentConfigSignal.data.notificationsByDate",currentDocumentName:"componentConfigSignal.data.currentDocumentName",settingsConfig:"componentConfigSignal.data.settingsConfig",settingsSelectedOption:"componentConfigSignal.data.settingsSelectedOption",selectedTab:"componentConfigSignal.uiState.selectedTab",tabConfig:"componentConfigSignal.uiState.tabConfig",TABS:"componentConfigSignal.uiState.TABS",tabPage:"componentConfigSignal.uiState.tabPage",pageSize:"componentConfigSignal.uiState.pageSize",panelOpenMode:"componentConfigSignal.uiState.panelOpenMode",settingsOpen:"componentConfigSignal.uiState.settingsOpen",settingsAccordionExpanded:"componentConfigSignal.uiState.settingsAccordionExpanded",settingsMutedAll:"componentConfigSignal.uiState.settingsMutedAll",settingsItemRecentlyClosed:"componentConfigSignal.uiState.settingsItemRecentlyClosed",settingsLayout:"componentConfigSignal.uiState.settingsLayout",tabCount:"componentConfigSignal.uiState.tabCount",usersExpanded:"componentConfigSignal.uiState.usersExpanded",documentExpanded:"componentConfigSignal.uiState.documentExpanded",shadowDom:"componentConfigSignal.uiState.shadowDom",settingsEnabled:"componentConfigSignal.featureState.settingsEnabled",selectedMinimalFilterDropdownOption:"selectedMinimalFilterDropdownOption",appliedFiltersCount:"appliedFiltersCount",filteredCommentAnnotationsCount:"filteredCommentAnnotationsCount",unreadCommentAnnotationCount:"unreadCommentAnnotationCount",isEnabled:"componentConfigSignal.featureState.isEnabled",allActivities:"componentConfigSignal.data.allActivities",filteredActivities:"componentConfigSignal.data.filteredActivities",groupedActivities:"componentConfigSignal.data.groupedActivities",virtualScrollItems:"componentConfigSignal.data.virtualScrollItems",activeFilter:"componentConfigSignal.data.activeFilter",availableFilters:"componentConfigSignal.data.availableFilters",isOpen:"componentConfigSignal.uiState.isOpen",expandedGroups:"componentConfigSignal.uiState.expandedGroups",defaultVisibleCount:"componentConfigSignal.uiState.defaultVisibleCount",filterDropdownOpen:"componentConfigSignal.uiState.filterDropdownOpen",activity:"activityRecord",activityRecord:"activityRecord",dateGroup:"dateGroup",filter:"filterOption",filterOption:"filterOption",isActive:"isActive",isExpanded:"isExpanded",remainingCount:"remainingCount",showAdder:"componentConfigSignal.uiState.showAdder",commentToolEnabled:"componentConfigSignal.uiState.commentToolEnabled",isUserAllowed:"componentConfigSignal.uiState.isUserAllowed",enableTextComments:"componentConfigSignal.uiState.enableTextComments",rewriterEnabled:"componentConfigSignal.uiState.rewriterEnabled",rewriterDefaultUIEnabled:"componentConfigSignal.uiState.rewriterDefaultUIEnabled",selectedWordsCount:"componentConfigSignal.data.selectedWordsCount",selectedCharactersCount:"componentConfigSignal.data.selectedCharactersCount",allowedElementIds:"componentConfigSignal.data.allowedElementIds",contextId:"componentConfigSignal.data.contextId",position:"componentConfigSignal.data.position",MIN_ALLOWED_WORDS_COUNT:"componentConfigSignal.uiState.MIN_ALLOWED_WORDS_COUNT",MIN_ALLOWED_CHARACTERS_COUNT:"componentConfigSignal.uiState.MIN_ALLOWED_CHARACTERS_COUNT",MAX_ALLOWED_CHARACTERS_COUNT:"componentConfigSignal.uiState.MAX_ALLOWED_CHARACTERS_COUNT",filteredAnnotations:"componentConfigSignal.data.filteredAnnotations",multiThreadCommentAnnotation:"componentConfigSignal.data.multiThreadCommentAnnotation",nonDraftCommentsCount:"componentConfigSignal.data.nonDraftCommentsCount",commentPinType:"componentConfigSignal.uiState.commentPinType",hideMultiThreadAnnotationComposer:"componentConfigSignal.uiState.hideMultiThreadAnnotationComposer",dialogVariant:"componentConfigSignal.uiState.dialogVariant",minimalFilter:"componentConfigSignal.uiState.minimalFilter",minimalFilterDropdownOpen:"componentConfigSignal.uiState.minimalFilterDropdownOpen",minimalActionsDropdownOpen:"componentConfigSignal.uiState.minimalActionsDropdownOpen",noCommentsFoundForAppliedFilters:"componentConfigSignal.uiState.noCommentsFoundForAppliedFilters",noCommentsFound:"componentConfigSignal.uiState.noCommentsFound",isSelected:"isSelected",composerCommentAnnotation:"componentConfigSignal.data.composerCommentAnnotation",statuses:"componentConfigSignal.data.statuses",skeletonLoading:"componentConfigSignal.uiState.skeletonLoading",filterState:"componentConfigSignal.uiState.filterState",sortState:"componentConfigSignal.uiState.sortState",isResolvedCommentsOnDomFilterSelected:"componentConfigSignal.uiState.isResolvedCommentsOnDomFilterSelected",resolvedCommentsOnDom:"componentConfigSignal.uiState.resolvedCommentsOnDom",selectedAnnotationsMap:"componentConfigSignal.uiState.selectedAnnotationsMap",selectedAnnotationsLocationMap:"componentConfigSignal.uiState.selectedAnnotationsLocationMap",composerVariant:"parentLocalUIState.composerVariant",multiThread:"parentLocalUIState.multiThread",commentPlaceholder:"parentLocalUIState.commentPlaceholder",replyPlaceholder:"parentLocalUIState.replyPlaceholder",composerPlaceholder:"parentLocalUIState.composerPlaceholder",editPlaceholder:"parentLocalUIState.editPlaceholder",editCommentPlaceholder:"parentLocalUIState.editCommentPlaceholder",editReplyPlaceholder:"parentLocalUIState.editReplyPlaceholder",targetElementId:"parentLocalUIState.targetElementId",folderId:"parentLocalUIState.folderId",veltFolderId:"parentLocalUIState.veltFolderId",clientDocumentId:"parentLocalUIState.clientDocumentId",documentId:"parentLocalUIState.documentId",locationId:"parentLocalUIState.locationId",contextOptions:"parentLocalUIState.contextOptions",messageTruncation:"parentLocalUIState.messageTruncation",messageTruncationLines:"parentLocalUIState.messageTruncationLines",unresolvedAnnotationsCount:"componentConfigSignal.data.unresolvedAnnotationsCount",unreadCount:"componentConfigSignal.data.unreadCount",commentBubbleTargetPinHover:"parentLocalUIState.commentBubbleTargetPinHover",openDialog:"parentLocalUIState.openDialog",showAvatar:"parentLocalUIState.showAvatar",commentCountType:"parentLocalUIState.commentCountType"},DWe=["user","annotation","annotations","allAnnotations","userContact","comment","commentAnnotation","commentAnnotations","recorderInitConfig","ghostComment","editComment","assignTo","customChipData","currentDialogView","context","focusedAnnotation","notification","selectedMinimalFilterDropdownOption","unreadNotificationsForYou","notificationsForYouInSession","notificationsInSession","notificationsByUserMap","notificationsByDocumentId","notificationsByDate","settingsConfig","settingsSelectedOption","settingsAccordionExpanded","tabConfig","tabPage","TABS","allActivities","filteredActivities","groupedActivities","virtualScrollItems","availableFilters","expandedGroups","activity","activityRecord","dateGroup","filter","filterOption","position","allowedElementIds","filteredAnnotations","multiThreadCommentAnnotation","composerCommentAnnotation","statuses","filterState","sortState","selectedAnnotationsMap","selectedAnnotationsLocationMap","contextOptions"],T=(()=>{let _DynamicDataService=class _DynamicDataService{constructor(n,o,r,e,t,i){this.authService=n,this.commentService=o,this.loggingService=r,this.injector=e,this.docService=t,this.configService=i,this.subscriptions=[],this.commonData$=new _e({}),this.evaluateConditionTriggered=new Ue,this.conditionRegex=/\{(.*?)\}/g,this.extractedProps={},this.condition="",this.dataComponentConfigSignal=De({});try{this.subscriptions.push(this.authService.getUser$().subscribe(a=>{this.commonData$.next(y(h({},this.commonData$.value),{user:a}))})),this.subscriptions.push(this.commentService.getUnreadCommentAnnotationCountOnCurrentDocument$().subscribe(a=>{this.commonData$.next(y(h({},this.commonData$.value),{unreadCommentAnnotationCount:a?.count||0}))})),this.subscriptions.push(this.commentService.getUnreadCommentCountOnCurrentDocument$().subscribe(a=>{this.commonData$.next(y(h({},this.commonData$.value),{unreadCommentCount:a?.count||0}))})),this.subscriptions.push(this.docService.getUIState$().subscribe(a=>{this.commonData$.next(h(h({},this.commonData$.value),a))})),this.subscriptions.push(this.getCommonData().subscribe(a=>{this.dataComponentConfigSignal.update(l=>(l=h(h({},l),a),l)),this.executeConditionalClasses()})),this.subscriptions.push(this.evaluateConditionTriggered.subscribe(a=>{this.extractedProps=a.extractedProps,this.evaluateCondition(a.className,a.elementRef,a.condition)}))}catch(a){this.loggingService.catch("Error in DynamicDataService constructor: ",a)}}ngOnDestroy(){try{this.subscriptions.forEach(n=>n.unsubscribe())}catch(n){this.loggingService.catch("Error in DynamicDataService ngOnDestroy: ",n)}}getCommonData(){return this.commonData$.asObservable()}getModifiedPathBasedOnCondition(n,o){try{return Object.keys(o).forEach(r=>{o[r].path=this.modifyPathBasedOnCondition(r,n)}),o}catch(r){this.loggingService.catch("Error in DynamicDataService getModifiedPathBasedOnCondition: ",r)}}getComputedValues(n,o,r,e,t,i){try{Object.keys(r).forEach(a=>{let l;if(vo(n)?l=oe(()=>Il(n(),r[a].path)):l=oe(()=>Il(n,r[a].path)),vo(l()))xn(()=>{try{let c=l()();r[a].value=c,this.evaluateConditionTriggered.emit({extractedProps:r,className:e,elementRef:t,condition:i})}catch{}},{injector:this.injector});else{let c=l();r[a].value=c,this.evaluateConditionTriggered.emit({extractedProps:r,className:e,elementRef:t,condition:i})}})}catch(a){this.loggingService.catch("Error in DynamicDataService getComputedValues: ",a)}}modifyPathBasedOnCondition(n,o){try{let r=n.match(/^([^\.\[]+)/),e=r?r[1]:n,t=n.slice(e.length);if(Rg[n])return Rg[n];if(["commentDialogOptionsDropdownConfigSignal","commentDialogStatusDropdownConfigSignal"].includes(e)&&t.startsWith(".")){let a=t.slice(1),l=a.match(/^([^\.\[]+)/),c=l?l[1]:a,d=a.slice(c.length);return Rg[c]?Rg[c]+d:"componentConfigSignal."+a}if(e&&o&&typeof o=="function"){let a=o();if(a&&e in a){let c=n.match(/\[(.*?)\]/);if(c&&c[1]){let d=c[1];if(d.includes(".")){let m=d.split(".")[0];if(Rg[m]){let u=d.replace(m,Rg[m]);return n.replace(`[${d}]`,`[${u}]`)}return m&&a&&m in a?n:n.replace(`[${d}]`,`[componentConfigSignal.${d}]`)}}return n}let l=a?.componentConfigSignal;if(l&&typeof l=="function"){let c=l();if(c&&e in c)return"componentConfigSignal."+n}}return Rg[e]?DWe.includes(e)?Rg[e]+t:Rg[e]:"componentConfigSignal."+n}catch(r){return this.loggingService.catch("Error in DynamicDataService modifyPathBasedOnCondition: ",r),n}}applyConditionalClasses(n,o){try{this.elementRef=n,this.data=o}catch(r){this.loggingService.catch("Error in DynamicDataService applyConditionalClasses: ",r)}}executeConditionalClasses(){try{let n=this.getHostElementAttributes(this.elementRef),r=[...Object.keys(n).filter(e=>e.startsWith("velt-class-")).map(e=>({name:e,value:n[e]}))];if(n["velt-class"]){let e=n["velt-class"],t=/'([^']+)':\s*([^,]+)(?:,|$)/g,i=[],a=0,l=100,c;for(;(c=t.exec(e))!==null;){if(a++>l){this.loggingService.catch("Too many class definitions detected.");break}if(c.length<3)continue;let[,d,m]=c;!d||!m||d.split(" ").forEach(u=>{u.trim()&&i.push({name:`velt-class-${u.trim()}`,value:m.trim()})})}r=[...r,...i]}this.data&&typeof this.data=="object"&&Object.keys(this.data).forEach(e=>{this.updateDataComponentConfigSignal(e,this.data[e])}),r.forEach(e=>{let t=e.name.replace("velt-class-","");this.condition=e.value,this.condition&&(this.extractProps(),this.extractedProps=this.getModifiedPathBasedOnCondition(this.dataComponentConfigSignal,this.extractedProps),this.getComputedValues(this.dataComponentConfigSignal,this.evaluateCondition,this.extractedProps,t,this.elementRef,e.value))})}catch(n){this.loggingService.catch("Error in DynamicDataService applyConditionalClasses: ",n)}}updateDataComponentConfigSignal(n,o){try{n==="dataComponentConfigSignal"?this.dataComponentConfigSignal.set(o):this.dataComponentConfigSignal.update(r=>y(h({},r),{[n]:o}))}catch(r){this.loggingService.catch("Error in DataComponent updateDataComponentConfigSignal: ",r)}}extractProps(){try{this.extractedProps={},this.conditionRegex.lastIndex=0;let n;for(;(n=this.conditionRegex.exec(this.condition))!==null;){let o=n[1];this.extractedProps[o]={value:null,path:null,isDynamicPath:this.hasDynamicParts(o)}}}catch(n){this.loggingService.catch("Error in DynamicDataService extractProps: ",n)}}hasDynamicParts(n){try{let o=/\[[^\]'"]*[^\]'"]\]/.test(n),r=/\[[^[\]]*[\.\[][^[\]]*\]/.test(n);return o||r}catch(o){return this.loggingService.catch("Error checking for dynamic path: ",o),!1}}evaluateCondition(n,o,r){try{if(r){let e=this.extractedProps,t=r.replace(this.conditionRegex,(l,c)=>{let d=e[c];if(d&&d.value!==void 0){let m=d.value;return typeof m=="string"?`'${m}'`:typeof m=="boolean"||typeof m=="number"?String(m):m===null?"null":typeof m=="object"?m?"true":"false":String(m)}return"false"}),i=this.sanitizeCondition(t),a=this.safeEval(i);return n&&o&&(a?this.setHostElementClasses(o,n):this.removeHostElementClasses(o,n)),a}return!1}catch(e){return this.loggingService.catch("Error in IfComponent evaluateCondition: ",e),!1}}sanitizeCondition(n){try{return n.replace(/[^a-zA-Z0-9\s\+\-\*\/\%\(\)\!\=\<\>\|\&\.\[\]\{\},'"]/g,"")}catch(o){return this.loggingService.catch("Error in IfComponent sanitizeCondition: ",o),""}}safeEval(expression){try{if(this.configService.getSafeEval()){let n=this.tokenize(expression.trim());return this.evaluateTokens(n)}else return eval(expression)}catch(n){return this.loggingService.catch("safeEval error",n),!1}}tokenize(n){try{if(!n||n.trim()==="")return[];let o=[],r=0;for(;r<n.length;){let e=n[r];if(/\s/.test(e)){r++;continue}if(e==='"'||e==="'"){let t=e,i="";for(r++;r<n.length;)if(n[r]==="\\"&&r+1<n.length)i+=n[r+1],r+=2;else if(n[r]===t){r++;break}else i+=n[r],r++;o.push({type:"string",value:i});continue}if(e==="("){o.push({type:"lparen",value:"("}),r++;continue}if(e===")"){o.push({type:"rparen",value:")"}),r++;continue}if(r<n.length-2&&n.substring(r,r+3)==="==="){o.push({type:"operator",value:"===",precedence:4}),r+=3;continue}if(r<n.length-2&&n.substring(r,r+3)==="!=="){o.push({type:"operator",value:"!==",precedence:4}),r+=3;continue}if(r<n.length-1&&n.substring(r,r+2)==="&&"){o.push({type:"operator",value:"&&",precedence:2}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="||"){o.push({type:"operator",value:"||",precedence:1}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="<="){o.push({type:"operator",value:"<=",precedence:4}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)===">="){o.push({type:"operator",value:">=",precedence:4}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="=="){o.push({type:"operator",value:"==",precedence:4}),r+=2;continue}if(r<n.length-1&&n.substring(r,r+2)==="!="){o.push({type:"operator",value:"!=",precedence:4}),r+=2;continue}if(e==="!"){o.push({type:"unary",value:"!",precedence:5}),r++;continue}if(e==="<"){o.push({type:"operator",value:"<",precedence:4}),r++;continue}if(e===">"){o.push({type:"operator",value:">",precedence:4}),r++;continue}if(/[a-zA-Z0-9._]/.test(e)){let t="";for(;r<n.length&&/[a-zA-Z0-9._]/.test(n[r]);)t+=n[r],r++;/^-?\d+(\.\d+)?$/.test(t)?o.push({type:"number",value:parseFloat(t)}):t==="true"||t==="false"?o.push({type:"boolean",value:t==="true"}):t==="null"?o.push({type:"null",value:null}):t==="undefined"?o.push({type:"undefined",value:void 0}):o.push({type:"identifier",value:t});continue}r++}return o}catch(o){return this.loggingService.catch("tokenize error",o),[]}}evaluateTokens(n){try{if(!n||n.length===0)return!1;let o=this.infixToPostfix(n);return this.evaluatePostfix(o)}catch(o){return this.loggingService.catch("evaluateTokens error",o),!1}}infixToPostfix(n){try{let o=[],r=[];for(let e of n)if(e.type==="string"||e.type==="number"||e.type==="boolean"||e.type==="null"||e.type==="undefined"||e.type==="identifier")o.push(e);else if(e.type==="unary")r.push(e);else if(e.type==="operator"){for(;r.length>0;){let t=r[r.length-1];if(t.type==="lparen"||t.precedence!==void 0&&t.precedence<e.precedence)break;o.push(r.pop())}r.push(e)}else if(e.type==="lparen")r.push(e);else if(e.type==="rparen"){for(;r.length>0&&r[r.length-1].type!=="lparen";)o.push(r.pop());r.length>0&&r.pop()}for(;r.length>0;){let e=r.pop();e.type!=="lparen"&&e.type!=="rparen"&&o.push(e)}return o}catch(o){return this.loggingService.catch("infixToPostfix error",o),[]}}evaluatePostfix(n){try{let o=[];for(let r of n)if(r.type==="string"||r.type==="number"||r.type==="boolean"||r.type==="null"||r.type==="undefined"||r.type==="identifier")o.push(r.value);else if(r.type==="unary"){if(o.length>=1){let e=o.pop();r.value==="!"&&o.push(!this.isTruthy(e))}}else if(r.type==="operator"&&o.length>=2){let e=o.pop(),t=o.pop();r.value==="&&"?o.push(this.isTruthy(t)&&this.isTruthy(e)):r.value==="||"?o.push(this.isTruthy(t)||this.isTruthy(e)):o.push(this.compare(t,e,r.value))}return o.length===1?this.isTruthy(o[0]):!1}catch(o){return this.loggingService.catch("evaluatePostfix error",o),!1}}parseValue(n){try{let o=n.trim();return o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'")?o.substring(1,o.length-1):/^-?\d+(\.\d+)?$/.test(o)?parseFloat(o):o==="true"?!0:o==="false"?!1:o==="null"?null:o==="undefined"?void 0:o}catch(o){return this.loggingService.catch("parseValue error",o),n}}compare(n,o,r){try{switch(r){case"===":return n===o;case"!==":return n!==o;case"==":return n==o;case"!=":return n!=o;case"<":return n<o;case">":return n>o;case"<=":return n<=o;case">=":return n>=o;default:return!1}}catch(e){return this.loggingService.catch("compare error",e),!1}}isTruthy(n){try{return n==null||n===""||n==="false"?!1:n==="true"?!0:typeof n=="number"?n!==0:!!n}catch(o){return this.loggingService.catch("isTruthy error",o),!1}}getHostElementAttributes(n){try{let o=n,r={};for(let e of o.attributes)r[e.name]=e.value;return r}catch{return{}}}setHostElementClasses(n,o){try{n.classList.add(o)}catch{}}removeHostElementClasses(n,o){try{n.classList.remove(o)}catch{}}};_DynamicDataService.\u0275fac=function(o){return new(o||_DynamicDataService)(K(qe),K(Re),K(k),K(Dt),K(st),K(Ft))},_DynamicDataService.\u0275prov=Ae({token:_DynamicDataService,factory:_DynamicDataService.\u0275fac,providedIn:"root"});let DynamicDataService=_DynamicDataService;return DynamicDataService})();var me=(()=>{let o=class o{set veltIf(e){try{e&&this.setIfCondition(e)}catch(t){this._loggingService.catch("Error in BaseComponent set veltIf:",t)}}constructor(e,t,i){this._elementRef=e,this._dynamicDataService=t,this._loggingService=i,this.componentConfigSignal=De({}),this.veltElement=!0,this.conditionSignal=De(null)}initializeComponentConfigSignal(e){try{this.componentConfigSignal.set(e)}catch(t){this._loggingService.catch("Error in BaseComponent initializeComponentConfigSignal:",t)}}ngOnInit(){try{this._dynamicDataService.applyConditionalClasses(this._elementRef?.nativeElement,{componentConfigSignal:this.componentConfigSignal})}catch(e){this._loggingService.catch("Error in BaseComponent ngOnInit:",e)}}ngOnDestroy(){}setIfCondition(e){try{this.conditionSignal.set(e)}catch(t){this._loggingService.catch("Error in BaseComponent setIfCondition:",t)}}};o.\u0275fac=function(t){return new(t||o)(x(Q),x(T),x(k))},o.\u0275cmp=O({type:o,selectors:[["app-base"]],hostVars:1,hostBindings:function(t,i){t&2&&w("data-velt-element",i.veltElement)},inputs:{componentConfigSignal:"componentConfigSignal",template:"template",wireframe:"wireframe",veltIf:"veltIf"},standalone:!1,decls:0,vars:0,template:function(t,i){},encapsulation:2});let n=o;return n})();var yt=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.configService=t,this.darkMode$=new _e(!1)}setDarkMode(e){try{let t=document.documentElement;if(!t)return;e?t.setAttribute(N.ATTRIBUTES.VELT_THEME,"dark"):t.removeAttribute(N.ATTRIBUTES.VELT_THEME),this.darkMode$.next(e)}catch(t){this.loggingService.catch("Error in theme service setDarkMode: ",t)}}getDarkMode$(){return this.darkMode$.asObservable()}updateListenerOnConfigChange(){try{this.configService.getConfig$().subscribe(e=>{if(e&&e.usePrefersColorScheme){this.enablePrefersColorScheme();return}this.disablePrefersColorScheme()})}catch(e){this.loggingService.catch("Error in theme service updateListenerOnConfigChange: ",e)}}enablePrefersColorScheme(){try{if(this.disablePrefersColorScheme(),!window.matchMedia)return;this.darkModeQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.setDarkMode(this.darkModeQuery.matches),this.darkModeQueryListener=e=>{this.setDarkMode(e.matches)},this.darkModeQuery.addEventListener("change",this.darkModeQueryListener)}catch(e){this.loggingService.catch("Error in theme service enablePrefersColorScheme: ",e)}}disablePrefersColorScheme(){try{this.darkModeQuery&&this.darkModeQueryListener&&this.darkModeQuery.removeEventListener("change",this.darkModeQueryListener)}catch(e){this.loggingService.catch("Error in theme service disablePrefersColorScheme: ",e)}}};o.\u0275fac=function(t){return new(t||o)(K(k),K(Ft))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var At=(()=>{let o=class o extends me{onDarkModeChange(){return this.darkModeSubject$.asObservable()}constructor(e,t,i,a,l,c,d){super(e,c,d),this._elementRef=e,this._themeService=t,this._changeDetector=i,this._featureService=a,this._componentDarkModeObservable=l,this._componentDarkMode=null,this._globalDarkMode=!1,this._featureDarkMode=!1,this._themeSubscriptions=[],this._darkMode=!1,this.darkMode=!1,this.darkModeSubject$=new _e(!1);try{this._themeSubscriptions.push(this._themeService.getDarkMode$().subscribe(m=>{this._globalDarkMode=m,this.setDarkMode()})),this._featureService&&(this._featureService instanceof Re?this._themeSubscriptions.push(this._featureService.getCommentContainerDarkMode().subscribe(m=>{this._featureDarkMode=m,this.setDarkMode()})):this._featureService instanceof zi&&this._themeSubscriptions.push(this._featureService.getDarkMode$().subscribe(m=>{m!==null&&(this._featureDarkMode=m),this.setDarkMode()}))),this._componentDarkModeObservable&&this._componentDarkModeObservable instanceof Vt&&this._themeSubscriptions.push(this._componentDarkModeObservable.subscribe(m=>{this._componentDarkMode=m,this.setDarkMode()}))}catch{}}ngOnInit(){super.ngOnInit()}ngOnChanges(e){try{if(e._darkMode){let t=e._darkMode.currentValue;typeof t=="string"&&(t=t==="true"),this._componentDarkMode=t,this.setDarkMode()}}catch{}}setComponentDarkMode(e){try{this._componentDarkMode=e,this.setDarkMode()}catch{}}setDarkMode(){try{this._componentDarkMode===null?this._featureDarkMode?this.darkMode=!0:this.darkMode=!!this._globalDarkMode:this.darkMode=!!this._componentDarkMode,this.darkMode?this._elementRef.nativeElement.hasAttribute("dark")||this._elementRef.nativeElement.setAttribute("dark",""):this._elementRef.nativeElement.hasAttribute("dark")&&this._elementRef.nativeElement.removeAttribute("dark"),this.darkModeSubject$.next(this.darkMode),this._changeDetector&&this._changeDetector.markForCheck()}catch{}}ngOnDestroy(){try{super.ngOnDestroy(),this._themeSubscriptions.forEach(e=>{e.unsubscribe()})}catch{}}};o.\u0275fac=function(t){return new(t||o)(x(Q),x(yt),x(tn),x("FeatureService",8),x(Vt),x(T),x(k))},o.\u0275cmp=O({type:o,selectors:[["app-themed"]],inputs:{_darkMode:[0,"darkMode","_darkMode"]},standalone:!1,features:[P,Qe],decls:0,vars:0,template:function(t,i){},encapsulation:2,changeDetection:0});let n=o;return n})();var Xe=(()=>{let o=class o{constructor(e){this.loggingService=e,this.wireframeMap=new _e(new Map);try{this.loggingService.log("%c[WB] Creating CLASS: WireframeService","color: blue;")}catch(t){this.loggingService.catch("Error in WireframeService constructor: ",t)}}setWireframe(e,t){try{let i=this.wireframeMap.value,a=i.get(e),l=t.children.length>0||t.innerHTML?.trim()?.length>0,c=a&&(a.children.length>0||a.innerHTML?.trim()?.length>0);(!a||l&&!c)&&(i.set(e,t),this.wireframeMap.next(i))}catch(i){this.loggingService.catch("Error in WireframeService setWireframe: ",i)}}setWireframeMap(e){try{let t=this.wireframeMap.value;e.forEach((i,a)=>{let l=t.get(a),c=i.children.length>0||i.innerHTML?.trim()?.length>0,d=l&&(l.children.length>0||l.innerHTML?.trim()?.length>0);(!l||c&&!d)&&t.set(a,i)}),this.wireframeMap.next(t)}catch(t){this.loggingService.catch("Error in WireframeService setWireframeMap: ",t)}}getWireframe(e,t=!0){try{let i=this.wireframeMap.value,a=i.get(e);if(!a&&t){let l=e?.split("---")[0];l&&(a=i.get(l))}return a&&(a?.children?.length>0||a?.innerHTML?.trim()?.length>0)?a:void 0}catch(i){this.loggingService.catch("Error in WireframeService getWireframe: ",i);return}}getConditionElement(e,t=!0){try{let i=this.wireframeMap.value,a=i.get(e);if(!a&&t){let l=e?.split("---")[0];l&&(a=i.get(l))}return a}catch(i){this.loggingService.catch("Error in WireframeService getConditionElement: ",i);return}}getWireframe$(e,t=!0){return this.wireframeMap.asObservable().pipe(ue(i=>this.getWireframe(e,t)))}setChildren(e){try{this.wireframeMap.next(e)}catch(t){this.loggingService.catch("Error in WireframeService setChildren: ",t)}}getWireframeMap(){return this.wireframeMap.value}};o.\u0275fac=function(t){return new(t||o)(K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Lbe=n=>({componentConfigSignal:n}),OWe=(n,o)=>({condition:n,data:o}),AWe=(n,o,r,e,t)=>({template:n,context:o,componentName:"velt-confirm-dialog-wireframe",variant:r,setIfCondition:e,componentElementRef:t});function MWe(n,o){if(n&1&&(C(0),D(1,"app-confirm-dialog-title",5)(2,"app-confirm-dialog-message",5),f(3,"div",6),D(4,"app-confirm-dialog-reject",5)(5,"app-confirm-dialog-approve",5),S(),b()),n&2){let r=s(3);v(),g("componentConfigSignal",r.componentConfigSignal),v(),g("componentConfigSignal",r.componentConfigSignal),v(2),g("componentConfigSignal",r.componentConfigSignal),v(),g("componentConfigSignal",r.componentConfigSignal)}}function PWe(n,o){if(n&1&&(C(0),p(1,MWe,6,4,"ng-container",4),b()),n&2){let r=s().ngIf,e=s();v(),g("veltDynamicTemplate",j(3,AWe,e.template,J(1,Lbe,e.componentConfigSignal),r==null?null:r.variant,e.setIfCondition.bind(e),e.elementRef))}}function RWe(n,o){if(n&1&&(C(0),p(1,PWe,2,9,"ng-container",3),b()),n&2){let r=s();v(),g("veltIf",E(3,OWe,r.conditionSignal(),J(1,Lbe,r.componentConfigSignal)))}}var al=(()=>{let o=class o extends At{constructor(e,t,i,a,l,c,d){super(l,a,void 0,void 0,void 0,d,e),this.loggingService=e,this.dialogRef=t,this.wireframeService=i,this.themeService=a,this.elementRef=l,this.dynamicDataService=d,this.subscriptions=[],this.componentConfigSignal=De({title:"",message:"",yesButton:"",noButton:"",variant:"",type:"",closeDialog:this.closeDialog.bind(this)}),this.componentId="velt-confirm-dialog",this.veltElement=!0;try{c&&(this.componentConfigSignal.update(m=>(m=h(h({},m),c),m)),c?.darkMode&&[!0,!1].includes(c?.darkMode)&&super.setComponentDarkMode(c?.darkMode)),this.setZIndex()}catch(m){this.loggingService.catch("Error in ConfirmDialogComponent constructor: ",m)}}ngOnInit(){try{this.loggingService.log("%c[WB] Calling FUNCTION: ngOnInit","color: green;");let e="velt-confirm-dialog-wireframe";super.ngOnInit(),this.componentConfigSignal()?.variant&&(e+=`---${this.componentConfigSignal()?.variant}`),this.subscriptions.push(this.wireframeService.getWireframe$(e).subscribe(t=>{if(t){let i=document.createElement(t.tagName);i.innerHTML=t.innerHTML,this.template=i}}))}catch(e){this.loggingService.catch("Error in ConfirmDialogComponent OnInit: ",e)}}ngOnDestroy(){super.ngOnDestroy();try{this.subscriptions.forEach(e=>e.unsubscribe())}catch(e){this.loggingService.catch("Error in ConfirmDialogComponent OnDestroy: ",e)}}setZIndex(){try{if(this.dialogRef){let e=this.dialogRef._overlayRef;e&&(e.backdropElement&&(e.backdropElement.style.zIndex="2147483647"),e.hostElement&&(e.hostElement.style.zIndex="2147483647"))}}catch(e){this.loggingService.catch("Error in ConfirmDialogComponent setZIndex: ",e)}}closeDialog(e){try{this.dialogRef.close(e)}catch(t){this.loggingService.catch("Error in ConfirmDialogComponent closeDialog: ",t)}}get variantClass(){return NWe(this.componentConfigSignal()?.type)}};o.\u0275fac=function(t){return new(t||o)(x(k),x(ji),x(Xe),x(yt),x(Q),x(nd,8),x(T))},o.\u0275cmp=O({type:o,selectors:[["snippyly-confirm-dialog"]],hostVars:1,hostBindings:function(t,i){t&2&&w("data-velt-element",i.veltElement)},standalone:!1,features:[B([T]),P],decls:3,vars:6,consts:[["floatingConfirmationRef",""],[1,"velt-confirm-dialog",3,"ngClass","snippylyOverlay","snippylyOverlayZIndex","snippylyOverlayBackdropZIndex"],[4,"ngIf"],[4,"veltIf"],[4,"veltDynamicTemplate"],[3,"componentConfigSignal"],["mat-dialog-actions","",1,"velt-confirm-dialog-actions"]],template:function(t,i){if(t&1&&(f(0,"div",1,0),p(2,RWe,2,6,"ng-container",2),S()),t&2){let a=Ee(1);g("ngClass",i.variantClass)("snippylyOverlay",a)("snippylyOverlayZIndex",1200)("snippylyOverlayBackdropZIndex",1100),w("data-testid",i.componentId),v(2),g("ngIf",i.componentConfigSignal())}},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}body.velt-pin-dragging[_ngcontent-%COMP%] iframe[_ngcontent-%COMP%]{pointer-events:none!important}[_nghost-%COMP%] *[_ngcontent-%COMP%]{outline:0}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent)}[dark][_nghost-%COMP%]{--velt-green: var(--velt-dark-mode-green);--velt-magenta: var(--velt-dark-mode-magenta);--velt-amber: var(--velt-dark-mode-amber);--velt-purple: var(--velt-dark-mode-purple);--velt-cyan: var(--velt-dark-mode-cyan);--velt-orange: var(--velt-dark-mode-orange);--velt-black: var(--velt-dark-mode-black);--velt-white: var(--velt-dark-mode-white);--velt-gray: var(--velt-dark-mode-gray);--velt-error: var(--velt-dark-mode-error);--velt-error-hover: var(--velt-dark-mode-error-hover);--velt-error-foreground: var(--velt-dark-mode-error-foreground);--velt-error-light: var(--velt-dark-mode-error-light);--velt-error-transparent: var(--velt-dark-mode-error-transparent);--velt-warning: var(--velt-dark-mode-warning);--velt-warning-hover: var(--velt-dark-mode-warning-hover);--velt-warning-foreground: var(--velt-dark-mode-warning-foreground);--velt-warning-light: var(--velt-dark-mode-warning-light);--velt-warning-transparent: var(--velt-dark-mode-warning-transparent);--velt-success: var(--velt-dark-mode-success);--velt-success-hover: var(--velt-dark-mode-success-hover);--velt-success-foreground: var(--velt-dark-mode-success-foreground);--velt-success-light: var(--velt-dark-mode-success-light);--velt-success-transparent: var(--velt-dark-mode-success-transparent);--velt-accent: var(--velt-dark-mode-accent);--velt-accent-text: var(--velt-dark-mode-accent-text);--velt-accent-hover: var(--velt-dark-mode-accent-hover);--velt-accent-foreground: var(--velt-dark-mode-accent-foreground);--velt-accent-light: var(--velt-dark-mode-accent-light);--velt-accent-transparent: var(--velt-dark-mode-accent-transparent);--velt-text-0: var(--velt-dark-mode-text-0);--velt-text-1: var(--velt-dark-mode-text-1);--velt-text-2: var(--velt-dark-mode-text-2);--velt-text-3: var(--velt-dark-mode-text-3);--velt-text-4: var(--velt-dark-mode-text-4);--velt-text-5: var(--velt-dark-mode-text-5);--velt-text-6: var(--velt-dark-mode-text-6);--velt-text-7: var(--velt-dark-mode-text-7);--velt-text-8: var(--velt-dark-mode-text-8);--velt-text-9: var(--velt-dark-mode-text-9);--velt-text-10: var(--velt-dark-mode-text-10);--velt-text-11: var(--velt-dark-mode-text-11);--velt-text-12: var(--velt-dark-mode-text-12);--velt-background-0: var(--velt-dark-mode-background-0);--velt-background-1: var(--velt-dark-mode-background-1);--velt-background-2: var(--velt-dark-mode-background-2);--velt-background-3: var(--velt-dark-mode-background-3);--velt-background-4: var(--velt-dark-mode-background-4);--velt-background-5: var(--velt-dark-mode-background-5);--velt-background-6: var(--velt-dark-mode-background-6);--velt-background-7: var(--velt-dark-mode-background-7);--velt-background-8: var(--velt-dark-mode-background-8);--velt-background-9: var(--velt-dark-mode-background-9);--velt-background-10: var(--velt-dark-mode-background-10);--velt-border-0: var(--velt-dark-mode-border-0);--velt-border-1: var(--velt-dark-mode-border-1);--velt-border-2: var(--velt-dark-mode-border-2);--velt-border-3: var(--velt-dark-mode-border-3);--velt-border-4: var(--velt-dark-mode-border-4);--velt-border-5: var(--velt-dark-mode-border-5);--velt-border-6: var(--velt-dark-mode-border-6);--velt-border-7: var(--velt-dark-mode-border-7);--velt-border-8: var(--velt-dark-mode-border-8);--velt-border-9: var(--velt-dark-mode-border-9);--velt-border-10: var(--velt-dark-mode-border-10);--velt-background-transparent: var(--velt-dark-mode-background-transparent);--velt-border-transparent: var(--velt-dark-mode-border-transparent);--velt-animation-transparent: var(--velt-dark-mode-animation-transparent)}.velt-confirm-dialog[_ngcontent-%COMP%]{width:455px;padding:40px;display:block;box-sizing:border-box;background-color:var(--velt-background-0)}.velt-confirm-dialog-actions[_ngcontent-%COMP%]{justify-content:space-between;gap:var(--velt-spacing-md);min-height:auto} .velt-mat-dialog-container mat-dialog-container .mat-mdc-dialog-surface.mdc-dialog__surface:has(snippyly-confirm-dialog){border-radius:var(--velt-border-radius-xl);padding:0}@media (max-width: 768px){.velt-confirm-dialog[_ngcontent-%COMP%]{width:auto;max-width:455px;padding:24px}}"],changeDetection:0});let n=o;return n})();function NWe(n){return n?`velt-confirm-dialog--${n}`:""}var mn=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A,M,V,q,ae,ye,ie,ge){this.afAuth=e,this.analyticsService=t,this.authService=i,this.configService=a,this.commonDbService=l,this.commonDbUtilsService=c,this.commentUtilsService=d,this.commentAnnotationsResolverService=m,this.notificationResolverService=u,this.databaseService=_,this.docService=I,this.domService=A,this.iamService=M,this.loggingService=V,this.notificationUtilsService=q,this.usersService=ae,this.functions=ye,this.userPermissionService=ie,this.coreActionsService=ge,this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new _e([]),this.rawNotificationsByIdMap$=new _e(new Map),this.processedNotifications$=new _e([]),this.userNotificationsFromServer$=new _e(null),this.readNotificationsOnForYouTab$=new _e(!1),this.currentDocumentOnly$=new _e(!1),this.notificationViews$=new _e({}),this.notificationsByIdMap$=new _e(new Map),this.historyPanelVisible$=new _e(!1),this.notificationsForYou$=new _e(null),this.notificationsByDocumentIdMap$=new _e(null),this.notificationsByDocumentIdSubscription={},this.allowedDocumentMetadataMap$=new _e(null),this.maxNotificationDays$=new _e(15),this.tabConfig$=new _e({people:{enable:!1}}),this.settingsConfig$=new _e(null),this.setSettingsConfigByOrganization$=new _e(!1),this.muteAllNotifications$=new _e(!1),this.enableSettings$=new _e(!1),this.selfNotifications$=new _e(!1),this.settingsInitialConfig$=new _e([{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 _e(!1);try{this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(Ge(Ie=>!!Ie),ut(1)).subscribe(Ie=>{if(Ie){this.db=Ie;try{let he=this.configService.getProxyConfig(),Te=On.firebaseNotificationsDatabaseURL;he?.v1DbHost&&Te&&(Te=KN(Te,he.v1DbHost)),this.notificationsDb=D_(void 0,Te),he?.v1DbHost&&Te&&this.databaseService.lockDatabaseHost(this.notificationsDb)}catch(he){this.loggingService.catch("Error initializing notifications DB, using default: ",he),this.notificationsDb=Ie}this.getDocumentIds(),this.subscribeGetNotificationsForYou()}},Ie=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",Ie)}),this.authService.getUser$().subscribe(Ie=>{Ie?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(he=>{this.notificationsByDocumentIdSubscription[he]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),this.docService.getLocationMetadata$().subscribe(Ie=>{if(Ie){let he=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(Ie||{}).forEach(Te=>{let Oe=he?.[Te]?.notifications;Oe?.length&&Oe.forEach(Pe=>{this.notificationUtilsService.mergeLocationWithNotification({notification:Pe},Ie)?.notification})}),this.notificationsByDocumentIdMap$.next(he)}})}catch(Ie){this.loggingService.catch("Error in NotificationService constructor: ",Ie)}}setDBConfigDataToInitialConfig(e){try{let t=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(e||{}).forEach(([i,a])=>{t[i]=a}),this.settingsConfig$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",t)}}getInitialConfigFromDB(e){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let t=++this.settingsConfigGeneration,i=It(this.authService.getUser()?.userId??""),a=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:this.getSettingsConfigByOrganization()?void 0:e?.documentId,organizationId:e?.organizationId??this.docService.getOrganizationConfig()?.organizationId,userId:i}});if(t!==this.settingsConfigGeneration)return;if(a?.notificationsConfig)this.setDBConfigDataToInitialConfig(a?.notificationsConfig);else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let l={};this.settingsInitialConfig$.getValue().forEach(d=>{if(d.enable){let m=d?.values?.find(u=>u.id===d.default);l[d.id]=m||d?.values?.[0]||{id:"NONE",name:"None"}}});let c={};Object.keys(l).forEach(d=>{c[d]=l[d].id}),yield this.updateSettingsConfigToDb(c)}}catch(t){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",t)}})}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let e=It(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(Ge(t=>t===!0),Se(()=>gn([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe(Ge(([t,i,a])=>(i||!!t)&&!!a?.organizationId),Se(([t,i,a])=>co(this.getInitialConfigFromDB(t)).pipe(Se(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:i?void 0:t?.documentId,organizationId:t?.organizationId??a?.organizationId,userId:e}}).pipe(ue(l=>{l?.data?.notificationsConfig&&!sr(l?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(l?.data?.notificationsConfig)})))))))).subscribe()}catch(e){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",e)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.setUserNotificationsFromServer(null),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.next(null)}catch(e){this.loggingService.catch("Error in NotificationService resetCacheData: ",e)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",e)}}setCommentService(e){try{this.commentService=e}catch(t){this.loggingService.catch("Error in NotificationService setCommentService: ",t)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=this.selfNotifications$.pipe(Se(()=>this.getCurrentDocumentOnly$().pipe(Se(e=>e?this.docService.getDocumentPaths$().pipe(ue(t=>{})):ce(void 0)))),ln(()=>{this.notificationsByDocumentIdMap$.next(null)}),Se(()=>this.getDocumentIdsByLastNotificationTimestamp().pipe(Fr(),ue(([e,t])=>{let i=e?.map(m=>m.documentId),a=t?.map(m=>m.documentId),l=i?.filter(m=>!a?.includes(m)),c=a?.map(m=>({documentId:m,timestamp:t?.find(u=>u.documentId===m)?.timestamp})).filter(m=>!i?.includes(m.documentId)),d=a?.map(m=>{let u=t?.find(_=>_.documentId===m)?.timestamp;return{documentId:m,timestamp:u}}).filter(m=>{let u=e?.find(_=>_.documentId===m.documentId)?.timestamp;return u&&m.timestamp&&u!==m.timestamp});c?.length&&this.fetchNotificationsForDocumentIds(c),d?.length&&this.fetchNotificationsForDocumentIds(d,1),l?.forEach(m=>{this.removeNotificationsForDocumentId(m)}),t&&!t?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))})))).subscribe(()=>{},e=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",e)})}catch(e){this.loggingService.catch("Error in NotificationService getDocumentIds: ",e)}}getDocumentIdsByLastNotificationTimestamp(e=15){try{return this.authService.getUser$().pipe(Se(t=>this.docService.getOrganizationConfig$().pipe(ue(i=>{let a=null,l=this.configService.getApiKey(),c=i?.organizationId||t?.organizationId,d=i?.clientOrganizationId||t?.clientOrganizationId||"";return l&&c&&(a=new bm({apiKey:l,organizationId:c})),{user:t,documentPaths:a,clientOrganizationId:d}}))),Se(t=>{let{user:i,documentPaths:a,clientOrganizationId:l}=t;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return ce(null);if(i&&a?.organizationNotificationsLastNotificationTimestamp){let c=new Date,d=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;c.setDate(c.getDate()-d);let m=c.getTime(),u=[yr(ft("timestamp",">=",m),...this.getCurrentDocumentOnly()&&this.docService.getDocumentPaths()?.documentId?[ft("metadata.documentId","==",this.docService.getDocumentPaths()?.documentId)]:[])];this.getCurrentDocumentOnly()||(u.push(uo("timestamp","desc")),u.push(hm(e)));let _=i?.userId??"";return co(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:l})??Promise.resolve({})).pipe(Se(I=>_&&l&&I?.[_]?.organization?.[l]?.errorCode===mr.PERMISSION_DENIED?ce(null):this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:a?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:u}}).pipe(ue(A=>A?.data),ue(A=>{let M=[];return Object.keys(A||{}).forEach(V=>{let q=this.commonDbService.shouldUseFirestore()?A[V]?.timestamp??0:A[V],ae=this.commonDbService.shouldUseFirestore()?A[V]?.deletedNotification??!1:!1;if(ae&&ae.id&&ae?.timestamp===q){let ye=ae.id,ie=A[V]?.metadata?.documentId,ge=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),Ie=ge?.[ie]??{documentMetadata:null,notifications:[]},he=Ie.notifications??[],Te=he?.findIndex(Oe=>Oe.id===ye);Te!==-1&&(he.splice(Te,1),this.notificationsByDocumentIdMap$.next(y(h({},ge),{[ie]:y(h({},Ie),{notifications:he})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById(ye)&&this.notificationResolverService.deleteNotification(ye,this.docService.getDocumentPaths()?.clientOrganizationId??"")}M.push({documentId:V,timestamp:q})}),M}),Xn(A=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",A),ce([]))))))}return ce(null)}))}catch(t){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",t),ce([])}}resolveAndUpdateDocumentNotifications(e,t){try{Object.keys(e).forEach(i=>{let a=e[i]?.documentMetadata||this.docService.getAllDocumentMetadataMap()?.[i]||{},l;if(t==="user")l=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:e[i]?.notifications||[]});else if(t==="notification"){let c=e[i]?.notifications?.reduce((m,u)=>(m[u.notificationId]=u,m),{}),d=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:c});l=Object.values(d??{})}else{let c=e[i]?.notifications?.reduce((m,u)=>(m[u.notificationId]=u,m),{}),d=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:c});l=Object.values(d??{})}l.forEach(c=>{c.notification=this.getClientNotificationObject(c)}),this.setNotificationForDocumentIdInCache(i,a,l)})}catch(i){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",i)}}resolveAndMergeUserNotifications(e,t,i=!1){try{let a=e;if(i&&t==="comment"){let u=this.getUserNotificationsFromServer()??[],_=new Set(e.map(I=>I.notificationId));a=u.filter(I=>_.has(I.notificationId)).concat(e.filter(I=>!u.some(A=>A.notificationId===I.notificationId)))}let l=a.reduce((u,_)=>(u[_.notificationId]=_,u),{}),c;if(t==="user"){let u=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:l});c=Object.values(u??{})}else if(t==="notification"){let u=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:l});c=Object.values(u??{})}else{let u=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:l});c=Object.values(u??{})}c.forEach(u=>{u.notification=this.getClientNotificationObject(u)});let d=this.getUserNotificationsFromServer()??[],m=new Map(d.map(u=>[u.notificationId,u]));c.forEach(u=>{m.set(u.notificationId,u)}),this.setUserNotificationsFromServer(Array.from(m.values()))}catch(a){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",a)}}fetchNotificationsForDocumentIds(e,t=15){return X(this,null,function*(){try{if(e?.length){let i=Yr(this.functions,Zr({url:On.cloudFunction.getNotificationsForDocuments,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=this.docService.getOrganizationConfig()?.organizationId??"";if(!a)return[];let l=this.getStartAtTimestamp(),c={};if(e.forEach(ie=>{if(ie?.documentId){let ge=this.getAllowedDocumentMetadataByDocumentId(ie.documentId);ge&&(c[ie.documentId]=ge)}}),this.userPermissionService?.isPermissionProviderAvailable())try{let ie=[];if(e.forEach(Oe=>{this.docService.getDocumentMetadata(Oe.documentId)||ie.push(Oe.documentId)}),ie.length){let Oe=this.authService.getUser(),Pe=Yr(this.functions,Zr({url:On?.cloudFunction?.sdkProxy,apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let $e=yield wl({methodName:"getDocumentMetadataFromIds",data:{type:"getDocumentMetadataFromIds",metadata:{organizationId:Oe?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:ie},getSdkProxy:Pe,userId:Oe?.userId??""});if($e?.data?.length){let ze={};$e.data.forEach(We=>{We?.documentId&&(ze[We.documentId]=We)}),this.docService.setAllDocumentMetadata(h(h({},this.docService.getAllDocumentMetadataMap()),ze))}}catch($e){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",$e)}}let ge=[],Ie=[];e.forEach(Oe=>{let Pe=this.docService.getDocumentMetadata(Oe.documentId);Pe?.clientDocumentId?ge.push({userId:this.authService.getUser()?.userId??"",resource:{id:Pe.clientDocumentId,type:bi.DOCUMENT,source:no.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""}}):Ie.push(Oe.documentId)}),Ie.length&&(e=e.filter(Oe=>!Ie.includes(Oe.documentId)));let he=lt();this.coreActionsService.triggerAction(tt.PERMISSION_PROVIDER,{event:Y.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:he,methodName:no.GET_NOTIFICATIONS,source:"internal",payload:{requests:ge}});let Te=yield this.userPermissionService?.onResourceAccessRequired({requests:ge,uniqueId:he,methodName:no.GET_NOTIFICATIONS});Te?.success&&Te?.data?.length?Te.data.forEach(Oe=>{!Oe.hasAccess&&Oe.resourceId&&(e=e.filter(Pe=>Pe.documentId!==mi(Oe.resourceId)))}):e=[]}catch(ie){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",ie),e=[]}if(!e.length)return this.notificationsByDocumentIdMap$.getValue()||(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),[];let d=this.userPermissionService?.getPermissionsCache()?.filter(ie=>ie.type===bi.CONTEXT),m={organizationId:a,documentIds:e.filter(ie=>!!ie.documentId&&!!ie.timestamp).map(ie=>({documentId:ie.documentId,timestamp:ie.timestamp??0})),timestamp:l,limitToLast:t,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:d,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},u=yield this.notificationUtilsService.handleNotificationEncryption({data:m}),_=yield i({veltData:u}),I=_?.data?.data?.veltData||{},A=_?.data?.data?.veltAdditionalData||{},M="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),V=yield u1(I,M),{userNotifications:q=[],userNotificationIdsInDocNotifications:ae=[],permissionResults:ye=[]}=yield u1(A,M);if(this.userPermissionService?.getIsContextEnabled()){let ie=[...this.userPermissionService?.getPermissionsCache()??[],...ye??[]];this.userPermissionService?.setPermissionsCache(ie)}if(V&&typeof V=="object"){let ie=this.usersService.userDataProviderAvailable(),ge=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),Ie=this.notificationResolverService.notificationDataProviderAvailable(),he=[],Te=[],Oe=[];Object.keys(V).forEach((ze,We)=>{let gr=V[ze].documentMetadata??this.docService.getAllDocumentMetadataMap()?.[ze];if(gr){let Et=this.allowedDocumentMetadataMap$.value||{};(!Et?.[ze]||!sr(Et?.[ze],gr))&&this.allowedDocumentMetadataMap$.next(y(h({},Et),{[ze]:gr}))}let nt=V[ze].notifications||[];nt.forEach(Et=>{ae.includes(Et.notificationId)&&!q.find(Je=>Je.notificationId===Et.notificationId)&&q.push(JSON.parse(JSON.stringify(Et))),Et.notification=this.getClientNotificationObject(Et)}),this.setNotificationForDocumentIdInCache(ze,gr,nt),ie&&(he.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:nt,shouldAwait:!0,forceResolve:!0})),he.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:q,shouldAwait:!0,forceResolve:!0}))),ge&&(Te.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:nt,shouldCommentAnnotationsResolverAwait:!0})),Te.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:q,shouldCommentAnnotationsResolverAwait:!0}))),Ie&&(Oe.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:nt,shouldNotificationResolverAwait:!0})),Oe.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:q,shouldNotificationResolverAwait:!0})))});let Pe=JSON.parse(JSON.stringify(q));this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...q]),(Ie||ie||ge)&&(()=>{let ze=Promise.resolve();if(Ie&&(ze=ze.then(()=>Promise.allSettled(Oe)).then(()=>{this.resolveAndUpdateDocumentNotifications(V,"notification"),this.resolveAndMergeUserNotifications(Pe,"notification")})),ie&&(ze=ze.then(()=>Promise.allSettled(he)).then(()=>{this.resolveAndUpdateDocumentNotifications(V,"user"),this.resolveAndMergeUserNotifications(Pe,"user")})),ge){let We=Ie||ie;ze=ze.then(()=>Promise.allSettled(Te)).then(()=>{this.resolveAndUpdateDocumentNotifications(V,"comment"),this.resolveAndMergeUserNotifications(Pe,"comment",We)})}return ze})().catch(ze=>{this.loggingService.catch("Error in NotificationService resolveChain: ",ze)})}}}catch(i){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",i),[]}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(e){try{let t=JSON.parse(JSON.stringify(e));t=t?.filter((i,a,l)=>a===l.findIndex(c=>c.notificationId===i.notificationId)),this.userNotificationsFromServer$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService setUserNotificationsFromServer: ",t)}}getUserNotificationsFromServer(){return this.userNotificationsFromServer$.getValue()}setNotificationForDocumentIdInCache(e,t,i,a){try{let l=this.docService.getOrganizationConfig()?.organizationId??"",c=this.docService.getOrganizationMetadata(l);t||(t=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),c||(c=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(l)||{})));let d=this.notificationsByDocumentIdMap$.getValue(),m=d?.[e]?.notifications||[],u=this.docService.getLocationMetadatas(),_=i?.map(M=>{let V=M?.notification;return V?(V.metadata&&(V.metadata.documentName=t?.documentName||V.metadata.documentName,V.metadata.organizationMetadata=c||V.metadata.organizationMetadata,V.metadata.documentMetadata=t||V.metadata.documentMetadata),u&&(V=this.notificationUtilsService.mergeLocationWithNotification({notification:V},u)?.notification),V):null})?.filter(M=>!!M)||[],I=new Map(m.map(M=>[M.id,M]));_.forEach(M=>{I.set(M.id,M)});let A=Array.from(I.values()).sort((M,V)=>(V.timestamp||0)-(M.timestamp||0));this.notificationsByDocumentIdMap$.next(y(h({},d),{[e]:{notifications:A,documentMetadata:t}}))}catch(l){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",l)}}removeNotificationsForDocumentId(e){try{this.notificationsByDocumentIdSubscription[e]&&this.notificationsByDocumentIdSubscription[e].unsubscribe();let t=this.notificationsByDocumentIdMap$.getValue();delete t?.[e],this.notificationsByDocumentIdMap$.next(t)}catch(t){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",t)}}getStartAtTimestamp(){try{let e=new Date,t=this.maxNotificationDays$.getValue()>0?this.maxNotificationDays$.getValue():15;return e.setDate(e.getDate()-t),e.getTime()}catch(e){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",e),0}}getNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(Se(e=>ce(e).pipe(Ge(t=>!!t),ue(t=>{let i=this.usersService.userDataProviderAvailable(),a=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),l=this.notificationResolverService?.notificationDataProviderAvailable();if(l||i||a){let d=t?.reduce((m,u)=>(m[u.notificationId]=u,m),{});l&&(d=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:d||[]})),i&&(d=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:d||[]})),a&&(d=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:d||[]})),t=Object.values(d??{})}return t.forEach(d=>{d.notification=this.getClientNotificationObject(d)}),t.sort((d,m)=>m.timestamp-d.timestamp),t.map(d=>d.notification).filter(d=>!!d)}),Se(t=>{let i={data:t?.reduce((a,l)=>(a[l.id]={notification:l},a),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:i,feature:"allUserNotifications"}).pipe(ue(a=>Object.values(a?.data||{}).map(l=>l?.notification)))}))),Se(e=>{let t=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(t).pipe(ue(()=>e))}),Se(e=>this.allowedDocumentMetadataMap$.pipe(ue(()=>e))),ue(e=>(e?.length&&(e=e.map(t=>{if(t?.metadata){let i=this.docService.getOrganizationConfig()?.organizationId??"",a=this.getAllowedDocumentMetadataByDocumentId(t.metadata.documentId),l=this.docService.getOrganizationMetadata(i);a||(a=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata()||{}))),l||(l=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(i)||{}))),t.metadata.documentName=a?.documentName||t.metadata.documentName,t.metadata.organizationMetadata=l||t.metadata.organizationMetadata,t.metadata.documentMetadata=a||t.metadata.documentMetadata}return t})),e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(JSON.parse(JSON.stringify(e))):this.notificationsForYou$.next([]),ce(e))))}catch(e){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",e),ce({})}}subscribeNotificationsData(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let i,a;try{if(e&&(a=er(e)),t&&typeof t=="object"){let l=Oi(t);i=er(JSON.stringify(l))}}catch(l){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",l)}return _r(this.afAuth).pipe(Ge(l=>!!l),Se(l=>this.isFeatureAllowed({firebaseUser:l})),Se(l=>l.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(c=>(l.featureAllowed=c,l))):ce(l)),Se(l=>!l.featureAllowed||l?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),ce([])):ce(l).pipe(Se(c=>this.docService.getDocumentPaths$().pipe(ue(d=>(this.documentPaths=d,c.documentPaths=d,c)))),Se(c=>this.getDataFromDocumentId(a)))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})),Se(t=>this.authService.getUser$().pipe(ue(i=>y(h({},t),{user:i})))),Se(t=>Ao(t.config,t.user,je.NOTIFICATION)?ce(y(h({},t),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),ce(y(h({},t),{featureAllowed:!1})))))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ge(t=>!!t),Se(t=>{if(this.db=t,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let i=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(i+=`/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let a=jr(this.db,`${e?i+"/"+N.FIREBASE_PARTIAL_PATH_DOCS+"/"+e+"/"+N.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return x8(a).pipe(Xn(l=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",l),ce(null))),ue(l=>{let c=[],d=new Map;l?.raw&&(Object.keys(l?.raw||{}).forEach(u=>{let _=l?.raw[u];_?.id&&c.push(_)}),c.forEach(u=>{u.id&&d.set(u.id,u)})),this.notifications$.next(c),this.rawNotificationsByIdMap$.next(d);let m=[];l?.processed&&Object.keys(l?.processed||{}).forEach(u=>{let _=l?.processed[u];_?.id&&m.push(_)}),this.processedNotifications$.next(m),this.setNotificationsByIdMap()}))}else return ce(null)}))}setNotificationsByIdMap(){try{let e=this.authService.getUser();if(e){let t=this.notificationViews$.getValue(),i;e?.email&&(i=It(e?.email));let a;e?.userId&&(a=It(e?.userId));let l=new Map;this.processedNotifications$.getValue().forEach(d=>{if(d.id&&d?.displayHeadlineMessageTemplate){let m=!1;(i&&d.notifyUsers?.[i]||a&&d.notifyUsers?.[a])&&(m=!0);let u={id:d.id,notificationSource:d.notificationSource,actionType:d.actionType,actionUser:d.actionUser,timestamp:d.timestamp,targetAnnotationId:d.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(d),displayBodyMessage:this.getNotificationBodyMessage(d),forYou:m,notificationSourceData:d.notificationSourceData},_=this.getRawNotificationById(u.id);if(_?.metadata&&(u.metadata={apiKey:_.metadata.apiKey,organizationId:_.metadata.organizationId,clientOrganizationId:_.metadata.clientOrganizationId,documentId:_.metadata.documentId,clientDocumentId:_.metadata.clientDocumentId,location:_?.location,locationId:_?.locationId}),u?.notificationSource==="comment"&&u?.targetAnnotationId){let I=this.commentService?.getAnnotationById(u.targetAnnotationId);I||_?.annotationData&&(I=_.annotationData),I&&(u.notificationSourceData=this.commentService?.getCommentAnnotationForClient(I))}l.set(d.id,u)}}),l.forEach((d,m)=>{d.isUnread=d?.actionUser?.userSnippylyId!==e?.userSnippylyId&&!t?.notification?.[m]?.views?.[e?.userSnippylyId],l.set(m,d)}),this.notificationsByIdMap$.next(l)}}catch(e){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",e)}}getClientNotificationObject({processed:e,raw:t,metadata:i,views:a,notification:l}){try{let c=this.authService.getUser(),d=l||e;if(d.id&&d?.displayHeadlineMessageTemplate&&c){let m=null;c?.email&&(m=It(c?.email));let u=null;c?.userId&&(u=It(c?.userId));let _=!1,I=!0;(m&&d.notifyUsers?.[m]||u&&d.notifyUsersByUserId?.[u])&&(_=!0),u&&a?.[u]&&(I=!1);let A={id:d.id};if(l?A=y(h(h({},A),l),{displayHeadlineMessage:this.getNotificationHeadlineMessage(l),displayBodyMessage:this.getNotificationBodyMessage(l),forYou:_,isUnread:I}):A={id:e.id,notificationSource:e.notificationSource,actionType:e.actionType,actionUser:e.actionUser,timestamp:e.timestamp,targetAnnotationId:e.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(e),displayBodyMessage:this.getNotificationBodyMessage(e),forYou:_,isUnread:I,metadata:i},A?.notificationSource==="comment"&&A?.targetAnnotationId){let M=this.commentService?.getAnnotationById(A.targetAnnotationId);M||l?.notificationSourceData&&(M=l?.notificationSourceData),M||t?.annotationData&&(M=t.annotationData),M&&(A.notificationSourceData=this.commentService?.getCommentAnnotationForClient(M))}return t?.targetAnnotationData?.isCommentResolverUsed&&(A.isCommentResolverUsed=t?.targetAnnotationData?.isCommentResolverUsed),l?.isNotificationResolverUsed&&(A.isNotificationResolverUsed=l.isNotificationResolverUsed),A}return}catch(c){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",c);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(ue(e=>e?Object.keys(e??{}).map(t=>{let i=e[t].notifications||[],a=i.filter(c=>c.isUnread).length,l=i.length>0&&i[0]?.timestamp||0;return{documentId:t,notifications:e[t]?.notifications,unreadNotificationsCount:a,latestNotificationTimestamp:l,documentMetadata:e[t]?.documentMetadata}}).filter(t=>t.notifications?.length>0).sort((t,i)=>i.latestNotificationTimestamp-t.latestNotificationTimestamp):null))}getAllNotifications$(){return this.getNotificationsByDocumentId$().pipe(ue(e=>{let t=null;return e?(t=[],e.forEach(i=>{i.notifications.forEach(a=>{t?.push(a)})}),t?.sort((i,a)=>a.timestamp-i.timestamp)):null}))}processNotificationData(e){try{let t=e?.annotationData?.metadata,i=this.docService.getOrganizationConfig()?.organizationId;e.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(t?.documentId)||{})),e.metadata||(e.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete e.metadata.locations,e.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(t?.documentId)||{})),e?.metadata?.documentMetadata?.clientDocumentId&&e?.metadata?.documentMetadata?.documentId&&(e.metadata.documentMetadata.documentId=e?.metadata?.documentMetadata?.clientDocumentId),delete e.metadata.documentMetadata.locations,e.metadata.organizationMetadata=JSON.parse(JSON.stringify(i?this.docService.getOrganizationMetadata(i)||{}:{})),e?.metadata?.organizationMetadata?.clientOrganizationId&&e?.metadata?.organizationMetadata?.organizationId&&(e.metadata.organizationMetadata.organizationId=e?.metadata?.organizationMetadata?.clientOrganizationId);let a=this.configService.getApiKey();e.metadata.apiKey=a,e.platform=this.configService.getSF()?"sf":"sdk",e.actionUser=this.authService.getUser();let l=t?.documentId?new bm({apiKey:a,documentId:t.documentId,organizationId:t?.organizationId}):this.docService.getDocumentPaths();e?.actionUser?.organizationId&&(e.metadata.organizationId=l?.organizationId||e.actionUser.organizationId,e.metadata.clientOrganizationId=l?.clientOrganizationId||e.actionUser.clientOrganizationId);let c=this.docService.getLocation();c&&(e.location=c?.location,e.locationId=c?.locationId),this.loggingService.log(`[NOTIFICATION] ${e?.notificationSource} ${e?.actionType}`,e);let d=this.commonDbService.getServerTimestamp(),m=this.notificationUtilsService.formatNotification(e,d);return JSON.parse(JSON.stringify(m))}catch(t){return this.loggingService.catch("Error in NotificationService processNotificationData: ",t),null}}updateNotificationDatabase(e){try{if(!this.notificationsDb)return;let t=jr(this.notificationsDb),i=this.processNotificationData(e);p8(t,JSON.parse(JSON.stringify(i)))}catch(t){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",t)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(e){return this.authService.getUser$().pipe(Se(t=>t?t.organizationId?this.getAllNotifications$().pipe(Se(i=>this.notificationsForYou$.pipe(ue(a=>{if(i||a){let l=new Map;return(!e?.type||["all","documents"].includes(e.type))&&(i||[]).forEach(c=>{c.id&&l.set(c.id,c)}),(!e?.type||["all","forYou"].includes(e.type))&&(a||[]).forEach(c=>{c.id&&!l.has(c.id)&&l.set(c.id,c)}),Array.from(l.values()).sort((c,d)=>(d.timestamp||0)-(c.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(ue(i=>Array.from(i.values())),ue(i=>i.sort((a,l)=>l.timestamp-a.timestamp)),Zh()):ce(null)),_t(Kt))}getRawNotificationById(e){try{return this.rawNotificationsByIdMap$.getValue()?.get(e)}catch(t){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",t);return}}setNotificationViews(e){try{this.notificationViews$.next(e),this.setNotificationsByIdMap()}catch(t){this.loggingService.catch("Error in NotificationService setNotificationViews: ",t)}}getNotificationHeadlineMessage(e){try{let t=this.authService.getUser();if(e?.displayHeadlineMessageTemplate&&e?.displayHeadlineMessageTemplateData){let i=e.displayHeadlineMessageTemplate,a=e.displayHeadlineMessageTemplateData,l=/\{(\w+)\}/g,c=i.replace(l,(d,m)=>(m==="actionUser"||m==="recipientUser")&&a[m]?t?.email&&a[m].email===t?.email||t?.userId&&a[m]?.userId===t?.userId?"You":a[m].name||a[m].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':a[m]?a[m]:d);return this.domService.sanitizeHtml(c)}return this.domService.sanitizeHtml(e.displayHeadlineMessageTemplate||"")}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",t),""}}getNotificationBodyMessage(e){try{if(e?.displayBodyMessageTemplate&&e?.displayBodyMessageTemplateData){let t=e?.displayBodyMessageTemplate;return e?.displayBodyMessageTemplateData&&e?.displayBodyMessageTemplateData?.users?.forEach(i=>{if(i?.userId){let a=this.usersService.getUserById(i?.userId);t=t?.replaceAll(`{{${i.userId}}}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>'),t=t?.replaceAll(`@User ${i.userId}`,a?.name||a?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(t)}return this.domService.sanitizeHtml(e.displayBodyMessage||"")}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",t),""}}setHistoryPanelVisibility(e,t=!1,i=!1){try{e?document.querySelector(N.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(e):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${N.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(e),e?this.analyticsService.trackEvent(Y.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(Y.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${N.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(e=!1,t=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(N.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(Y.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(Y.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${N.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${N.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(e){return X(this,null,function*(){try{let t=JSON.parse(JSON.stringify(this.getUserNotificationsFromServer()??[]));if(e?.length){for(let c=0;c<e.length;c+=50){let m=e.slice(c,c+50).filter(I=>I?.id),u=m.map(I=>this.setNotificationAsRead({notification:I,userNotifications:JSON.parse(JSON.stringify(t))})),_=yield Promise.all(u);m.forEach((I,A)=>{let M=_[A];if(!M.some(q=>q.notificationId===I.id))t=t.filter(q=>q.notificationId!==I.id);else{let q=t.find(ye=>ye.notificationId===I.id),ae=M.find(ye=>ye.notificationId===I.id);q&&ae?.views&&(q.views=ae.views)}})}let a=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));e.forEach(c=>{let d=c.metadata?.documentId;if(d&&a?.[d]){let m=a?.[d]?.notifications||[],u=m.find(_=>_.id===c.id);u&&(u.isUnread=!1),a[d].notifications=m}}),this.notificationsByDocumentIdMap$.next(a),!sr(t,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(t)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",t)}})}setAllNotificationsAsRead(e){return X(this,null,function*(){try{if(e?.tabId==="for-you"){let t=this.notificationsForYou$.value||[];this.setNotificationsAsRead(t)}else this.getNotifications$().pipe(ut(1)).subscribe(t=>{t&&this.setNotificationsAsRead(t)})}catch(t){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",t)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(ue(e=>e?.filter(i=>i?.isUnread)?.length??null),Se(e=>this.getNotifications$().pipe(ue(t=>{let i=t?.filter(a=>a?.isUnread)?.length??null;return{forYou:e,all:i}}))))}catch(e){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",e),ce({forYou:null,all:null})}}setNotificationAsRead(i){return X(this,arguments,function*({notification:e,userNotifications:t}){try{let a=this.authService.getUser();if(a&&e?.id){let l=It(a?.userId),{metadata:c}=e;if(c){let{apiKey:d,organizationId:m,documentId:u}=c;if(d&&m&&u&&l){let _=yield this.commonDbService.getData({feature:"docNotification",properties:{id:e.id,organizationId:m,documentId:u,apiKey:d}});_?.notificationId&&(_?.views?.[l]||(_.views||(_.views={}),_.views[l]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:e.id,organizationId:m,documentId:u,apiKey:d},data:_})));let I=yield this.commonDbService.getData({feature:"userNotification",properties:{id:e.id,userId:l,documentId:u,organizationId:m}});if(I?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:e.id,userId:l,documentId:u,organizationId:m}}),t=t.filter(A=>A.notificationId!==e.id);else if(!I?.views?.[l]){I.views||(I.views={}),I.views[l]={timestamp:Date.now()};let A=t.find(M=>M.notificationId===e.id);A&&(A.views=I.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:e.id,userId:l,documentId:u,organizationId:m},data:I})}}}}}return t}catch(a){return this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",a),t}})}setMaxDays(e){try{e>0?this.maxNotificationDays$.next(e):this.maxNotificationDays$.next(15)}catch(t){this.loggingService.catch("Error in NotificationService setMaxDays: ",t)}}setTabConfig(e){try{e&&this.tabConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setTabConfig: ",t)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}enableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!0)return;this.currentDocumentOnly$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableCurrentDocumentOnly: ",e)}}disableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!1)return;this.currentDocumentOnly$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableCurrentDocumentOnly: ",e)}}getCurrentDocumentOnly$(){return this.currentDocumentOnly$.asObservable()}getCurrentDocumentOnly(){return this.currentDocumentOnly$.value}markNotificationAsReadById(e){return X(this,null,function*(){try{this.getNotifications$().pipe(ut(1)).subscribe(t=>{if(t){let i=t.filter(a=>a.id===e);this.setNotificationsAsRead(i)}})}catch(t){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",t)}})}getAllowedDocumentMetadataByDocumentId(e){try{return this.allowedDocumentMetadataMap$.value?.[e]||null}catch(t){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",t),null}}setSettingsConfig(e){try{this.enableSettings$.value&&this.settingsConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",t)}}setSettingsConfigWithDB(e){try{this.enableSettings$.value&&(this.settingsConfig$.next(e),this.updateSettingsConfigToDb())}catch(t){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",t)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",e)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSettings: ",e)}}enableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!0&&this.setSettingsConfigByOrganization$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSettingsConfigByOrganization: ",e)}}disableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!1&&this.setSettingsConfigByOrganization$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSettingsConfigByOrganization: ",e)}}getSettingsConfigByOrganization$(){return this.setSettingsConfigByOrganization$.asObservable()}getSettingsConfigByOrganization(){return this.setSettingsConfigByOrganization$.value}enableSelfNotifications(){try{this.selfNotifications$.value!==!0&&this.selfNotifications$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService enableSelfNotifications: ",e)}}disableSelfNotifications(){try{this.selfNotifications$.value!==!1&&this.selfNotifications$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSelfNotifications: ",e)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService disableSettings: ",e)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(e){try{let t=!1;if(e.forEach(i=>{["email","inbox"].includes(i.id)&&(t=!i.values?.every(a=>["ALL","NONE","MINE"].includes(a.id)))}),t){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",t)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(e){return X(this,null,function*(){try{let t=this.authService.getUser(),i=It(t?.userId??""),a=this.docService.getDocumentPaths(),l=this.docService.getOrganizationConfig(),c=a?.organizationId??l?.organizationId,d=a?.clientOrganizationId??l?.clientOrganizationId,m={apiKey:this.configService.getApiKey(),organizationId:c,documentId:a?.documentId,clientOrganizationId:d,clientDocumentId:a?.clientDocumentId,userId:i,clientUserId:this.authService.getUser()?.userId};i&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:d??t?.clientOrganizationId??"",user:{userId:t?.userId??""},notificationsConfig:e||this.settingsConfig$.getValue()}):a?.documentId&&(yield this.commonDbService.updateData({feature:"userConfig",properties:{documentId:a?.documentId,userId:i},data:{id:a?.documentId,notificationsConfig:e||this.settingsConfig$.getValue(),metadata:m}})))}catch(t){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",t)}})}openNotificationsPanel(){try{this.notificationsPanelVisible$.next(!0)}catch(e){this.loggingService.catch("Error in NotificationService openNotificationsPanel: ",e)}}closeNotificationsPanel(){try{this.notificationsPanelVisible$.next(!1)}catch(e){this.loggingService.catch("Error in NotificationService closeNotificationsPanel: ",e)}}getNotificationsPanelVisible$(){return this.notificationsPanelVisible$.asObservable()}getNotificationsPanelVisible(){return this.notificationsPanelVisible$.value}};o.\u0275fac=function(t){return new(t||o)(K(eo),K(ct),K(qe),K(Ft),K(yn),K(vd),K(Cm),K(ol),K(_m),K($n),K(st),K(Ve),K(Vn),K(k),K(WL),K(An),K(Do),K(Ia),K(nr))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var uv=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A,M){this.analyticsService=e,this.configService=t,this.docService=i,this.databaseService=a,this.commonDbService=l,this.authService=c,this.domService=d,this.afAuth=m,this.iamService=u,this.dialog=_,this.loggingService=I,this.notificationService=A,this.userPermissionService=M,this.areaAnnotationById$=new _e({}),this.documentPaths=null,this.areaEnabled$=new _e(!0),this.allowedElementIds$=new _e([]),this.addAreaMode$=new _e(!1),this.loggingService.log("%c[WB] Creating CLASS: AreaService","color: blue;"),this.analyticsService.setAreaService(this),this.authService.setAreaService(this),this.databaseService.getDb().pipe(Ge(V=>!!V),ut(1)).subscribe(V=>{V&&this.getDocumentPaths()},V=>{this.loggingService.catch("Error in AreaService getDb subscription: ",V)}),this.domService.onWindowPointerMove$().subscribe(V=>{if(this.addAreaMode$.value){this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement);let q=this.domService.getBackgroundElement(V.clientX,V.clientY);q&&(this.isElementInsideAllowedElements(q)?eF(V.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement=q,this.domService.highlightElement(this.highlightElement,N.CURSOR.AREA_PIN)):this.domService.removeClassFromElement(document.body,"show-pin-cursor"))}},V=>{this.loggingService.catch("Error in AreaService onWindowPointerMove$ subscription: ",V)}),this.domService.onWindowKeyupEsc$().subscribe(V=>{this.addAreaMode$.value&&this.disableAddAreaMode()},V=>{this.loggingService.catch("Error in AreaService onWindowKeyupEsc$ subscription: ",V)}),this.domService.onDocumentClick$().subscribe(V=>{if(V&&this.addAreaMode$.value){if(V.preventDefault(),V.stopPropagation(),!eF(V.target)){let q=this.domService.getBackgroundElement(V.clientX,V.clientY);q&&this.isElementInsideAllowedElements(q)&&this.addArea(V)}this.disableAddAreaMode()}},V=>{this.loggingService.catch("Error in AreaService onDocumentClick$ subscription: ",V)}),this.addAreaMode$.subscribe(V=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),V?this.domService.addClassToElement(document.body,"snippyly-add-area-mode"):(this.domService.removeClassFromElement(document.body,"snippyly-add-area-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"))},V=>{this.loggingService.catch("Error in AreaService addAreaMode$ subscription: ",V)}),this.domService.onWindowKeyupBackspace$().subscribe(V=>{this.deleteAreaPinAnnotations("keyupBackspace")},V=>{this.loggingService.catch("Error in AreaService onWindowKeyupBackspace$ subscription: ",V)}),this.domService.onWindowKeyupDelete$().subscribe(V=>{this.deleteAreaPinAnnotations("keyupDelete")},V=>{this.loggingService.catch("Error in AreaService onWindowKeyupDelete$ subscription: ",V)})}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in AreaService","color: green;");try{this.areaAnnotationById$.next({}),this.areaEnabled$.next(!0),this.allowedElementIds$.next([]),this.addAreaMode$.next(!1),this.highlightElement=null}catch(e){this.loggingService.catch("Error in AreaService clearCache: ",e)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$()}setAllowedElementIds(e){this.allowedElementIds$.next(e||[])}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}getAllAreaAnnotations(e,t,i){this.loggingService.log("%c[WB] Calling FUNCTION: getAllAreaAnnotations","color: green;");let a,l;try{if(e&&(l=er(e)),t&&typeof t=="object"){let c=Oi(t);a=er(JSON.stringify(c))}}catch(c){this.loggingService.catch("Error in AreaService getAllAreaAnnotations: ",c)}return _r(this.afAuth).pipe(Ge(c=>!!c),Se(c=>this.isFeatureAllowed({firebaseUser:c,annotations:[],filteredAnnotations:[]})),Se(c=>c.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(d=>(c.featureAllowed=d,c))):ce(c)),Se(c=>c.featureAllowed?this.authService.isPlanExpired$().pipe(ue(d=>(c.featureAllowed=!d,c))):ce(c)),Se(c=>c.featureAllowed?ce(c).pipe(Se(d=>this.docService.getDocumentPaths$().pipe(ue(m=>(this.documentPaths=m,d.documentPaths=m,d)))),Se(d=>l?this.getDataFromDocumentIds([l]).pipe(ue(m=>(d.annotations=m||[],h({},d)))):this.docService.getDocumentIds$().pipe(Se(m=>{let u=m?.length>0?m.map(_=>_.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(u).pipe(ue(_=>(d.annotations=_||[],h({},d))))}))),Se(d=>this.docService.getLocation$().pipe(ue(m=>(d.location=m,d)))),Se(d=>this.docService.getLocations$().pipe(ue(m=>(d.customLocations=m,d)))),ue(d=>{if(d.filteredAnnotations=[],l&&!a)return d.filteredAnnotations=d.annotations?.slice(),d;{let m=[],u=[];return a?m.push(a):(m.push(d?.location?.locationId),m.push(...Object.values(d?.customLocations||[]).map(_=>_.locationId)),d?.location?.location?.id&&u.push(d?.location?.location?.id)),d.filteredAnnotations=this.filterAnnotationsByLocationIds(d?.annotations,m,u),d}}),Se(d=>i?ce(d):d?.annotations?.length?this.domService.onWindowResize$().pipe(ue(()=>d)):ce(d)),Se(d=>i?ce(d):d?.annotations?.length?this.domService.onDomChange$("AreaService getAllAreaAnnotations").pipe(ue(()=>d)):ce(d)),ue(d=>(d.filteredAnnotations=d.filteredAnnotations?.map(m=>{let u=Object.assign({},m);return u.areaProperties=this.calculateAreaAnnotationPosition(u),u}),d)),Se(d=>d?.filteredAnnotations?ce(d?.filteredAnnotations||[]):ce([])),Se(d=>{if(this.authService.isFeatureAllowed(je.COMMENT))return ce(d);{let m=d?.filter(u=>!u?.targetAnnotations?.filter(_=>_?.type===je.COMMENT)?.length);return ce(m)}})):ce([])),_t(Kt))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})),Se(t=>this.authService.getUser$().pipe(ue(i=>y(h({},t),{user:i})))),Se(t=>Ao(t.config,t.user,je.AREA)?ce(y(h({},t),{featureAllowed:!0})):(this.loggingService.warn("Area feature is not allowed."),ce(y(h({},t),{featureAllowed:!1})))),_t((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getDataFromDocuments(e){if(this.configService.getApiKey()){let{documentIds:t,filters:i}=e;if(t?.some(d=>!d)||!this.documentPaths)return ce([]);let a=this.docService.getDocumentPaths()?.veltFolderId,l=ce([]),c={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(c.documentId=t?.length?t[0]:void 0,c.organizationId=this.documentPaths?.organizationId),this.userPermissionService?.getIsContextEnabled()){let d=[N.DEFAULT_VELT_CONTEXT,...this.docService.getProcessedDocContext()],m=[];for(let u=0;u<(d?.length??0);u+=N.LISTENER_CONTEXT_BATCH_SIZE)m.push(d?.slice(u,u+N.LISTENER_CONTEXT_BATCH_SIZE)??[]);l=gn(m.map(u=>this.commonDbService.dbListener({feature:"allAreas",properties:y(h({},c),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",t),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[],...u?.length?[ft("context.accessFields","array-contains-any",u)]:[])]})}).pipe(la()))).pipe(ue(u=>Na(u)))}else{let d=[];for(let m=0;m<(t?.length??0);m+=N.LISTENER_BATCH_SIZE)d.push(t?.slice(m,m+N.LISTENER_BATCH_SIZE)??[]);l=gn(d.map(m=>this.commonDbService.dbListener({feature:"allAreas",properties:y(h({},c),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",m),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[])]})}).pipe(la()))).pipe(ue(m=>Na(m)))}return l.pipe(ue(({data:d,operation:m})=>{let u=[];return d&&(u=Object.values(d??{}).filter(_=>typeof _=="object")),{data:u,operation:m}}),ue(({data:d,operation:m})=>{if(!t)return{data:d,documentMap:{},operation:m};let u=d.reduce((_,I)=>{let A=I.metadata?.documentId;return A&&(_[A]||(_[A]=[]),_[A].push(I)),_},{});return{data:d,documentMap:u,operation:m}}),ue(({data:d,documentMap:m,operation:u})=>{if(!i)if(u?.type==="removed"){if(u?.ids?.length){let _=this.areaAnnotationById$.value;u?.ids?.forEach(I=>{delete _?.[I]}),this.areaAnnotationById$.next(_)}}else Object.entries(m??{}).forEach(([_,I])=>{this.setAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:_,annotations:I})});return d}))}else return ce([])}setAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:i,queryHash:a}){try{if(t){e||(e=N.NO_ORGANIZATION_ID),a||(a=N.DEFAULT_QUERY_HASH);let l={};i?.forEach(d=>{d?.annotationId&&(l[d?.annotationId]=d)});let c=h(h({},this.areaAnnotationById$.value),l);this.areaAnnotationById$.next(c)}}catch(l){this.loggingService.catch("Error in AreaService setAreaAnnotationsByOrganizationIdAndDocumentId:",l)}}getAnnotationById(e){try{return this.areaAnnotationById$.value?.[e]?this.areaAnnotationById$.value?.[e]:void 0}catch(t){this.loggingService.catch("Error in AreaService getAnnotationById: ",t);return}}filterAnnotationsByLocationIds(e,t,i){try{return e.filter(a=>t.includes(a.locationId)||i?.includes(a?.location?.id)||t?.find(l=>l==a?.location?.id)||i?.find(l=>l==a?.locationId+""))}catch(a){return this.loggingService.catch("Error in AreaService filterAnnotationsByLocations:",a),[]}}calculateAreaAnnotationPosition(e,t=!1){try{if(e.targetElements?.length){let i=e.targetElements[0],a=e.targetElements[1];if(i?.xpath&&a?.xpath||i?.anchor&&a?.anchor){let l=null,c=null;if(i?.anchor){let d=this.domService.resolveAnchorRecord(i.anchor);d?.element&&d?.element instanceof HTMLElement&&!Mo(d.element)&&this.domService.isElementVisible(d.element)&&Kr(d.element)&&(l=d.element)}else i?.xpath&&(l=this.domService.getElementFromXPath(i.xpath),l&&Mo(l)&&(l=null),this.domService.isXpathWithId(i.xpath)||(!l&&i.cfXpath&&(l=this.domService.getElementFromXPath(i.cfXpath),l&&Mo(l)&&(l=null)),!l&&i.fXpath&&(l=this.domService.getElementFromXPath(i.fXpath),l&&Mo(l)&&(l=null))));if(a?.anchor){let d=this.domService.resolveAnchorRecord(a.anchor);d?.element&&d?.element instanceof HTMLElement&&!Mo(d.element)&&this.domService.isElementVisible(d.element)&&Kr(d.element)&&(c=d.element)}else a?.xpath&&(c=this.domService.getElementFromXPath(a.xpath),c&&Mo(c)&&(c=null),this.domService.isXpathWithId(a.xpath)||(!c&&a.cfXpath&&(c=this.domService.getElementFromXPath(a.cfXpath),c&&Mo(c)&&(c=null)),!c&&a.fXpath&&(c=this.domService.getElementFromXPath(a.fXpath),c&&Mo(c)&&(c=null))));if(l&&c){let d=eZ(l,c);if(d){let m=l,u=c,_=m.getBoundingClientRect(),I=u.getBoundingClientRect(),A=t?_.width:m.offsetWidth||_.width,M=t?_.height:m.offsetHeight||_.height,V=t?I.width:u.offsetWidth||I.width,q=t?I.height:u.offsetHeight||I.height,ae={};A&&M&&(ae={top:M*i.topPercentage/100,left:A*i.leftPercentage/100});let ye={};V&&q&&(ye={top:q*a.topPercentage/100,left:V*a.leftPercentage/100});let ie=!t,ge=tZ(ae.left,ae.top,l,d,ie),Ie=tZ(ye.left,ye.top,c,d,ie),he,Te,Oe,Pe,$e={};ge.x>Ie.x?ge.y>Ie.y?(Pe={x:ge.x,y:ge.y},he={x:Ie.x,y:Ie.y},$e.handle1=Pe,$e.handle2=he):(Te={x:ge.x,y:ge.y},Oe={x:Ie.x,y:Ie.y},$e.handle1=Te,$e.handle2=Oe):ge.y>Ie.y?(Oe={x:ge.x,y:ge.y},Te={x:Ie.x,y:Ie.y},$e.handle1=Oe,$e.handle2=Te):(he={x:ge.x,y:ge.y},Pe={x:Ie.x,y:Ie.y},$e.handle1=he,$e.handle2=Pe);let ze={topLeft:he||{x:Oe?.x,y:Te?.y},bottomRight:Pe||{x:Te?.x,y:Oe?.y},topRight:Te||{x:Pe?.x,y:he?.y},bottomLeft:Oe||{x:he?.x,y:Pe?.y}};return $e.coordinates=ze,$e.targetElement=this.domService.getXPath(d),$e}}}}return}catch(i){this.loggingService.catch("Error in AreaService calculateAreaAnnotationPosition:",i);return}}addArea(e,t=[],i,a,l,c){this.loggingService.log("%c[WB] Calling FUNCTION: addArea","color: green;");try{let d=this.authService.getUser();if(d)if(d.isReadOnly||d.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add areas.");else{let m=new TN;a&&(m.annotationId=a),m.from=d,m.color=N.DEFAULT_ANNOTATION_COLOR,m.lastUpdated=this.timestamp,i&&(m.targetAnnotations=[i]),m.props=new ad;let u=this.domService.getCurrentWindowSizeValue();if(m.props.screenWidth=u.screenWidth,m.props.screenHeight=u.screenHeight,m.props.screenScrollHeight=u.screenScrollHeight,m.props.viewportWidth=window.innerWidth,m.props.viewportHeight=window.innerHeight,e||t?.length>0){let A=e?this.getPointsForAreaPinAnnotation(e):t;m.targetElements=[],A.forEach(M=>{m.targetElements.push(this.domService.getTargetElementForCursorPosition(e,void 0,void 0,void 0,void 0,!0,{clientX:M.x,clientY:M.y}))})}this.setLocationToAreaAnnotation(m),l&&(m.locationId=l.locationId,m.location=l.location),m.pageInfo=ro(),m.pageInfo&&(m.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth);let _=this.getElementForAreaAnnotation(m),I=this.docService.getBaseMetadata("area",{element:_});if(m?.metadata||(m.metadata={}),m.metadata=h(h({},m.metadata),I),c?.accessFields){if(!this.userPermissionService?.hasUserContextAccess({userId:d.userId,accessFields:c.accessFields})){this.loggingService.catch("User does not have context access to add area annotation.",void 0,void 0,!0);return}m.context=y(h({},c.access?{access:c.access}:{}),{accessFields:c.accessFields})}return this.saveAreaToDb(m),m}return}catch(d){this.loggingService.catch("Error in AreaService addArea: ",d);return}}setLocationToAreaAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location)}catch(t){this.loggingService.catch("Error in AreaService setLocationToAreaAnnotation:",t)}}getElementForAreaAnnotation(e){try{let t,i,a;if(e.targetElements?.length){if(e.targetElements[0]?.anchor){let l=this.domService.resolveAnchorRecord(e.targetElements[0].anchor);l?.element&&this.domService.isElementVisible(l.element)&&Kr(l.element)&&(i=l.element)}else e.targetElements[0]?.xpath&&(i=this.domService.getElementFromXPath(e.targetElements[0].xpath));if(e.targetElements[1]?.anchor){let l=this.domService.resolveAnchorRecord(e.targetElements[1].anchor);l?.element&&this.domService.isElementVisible(l.element)&&Kr(l.element)&&(a=l.element)}else e.targetElements[1]?.xpath&&(a=this.domService.getElementFromXPath(e.targetElements[1].xpath))}return i&&a&&(t=eZ(i,a)),t}catch(t){return this.loggingService.catch("Error in AreaService getElementForAreaAnnotation: ",t),null}}saveAreaToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: saveAreaToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(je.AREA)&&gn([this.docService.getDocumentPaths$(),this.databaseService.getDb()]).pipe(Ge(([t,i])=>!!t&&!!i),ut(1),Se(([t,i])=>{if(this.documentPaths=t,this.documentPaths?.area){e.annotationId||(e.annotationId=this.commonDbService.generateDocumentId()),e.pageInfo&&(e.pageInfo.areaUrl=this.generateAreaUrl(e));let a=JSON.parse(JSON.stringify(e));if(a.position=null,!a?.metadata?.documentId){a?.metadata||(a.metadata={});let d=this.docService.getBaseMetadata("area");a.metadata=h(h({},a?.metadata),d)}this.domService.toggleAnnotationSelection(a),this.analyticsService.trackEvent(Y.Events.Area.AREA_ADDED,{annotationId:e.annotationId});let{documentId:l,organizationId:c}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);return this.commonDbService.setData({feature:"area",properties:{id:e.annotationId,documentId:l,organizationId:c},data:JSON.parse(JSON.stringify(a))})}else return ce(null)})).subscribe(()=>{},t=>{this.loggingService.catch("Error in AreaService saveAreaToDb subscription: ",t)})}catch(t){this.loggingService.catch("Error in AreaService saveAreaToDb: ",t)}}getDocumentIdAndOrganizationIdFromAreaAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in AreaService getDocumentIdAndOrganizationIdFromAreaAnnotation: ",t),{}}}updateArea(e,t=!1,i){try{i&&this.setLocationToAreaAnnotation(e),t&&this.updateNotificationsDatabase(e,EN.UPDATED),this.updateAreaToDb(e)}catch(a){this.loggingService.catch("Error in AreaService updateArea: ",a)}}updateAreaToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateAreaToDb","color: green;");try{if(this.domService.updateSelectedAnnotationInMap([e]),this.authService.getUser()&&this.authService.isFeatureAllowed(je.AREA)){let t=JSON.parse(JSON.stringify(e));if(t.position=null,!t?.metadata?.documentId){t?.metadata||(t.metadata={});let l=this.docService.getBaseMetadata("area");t.metadata=h(h({},t?.metadata),l)}let{documentId:i,organizationId:a}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);this.commonDbService.setData({feature:"area",properties:{id:e.annotationId,documentId:i,organizationId:a},data:JSON.parse(JSON.stringify(t))})}}catch(t){this.loggingService.catch("Error in AreaService updateAreaToDb: ",t)}}deleteAreaPinAnnotations(e){try{let t=this.domService.getSelectedAnnotationsMap(),i=this.authService.getUser(),a=[];Object.keys(t??{}).forEach(l=>X(this,null,function*(){let c=t[l];c.type==="area"&&i&&c.from&&(i?.isAdmin||c.from.userId===i.userId)&&a.push(c)})),a?.length&&(this.analyticsService.trackEvent(Y.Events.Area.AREA_DELETE_TRIGGERED,{triggerType:e,annotationId:a.map(l=>l.annotationId).join()}),this.dialog.open(al,{panelClass:"velt-mat-dialog-container",data:{title:"Delete area?",message:"This selected area will be deleted.",yesButton:"Delete",noButton:"Cancel",variant:"area"}}).afterClosed().pipe(ut(1)).subscribe(l=>{l&&(a.forEach(c=>X(this,null,function*(){yield this.deleteAreaPinAnnotation(c)})),setTimeout(()=>{document.querySelectorAll(`[${N.SNIPPYLY_HIGHLIGHT}]`).forEach(d=>{this.domService.removeHighlightFromElement(d)})},100))})),this.domService.resetSelectedAnnotationsMap(!0,"area")}catch(t){this.loggingService.catch("Error in AreaService deleteAreaPinAnnotations: ",t)}}getAreaAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let i={};return Object.values(this.areaAnnotationById$.value??{}).forEach(a=>{a?.metadata?.documentId==t&&a?.metadata?.organizationId==e&&(i[a?.annotationId]=a)}),Object.values(i??{})}catch(i){return this.loggingService.catch("Error in AreaService getAreaAnnotationsByOrganizationIdAndDocumentId:",i),[]}}onDeleteTargetAnnotation(e,t){try{if(this.docService.getDocumentId()&&this.areaAnnotationById$.value){let a=Object.values(this.areaAnnotationById$.value||{}),l;t?l=a.find(c=>c?.annotationId===t):l=a.find(c=>c?.targetAnnotations?.find(d=>d?.annotationId===e)),l&&(l.targetAnnotations=l.targetAnnotations?.filter(c=>c?.annotationId!==e),l.targetAnnotations?.length?this.updateAreaToDb(l):this.deleteAreaPinAnnotation(l))}}catch(i){this.loggingService.catch("Error in AreaService onDeleteTargetAnnotation: ",i)}}deleteAreaPinAnnotation(e){if(this.authService.isFeatureAllowed(je.AREA)&&this.documentPaths?.area&&e?.annotationId){this.updateNotificationsDatabase(e,EN.DELETED),this.analyticsService.trackEvent(Y.Events.Area.AREA_DELETED,{annotationId:e.annotationId});let{documentId:t,organizationId:i}=this.getDocumentIdAndOrganizationIdFromAreaAnnotation(e);return this.commonDbService.deleteData({feature:"area",properties:{id:e.annotationId,documentId:t,organizationId:i}})}else return Promise.resolve()}enableArea(){try{this.areaEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in AreaService enableArea: ",e)}}disableArea(){try{this.areaEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in AreaService disableArea: ",e)}}getAreaEnabled$(){try{return this.areaEnabled$.asObservable()}catch(e){return this.loggingService.catch("Error in AreaService getAreaEnabled$: ",e),ce(!1)}}getAreaEnabled(){try{return this.areaEnabled$.value}catch(e){return this.loggingService.catch("Error in AreaService getAreaEnabled: ",e),!1}}enableAddAreaMode(){this.authService.isFeatureAllowed(je.AREA)?(this.analyticsService.trackEvent(Y.Events.Area.AREA_ADD_MODE_ENABLED),this.addAreaMode$.next(!0)):this.loggingService.catch("Error in AreaService enableAddAreaMode: ","Area feature is not enabled.")}disableAddAreaMode(){this.analyticsService.trackEvent(Y.Events.Area.AREA_ADD_MODE_DISABLED),this.addAreaMode$.next(!1)}addAreaModeChange(){return this.addAreaMode$.asObservable()}getPointsForAreaPinAnnotation(e){let t=[],i=e,a=i?.touches?.length?i.touches[0]?.clientX:i.clientX,l=i?.touches?.length?i.touches[0]?.clientY:i.clientY;return t.push({x:a,y:l}),t.push({x:a+100,y:l+100}),t}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(t){return this.loggingService.catch("Error in AreaService isElementInsideAllowedElements: ",t),!1}}updateNotificationsDatabase(e,t){try{let i={annotationData:e,actionType:t,notificationSource:"area"};this.notificationService.updateNotificationDatabase(i)}catch(i){this.loggingService.catch("Error in AreaService updateNotificationsDatabase: ",i)}}getAreaUrl(e){try{return e?.pageInfo?.areaUrl?e.pageInfo.areaUrl:(e?.pageInfo||(e.pageInfo=ro(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.areaUrl=this.generateAreaUrl(e),this.updateArea(e),e.pageInfo?.areaUrl)}catch(t){this.loggingService.catch("Error in AreaService getAreaUrl: ",t);return}}generateAreaUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(N.URL_PARAMS.TAG_ID),t.searchParams.append(N.URL_PARAMS.TAG_ID,e.annotationId),t.href}generateAreaAnnotationId(){return X(this,null,function*(){try{if(this.docService.getDocumentPaths()?.area){let t=this.commonDbService.generateDocumentId();return yield tp(10),t||""}else return""}catch(e){return this.loggingService.catch("Error in AreaService generateAreaAnnotationId: ",e),""}})}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(Ft),K(st),K($n),K(yn),K(qe),K(Ve),K(eo),K(Vn),K(Lo),K(k),K(mn),K(Ia))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Ube=n=>{try{let o={USE_PROFILES:{svg:!0,svgFilters:!0},FORBID_ATTR:["onerror","onload","onclick","onmouseover","onmouseout","onmouseenter","onmouseleave","onmousemove","onmousedown","onmouseup","onwheel","onscroll","onkeydown","onkeyup","onkeypress","onfocus","onblur","onchange","onsubmit","on*"],FORBID_TAGS:["script","style","iframe","object","embed","form"]};return vS.sanitize(n,o)}catch(o){return it.catch("Error in File utils sanitizeSvg: ",o),""}},Vbe=n=>{try{return n.name.split(".").slice(0,-1).join(".")}catch(o){it.catch("Error in File utils getFileName: ",o);return}},IQ=n=>{try{return/(?:\.([^.]+))?$/.exec(n?.name)[1]}catch(o){it.catch("Error in File utils getFileExtension: ",o);return}},Bbe=(n,o)=>{try{let r=n.slice(0,-1,n.type);return new File([r],o+"."+IQ(n),{type:n.type})}catch(r){it.catch("Error in File utils updateFile: ",r);return}};var EQ={mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",wmv:"video/x-ms-wmv",flv:"video/x-flv",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",webm:"video/webm",mkv:"video/x-matroska",m4v:"video/x-m4v",m4a:"audio/x-m4a",aac:"audio/aac","3gp":"video/3gpp","3g2":"video/3gpp2",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",bmp:"image/bmp",svg:"image/svg+xml",webp:"image/webp",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",odt:"application/vnd.oasis.opendocument.text",ods:"application/vnd.oasis.opendocument.spreadsheet",zip:"application/zip",rar:"application/x-rar-compressed",txt:"text/plain",rtf:"application/rtf",html:"text/html",htm:"text/html",csv:"text/csv",ics:"text/calendar",vcf:"text/x-vcard",js:"application/javascript",css:"text/css",json:"application/json",xml:"application/xml",swf:"application/x-shockwave-flash"};var Pp=(()=>{let o=class o{constructor(e,t,i,a,l){this.authService=e,this.configService=t,this.coreActionsService=i,this.loggingService=a,this.attachmentResolverService=l,this.storage=VD();try{this.configService.getApiKey$().subscribe(c=>{this.apiKey=c}),this.authService.getFirebaseConfig$().subscribe(c=>{if(c&&c.firebaseOptions?.storageBucket){this.storage=VD(void 0,c?.firebaseOptions?.storageBucket);let d=this.configService.getProxyConfig();d?.storageHost&&(this.storage.host=d.storageHost)}},c=>{this.loggingService.catch("Error in StorageService constructor: ",c)})}catch(c){this.loggingService.catch("Error in StorageService constructor:",c)}}createAttachment({path:e,file:t}){try{let i=new o1;i.name=t.name;let a=Bbe(t,`${i.attachmentId}_${Vbe(t)}`),l=`${this.apiKey}/${e}/${a?.name}`;return i.bucketPath=l,i.size=t.size,i.type=IQ(t),i?.type&&(i.mimeType=EQ[i?.type]),i}catch(i){return this.loggingService.catch("Error in StorageService createAttachment: ",i),null}}sanitizeSvgFile(e){return X(this,null,function*(){if(e.type===EQ.svg)try{let t=yield e.text(),i=Ube(t);return new File([i],e.name,{type:e.type})}catch(t){return this.loggingService.catch("Error in StorageService sanitizeSvgFile: ",t),e}return e})}uploadAttachmentToStorage(l){return X(this,arguments,function*({attachment:e,file:t,resolve:i,reject:a}){try{let c=BD(this.storage,e.bucketPath),d=xY(c,t,{cacheControl:"public,max-age=3600"});d.on("state_changed",m=>{let u=m.bytesTransferred/m.totalBytes*100},m=>{a(m)},()=>{kY(d.snapshot.ref).then(m=>{e.url=m,i(e)})})}catch(c){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",c),a(c)}})}uploadToResolver(d){return X(this,arguments,function*({file:e,attachment:t,metadata:i,resolve:a,reject:l,scope:c}){try{i.attachmentId=t.attachmentId;let m={attachmentId:t.attachmentId,name:t.name,file:e,metadata:i,mimeType:t.mimeType},u=lt();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:u,methodName:xs.UPLOAD_TO_RESOLVER,source:"internal",payload:{attachment:m,eventType:ko.ATTACHMENT_ADD}});let _=yield this.attachmentResolverService.saveAttachment({attachment:m,eventType:ko.ATTACHMENT_ADD},u,c);_&&_.data?.url?(t.url=_.data?.url,a(t)):l(new Error("Failed to upload attachment to resolver"))}catch(m){this.loggingService.catch("Error in StorageService uploadToResolver: ",m),l(m)}})}uploadFile({path:e,file:t,useAttachmentResolver:i,metadata:a,attachmentScope:l}){return new Promise((c,d)=>X(this,null,function*(){try{if(!this.apiKey)throw new Error("API key not configured");let m=yield this.sanitizeSvgFile(t),u=this.createAttachment({path:e,file:m});if(!u)throw new Error("Attachment not created");i?this.uploadToResolver({file:m,attachment:u,metadata:a,resolve:c,reject:d,scope:l}):this.uploadAttachmentToStorage({attachment:u,file:m,resolve:c,reject:d})}catch(m){this.loggingService.catch("Error in StorageService uploadFile:",m),d(m)}}))}uploadChunk(e,t,i,a){return new Promise((l,c)=>{try{if(a?.useAttachmentResolver){let d=this.createAttachment({path:e,file:t});if(!d){c(new Error("Attachment not created for chunk upload"));return}this.uploadToResolver({file:t,attachment:d,metadata:a.metadata,resolve:m=>l(m.url),reject:c,scope:a.attachmentScope});return}if(this.apiKey){let d=`${this.apiKey}/${e}/${t.name}`,m=BD(this.storage,d),u=xY(m,t,{cacheControl:"public,max-age=3600"});u.on("state_changed",_=>{let I=_.bytesTransferred/_.totalBytes*100},_=>{c(_)},()=>{kY(u.snapshot.ref).then(_=>{l(_)}).catch(_=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${i}:`,_),c(_)})})}else{let d=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",d),c(d)}}catch(d){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${i}: `,d),c(d)}})}downloadAttachment(e){try{if(e.url){let t=new XMLHttpRequest;t.responseType="blob",t.onload=()=>{let i=t.response,a=document.createElement("a"),l=window.URL.createObjectURL(i);a.setAttribute("type","hidden"),a.setAttribute(N.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),a.classList.add("snippyly-overlay-panel"),a.href=l,e?.name&&(a.download=e?.name),document.body.appendChild(a);let c=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});a.dispatchEvent(c),window.URL.revokeObjectURL(l),a.remove()},t.onerror=()=>{window.open(e.url,"_blank")},t.open("GET",e.url),t.send()}}catch(t){this.loggingService.catch("Error in StorageService downloadAttachment: ",t)}}deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:i,attachmentScope:a}){return new Promise((l,c)=>{if(i){let d=lt();this.coreActionsService.triggerAction(tt.ATTACHMENT_RESOLVER,{event:Y.Events.Resolver.ATTACHMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:d,methodName:xs.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:e.attachmentId,metadata:t}}),this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:t},d,a).then(()=>{l(null)}).catch(m=>{c(m)})}else{let d=BD(this.storage,e.bucketPath);yY(d).then(()=>{l(null)}).catch(m=>{l(null)})}})}deleteFileFromPath(e){return new Promise((t,i)=>{let a=BD(this.storage,e);yY(a).then(()=>{t(null)}).catch(l=>{i(l)})})}};o.\u0275fac=function(t){return new(t||o)(K(qe),K(Ft),K(nr),K(k),K(es))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var po=(()=>{let o=class o{constructor(e){this.loggingService=e,this._customStatusMap=new _e(N.CommentAnnotationStatusMap),this._customPriorityMap=new _e(N.CommentAnnotationPriorityMap),this._customCategoryMap=new _e(N.CommentCategoryMap);try{let t=sessionStorage.getItem(N.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP);t&&this._customPriorityMap.next(JSON.parse(t));let i=sessionStorage.getItem(N.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP);i&&this._customStatusMap.next(JSON.parse(i));let a=sessionStorage.getItem(N.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP);a&&this._customCategoryMap.next(JSON.parse(a))}catch(t){this.loggingService.catch("Error in CustomFilterService constructor: ",t)}}setCustomStatusFilters(e){try{if(e.length<2){this._customStatusMap.next(N.CommentAnnotationStatusMap),sessionStorage.setItem(N.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(N.CommentAnnotationStatusMap)),this.loggingService.catch("Custom status filters must have at least 2 filters");return}let t={};e.forEach(i=>{t[i.id]=i,i.type||(i.type="ongoing")}),this._customStatusMap.next(t),sessionStorage.setItem(N.SESSION_STORAGE.VELT_CUSTOM_STATUS_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomStatusFilters: ",t)}}setCustomPriorityFilters(e){try{if(e.length<2){this._customPriorityMap.next(N.CommentAnnotationPriorityMap),sessionStorage.setItem(N.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(N.CommentAnnotationPriorityMap)),this.loggingService.catch("Custom priority filters must have at least 2 filters");return}let t={};e.forEach(i=>{t[i.id]=i}),this._customPriorityMap.next(t),sessionStorage.setItem(N.SESSION_STORAGE.VELT_CUSTOM_PRIORITY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomPriorityFilters: ",t)}}setCustomCategories(e){try{let t={};e.forEach(i=>{t[i.id]=i}),this._customCategoryMap.next(t),sessionStorage.setItem(N.SESSION_STORAGE.VELT_CUSTOM_CATEGORY_MAP,JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CustomFilterService setCustomCategories: ",t)}}get customStatusMap$(){return this._customStatusMap.asObservable()}get customPriorityMap$(){return this._customPriorityMap.asObservable()}get customCategoryMap$(){return this._customCategoryMap.asObservable()}get defaultStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([i,a])=>a.type==="default");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService defaultStatus: ",e)}return N.CommentAnnotationStatusMap.OPEN}get resolvedStatus(){try{let t=Object.entries(this._customStatusMap.value).find(([i,a])=>a.type==="terminal");if(t)return t[1]}catch(e){this.loggingService.catch("Error in CustomFilterService resolvedStatus: ",e)}return N.CommentAnnotationStatusMap.OPEN}get ongoingStatuses(){try{let t=Object.entries(this._customStatusMap.value).filter(([i,a])=>a.type==="ongoing");if(t)return t.map(i=>i[1])}catch(e){this.loggingService.catch("Error in CustomFilterService ongoingStatuses: ",e)}return[N.CommentAnnotationStatusMap.IN_PROGRESS]}convertLegacyAnnotationStatus(e){try{if(typeof e.status=="string"||e.status===void 0){let t=Object.entries(this._customStatusMap.value),i=t.find(([a,l])=>l.type==="default");switch(e.status){case"open":i&&(e.status=i[1]);break;case"inProgress":let a=t.find(([c,d])=>d.type==="ongoing");a&&(e.status=a[1]);break;case"resolved":let l=t.find(([c,d])=>d.type==="terminal");l&&(e.status=l[1]);break;default:i&&(e.status=i[1]);break}}return e}catch(t){return this.loggingService.catch("Error in CustomFilterService convertLegacyAnnotation: ",t),e}}convertLegacyPriority(e){try{typeof e.priority=="string"&&(e.priority=N.CommentAnnotationPriorityMap[e.priority])}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyPriority: ",t)}return e}convertLegacyCategory(e){try{if(e.commentCategories===void 0||e.commentCategories===null||!Array.isArray(e.commentCategories)||e.commentCategories.length===0)return e;typeof e.commentCategories[0]=="string"&&(e.commentCategories=e.commentCategories.map(t=>N.CommentCategoryMap[t]))}catch(t){this.loggingService.catch("Error in CustomFilterService convertLegacyCategory: ",t)}return e}};o.\u0275fac=function(t){return new(t||o)(K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var jbe=(()=>{let o=class o{constructor(e,t){this.domService=e,this.loggingService=t,this.keyEventSubject$=new at;try{this.loggingService.log("%c[WB] Creating CLASS: HotkeyService","color: blue;"),this.keyEvent$=this.keyEventSubject$.asObservable().pipe(Zh()),this.domService.onWindowKeydown$().subscribe(i=>{this.keyEventSubject$.next(i)})}catch(i){this.loggingService.catch("Error in HotkeyService constructor: ",i)}}getKeyPressEvent(e,t={}){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getKeyPressEvent","color: green;"),this.keyEvent$.pipe(Ge(i=>i?.key===e),Ge(i=>!(!!t?.includeCtrl!==i.ctrlKey||!!t?.includeAlt!==i.altKey||!!t?.includeShift!==i.shiftKey||!!t?.includeMeta!==i.metaKey)),Ge(()=>this.isNoInputFocused()))}catch(i){return this.loggingService.catch("Error in HotkeyService getKeyPressEvent: ",i),new Vt}}isNoInputFocused(){try{let e=document.activeElement;for(;e&&e?.tagName!=="BODY";){if(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e?.isContentEditable)return!1;e=e?.parentElement}return!0}catch(e){return this.loggingService.catch("Error in HotkeyService isNoInputFocused: ",e),!1}}};o.\u0275fac=function(t){return new(t||o)(K(Ve),K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();function LWe(n,o){n&1&&(se(),f(0,"svg",16),D(1,"rect",17)(2,"path",18)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function UWe(n,o){n&1&&(se(),f(0,"svg",16),D(1,"rect",22)(2,"path",23)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function VWe(n,o){if(n&1&&(C(0),f(1,"div",6)(2,"div",7),p(3,LWe,6,0,"svg",8)(4,UWe,6,0,"ng-template",null,1,Be),S(),f(6,"div",9),re(7),R(8,"translate"),D(9,"br"),re(10),R(11,"translate"),S(),f(12,"div",10)(13,"p"),re(14),R(15,"translate"),se(),f(16,"svg",11),D(17,"path",12)(18,"path",13)(19,"path",14)(20,"path",15),S(),re(21),R(22,"translate"),S(),St(),f(23,"p"),re(24),R(25,"translate"),S()()(),b()),n&2){let r=Ee(5),e=s();v(3),g("ngIf",e.darkMode)("ngIfElse",r),v(4),we(" ",F(8,7,"Allow mic permission to")),v(3),we("",F(11,9,"enable your audio")," "),v(4),we(" ",F(15,11,"1. Click the")," "),v(7),we(" ",F(22,13,"page info icon in your browser\u2019s address bar")," "),v(3),we(" ",F(25,15,"2. Turn on Microphone")," ")}}function BWe(n,o){n&1&&(se(),f(0,"svg",16),D(1,"rect",17)(2,"path",24)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function jWe(n,o){n&1&&(se(),f(0,"svg",16),D(1,"rect",22)(2,"path",25)(3,"path",19)(4,"rect",20)(5,"path",21),S())}function $We(n,o){if(n&1&&(C(0),f(1,"div",6)(2,"div",7),p(3,BWe,6,0,"svg",8)(4,jWe,6,0,"ng-template",null,2,Be),S(),f(6,"div",9),re(7),R(8,"translate"),D(9,"br"),re(10),R(11,"translate"),S(),f(12,"div",10)(13,"p"),re(14),R(15,"translate"),se(),f(16,"svg",11),D(17,"path",12)(18,"path",13)(19,"path",14)(20,"path",15),S(),re(21),R(22,"translate"),S(),St(),f(23,"p"),re(24),R(25,"translate"),S()()(),b()),n&2){let r=Ee(5),e=s();v(3),g("ngIf",e.darkMode)("ngIfElse",r),v(4),we(" ",F(8,7,"Allow camera permission")),v(3),we("",F(11,9,"to enable your video")," "),v(4),we(" ",F(15,11,"1. Click the")," "),v(7),we(" ",F(22,13,"page info icon in your browser\u2019s address bar")," "),v(3),we(" ",F(25,15,"2. Turn on Camera")," ")}}var KL=(()=>{let o=class o{constructor(e,t,i,a,l){this.loggingService=e,this.themeService=t,this.elementRef=i,this.matDialogRef=a,this.data=l,this.veltElement=!0,this.darkMode=!0;try{this.loggingService.log("%c[WB] Creating CLASS: DevicePermissionDeniedDialogComponent","color: blue;"),this.type=this.data?.type,[!0,!1].includes(this.data?.darkMode)&&(this.darkMode=this.data?.darkMode)}catch(c){this.loggingService.catch("Error in DevicePermissionDeniedDialogComponent constructor: ",c)}}ngOnDestroy(){}};o.\u0275fac=function(t){return new(t||o)(x(k),x(yt),x(Q),x(ji,8),x(nd,8))},o.\u0275cmp=O({type:o,selectors:[["velt-device-permission-denied-dialog-internal"]],hostVars:1,hostBindings:function(t,i){t&2&&w("data-velt-element",i.veltElement)},inputs:{type:"type"},standalone:!1,decls:5,vars:5,consts:[["devicePermissionDialogRef",""],["defaultAudioIcon",""],["defaultVideoIcon",""],[1,"velt-device-permission-denied-dialog--container",3,"snippylyOverlay","snippylyOverlayZIndex"],[3,"ngSwitch"],[4,"ngSwitchCase"],[1,"velt-device-permission-denied-dialog"],[1,"velt-device-permission-denied-dialog--icon"],["width","61","height","60","viewBox","0 0 61 60","fill","none","xmlns","http://www.w3.org/2000/svg",4,"ngIf","ngIfElse"],[1,"velt-device-permission-denied-dialog--header"],[1,"velt-device-permission-denied-dialog--content"],["width","13","height","12","viewBox","0 0 13 12","fill","none","xmlns","http://www.w3.org/2000/svg",1,"velt-device-permission-denied-dialog--page-info-icon"],["d","M4.375 2.5C4.375 3.53553 3.53553 4.375 2.5 4.375C1.46447 4.375 0.625 3.53553 0.625 2.5C0.625 1.46447 1.46447 0.625 2.5 0.625C3.53553 0.625 4.375 1.46447 4.375 2.5Z","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["d","M5 2.5H12.5","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["d","M0 8.75H7.5","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["d","M11.875 8.75C11.875 9.78553 11.0355 10.625 10 10.625C8.96447 10.625 8.125 9.78553 8.125 8.75C8.125 7.71447 8.96447 6.875 10 6.875C11.0355 6.875 11.875 7.71447 11.875 8.75Z","stroke","currentColor","stroke-opacity","0.6","stroke-width","1.25"],["width","61","height","60","viewBox","0 0 61 60","fill","none","xmlns","http://www.w3.org/2000/svg"],["x","0.5","y","4","width","56","height","56","rx","28","fill","white","fill-opacity","0.04"],["d","M23.5026 20.333C23.5026 19.0069 24.0294 17.7352 24.9671 16.7975C25.9048 15.8598 27.1765 15.333 28.5026 15.333C29.8287 15.333 31.1005 15.8598 32.0381 16.7975C32.9758 17.7352 33.5026 19.0069 33.5026 20.333V28.6663C33.5027 29.1599 33.4297 29.6508 33.2859 30.123M29.9526 33.4563C29.2054 33.6828 28.4155 33.7311 27.6463 33.5973C26.8771 33.4636 26.1499 33.1516 25.5229 32.6863C24.8959 32.2211 24.3866 31.6154 24.0358 30.9179C23.685 30.2204 23.5024 29.4504 23.5026 28.6697V27.003M16.8359 28.6663C16.8356 30.7719 17.405 32.8383 18.484 34.6465C19.5629 36.4546 21.111 37.9371 22.9642 38.9366C24.8174 39.9362 26.9066 40.4156 29.0102 40.324C31.1137 40.2324 33.1533 39.5732 34.9126 38.4163M38.2459 35.083C39.5023 33.1791 40.1701 30.9474 40.1659 28.6663M21.8359 46.9997H35.1693M28.5026 40.333V46.9997","stroke","white","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["d","M13.5 17L43.5 47","stroke","currentColor","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["x","36.5","width","24","height","24","rx","12","fill","currentColor"],["d","M48.5 18.99V19M48.5 14V5","stroke","white","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["x","0.5","y","4","width","56","height","56","rx","28","fill","black","fill-opacity","0.04"],["d","M23.5026 20.333C23.5026 19.0069 24.0294 17.7352 24.9671 16.7975C25.9048 15.8598 27.1765 15.333 28.5026 15.333C29.8287 15.333 31.1005 15.8598 32.0381 16.7975C32.9758 17.7352 33.5026 19.0069 33.5026 20.333V28.6663C33.5027 29.1599 33.4297 29.6508 33.2859 30.123M29.9526 33.4563C29.2054 33.6828 28.4155 33.7311 27.6463 33.5973C26.8771 33.4636 26.1499 33.1516 25.5229 32.6863C24.8959 32.2211 24.3866 31.6154 24.0358 30.9179C23.685 30.2204 23.5024 29.4504 23.5026 28.6697V27.003M16.8359 28.6663C16.8356 30.7719 17.405 32.8383 18.484 34.6465C19.5629 36.4546 21.111 37.9371 22.9642 38.9366C24.8174 39.9362 26.9066 40.4156 29.0102 40.324C31.1137 40.2324 33.1533 39.5732 34.9126 38.4163M38.2459 35.083C39.5023 33.1791 40.1701 30.9474 40.1659 28.6663M21.8359 46.9997H35.1693M28.5026 40.333V46.9997","stroke","black","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["d","M42.375 39.2135C42.7034 39.1007 42.9883 38.8881 43.19 38.6054C43.3917 38.3227 43.5001 37.9841 43.5 37.6369V26.3635C43.4998 26.0795 43.4271 25.8003 43.2888 25.5523C43.1504 25.3043 42.9509 25.0958 42.7093 24.9465C42.4677 24.7973 42.192 24.7122 41.9083 24.6994C41.6246 24.6867 41.3424 24.7466 41.0883 24.8735L33.5 28.6669V30.3335V25.3333C33.5 24.4493 33.1488 23.6014 32.5237 22.9763C31.8986 22.3512 31.0507 22 30.1667 22H25.1667M33.5 37V38.6667C33.5 39.5507 33.1488 40.3986 32.5237 41.0237C31.8986 41.6488 31.0507 42 30.1667 42H16.8333C15.9493 42 15.1014 41.6488 14.4763 41.0237C13.8512 40.3986 13.5 39.5507 13.5 38.6667V25.3333C13.5 24.4493 13.8512 23.6014 14.4763 22.9763C15.1014 22.3512 15.9493 22 16.8333 22H18.5","stroke","white","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"],["d","M42.375 39.2135C42.7034 39.1007 42.9883 38.8881 43.19 38.6054C43.3917 38.3227 43.5001 37.9841 43.5 37.6369V26.3635C43.4998 26.0795 43.4271 25.8003 43.2888 25.5523C43.1504 25.3043 42.9509 25.0958 42.7093 24.9465C42.4677 24.7973 42.192 24.7122 41.9083 24.6994C41.6246 24.6867 41.3424 24.7466 41.0883 24.8735L33.5 28.6669V30.3335V25.3333C33.5 24.4493 33.1488 23.6014 32.5237 22.9763C31.8986 22.3512 31.0507 22 30.1667 22H25.1667M33.5 37V38.6667C33.5 39.5507 33.1488 40.3986 32.5237 41.0237C31.8986 41.6488 31.0507 42 30.1667 42H16.8333C15.9493 42 15.1014 41.6488 14.4763 41.0237C13.8512 40.3986 13.5 39.5507 13.5 38.6667V25.3333C13.5 24.4493 13.8512 23.6014 14.4763 22.9763C15.1014 22.3512 15.9493 22 16.8333 22H18.5","stroke","currentColor","stroke-opacity","0.52","stroke-width","2.5","stroke-linecap","round","stroke-linejoin","round"]],template:function(t,i){if(t&1&&(f(0,"div",3,0),C(2,4),p(3,VWe,26,17,"ng-container",5)(4,$We,26,17,"ng-container",5),b(),S()),t&2){let a=Ee(1);g("snippylyOverlay",a)("snippylyOverlayZIndex",3e3),v(2),g("ngSwitch",i.type),v(),g("ngSwitchCase","audio"),v(),g("ngSwitchCase","video")}},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}body.velt-pin-dragging[_ngcontent-%COMP%] iframe[_ngcontent-%COMP%]{pointer-events:none!important}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent)}[dark][_nghost-%COMP%]{--velt-green: var(--velt-dark-mode-green);--velt-magenta: var(--velt-dark-mode-magenta);--velt-amber: var(--velt-dark-mode-amber);--velt-purple: var(--velt-dark-mode-purple);--velt-cyan: var(--velt-dark-mode-cyan);--velt-orange: var(--velt-dark-mode-orange);--velt-black: var(--velt-dark-mode-black);--velt-white: var(--velt-dark-mode-white);--velt-gray: var(--velt-dark-mode-gray);--velt-error: var(--velt-dark-mode-error);--velt-error-hover: var(--velt-dark-mode-error-hover);--velt-error-foreground: var(--velt-dark-mode-error-foreground);--velt-error-light: var(--velt-dark-mode-error-light);--velt-error-transparent: var(--velt-dark-mode-error-transparent);--velt-warning: var(--velt-dark-mode-warning);--velt-warning-hover: var(--velt-dark-mode-warning-hover);--velt-warning-foreground: var(--velt-dark-mode-warning-foreground);--velt-warning-light: var(--velt-dark-mode-warning-light);--velt-warning-transparent: var(--velt-dark-mode-warning-transparent);--velt-success: var(--velt-dark-mode-success);--velt-success-hover: var(--velt-dark-mode-success-hover);--velt-success-foreground: var(--velt-dark-mode-success-foreground);--velt-success-light: var(--velt-dark-mode-success-light);--velt-success-transparent: var(--velt-dark-mode-success-transparent);--velt-accent: var(--velt-dark-mode-accent);--velt-accent-text: var(--velt-dark-mode-accent-text);--velt-accent-hover: var(--velt-dark-mode-accent-hover);--velt-accent-foreground: var(--velt-dark-mode-accent-foreground);--velt-accent-light: var(--velt-dark-mode-accent-light);--velt-accent-transparent: var(--velt-dark-mode-accent-transparent);--velt-text-0: var(--velt-dark-mode-text-0);--velt-text-1: var(--velt-dark-mode-text-1);--velt-text-2: var(--velt-dark-mode-text-2);--velt-text-3: var(--velt-dark-mode-text-3);--velt-text-4: var(--velt-dark-mode-text-4);--velt-text-5: var(--velt-dark-mode-text-5);--velt-text-6: var(--velt-dark-mode-text-6);--velt-text-7: var(--velt-dark-mode-text-7);--velt-text-8: var(--velt-dark-mode-text-8);--velt-text-9: var(--velt-dark-mode-text-9);--velt-text-10: var(--velt-dark-mode-text-10);--velt-text-11: var(--velt-dark-mode-text-11);--velt-text-12: var(--velt-dark-mode-text-12);--velt-background-0: var(--velt-dark-mode-background-0);--velt-background-1: var(--velt-dark-mode-background-1);--velt-background-2: var(--velt-dark-mode-background-2);--velt-background-3: var(--velt-dark-mode-background-3);--velt-background-4: var(--velt-dark-mode-background-4);--velt-background-5: var(--velt-dark-mode-background-5);--velt-background-6: var(--velt-dark-mode-background-6);--velt-background-7: var(--velt-dark-mode-background-7);--velt-background-8: var(--velt-dark-mode-background-8);--velt-background-9: var(--velt-dark-mode-background-9);--velt-background-10: var(--velt-dark-mode-background-10);--velt-border-0: var(--velt-dark-mode-border-0);--velt-border-1: var(--velt-dark-mode-border-1);--velt-border-2: var(--velt-dark-mode-border-2);--velt-border-3: var(--velt-dark-mode-border-3);--velt-border-4: var(--velt-dark-mode-border-4);--velt-border-5: var(--velt-dark-mode-border-5);--velt-border-6: var(--velt-dark-mode-border-6);--velt-border-7: var(--velt-dark-mode-border-7);--velt-border-8: var(--velt-dark-mode-border-8);--velt-border-9: var(--velt-dark-mode-border-9);--velt-border-10: var(--velt-dark-mode-border-10);--velt-background-transparent: var(--velt-dark-mode-background-transparent);--velt-border-transparent: var(--velt-dark-mode-border-transparent);--velt-animation-transparent: var(--velt-dark-mode-animation-transparent)} .velt-mat-dialog-container.velt-device-permission-denied-dialog--panel mat-dialog-container .mat-mdc-dialog-surface.mdc-dialog__surface{padding:0;background-color:transparent;box-shadow:none;overflow:unset}.velt-device-permission-denied-dialog[_ngcontent-%COMP%]{display:flex;flex-direction:column;gap:var(--velt-spacing-lg);align-items:center;justify-content:center;padding:4rem;box-sizing:border-box;word-break:break-word;max-width:600px;max-height:400px;text-align:center;background-color:var(--velt-background-0);border-radius:var(--velt-border-radius-2xl);box-shadow:0 calc((4rem + 0px) * var(--velt-base-rem-unit)) calc((4rem + 0px) * var(--velt-base-rem-unit)) calc((-3rem + 0px) * var(--velt-base-rem-unit)) #1f2f461f}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--icon[_ngcontent-%COMP%]{color:var(--velt-error)}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--header[_ngcontent-%COMP%]{font-size:var(--velt-font-size-lg);font-weight:600;line-height:36px;letter-spacing:-.02em;text-align:center;color:var(--velt-text-0)}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--content[_ngcontent-%COMP%]{font-size:var(--velt-font-size-sm);font-weight:400;line-height:21px;text-align:center;color:var(--velt-text-0)}.velt-device-permission-denied-dialog[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--content[_ngcontent-%COMP%] .velt-device-permission-denied-dialog--page-info-icon[_ngcontent-%COMP%]{margin-left:var(--velt-spacing-sm);margin-right:var(--velt-spacing-sm);color:var(--velt-error)}"],changeDetection:0});let n=o;return n})();var ym=(()=>{let o=class o{constructor(e,t){this.loggingService=e,this.matDialog=t,this.audioPermissionState$=new _e(null),this.videoPermissionState$=new _e(null);try{this.loggingService.log("%c[WB] Creating CLASS: DevicePermissionService","color: blue;"),this.checkPermissions()}catch(i){this.loggingService.catch("Error in DevicePermissionService constructor: ",i)}}checkPermissions(){try{this.loggingService.log("%c[WB] Calling DevicePermissionService FUNCTION: checkPermissions","color: green;"),new hr().browserName!=="Firefox"&&(navigator.permissions.query({name:"microphone"}).then(t=>{this.audioPermissionState$.next(t.state),t.onchange=()=>{this.audioPermissionState$.next(t.state)}}).catch(t=>{}),navigator.permissions.query({name:"camera"}).then(t=>{this.videoPermissionState$.next(t.state),t.onchange=()=>{this.videoPermissionState$.next(t.state)}}).catch(t=>{}))}catch(e){this.loggingService.catch("Error in DevicePermissionService checkPermissions: ",e)}}getPermissionState$(e){try{switch(this.loggingService.log("%c[WB] Calling DevicePermissionService FUNCTION: getPermissionState$","color: green;"),e){case"audio":return this.getAudioPermissionState$();case"video":return this.getVideoPermissionState$();default:return ce(null)}}catch(t){return this.loggingService.catch("Error in DevicePermissionService getPermissionState$: ",t),ce(null)}}getAudioPermissionState$(){return this.audioPermissionState$.asObservable()}getVideoPermissionState$(){return this.videoPermissionState$.asObservable()}openDevicePermissionDeniedDialog(e,t){try{this.loggingService.log("%c[WB] Calling DevicePermissionService FUNCTION: openDevicePermissionDeniedDialog","color: green;"),this.matDialog.open(KL,{panelClass:["velt-device-permission-denied-dialog--panel","velt-mat-dialog-container"],backdropClass:["velt-device-permission-denied-dialog--backdrop","s-background-blur-1"],data:h({type:e},t||{})})}catch(i){this.loggingService.catch("Error in DevicePermissionService openDevicePermissionDeniedDialog: ",i)}}};o.\u0275fac=function(t){return new(t||o)(K(k),K(Lo))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var GWe=()=>["video","screen"];function HWe(n,o){if(n&1&&D(0,"app-recording-preview-steps-dialog-video",4),n&2){let r=s(2);g("componentConfigSignal",r.componentConfigSignal)}}function zWe(n,o){if(n&1&&D(0,"app-recording-preview-steps-dialog-audio",4),n&2){let r=s(2);g("componentConfigSignal",r.componentConfigSignal)}}function WWe(n,o){if(n&1&&(C(0),f(1,"div",2,0),p(3,HWe,1,1,"app-recording-preview-steps-dialog-video",3)(4,zWe,1,1,"app-recording-preview-steps-dialog-audio",3),S(),b()),n&2){let r=o.ngIf,e=Ee(2),t=s();v(),g("snippylyOverlay",e)("snippylyOverlayZIndex",2e3),w("aria-label","Recording preview - "+r.type+" mode")("data-testid",t.componentId),v(2),g("ngIf",xt(6,GWe).includes(r.type)),v(),g("ngIf",r.type==="audio")}}var ZL=(()=>{let o=class o{constructor(e,t,i,a,l,c,d){this.loggingService=e,this.recorderService=t,this.dialog=i,this.devicePermissionService=a,this.dialogRef=l,this.elementRef=c,this.data=d,this.darkMode=!1,this.shadowDom=!0,this.startCountdownFrom=3,this.defaultMediaSourceOptions=lv(),this.recordingCountdownEnabled=!1,this.subscriptions=[],this.veltElement=!0,this.componentId="velt-recording-preview-steps-dialog",this.componentConfigSignal=De({closeDialog:this.closeDialog.bind(this),startCountdown:this.startCountdown.bind(this),toggleAudio:this.toggleAudio.bind(this),toggleVideo:this.toggleVideo.bind(this),toggleSettings:this.toggleSettings.bind(this),cancelCountdown:this.cancelCountdown.bind(this),updateMediaConfig:this.updateMediaConfig.bind(this),handleOverlayClick:this.handleOverlayClick.bind(this),countdownStarted:!1,mediaConfig:{audio:{enabled:!1},video:{enabled:!1}},mediaState:{audio:{enabled:!1},video:{enabled:!1}},type:"video",countdown:this.startCountdownFrom,mediaStream:void 0,isSettingsOpen:!1,darkMode:this.darkMode,shadowDom:this.shadowDom,isExplicitShadowDom:!1});try{this.devicePermissionService.getPermissionState$("video").subscribe(m=>{this.componentConfigSignal.update(u=>(u=y(h({},u),{mediaState:y(h({},u.mediaState),{video:{enabled:m!=="denied"}})}),u))}),this.devicePermissionService.getPermissionState$("audio").subscribe(m=>{this.componentConfigSignal.update(u=>(u=y(h({},u),{mediaState:y(h({},u.mediaState),{audio:{enabled:m!=="denied"}})}),u))}),this.subscriptions.push(this.recorderService.getRecordingCountdownEnabled$().subscribe(m=>{this.recordingCountdownEnabled=m})),this.subscriptions.push(this.recorderService.getRecordingMicEnabled$().subscribe(m=>{m!==null&&(m?this.toggleAudioOn():this.toggleAudioOff())})),d&&(d.type&&this.componentConfigSignal.update(m=>(m=y(h({},m),{type:d.type}),m)),d.recordingCountdown!==void 0&&(this.recordingCountdownEnabled=!!d.recordingCountdown),d.mediaConfig&&(d.mediaConfig?.audio?.enabled&&!d.mediaConfig?.audio?.deviceId&&(d.mediaConfig.audio.deviceId=this.defaultMediaSourceOptions?.selectedAudioDevice?.deviceId),d.mediaConfig?.video?.enabled&&!d.mediaConfig?.video?.deviceId&&(d.mediaConfig.video.deviceId=this.defaultMediaSourceOptions?.selectedVideoDevice?.deviceId),d?.darkMode?this.elementRef.nativeElement.setAttribute("dark",""):this.elementRef.nativeElement.removeAttribute("dark"),this.componentConfigSignal.update(m=>(m=y(h({},m),{shadowDom:d?.shadowDom!==!1,isExplicitShadowDom:!!d?.isExplicitShadowDom,darkMode:d.darkMode||!1}),m)),this.updateMediaConfig(d.mediaConfig)))}catch(m){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent constructor: ",m)}}ngOnInit(){try{this.setupA11yAttributes(),this.componentConfigSignal().type==="screen"&&this.subscriptions.push(this.recorderService.getScreenStream$().subscribe(e=>{e&&e.active&&e.getVideoTracks().some(t=>t.readyState==="live")&&this.componentConfigSignal.update(t=>(t=h({},t),t.mediaConfig.screen={enabled:!0,stream:e},t))}))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngOnInit:",e)}}setupA11yAttributes(){try{let e=this.elementRef.nativeElement;e.setAttribute("data-testid",this.componentId+"-container"),e.setAttribute("role","dialog"),e.setAttribute("aria-label","Recording preview steps dialog")}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent setupA11yAttributes:",e)}}ngOnChanges(e){try{e&&Object.keys(e).forEach(t=>{this.componentConfigSignal.update(i=>(i=y(h({},i),{[t]:e[t].currentValue}),i))})}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngOnChanges: ",t)}}ngAfterViewInit(){try{this.dialogRef.addPanelClass("snippyly-recording-preview-steps-dialog"),this.dialogRef.disableClose=!0}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngAfterViewInit: ",e)}}toggleSettings(e){try{e.stopPropagation(),this.componentConfigSignal.update(t=>(t=y(h({},t),{isSettingsOpen:!t.isSettingsOpen}),t))}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleSettings: ",t)}}toggleAudio(){try{this.componentConfigSignal().mediaConfig.audio||this.componentConfigSignal.update(i=>(i=y(h({},i),{mediaConfig:y(h({},i.mediaConfig),{audio:{enabled:!0}})}),i));let e=!this.componentConfigSignal().mediaConfig.audio?.enabled;this.componentConfigSignal.update(i=>(i=y(h({},i),{mediaConfig:y(h({},i.mediaConfig),{audio:{enabled:e}})}),i));let t=this.componentConfigSignal().mediaStream?.getAudioTracks()[0];t?t.enabled=e:e&&(this.componentConfigSignal.update(i=>(i=y(h({},i),{mediaConfig:y(h({},i.mediaConfig),{audio:y(h({},i.mediaConfig.audio),{deviceId:this.defaultMediaSourceOptions?.selectedAudioDevice?.deviceId})})}),i)),this.updateMediaConfig(this.componentConfigSignal().mediaConfig))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleAudio: ",e)}}toggleAudioOn(){try{this.componentConfigSignal.update(t=>(t=y(h({},t),{mediaConfig:y(h({},t.mediaConfig),{audio:{enabled:!0}})}),t));let e=this.componentConfigSignal().mediaStream?.getAudioTracks()[0];e?e.enabled=!0:(this.componentConfigSignal.update(t=>(t=y(h({},t),{mediaConfig:y(h({},t.mediaConfig),{audio:y(h({},t.mediaConfig.audio),{deviceId:this.defaultMediaSourceOptions?.selectedAudioDevice?.deviceId})})}),t)),this.updateMediaConfig(this.componentConfigSignal().mediaConfig))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleAudioOn: ",e)}}toggleAudioOff(){try{this.componentConfigSignal.update(t=>(t=y(h({},t),{mediaConfig:y(h({},t.mediaConfig),{audio:{enabled:!1}})}),t));let e=this.componentConfigSignal().mediaStream?.getAudioTracks()[0];e&&(e.enabled=!1)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleAudioOn: ",e)}}toggleVideo(){try{this.componentConfigSignal.update(e=>(e=h({},e),e.mediaConfig.video||(e.mediaConfig.video={enabled:!0}),e.mediaConfig.video.enabled=!e.mediaConfig.video.enabled,e.mediaConfig.video.deviceId=this.defaultMediaSourceOptions?.selectedVideoDevice?.deviceId,e)),this.updateMediaConfig(this.componentConfigSignal().mediaConfig)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent toggleVideo: ",e)}}updateMediaConfig(e){try{this.stopMediaStream(),this.getMediaStream(e)}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent updateMediaConfig: ",t)}}getMediaStream(e){try{if(!navigator.mediaDevices){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream: ","No media devices");return}if(!navigator.mediaDevices.getUserMedia){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream: ","No getUserMedia");return}if(e.audio?.enabled||e.video?.enabled){let t=$be(e);navigator.mediaDevices.getUserMedia(t).then(i=>{this.componentConfigSignal.update(a=>(a=y(h({},a),{mediaConfig:e,mediaStream:i}),a))}).catch(i=>{this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream catch: ",i)})}else this.componentConfigSignal.update(t=>(t=y(h({},t),{mediaStream:void 0,mediaConfig:e}),t))}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent getMediaStream: ",t)}}stopMediaStream(){try{this.componentConfigSignal.update(e=>(e=h({},e),e.mediaStream?.getTracks().forEach(t=>{t.stop()}),e.mediaStream=void 0,e))}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent stopMediaStream: ",e)}}startCountdown(){return X(this,null,function*(){try{let t=new hr().getBrowserName()==="Firefox",i=null;if(t&&this.componentConfigSignal().type==="screen")try{let a=this.componentConfigSignal().mediaConfig,l=$be(a);Object.keys(l).length>0&&(i=yield navigator.mediaDevices.getUserMedia(l))}catch(a){this.loggingService.catch("Error getting Firefox user media stream:",a),i=null}if(this.componentConfigSignal().type==="screen"){if(!this.componentConfigSignal().mediaConfig.screen?.stream)try{let l=yield navigator.mediaDevices.getDisplayMedia({video:!0,audio:!0});this.componentConfigSignal.update(c=>(c=h({},c),c.mediaConfig.screen={enabled:!0,stream:l},c))}catch(l){this.loggingService.catch("Error getting screen media stream:",l),this.cancelCountdown();return}this.componentConfigSignal.update(l=>(l=h({},l),i&&(l.mediaConfig.audio?.enabled&&(l.mediaConfig.audio.stream=i),l.mediaConfig.video?.enabled&&(l.mediaConfig.video.stream=i)),l)),this.componentConfigSignal().mediaConfig.screen?.stream?.getTracks().forEach(l=>{l&&(l.onended=()=>{this.cancelCountdown()})})}this.recordingCountdownEnabled?(this.componentConfigSignal.update(a=>(a=y(h({},a),{countdownStarted:!0}),a)),this.countdownInterval=setInterval(()=>{this.componentConfigSignal().countdown>1?this.componentConfigSignal.update(a=>(a=y(h({},a),{countdown:a.countdown-1}),a)):this.closeDialog(this.componentConfigSignal().mediaConfig)},1e3)):this.closeDialog(this.componentConfigSignal().mediaConfig)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent startCountdown: ",e)}})}cancelCountdown(){try{if(this.componentConfigSignal.update(e=>(e=y(h({},e),{countdownStarted:!1,countdown:this.startCountdownFrom}),e)),this.clearInterval(),this.componentConfigSignal().type==="screen"){let e=this.componentConfigSignal().mediaConfig.screen?.stream;e&&e.getTracks().forEach(t=>{t.stop()}),this.componentConfigSignal.update(t=>(t=h({},t),t.mediaConfig.screen=void 0,t))}}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent cancelCountdown: ",e)}}closeDialog(e){return X(this,null,function*(){try{this.clearInterval(),e||(this.stopMediaStream(),this.componentConfigSignal.update(t=>(t=h({},t),t.mediaConfig&&(t.mediaConfig.screen?.stream&&(t.mediaConfig.screen.stream.getTracks().forEach(i=>i.stop()),t.mediaConfig.screen.stream=void 0),t.mediaConfig.audio?.stream&&(t.mediaConfig.audio.stream.getTracks().forEach(i=>i.stop()),t.mediaConfig.audio.stream=void 0),t.mediaConfig.video?.stream&&(t.mediaConfig.video.stream.getTracks().forEach(i=>i.stop()),t.mediaConfig.video.stream=void 0)),t))),this.dialogRef.close(e)}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent closeDialog: ",t)}})}handleOverlayClick(e){try{this.componentConfigSignal.update(t=>(t=y(h({},t),{isSettingsOpen:!1}),t)),e.stopPropagation()}catch(t){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent handleOverlayClick: ",t)}}clearInterval(){try{this.countdownInterval&&(clearInterval(this.countdownInterval),this.countdownInterval=void 0)}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent clearInterval: ",e)}}ngOnDestroy(){try{this.clearInterval(),this.stopMediaStream(),this.subscriptions.forEach(e=>{e?.unsubscribe()})}catch(e){this.loggingService.catch("Error in RecordingPreviewStepsDialogComponent ngOnDestroy: ",e)}}};o.\u0275fac=function(t){return new(t||o)(x(k),x(Un),x(Lo),x(ym),x(ji),x(Q),x(nd,8))},o.\u0275cmp=O({type:o,selectors:[["snippyly-recording-preview-steps-dialog"]],hostVars:1,hostBindings:function(t,i){t&2&&w("data-velt-element",i.veltElement)},inputs:{darkMode:"darkMode",shadowDom:"shadowDom"},standalone:!1,features:[Qe],decls:1,vars:1,consts:[["recordingPreviewDialogRef",""],[4,"ngIf"],["role","dialog","aria-modal","true",3,"snippylyOverlay","snippylyOverlayZIndex"],[3,"componentConfigSignal",4,"ngIf"],[3,"componentConfigSignal"]],template:function(t,i){t&1&&p(0,WWe,5,7,"ng-container",1),t&2&&g("ngIf",i.componentConfigSignal())},styles:["html[_ngcontent-%COMP%]{--velt-base-rem-unit: 1}*[data-snippyly-element=true][_ngcontent-%COMP%], *[data-velt-element=true][_ngcontent-%COMP%]{font-family:var(--velt-default-font-family)}velt-wireframe[_ngcontent-%COMP%]{display:none!important}body.velt-pin-dragging[_ngcontent-%COMP%] iframe[_ngcontent-%COMP%]{pointer-events:none!important}[_nghost-%COMP%]{--velt-green: var(--velt-light-mode-green);--velt-magenta: var(--velt-light-mode-magenta);--velt-amber: var(--velt-light-mode-amber);--velt-purple: var(--velt-light-mode-purple);--velt-cyan: var(--velt-light-mode-cyan);--velt-orange: var(--velt-light-mode-orange);--velt-black: var(--velt-light-mode-black);--velt-white: var(--velt-light-mode-white);--velt-gray: var(--velt-light-mode-gray);--velt-error: var(--velt-light-mode-error);--velt-error-hover: var(--velt-light-mode-error-hover);--velt-error-foreground: var(--velt-light-mode-error-foreground);--velt-error-light: var(--velt-light-mode-error-light);--velt-error-transparent: var(--velt-light-mode-error-transparent);--velt-warning: var(--velt-light-mode-warning);--velt-warning-hover: var(--velt-light-mode-warning-hover);--velt-warning-foreground: var(--velt-light-mode-warning-foreground);--velt-warning-light: var(--velt-light-mode-warning-light);--velt-warning-transparent: var(--velt-light-mode-warning-transparent);--velt-success: var(--velt-light-mode-success);--velt-success-hover: var(--velt-light-mode-success-hover);--velt-success-foreground: var(--velt-light-mode-success-foreground);--velt-success-light: var(--velt-light-mode-success-light);--velt-success-transparent: var(--velt-light-mode-success-transparent);--velt-accent: var(--velt-light-mode-accent);--velt-accent-text: var(--velt-light-mode-accent-text);--velt-accent-hover: var(--velt-light-mode-accent-hover);--velt-accent-foreground: var(--velt-light-mode-accent-foreground);--velt-accent-light: var(--velt-light-mode-accent-light);--velt-accent-transparent: var(--velt-light-mode-accent-transparent);--velt-text-0: var(--velt-light-mode-text-0);--velt-text-1: var(--velt-light-mode-text-1);--velt-text-2: var(--velt-light-mode-text-2);--velt-text-3: var(--velt-light-mode-text-3);--velt-text-4: var(--velt-light-mode-text-4);--velt-text-5: var(--velt-light-mode-text-5);--velt-text-6: var(--velt-light-mode-text-6);--velt-text-7: var(--velt-light-mode-text-7);--velt-text-8: var(--velt-light-mode-text-8);--velt-text-9: var(--velt-light-mode-text-9);--velt-text-10: var(--velt-light-mode-text-10);--velt-text-11: var(--velt-light-mode-text-11);--velt-text-12: var(--velt-light-mode-text-12);--velt-background-0: var(--velt-light-mode-background-0);--velt-background-1: var(--velt-light-mode-background-1);--velt-background-2: var(--velt-light-mode-background-2);--velt-background-3: var(--velt-light-mode-background-3);--velt-background-4: var(--velt-light-mode-background-4);--velt-background-5: var(--velt-light-mode-background-5);--velt-background-6: var(--velt-light-mode-background-6);--velt-background-7: var(--velt-light-mode-background-7);--velt-background-8: var(--velt-light-mode-background-8);--velt-background-9: var(--velt-light-mode-background-9);--velt-background-10: var(--velt-light-mode-background-10);--velt-border-0: var(--velt-light-mode-border-0);--velt-border-1: var(--velt-light-mode-border-1);--velt-border-2: var(--velt-light-mode-border-2);--velt-border-3: var(--velt-light-mode-border-3);--velt-border-4: var(--velt-light-mode-border-4);--velt-border-5: var(--velt-light-mode-border-5);--velt-border-6: var(--velt-light-mode-border-6);--velt-border-7: var(--velt-light-mode-border-7);--velt-border-8: var(--velt-light-mode-border-8);--velt-border-9: var(--velt-light-mode-border-9);--velt-border-10: var(--velt-light-mode-border-10);--velt-background-transparent: var(--velt-light-mode-background-transparent);--velt-border-transparent: var(--velt-light-mode-border-transparent);--velt-animation-transparent: var(--velt-light-mode-animation-transparent)}[dark][_nghost-%COMP%]{--velt-green: var(--velt-dark-mode-green);--velt-magenta: var(--velt-dark-mode-magenta);--velt-amber: var(--velt-dark-mode-amber);--velt-purple: var(--velt-dark-mode-purple);--velt-cyan: var(--velt-dark-mode-cyan);--velt-orange: var(--velt-dark-mode-orange);--velt-black: var(--velt-dark-mode-black);--velt-white: var(--velt-dark-mode-white);--velt-gray: var(--velt-dark-mode-gray);--velt-error: var(--velt-dark-mode-error);--velt-error-hover: var(--velt-dark-mode-error-hover);--velt-error-foreground: var(--velt-dark-mode-error-foreground);--velt-error-light: var(--velt-dark-mode-error-light);--velt-error-transparent: var(--velt-dark-mode-error-transparent);--velt-warning: var(--velt-dark-mode-warning);--velt-warning-hover: var(--velt-dark-mode-warning-hover);--velt-warning-foreground: var(--velt-dark-mode-warning-foreground);--velt-warning-light: var(--velt-dark-mode-warning-light);--velt-warning-transparent: var(--velt-dark-mode-warning-transparent);--velt-success: var(--velt-dark-mode-success);--velt-success-hover: var(--velt-dark-mode-success-hover);--velt-success-foreground: var(--velt-dark-mode-success-foreground);--velt-success-light: var(--velt-dark-mode-success-light);--velt-success-transparent: var(--velt-dark-mode-success-transparent);--velt-accent: var(--velt-dark-mode-accent);--velt-accent-text: var(--velt-dark-mode-accent-text);--velt-accent-hover: var(--velt-dark-mode-accent-hover);--velt-accent-foreground: var(--velt-dark-mode-accent-foreground);--velt-accent-light: var(--velt-dark-mode-accent-light);--velt-accent-transparent: var(--velt-dark-mode-accent-transparent);--velt-text-0: var(--velt-dark-mode-text-0);--velt-text-1: var(--velt-dark-mode-text-1);--velt-text-2: var(--velt-dark-mode-text-2);--velt-text-3: var(--velt-dark-mode-text-3);--velt-text-4: var(--velt-dark-mode-text-4);--velt-text-5: var(--velt-dark-mode-text-5);--velt-text-6: var(--velt-dark-mode-text-6);--velt-text-7: var(--velt-dark-mode-text-7);--velt-text-8: var(--velt-dark-mode-text-8);--velt-text-9: var(--velt-dark-mode-text-9);--velt-text-10: var(--velt-dark-mode-text-10);--velt-text-11: var(--velt-dark-mode-text-11);--velt-text-12: var(--velt-dark-mode-text-12);--velt-background-0: var(--velt-dark-mode-background-0);--velt-background-1: var(--velt-dark-mode-background-1);--velt-background-2: var(--velt-dark-mode-background-2);--velt-background-3: var(--velt-dark-mode-background-3);--velt-background-4: var(--velt-dark-mode-background-4);--velt-background-5: var(--velt-dark-mode-background-5);--velt-background-6: var(--velt-dark-mode-background-6);--velt-background-7: var(--velt-dark-mode-background-7);--velt-background-8: var(--velt-dark-mode-background-8);--velt-background-9: var(--velt-dark-mode-background-9);--velt-background-10: var(--velt-dark-mode-background-10);--velt-border-0: var(--velt-dark-mode-border-0);--velt-border-1: var(--velt-dark-mode-border-1);--velt-border-2: var(--velt-dark-mode-border-2);--velt-border-3: var(--velt-dark-mode-border-3);--velt-border-4: var(--velt-dark-mode-border-4);--velt-border-5: var(--velt-dark-mode-border-5);--velt-border-6: var(--velt-dark-mode-border-6);--velt-border-7: var(--velt-dark-mode-border-7);--velt-border-8: var(--velt-dark-mode-border-8);--velt-border-9: var(--velt-dark-mode-border-9);--velt-border-10: var(--velt-dark-mode-border-10);--velt-background-transparent: var(--velt-dark-mode-background-transparent);--velt-border-transparent: var(--velt-dark-mode-border-transparent);--velt-animation-transparent: var(--velt-dark-mode-animation-transparent)} .velt-mat-dialog-container.snippyly-recording-preview-steps-dialog{max-width:none} .velt-mat-dialog-container.snippyly-recording-preview-steps-dialog mat-dialog-container .mat-mdc-dialog-surface.mdc-dialog__surface{background:transparent;padding:0;margin:0;border-radius:var(--velt-border-radius-lg)}"],changeDetection:0});let n=o;return n})();function $be(n){try{let o={};return n.audio?.enabled&&(o.audio={deviceId:n.audio.deviceId?{exact:n.audio.deviceId}:void 0}),n.video?.enabled&&(o.video={deviceId:n.video.deviceId?{exact:n.video.deviceId}:void 0}),o}catch{return{}}}var oc=(()=>{let o=class o{constructor(e){this.loggingService=e,this.isPipActive$=new _e(!1),this.pipStopRecordingTriggered$=new _e(!1),this.pipPauseRecordingTriggered$=new _e(!1),this.pictureInPicture$=new _e(!1),this.pipClearRecordingTriggered$=new _e(!1)}getPipClearRecordingTriggered$(){return this.pipClearRecordingTriggered$.asObservable()}resetPipClearRecordingTriggered(){this.pipClearRecordingTriggered$.next(!1)}openPictureInPicture(e,t){return X(this,null,function*(){try{if(!this.isPictureInPictureEnabled()||!e||document.pictureInPictureElement||window.documentPictureInPicture?.window)return;if("documentPictureInPicture"in window){yield this.createDocumentPip(e,t);return}if(document.pictureInPictureEnabled){let i=yield this.findVideoElement();if(!i){this.loggingService.warn("No video element found for Picture-in-Picture");return}yield i.requestPictureInPicture(),this.isPipActive$.next(!0);return}}catch(i){this.loggingService.catch("Error in PipService openPictureInPicture:",i)}})}createDocumentPip(e,t){return X(this,null,function*(){try{let i=window.documentPictureInPicture;this.pipWindow=yield i.requestWindow({width:320,height:288}),yield this.addStylesToPip(),yield this.createControlPanelInPip(e,t),this.pipWindow?.addEventListener("unload",()=>{try{this.isPipActive$.next(!1),this.pipWindow=void 0}catch(a){this.loggingService.catch("Error in PipService createDocumentPip unload:",a)}}),this.isPipActive$.next(!0)}catch{this.isPipActive$.next(!1),this.pipWindow=void 0}})}addStylesToPip(){return X(this,null,function*(){try{if(!this.pipWindow)return;this.pipWindow.document.body.style.margin="0",this.pipWindow.document.body.style.padding="0",this.pipWindow.document.body.style.backgroundColor="#000",this.pipWindow.document.body.style.display="flex",this.pipWindow.document.body.style.alignItems="center",this.pipWindow.document.body.style.justifyContent="center"}catch(e){this.loggingService.catch("Error in PipService copyStylesToPip:",e)}})}createControlPanelInPip(e,t){return X(this,null,function*(){if(this.pipWindow)try{let i=this.pipWindow.document.createElement("div");i.style.cssText=`
409
409
  display: flex;
410
410
  flex-direction: column;
411
411
  `;let a=this.pipWindow.document.createElement("div");a.style.cssText=`
@@ -497,7 +497,7 @@ This typically indicates that your device does not have a healthy Internet conne
497
497
  <path d="M6 4.66685V15.3335C5.99997 15.4521 6.03158 15.5686 6.09159 15.6709C6.15159 15.7733 6.23781 15.8577 6.34135 15.9156C6.44489 15.9735 6.562 16.0027 6.68059 16.0002C6.79918 15.9978 6.91497 15.9637 7.016 15.9015L15.6827 10.5682C15.7797 10.5085 15.8599 10.425 15.9155 10.3256C15.9711 10.2261 16.0003 10.1141 16.0003 10.0002C16.0003 9.88626 15.9711 9.77423 15.9155 9.6748C15.8599 9.57536 15.7797 9.49183 15.6827 9.43219L7.016 4.09885C6.91497 4.0367 6.79918 4.00262 6.68059 4.00015C6.562 3.99767 6.44489 4.02688 6.34135 4.08476C6.23781 4.14265 6.15159 4.22711 6.09159 4.32943C6.03158 4.43175 5.99997 4.54823 6 4.66685Z" fill="currentColor"/>
498
498
  </svg>
499
499
  `;break}l.innerHTML=c.trim();let d=l.firstElementChild;return d&&a.appendChild(d),a.addEventListener("click",i),a.__cleanup=()=>{a.removeEventListener("click",i)},a}exitPictureInPicture(){return X(this,null,function*(){try{if("documentPictureInPicture"in window&&(window.documentPictureInPicture.window||this.pipWindow)){this.pipWindow&&!this.pipWindow.closed&&this.pipWindow.close(),this.pipWindow=void 0,this.isPipActive$.next(!1);return}if(document.pictureInPictureElement){yield document.exitPictureInPicture(),this.isPipActive$.next(!1);return}this.isPipActive$.next(!1),this.pipWindow=void 0}catch(e){this.loggingService.catch("Error in PipService exitPictureInPicture:",e),this.isPipActive$.next(!1),this.pipWindow=void 0}})}togglePictureInPicture(e,t){return X(this,null,function*(){try{this.isPipActive$.value||this.pipWindow||document.pictureInPictureElement?yield this.exitPictureInPicture():yield this.openPictureInPicture(e,t)}catch(i){this.loggingService.catch("Error in PipService togglePictureInPicture:",i),this.isPipActive$.next(!1),this.pipWindow=void 0}})}findVideoElement(){return X(this,null,function*(){try{let e=['[data-testid*="velt-recorder-control-panel-video-video"]','[data-testid*="velt-recorder-control-panel-screen-screen"]','video[data-testid*="recorder"]'];for(let i of e){let a=document.querySelector(i);if(a&&a.srcObject)return a}let t=Array.from(document.querySelectorAll("video"));for(let i of t)if(i.srcObject)return i;return null}catch(e){return this.loggingService.catch("Error in PipService findVideoElement:",e),null}})}getIsPipActive$(){return this.isPipActive$.asObservable()}getIsPipActive(){return this.isPipActive$.value}getPipStopRecordingTriggered$(){return this.pipStopRecordingTriggered$.asObservable()}resetPipStopRecordingTriggered(){this.pipStopRecordingTriggered$.next(!1)}getPipPauseRecordingTriggered$(){return this.pipPauseRecordingTriggered$.asObservable()}resetPipPauseRecordingTriggered(){this.pipPauseRecordingTriggered$.next(!1)}enablePictureInPicture(){try{if(this.pictureInPicture$.value===!0)return;this.pictureInPicture$.next(!0),this.messageListener||(this.messageListener=e=>{try{if(e.origin!==window.location.origin){this.loggingService.warn("Received message from untrusted origin:",e.origin);return}if(e.source!==this.pipWindow&&e.source!==window.parent){this.loggingService.warn("Received message from untrusted source window");return}e.data?.type==="pip-stop-recording"?this.pipStopRecordingTriggered$.next(!0):e.data?.type==="pip-pause-recording"||e.data?.type==="pip-resume-recording"?this.pipPauseRecordingTriggered$.next(!0):e.data?.type==="pip-clear-recording"&&this.pipClearRecordingTriggered$.next(!0)}catch(t){this.loggingService.catch("Error in PipService enablePictureInPicture message listener:",t)}},window.addEventListener("message",this.messageListener))}catch(e){this.loggingService.catch("Error in PipService enablePictureInPicture: ",e)}}disablePictureInPicture(){try{if(this.pictureInPicture$.value===!1)return;this.pictureInPicture$.next(!1),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=void 0),this.pipStopRecordingTriggered$.next(!1),this.pipPauseRecordingTriggered$.next(!1),this.pipClearRecordingTriggered$.next(!1),this.isPipActive$.next(!1),this.pipWindow&&!this.pipWindow.closed&&this.pipWindow.close(),this.pipWindow=void 0}catch(e){this.loggingService.catch("Error in PipService disablePictureInPicture: ",e)}}getPictureInPicture$(){return this.pictureInPicture$.asObservable()}isPictureInPictureEnabled(){try{let e=new hr;return this.pictureInPicture$.value&&e.getBrowserName()==="Chrome"}catch(e){return this.loggingService.catch("Error in PipService isPictureInPictureEnabled: ",e),!1}}};o.\u0275fac=function(t){return new(t||o)(K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Un=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_){this.analyticsService=e,this.loggingService=t,this.matDialog=i,this.storageService=a,this.docService=l,this.databaseService=c,this.domService=d,this.attachmentResolverService=m,this.pipService=u,this.recorderAnnotationsResolverService=_,this.recorderStatusSubject$=new _e(null),this.recorderDurationSubject$=new _e(null),this.darkMode$=new _e(null),this.shadowDom$=new _e(null),this.recordingDurations=[],this.chunks=[],this.recordingCountdownEnabled$=new _e(!0),this.recorderInitData$=new at,this.recordedRawData$=new at,this.recordedData$=new at,this.onInitRecording$=new _e(null),this.onRecordingAttributeRemovedFromBodySubject$=new at,this.videoEditor$=new _e(!1),this.videoEditorTimelinePreview$=new _e(!1),this.settingsEmbedded$=new _e(!1),this.autoOpenVideoEditor$=new _e(!1),this.playVideoInFullScreen$=new _e(void 0),this.recordedDataStream=[],this.documentPaths=null,this.uploadPromises=[],this.chunkUrls$=new _e({}),this.recordingQualityConstraints=new _e({safari:{audio:{sampleRate:48e3,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:{width:{min:640,ideal:1280,max:1280},height:{min:360,ideal:720,max:720},frameRate:{min:15,ideal:20,max:30},aspectRatio:{ideal:1.777777778}}},other:{audio:{sampleRate:48e3,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:{width:{min:640,ideal:1280,max:1280},height:{min:360,ideal:720,max:720},frameRate:{min:15,ideal:20,max:30},aspectRatio:{ideal:1.777777778}}}}),this.recordingEncodingOptions=new _e({safari:{videoBitsPerSecond:25e5,audioBitsPerSecond:128e3},other:{videoBitsPerSecond:1e6,audioBitsPerSecond:128e3}}),this.recordingMicEnabled$=new _e(null),this.onboardingTooltip$=new _e(!1),this.audioContext=null,this.audioDestination=null,this.activeInputTracks=new Set,this.retakeOnVideoEditor$=new _e(!1),this.maxRecordingLength=null,this.screenStreamSubject$=new _e(null),this.playbackOnPreviewClick$=new _e(!0),this.onInitRecording$.subscribe(I=>{I?this.setRecordingAttributeAtBody():this.removeRecordingAttributeFromBody()}),this.pipService.getPipPauseRecordingTriggered$().subscribe(I=>{I&&(this.recorderStatusSubject$.value==="started"||this.recorderStatusSubject$.value==="resumed"?this.pauseRecording():this.recorderStatusSubject$.value==="paused"&&this.resumeRecording(),this.pipService.resetPipPauseRecordingTriggered())}),this.databaseService.getDb().pipe(Ge(I=>!!I),ut(1)).subscribe(I=>{I&&this.getDocumentPaths()},I=>{this.loggingService.catch("Error in RecorderAnnotationService getDb subscription: ",I)})}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;");try{this.docService.getDocumentPaths$().pipe(ln(e=>{this.documentPaths=e})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getDocumentPaths subscription: ",e)})}catch(e){this.loggingService.catch("Error in CursorService getDocumentPaths: ",e)}}setRecordedDataStream(e){this.recordedDataStream=e}getRecordedDataStream(){return this.recordedDataStream}setRecordingAttributeAtBody(){try{let e=this.onInitRecording$.getValue();e&&(document.body.setAttribute(N.ATTRIBUTES.VELT_ONGOING_RECORDING,e.type),e?.isCommentRecording&&document.body.setAttribute(N.ATTRIBUTES.VELT_COMMENT_RECORDING,"true"))}catch(e){this.loggingService.catch("Error in RecorderService setRecordingAttributeAtBody: ",e)}}removeRecordingAttributeFromBody(){try{document.body.removeAttribute(N.ATTRIBUTES.VELT_ONGOING_RECORDING),document.body.removeAttribute(N.ATTRIBUTES.VELT_COMMENT_RECORDING),this.onRecordingAttributeRemovedFromBodySubject$.next()}catch(e){this.loggingService.catch("Error in RecorderService removeRecordingAttributeFromBody: ",e)}}onRecordingAttributeRemovedFromBody$(){return this.onRecordingAttributeRemovedFromBodySubject$.asObservable()}getRecorderInitData(){return this.recorderInitData$.asObservable()}onInitRecording(){return this.onInitRecording$.asObservable()}onRecordedData(){return this.recordedData$.asObservable()}setRecordedData(e){this.recordedData$.next(e)}initRecording(e,t,i,a,l,c,d,m,u,_){return X(this,null,function*(){try{let I={};switch(e){case"audio":I.audio={enabled:!0};break;case"video":I.video={enabled:!0},I.audio={enabled:!0};break;case"screen":I.screen={enabled:!0,stream:u},I.video={enabled:!1},I.audio={enabled:!1};break;default:break}u&&e==="screen"&&(I.screen={enabled:!0,stream:u}),this.matDialog.open(ZL,{panelClass:"velt-mat-dialog-container",data:{type:e,mediaConfig:I,darkMode:[!0,!1].includes(a)?a:this.darkMode$.value,shadowDom:l,isExplicitShadowDom:_,recordingCountdown:m}}).afterClosed().subscribe(A=>{if(A){let M={};switch(e){case"audio":M.audio={enabled:!0,deviceId:A.audio?.deviceId},M.audio=A.audio;break;case"video":M.video={enabled:!0,deviceId:A.video?.deviceId},M.audio={enabled:!0,deviceId:A.audio?.deviceId},M.video=A.video,M.audio=A.audio;break;case"screen":M.screen={enabled:!0},M.audio=A.audio,M.video=A.video,M.screen=A.screen;break;default:break}this.onInitRecording$.next({type:e,panelId:t,mediaConfig:M,isCommentRecording:i,darkMode:[!0,!1].includes(a)?a:!!this.darkMode$.value,shadowDom:l,isExplicitShadowDom:_,commentAnnotationId:c,clientDocumentId:d})}},A=>{this.loggingService.catch("Error in RecorderService initRecording afterClosed: ",A)})}catch(I){this.loggingService.catch("Error in RecorderService initRecording: ",I)}})}startRecording(e,t){return X(this,null,function*(){try{this.loggingService.log("[startRecording] Starting with config:",e,"mediaConfig:",t);let i=new MediaStream,a=yield this.getBrowserSpecificOptions();return yield this.collectMediaTracks(i,e,t),yield this.initializeMediaRecorder(i,a,e),this.setupRecorderData(e,i),i}catch(i){return this.loggingService.catch("Error in RecorderService startRecording: ",i),Promise.reject(i)}})}getBrowserSpecificOptions(){return X(this,null,function*(){try{let e={videoBitsPerSecond:this.recordingEncodingOptions.value[this.isSafari()?"safari":"other"]?.videoBitsPerSecond,audioBitsPerSecond:this.recordingEncodingOptions.value[this.isSafari()?"safari":"other"]?.audioBitsPerSecond},t=this.getSupportedMimeTypes();if(t.length>0){let a=t.find(l=>l.includes("mp4")&&l.includes("h264"))||t.find(l=>l.includes("mp4"))||t[0];e.mimeType=a}return new hr().getBrowserName()==="Firefox"&&(t.includes("video/webm")&&(e.mimeType="video/webm"),e.videoBitsPerSecond=Math.min(e.videoBitsPerSecond||1e6,2e6),e.audioBitsPerSecond=Math.min(e.audioBitsPerSecond||128e3,256e3)),e}catch(e){return this.loggingService.catch("Error in RecorderService getBrowserSpecificOptions: ",e),{}}})}collectMediaTracks(e,t,i){return X(this,null,function*(){try{let a=[],l=[];if(t.type.screen&&i?.screen?.stream){let c=this.getCommonVideoQualityConstraints(!0);i.screen.stream.getTracks().forEach(d=>{d.onended=()=>this.stopRecording(),d.kind==="video"?(d.applyConstraints(h({},c)),l.push(d),this.loggingService.log("[collectMediaTracks] Added screen video track"),this.registerActiveTrack(d)):d.kind==="audio"&&(a.push(d),this.loggingService.log("[collectMediaTracks] Collected tab audio track for mixing"),this.registerActiveTrack(d))})}if(t?.type.audio||t?.type.video)if(this.isFirefox()&&t.type.screen&&(i?.audio?.stream||i?.video?.stream))t.type.audio&&i?.audio?.stream&&i.audio.stream.getAudioTracks().forEach(m=>{a.push(m),this.loggingService.log("[collectMediaTracks] Collected mic audio track for mixing (Firefox)"),this.registerActiveTrack(m)}),t.type.video&&i?.video?.stream&&i.video.stream.getVideoTracks().forEach(m=>{l.push(m),this.loggingService.log("[collectMediaTracks] Added user video track (Firefox)"),this.registerActiveTrack(m)});else{let d=this.buildMediaConstraints(t,i),m=yield navigator.mediaDevices.getUserMedia(d);if(m){if(t?.type.audio){let u=m.getAudioTracks();if(u.length>0)if(this.isSafari()){let _=u[0];if(_.getSettings().sampleRate!==48e3){this.loggingService.log("[collectMediaTracks] Adjusting audio sample rate for Safari");let M=(yield navigator.mediaDevices.getUserMedia({audio:{sampleRate:48e3}})).getAudioTracks()[0];a.push(M),this.registerActiveTrack(M),_.stop()}else a.push(_),this.registerActiveTrack(_)}else u.forEach(_=>{a.push(_),this.loggingService.log("[collectMediaTracks] Collected mic audio track for mixing"),this.registerActiveTrack(_)})}if(t?.type.video){let u=m.getVideoTracks();if(u.length>0)if(this.isSafari()){let _=u[0];_.enabled=!0;let I=_.clone();l.push(I),this.loggingService.log("[collectMediaTracks] Added user video track (Safari, cloned)"),i&&i.video&&(i.video.track=_),this.registerActiveTrack(_)}else u.forEach(_=>{l.push(_),this.loggingService.log("[collectMediaTracks] Added user video track"),this.registerActiveTrack(_)})}}}if(a.length>0)if(this.loggingService.log(`[collectMediaTracks] Processing ${a.length} audio track(s)`),a.length===1)e.addTrack(a[0]),this.loggingService.log("[collectMediaTracks] Added single audio track (no mixing needed)");else{this.loggingService.log("[collectMediaTracks] Mixing multiple audio tracks...");let c=yield this.mixAudioTracks(a);c?(e.addTrack(c),this.loggingService.log("[collectMediaTracks] Added mixed audio track to stream")):(this.loggingService.warn("[collectMediaTracks] Failed to mix audio tracks, adding first track only"),e.addTrack(a[0]))}l.forEach(c=>{e.addTrack(c)}),this.loggingService.log(`[collectMediaTracks] Added ${l.length} video track(s) to stream`),this.loggingService.log(`[collectMediaTracks] Final stream: ${e.getAudioTracks().length} audio track(s), ${e.getVideoTracks().length} video track(s)`)}catch(a){this.loggingService.catch("Error in RecorderService collectMediaTracks: ",a);return}})}buildMediaConstraints(e,t){try{let i=this.getCommonVideoQualityConstraints(!!e.type.video),a=this.getCommonAudioConstraints(!!e.type.audio,t);return qWe(!!e.type.video,a,i,t)}catch(i){return this.loggingService.catch("Error in RecorderService buildMediaConstraints: ",i),{}}}getCommonAudioConstraints(e,t){try{if(!e)return!1;let i=this.recordingQualityConstraints.value[this.isSafari()?"safari":"other"]?.audio||{};return YWe(t,i)}catch(i){return this.loggingService.catch("Error in RecorderService getCommonAudioConstraints: ",i),{}}}getCommonVideoQualityConstraints(e){try{return e?this.recordingQualityConstraints.value[this.isSafari()?"safari":"other"]?.video||{}:{}}catch(t){return this.loggingService.catch("Error in RecorderService getCommonVideoQualityConstraints: ",t),{}}}adjustSafariAudioTrack(e,t){return X(this,null,function*(){try{let i=t.getAudioTracks()[0];if(i.getSettings().sampleRate!==48e3){this.loggingService.log("[startRecording] Adjusting audio sample rate for Safari");let l=yield navigator.mediaDevices.getUserMedia({audio:{sampleRate:48e3}});e.addTrack(l.getAudioTracks()[0])}else e.addTrack(i)}catch(i){this.loggingService.catch("Error in RecorderService adjustSafariAudioTrack: ",i);return}})}registerActiveTrack(e){try{e&&this.activeInputTracks.add(e)}catch(t){this.loggingService.catch("Error in RecorderService registerActiveTrack:",t)}}stopAllActiveInputTracks(){try{this.activeInputTracks.forEach(e=>{try{e?.readyState!=="ended"&&e.stop()}catch{}}),this.activeInputTracks.clear()}catch(e){this.loggingService.catch("Error in RecorderService stopAllActiveInputTracks:",e)}}mixAudioTracks(e){return X(this,null,function*(){try{if(e.length===0)return this.loggingService.warn("[mixAudioTracks] No audio tracks provided"),null;if(e.length===1)return this.loggingService.log("[mixAudioTracks] Only one audio track, no mixing needed"),e[0];this.loggingService.log(`[mixAudioTracks] Mixing ${e.length} audio tracks`),this.cleanupAudioMixing(),this.audioContext=new AudioContext,this.audioDestination=this.audioContext.createMediaStreamDestination();let t=this.audioContext.createGain();t.gain.value=1,t.connect(this.audioDestination);for(let a of e)try{let l=new MediaStream([a]),c=this.audioContext.createMediaStreamSource(l),d=this.audioContext.createGain();d.gain.value=1,c.connect(d),d.connect(t),this.loggingService.log(`[mixAudioTracks] Connected audio track: ${a.label||"unlabeled"}`)}catch(l){this.loggingService.catch(`[mixAudioTracks] Error connecting track ${a.label}:`,l)}let i=this.audioDestination.stream.getAudioTracks();return i.length>0?(this.loggingService.log("[mixAudioTracks] Successfully created mixed audio track"),i[0]):(this.loggingService.warn("[mixAudioTracks] No mixed track created"),null)}catch(t){return this.loggingService.catch("Error in RecorderService mixAudioTracks:",t),this.cleanupAudioMixing(),null}})}cleanupAudioMixing(){try{this.audioDestination&&(this.audioDestination.stream.getTracks().forEach(e=>{e.stop()}),this.audioDestination=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close().catch(e=>{this.loggingService.catch("Error closing audio context:",e)}),this.audioContext=null)}catch(e){this.loggingService.catch("Error in RecorderService cleanupAudioMixing:",e)}}initializeMediaRecorder(e,t,i){return X(this,null,function*(){try{if(this.mediaRecorder)try{this.mediaRecorder.state!=="inactive"&&this.mediaRecorder.stop(),this.mediaRecorder=null}catch(m){this.loggingService.catch("Error cleaning up old mediaRecorder:",m)}if(e.getTracks().length===0)throw new Error("MediaStream has no tracks");this.mediaRecorder=new MediaRecorder(e,t),this.chunks=[],this.chunkUrls$.next({}),this.uploadPromises=[];let a=0;if(this.isSafari()){let m=e.getVideoTracks();m.length>0&&m.forEach(u=>{u.contentHint="detail",u.enabled=!0})}let c=new hr().getBrowserName()==="Firefox";c&&e.getTracks().forEach(m=>{m.enabled=!0}),this.mediaRecorder.addEventListener("dataavailable",m=>{if(m.data?.size>0){let u=a++;if(this.chunks.push(m.data),this.recorderAnnotationsResolverService.shouldUploadFullRecording())return;let _=`recording_${new Date().getTime()}_${Math.random().toString(36).substring(2,9)}`,I=m.data,A=this.uploadChunk(I,_,u);this.uploadPromises||(this.uploadPromises=[]),this.uploadPromises.push({promise:A,index:u}),A.then(M=>{this.chunkUrls$.next(y(h({},this.chunkUrls$.value),{[u]:M}))}).catch(M=>{})}}),this.mediaRecorder.addEventListener("stop",()=>{c&&this.chunks.length===0&&this.attemptFirefoxCanvasRecording(e),this.onStopRecording()}),this.mediaRecorder.addEventListener("error",m=>{this.loggingService.catch("MediaRecorder error event:",m)});let d=4e3;c&&i.type.screen&&(d=void 0),d?this.mediaRecorder.start(d):this.mediaRecorder.start(),c&&setTimeout(()=>{if(this.chunks.length===0&&this.mediaRecorder.state==="recording")try{this.mediaRecorder.requestData&&this.mediaRecorder.requestData()}catch{}},2e3)}catch(a){throw this.loggingService.catch("Error in RecorderService initializeMediaRecorder: ",a),a}})}uploadChunk(e,t,i){return X(this,null,function*(){try{let l=this.mediaRecorder.mimeType||"video/mp4",c=l.includes("webm")?"webm":"mp4",d=`chunk_${i}_${new Date().getTime()}.${c}`,m=new File([e],d,{type:l});return yield this.uploadChunkToStorage(m,t,i)}catch(a){throw a}})}uploadChunkToStorage(e,t,i){try{if(!this.documentPaths?.documentId)throw new Error("Document ID is required for chunk upload");let a=this.documentPaths?.organizationId,l=this.documentPaths?.documentId,c=`${N.FIREBASE_PARTIAL_PATH_DOCS}/${l}/${N.FIREBASE_PARTIAL_PATH_RECORDER}/${t}`;if(a&&(c=`${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${a}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${l}/${N.FIREBASE_PARTIAL_PATH_RECORDER}/${t}`),this.attachmentResolverService.attachmentDataProviderAvailable("recorder")){let d=this.docService.getBaseMetadata("recorder");return this.storageService.uploadChunk(c,e,i,{useAttachmentResolver:!0,metadata:d,attachmentScope:"recorder"})}return this.storageService.uploadChunk(c,e,i)}catch(a){throw this.loggingService.catch("Error in RecorderService uploadChunkToStorage: ",a),a}}setupRecorderData(e,t){try{return this.recorderInitData=new UN,this.recorderStatusSubject$.next("started"),this.isSafari()&&e.type.video&&t.getVideoTracks().forEach(i=>{i.enabled=!0}),this.recorderInitData.stream=t,this.recorderInitData.status=this.recorderStatusSubject$.asObservable(),this.recorderInitData.type=this.determineRecorderType(e),this.recorderInitData.recordedTime=this.recorderDurationSubject$.asObservable(),this.recorderInitData.recordedRawData$=this.recordedRawData$.asObservable(),this.recordingDurations=[{start:new Date().getTime()}],this.startTimer(),this.recorderInitData$.next(this.recorderInitData),this.recorderActionsService?.onRecordingStarted(this.getRecorderDataFromInitData()),this.pipService.getIsPipActive()&&window.postMessage({type:"recording-status-update",status:"started"},"*"),this.recorderInitData}catch(i){return this.loggingService.catch("Error in RecorderService setupRecorderData: ",i),null}}determineRecorderType(e){try{return e.type.video?"video":e.type.screen?"screen":(e.type.audio,"audio")}catch(t){return this.loggingService.catch("Error in RecorderService determineRecorderType: ",t),"audio"}}timeout(e){return new Promise(t=>setTimeout(t,e))}pauseRecording(){try{if(this.recorderStatusSubject$.next("paused"),this.mediaRecorder.pause(),this.firefoxFallbackRecorder?.state==="recording")try{this.firefoxFallbackRecorder.pause()}catch(e){this.loggingService.catch("Error pausing Firefox fallback recorder: ",e)}this.recordingDurations?.length&&(this.recordingDurations[this.recordingDurations.length-1].end=new Date().getTime()),this.stopTimer(),this.recorderActionsService?.onRecordingPaused(this.getRecorderDataFromInitData()),this.pipService.getIsPipActive()&&window.postMessage({type:"recording-status-update",status:"paused",recordingType:this.recorderInitData?.type||"video"},window.location.origin)}catch(e){this.loggingService.catch("Error in RecorderService pauseRecording: ",e)}}resumeRecording(){try{if(this.recorderStatusSubject$.next("resumed"),this.mediaRecorder.resume(),this.firefoxFallbackRecorder?.state==="paused")try{this.firefoxFallbackRecorder.resume()}catch(e){this.loggingService.catch("Error resuming Firefox fallback recorder: ",e)}this.recordingDurations.push({start:new Date().getTime()}),this.startTimer(),this.recorderActionsService?.onRecordingResumed(this.getRecorderDataFromInitData()),this.pipService.getIsPipActive()&&window.postMessage({type:"recording-status-update",status:"started",recordingType:this.recorderInitData?.type||"video"},"*")}catch(e){this.loggingService.catch("Error in RecorderService resumeRecording: ",e)}}stopRecording(){try{if(this.mediaRecorder?.state!=="inactive"?(this.mediaRecorder.stop(),this.removeRecordingAttributeFromBody(),this.stopAllActiveInputTracks(),this.cleanupAudioMixing()):this.clearRecording(),this.firefoxFallbackRecorder?.state==="recording")try{this.firefoxFallbackRecorder.stop()}catch(e){this.loggingService.catch("Error stopping Firefox fallback recorder: ",e)}this.recorderActionsService?.onRecordingStopped(this.getRecorderDataFromInitData())}catch(e){this.loggingService.catch("Error in RecorderService stopRecording: ",e)}}onStopRecording(){return X(this,null,function*(){try{this.loggingService.log("[onStopRecording] Starting, current chunks:",this.chunks.length),this.recordingDurations?.length&&(this.recordingDurations[this.recordingDurations?.length-1].end=new Date().getTime()),this.stopTimer(),this.recorderStatusSubject$.next("stopped"),(this.recorderInitData?.stream?.getTracks()||[]).forEach(i=>{i.stop()}),this.stopAllActiveInputTracks(),this.cleanupAudioMixing(),yield this.timeout(100);let t=new y3;if(this.chunks.length>0){let i=this.recorderInitData?.type==="audio"?"audio/mp4":"video/mp4";this.loggingService.log("[onStopRecording] Creating blob with type:",i),t.blob=new Blob(this.chunks,{type:i}),this.loggingService.log("[onStopRecording] Blob created, size:",t.blob.size);try{let a=yield this.getVideoDuration(t.blob);if(a&&isFinite(a)&&a>0){let l={};l.duration=a*1e3,l.display=this.convertMillisecondsToTime(a*1e3),this.recorderDurationSubject$.next(l),t.recordedTime=l}else{let l=this.recorderDurationSubject$.value;t.recordedTime=l}}catch(a){let l=this.recorderDurationSubject$.value;t.recordedTime=l,this.recorderInitData&&this.loggingService.catch("Error in RecorderService onStopRecording getVideoDuration: ",a)}if(t.blob.size===0)throw new Error("Recorded blob has zero size");if(t.url=URL.createObjectURL(t.blob),t.type=this.recorderInitData?.type,t.recordedTime=this.recorderDurationSubject$.value,t?.type!=="audio")try{yield this.timeout(200);let a=yield rhe(t.blob,3);a&&(t.thumbnail=yield ohe(a))}catch(a){this.recorderInitData&&this.loggingService.catch("Error in RecorderService onStopRecording getVideoCover: ",a)}}this.recordedRawData$.next(t)}catch(e){this.loggingService.catch("Error in RecorderService onStopRecording: ",e),this.recordedRawData$.error(e)}})}clearRecording(e){return X(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling RecorderService FUNCTION: clearRecording","color: green;"),this.mediaRecorder)try{this.mediaRecorder.state!=="inactive"&&this.mediaRecorder.stop(),this.mediaRecorder=null}catch(t){this.loggingService.catch("Error cleaning up mediaRecorder:",t)}if(this.recorderStatusSubject$.next(null),this.recorderDurationSubject$.next(null),this.onInitRecording$.next(null),this.recordingDurations=[],this.domService.resetRecordingInProgress(),this.firefoxFallbackRecorder){try{this.firefoxFallbackRecorder.state==="recording"&&this.firefoxFallbackRecorder.stop()}catch(t){this.loggingService.catch("Error stopping Firefox fallback recorder during cleanup: ",t)}this.firefoxFallbackRecorder=void 0}this.cleanupAudioMixing(),this.stopAllActiveInputTracks();try{this.screenStreamSubject$?.value?.getTracks()?.forEach(i=>{i?.readyState!=="ended"&&i.stop()}),this.screenStreamSubject$?.next(null)}catch{}this.recorderInitData?.stream?.getTracks()?.forEach(t=>{t.stop()}),e?.triggerEvent==="cancelled"&&this.recorderActionsService?.onRecordingCancelled(this.getRecorderDataFromInitData()),this.recorderInitData=null,this.recorderInitData$.next(null),this.chunks=[],this.chunkUrls$.next({}),this.stopTimer()}catch(t){this.loggingService.catch("Error in RecorderService clearRecording: ",t)}})}startTimer(){try{this.stopTimer(),this.durationInterval=setInterval(()=>{this.calculateRecordedTime()},1e3)}catch(e){this.loggingService.catch("Error in RecorderService startTimer: ",e)}}stopTimer(){try{this.durationInterval&&clearInterval(this.durationInterval)}catch(e){this.loggingService.catch("Error in RecorderService stopTimer: ",e)}}calculateRecordedTime(){try{if(this?.recordingDurations?.length){let e=0;this.recordingDurations.forEach(i=>{i.end?e+=i?.end-i.start:e+=new Date().getTime()-i.start});let t={};t.duration=e,t.display=this.convertMillisecondsToTime(e),this.recorderDurationSubject$.next(t),this.pipService.getIsPipActive()&&window.postMessage({type:"recording-timer-update",display:t.display},"*")}else this.recorderDurationSubject$.next(null)}catch(e){this.loggingService.catch("Error in RecorderService calculateRecordedTime: ",e)}}checkMaxLength(){try{if(!this.maxRecordingLength||!this.recordingDurations?.length)return!1;let e=0;this.recordingDurations.forEach(i=>{i.end?e+=i?.end-i.start:e+=new Date().getTime()-i.start});let t=e>=this.maxRecordingLength*1e3+500;return t&&this.loggingService.log("%c[WB] Max recording length reached. Duration: "+e+"ms, Target: "+this.maxRecordingLength+"s","color: orange;"),t}catch(e){return this.loggingService.catch("Error in RecorderService checkMaxLength: ",e),!1}}convertMillisecondsToTime(e){try{let t=Math.floor(e/1e3),i=Math.floor(t/60),a=Math.floor(i/60);return t=t%60,i=i%60,`${a.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}`}catch(t){return this.loggingService.catch("Error in RecorderService convertMillisecondsToTime: ",t),""}}getRecorderStatus$(){return this.recorderDurationSubject$.asObservable()}enableRecordingCountdown(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableRecordingCountdown","color: green;"),this.recordingCountdownEnabled$.value===!0)return;this.recordingCountdownEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableRecordingCountdown: ",e)}}disableRecordingCountdown(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableRecordingCountdown","color: green;"),this.recordingCountdownEnabled$.value===!1)return;this.recordingCountdownEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableRecordingCountdown: ",e)}}getRecordingCountdownEnabled$(){return this.recordingCountdownEnabled$.asObservable()}enableDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDarkMode","color: green;"),this.darkMode$.value===!0)return;this.darkMode$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableDarkMode: ",e)}}disableDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDarkMode","color: green;"),this.darkMode$.value===!1)return;this.darkMode$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableDarkMode: ",e)}}getDarkMode(){return this.darkMode$.value}getDarkMode$(){return this.darkMode$.asObservable()}enableShadowDom(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableShadowDom","color: green;"),this.shadowDom$.value===!0)return;this.shadowDom$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableShadowDom: ",e)}}disableShadowDom(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableShadowDom","color: green;"),this.shadowDom$.value===!1)return;this.shadowDom$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableShadowDom: ",e)}}getShadowDom(){return this.shadowDom$.value}getShadowDom$(){return this.shadowDom$.asObservable()}isSafari(){try{this.loggingService.log("%c[WB] Calling FUNCTION: isSafari","color: green;");let e=navigator.userAgent.toLowerCase();return e.includes("safari")&&!e.includes("chrome")&&!e.includes("android")}catch(e){return this.loggingService.catch("Error in RecorderService isSafari: ",e),!1}}isFirefox(){try{return new hr().getBrowserName()==="Firefox"}catch(e){return this.loggingService.catch("Error in RecorderService isFirefox: ",e),!1}}getSupportedMimeTypes(){try{return["video/mp4;codecs=h264,aac","video/mp4","audio/mp4","video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=h264,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","audio/webm;codecs=opus","audio/webm"].filter(i=>MediaRecorder.isTypeSupported(i))}catch(e){return this.loggingService.catch("Error in RecorderService getSupportedMimeTypes: ",e),[]}}enableVideoEditor(){try{if(this.videoEditor$.value===!0)return;this.videoEditor$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableVideoEditor: ",e)}}disableVideoEditor(){try{if(this.videoEditor$.value===!1)return;this.videoEditor$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableVideoEditor: ",e)}}getVideoEditor$(){return this.videoEditor$.asObservable()}getVideoEditor(){return this.videoEditor$.value}enableVideoEditorTimelinePreview(){try{if(this.videoEditorTimelinePreview$.value===!0)return;this.videoEditorTimelinePreview$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableVideoEditorTimelinePreview: ",e)}}disableVideoEditorTimelinePreview(){try{if(this.videoEditorTimelinePreview$.value===!1)return;this.videoEditorTimelinePreview$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableVideoEditorTimelinePreview: ",e)}}getVideoEditorTimelinePreview$(){return this.videoEditorTimelinePreview$.asObservable()}getVideoEditorTimelinePreview(){return this.videoEditorTimelinePreview$.value}waitForChunksUpload(){return X(this,null,function*(){try{if(this.uploadPromises.length===0)return{};let e=this.uploadPromises.map(t=>t.promise);return yield Promise.all(e),this.chunkUrls$.value}catch(e){return this.loggingService.catch("Error in RecorderService waitForChunksUpload: ",e),this.chunkUrls$.value}})}getChunkUrls$(){return this.chunkUrls$.asObservable()}getChunkUrls(){return this.chunkUrls$.value}shouldUploadFullRecording(){return this.recorderAnnotationsResolverService.shouldUploadFullRecording()}setRecorderActionsService(e){try{this.recorderActionsService=e}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setRecorderActionsService: ",t)}}enableSettingsEmbedded(){try{if(this.settingsEmbedded$.value===!0)return;this.settingsEmbedded$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableSettingsEmbedded: ",e)}}disableSettingsEmbedded(){try{if(this.settingsEmbedded$.value===!1)return;this.settingsEmbedded$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableSettingsEmbedded: ",e)}}getSettingsEmbedded$(){return this.settingsEmbedded$.asObservable()}getSettingsEmbedded(){return this.settingsEmbedded$.value}enableAutoOpenVideoEditor(){try{if(this.autoOpenVideoEditor$.value===!0)return;this.autoOpenVideoEditor$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableAutoOpenVideoEditor: ",e)}}disableAutoOpenVideoEditor(){try{if(this.autoOpenVideoEditor$.value===!1)return;this.autoOpenVideoEditor$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableAutoOpenVideoEditor: ",e)}}getAutoOpenVideoEditor$(){return this.autoOpenVideoEditor$.asObservable()}getAutoOpenVideoEditor(){return this.autoOpenVideoEditor$.value}enablePlayVideoInFullScreen(){try{if(this.playVideoInFullScreen$.value===!0)return;this.playVideoInFullScreen$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enablePlayVideoInFullScreen: ",e)}}disablePlayVideoInFullScreen(){try{if(this.playVideoInFullScreen$.value===!1)return;this.playVideoInFullScreen$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disablePlayVideoInFullScreen: ",e)}}getPlayVideoInFullScreen$(){return this.playVideoInFullScreen$.asObservable()}getPlayVideoInFullScreen(){return this.playVideoInFullScreen$.value}setRecordingQualityConstraints(e){try{let t=this.recordingQualityConstraints.value;t={other:{audio:h(h({},t.other?.audio),e.other?.audio),video:h(h({},t.other?.video),e.other?.video)},safari:{audio:h(h({},t.safari?.audio),e.safari?.audio),video:h(h({},t.safari?.video),e.safari?.video)}},this.recordingQualityConstraints.next(t)}catch(t){this.loggingService.catch("Error in RecorderService setRecordingQualityConstraints: ",t)}}setRecordingEncodingOptions(e){try{let t=this.recordingEncodingOptions.value;t={other:h(h({},t.other),e.other),safari:h(h({},t.safari),e.safari)},this.recordingEncodingOptions.next(t)}catch(t){this.loggingService.catch("Error in RecorderService setRecordingEncodingOptions: ",t)}}getVideoDuration(e){return X(this,null,function*(){return new Promise((t,i)=>{try{let a=URL.createObjectURL(e),l=document.createElement("video"),c=navigator.userAgent.includes("Firefox");c&&(l.preload="auto"),l.onloadedmetadata=()=>{let d=l.duration;c&&d>0&&d<10&&e.size>1e6?setTimeout(()=>{let m=l.duration;URL.revokeObjectURL(a),t(m)},1e3):(URL.revokeObjectURL(a),t(d))},l.onerror=d=>{URL.revokeObjectURL(a),i(d)},l.src=a,l.load()}catch(a){this.loggingService.catch("Error in RecorderService getVideoDuration: ",a),i(a)}})})}enableRecordingMic(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableRecordingMic","color: green;"),this.recordingMicEnabled$.value===!0)return;this.recordingMicEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableRecordingMic: ",e)}}disableRecordingMic(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableRecordingMic","color: green;"),this.recordingMicEnabled$.value===!1)return;this.recordingMicEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableRecordingMic: ",e)}}getRecordingMicEnabled$(){return this.recordingMicEnabled$.asObservable()}getRecordingMicEnabled(){return this.recordingMicEnabled$.value}setOnboardingTooltip(e){try{if(this.onboardingTooltip$.value===e)return;this.onboardingTooltip$.next(e)}catch(t){this.loggingService.catch("Error in RecorderService setOnboardingTooltip: ",t)}}enableOnboardingTooltip(){try{if(this.onboardingTooltip$.value===!0)return;this.onboardingTooltip$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableOnboardingTooltip: ",e)}}disableOnboardingTooltip(){try{if(this.onboardingTooltip$.value===!1)return;this.onboardingTooltip$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableOnboardingTooltip: ",e)}}getOnboardingTooltip$(){return this.onboardingTooltip$.asObservable()}getOnboardingTooltip(){return this.onboardingTooltip$.value}enableRetakeOnVideoEditor(){try{if(this.retakeOnVideoEditor$.value===!0)return;this.retakeOnVideoEditor$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enableRetakeOnVideoEditor: ",e)}}disableRetakeOnVideoEditor(){try{if(this.retakeOnVideoEditor$.value===!1)return;this.retakeOnVideoEditor$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disableRetakeOnVideoEditor: ",e)}}getRetakeOnVideoEditor$(){return this.retakeOnVideoEditor$.asObservable()}getRetakeOnVideoEditor(){return this.retakeOnVideoEditor$.value}getRecorderStream(){return this.recorderInitData?.stream}getScreenStream$(){return this.screenStreamSubject$.asObservable()}requestScreenPermission(){return X(this,null,function*(){try{if(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)throw new Error("Screen sharing is not supported in this browser");let e=yield navigator.mediaDevices.getDisplayMedia({video:!0,audio:!0});if(!e.getVideoTracks()[0])throw new Error("No video track available in screen share stream");return e.getTracks().forEach(i=>{i.onended=()=>{this.screenStreamSubject$.next(null),this.clearRecording()}}),this.screenStreamSubject$.next(e),e}catch(e){return e.name==="NotAllowedError"||e.name==="PermissionDeniedError"?this.loggingService.catch("Screen sharing permission denied by user"):e.name==="NotFoundError"?this.loggingService.catch("No screen sharing device found"):e.name==="NotReadableError"||e.name==="OverconstrainedError"?this.loggingService.catch("Could not access screen sharing device"):this.loggingService.catch("Error in RecorderService requestScreenPermission: ",e),null}})}setMaxRecordingLength(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setMaxRecordingLength","color: green;"),this.maxRecordingLength=e}catch(t){this.loggingService.catch("Error in RecorderService setMaxRecordingLength: ",t)}}getMaxRecordingLength(){return this.maxRecordingLength}attemptFirefoxCanvasRecording(e){return X(this,null,function*(){try{let t=document.createElement("video");t.srcObject=e,t.muted=!0,t.autoplay=!0;let i=document.createElement("canvas"),a=i.getContext("2d");yield new Promise(m=>{t.onloadedmetadata=m}),i.width=t.videoWidth||1280,i.height=t.videoHeight||720;let l=i.captureStream(30);this.firefoxFallbackRecorder=new MediaRecorder(l,{mimeType:"video/webm;codecs=vp8",videoBitsPerSecond:this.recordingEncodingOptions.value.other?.videoBitsPerSecond||1e6});let c=[];this.firefoxFallbackRecorder.addEventListener("dataavailable",m=>{m.data.size>0&&c.push(m.data)}),this.firefoxFallbackRecorder.addEventListener("stop",()=>{if(c.length>0){let m=new Blob(c,{type:"video/webm"});this.chunks=c;let u=new y3;u.blob=m,u.url=URL.createObjectURL(m),u.type=this.recorderInitData?.type,u.recordedTime=this.recorderDurationSubject$.value,this.recordedRawData$.next(u)}this.firefoxFallbackRecorder=void 0});let d=()=>{t.readyState>=2&&a&&a.drawImage(t,0,0,i.width,i.height),t.srcObject&&this.firefoxFallbackRecorder?.state==="recording"&&requestAnimationFrame(d)};this.firefoxFallbackRecorder.start(1e3),d()}catch(t){this.loggingService.catch("Error in RecorderService attemptFirefoxCanvasRecording: ",t)}})}getRecorderDataFromInitData(){return{type:this.recorderInitData?.type}}askDevicePermission(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: askDevicePermission","color: green;"),navigator.mediaDevices.getUserMedia({audio:e.audio??!1,video:e.video??!1}).then(t=>{t.getTracks().forEach(i=>{i.stop()})}).catch(t=>{this.loggingService.catch("Error in RecorderService askDevicePermission: ",t)})}catch(t){this.loggingService.catch("Error in RecorderService askDevicePermission: ",t)}}openPictureInPicture(){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: openPictureInPicture","color: green;");let e=this.getRecorderStream();if(!e)return;yield this.pipService.openPictureInPicture(e,()=>this.stopRecording())}catch(e){this.loggingService.catch("Error in RecorderService openPictureInPicture: ",e)}})}enablePlaybackOnPreviewClick(){try{if(this.playbackOnPreviewClick$.value===!0)return;this.playbackOnPreviewClick$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderService enablePlaybackOnPreviewClick: ",e)}}disablePlaybackOnPreviewClick(){try{if(this.playbackOnPreviewClick$.value===!1)return;this.playbackOnPreviewClick$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderService disablePlaybackOnPreviewClick: ",e)}}getPlaybackOnPreviewClick$(){return this.playbackOnPreviewClick$.asObservable()}getPlaybackOnPreviewClick(){return this.playbackOnPreviewClick$.value}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(k),K(Lo),K(Pp),K(st),K($n),K(Ve),K(es),K(oc),K(il))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();function qWe(n,o,r,e){try{return{audio:o,video:n?h(h({deviceId:e?.video?.deviceId?{exact:e.video.deviceId}:void 0},r),e?.video?.deviceId?{}:{facingMode:"user"}):!1}}catch{return{}}}function YWe(n,o={}){try{return h({deviceId:n?.audio?.deviceId?{exact:n.audio.deviceId}:void 0},o)}catch{return{}}}var Ol=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_){this.afAuth=e,this.authService=t,this.configService=i,this.databaseService=a,this.docService=l,this.commonDbService=c,this.iamService=d,this.loggingService=m,this.notificationService=u,this.userPermissionService=_,this.documentPaths=null,this.views$=new _e({}),this.commentViews$=new _e({}),this.documentViews$=new _e({}),this.locationViews$=new _e({}),this.commentViewsByOrganizationIdAndDocumentId$=new _e({}),this.documentViewsByOrganizationIdAndDocumentId$=new _e({}),this.locationViewsByOrganizationIdAndLocationId$=new _e({}),this.documentViewsEnabled$=new _e(!1),this.documentViewsSetByDocumentId={},this.loggingService.log("%c[WB] Creating CLASS: ViewsService","color: blue;");try{this.authService.setViewsService(this),this.databaseService.getDb().pipe(Ge(I=>!!I),ut(1)).subscribe(I=>{I&&(this.subscribeViewsData().subscribe(),this.getNotificationFeatureViews$().subscribe(A=>{this.notificationService.setNotificationViews(A)}),this.authService.getUser$().pipe(Ge(A=>!!A),Se(A=>this.documentViewsEnabled$.pipe(Ge(M=>M),ue(()=>A))),Se(A=>this.docService.getDocumentPaths$().pipe(_o(null),Fr(),ue(([M,V])=>(M?.documentId!==V?.documentId&&this.views$.next({}),V)),ue(M=>(this.documentPaths=M,this.setDocumentAsRead({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),{_user:A,_documentPaths:M})),Se(M=>this.docService.getDocumentIds$().pipe(Se(V=>(V?.length&&(V.find(q=>q.documentId===this.documentPaths?.documentId)||V.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),V.forEach(q=>{this.setDocumentAsRead({documentId:q.documentId,clientDocumentId:q.clientDocumentId})})),ce(M))))))),Se(A=>this.docService.getDocumentMetadata$().pipe(Ge(M=>!!M),ue(M=>y(h({},A),{_documentMetadata:M}))))).subscribe(),this.authService.getUser$().pipe(Ge(A=>!!A),Se(A=>this.documentViewsEnabled$.pipe(Ge(M=>M),ue(()=>A))),Se(A=>this.docService.getLocation$().pipe(Ge(M=>!!M))),Se(A=>this.docService.getDocumentIds$().pipe(Se(M=>(M.find(V=>V.documentId===this.documentPaths?.documentId)||M.push({documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId??""}),M.forEach(V=>{this.setLocationAsRead({documentId:V.documentId,clientDocumentId:V.clientDocumentId})}),ce(A)))))).subscribe())},I=>{this.loggingService.catch("Error in ViewsService getDb subscription: ",I)})}catch(I){this.loggingService.catch("Error in ViewsService constructor: ",I)}}setCommentService(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;"),this.commentService=e}catch(t){this.loggingService.catch("Error in ViewsService setCommentService: ",t)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in ViewsService","color: green;");try{this.documentPaths=null,this.documentViews$.next({}),this.views$.next({}),this.commentViews$.next({}),this.locationViews$.next({}),this.commentViewsByOrganizationIdAndDocumentId$.next({}),this.documentViewsByOrganizationIdAndDocumentId$.next({}),this.locationViewsByOrganizationIdAndLocationId$.next({})}catch(e){this.loggingService.catch("Error in ViewsService clearCache: ",e)}}subscribeViewsData(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let i,a;try{if(e&&(a=er(e)),t&&typeof t=="object"){let l=Oi(t);i=er(JSON.stringify(l))}}catch(l){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",l)}return _r(this.afAuth).pipe(Ge(l=>!!l),Se(l=>this.isFeatureAllowed({firebaseUser:l})),Se(l=>l.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(c=>(l.featureAllowed=c,l))):ce(l)),Se(l=>l.featureAllowed?ce(l).pipe(Se(c=>this.docService.getDocumentPaths$().pipe(ue(d=>(this.documentPaths=d,c.documentPaths=d,c)))),Se(c=>a?this.getDataFromDocumentIds([a]):this.docService.getDocumentIds$().pipe(Se(d=>{let m=d?.length>0?d.map(u=>u.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(m)})))):ce([])))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})),Se(t=>this.authService.getUser$().pipe(ue(i=>y(h({},t),{user:i})))),Se(t=>t.user?ce(y(h({},t),{featureAllowed:!0})):ce(y(h({},t),{featureAllowed:!1}))),_t((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getCommentViewsById(e){try{return this.commentViews$.value?.[e]?this.commentViews$.value?.[e]:void 0}catch(t){this.loggingService.catch("Error in ViewsService getCommentViewsById: ",t);return}}getDocumentViewsById(e){try{return this.documentViews$.value?.[e]}catch(t){this.loggingService.catch("Error in ViewsService getDocumentViewsById: ",t);return}}getLocationViewsById(e){try{return this.locationViews$.value?.[e]}catch(t){this.loggingService.catch("Error in ViewsService getLocationViewsById: ",t);return}}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t,filters:i}=e;return t?.some(a=>!a)||!this.documentPaths?ce([]):this.documentViewsEnabled$.pipe(Se(a=>a?gn([this.getCommentViewsDataFromDocuments(),this.getDocumentViewsDataFromDocuments(t),this.getLocationViewsDataFromDocuments(t)]):gn([this.getCommentViewsDataFromDocuments()])))}else return ce(null)}getCommentViews(e){try{let t={};Object.entries(e??{}).forEach(([i,a])=>{let l=a.metadata?.documentId,c=a.views;!l||!c||(t[l]||(t[l]={}),t[l][a.annotationId]=c)}),Object.entries(t??{}).forEach(([i,a])=>{this.setCommentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:i,commentViews:a})})}catch(t){this.loggingService.catch("Error in ViewsService getCommentViews: ",t)}}getCommentViewsDataFromDocuments(){try{return this.commentService?this.commentService?.getAllCommentAnnotations({detectGhostComments:!0,addFilterCommentsOnDomCheck:!0,fromCommentSidebar:!0,skipPositionCalculation:!0,analytics:{enabled:!0,properties:{source:"internal",sourceId:"commentsContainer"}}}).pipe(Ge(e=>!!e),ln(e=>{this.getCommentViews(e)})):ce([])}catch(e){return this.loggingService.catch("Error in ViewsService getCommentViewsDataFromDocuments: ",e),ce([])}}getDocumentViewsDataFromDocuments(e){let t=this.docService.getDocumentPaths()?.veltFolderId,i=ce([]),a={useCollectionGroup:!0,isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(a.documentId=e?.length?e[0]:void 0,a.organizationId=this.documentPaths?.organizationId);let l=[];for(let c=0;c<(e?.length??0);c+=N.LISTENER_BATCH_SIZE)l.push(e?.slice(c,c+N.LISTENER_BATCH_SIZE)??[]);return i=gn(l.map(c=>this.commonDbService.dbListener({feature:"allDocumentViews",properties:y(h({},a),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",c),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[ft("metadata.veltFolderId","==",t)]:[])]})}).pipe(la()))).pipe(ue(c=>Na(c))),i.pipe(ue(c=>({data:c?.data,operation:c?.operation})),ue(({data:c,operation:d})=>{let m={};return e?(Object.entries(c??{}).forEach(([u,_])=>{let I=_.metadata?.documentId;I&&(m[I]||(m[I]={}),m[I][u]=_)}),{data:c,documentMap:m,operation:d}):{data:c,documentMap:m,operation:d}}),ue(({data:c,documentMap:d,operation:m})=>{if(m?.type==="removed"){if(m?.ids?.length){let u=this.documentViews$.value;m?.ids?.forEach(_=>{delete u?.[_]}),this.documentViews$.next(u)}}else Object.entries(d??{}).forEach(([u,_])=>{this.setDocumentViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:u,documentViews:_})})}))}getLocationViewsDataFromDocuments(e){let t=this.docService.getDocumentPaths()?.veltFolderId,i=ce([]),a={useCollectionGroup:!0,isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(a.documentId=e?.length?e[0]:void 0,a.organizationId=this.documentPaths?.organizationId);let l=[];for(let c=0;c<(e?.length??0);c+=N.LISTENER_BATCH_SIZE)l.push(e?.slice(c,c+N.LISTENER_BATCH_SIZE)??[]);return i=gn(l.map(c=>this.commonDbService.dbListener({feature:"allLocationViews",properties:y(h({},a),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",c),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...t?[ft("metadata.veltFolderId","==",t)]:[])]})}).pipe(la()))).pipe(ue(c=>Na(c))),i.pipe(ue(c=>({data:c?.data,operation:c?.operation})),ue(({data:c,operation:d})=>{let m={};return e?(Object.entries(c??{}).forEach(([u,_])=>{let I=_.metadata?.documentId;I&&(m[I]||(m[I]={}),m[I][u]=_)}),{data:c,documentMap:m,operation:d}):{data:c,documentMap:m,operation:d}}),ue(({data:c,documentMap:d,operation:m})=>{if(m?.type==="removed"){if(m?.ids?.length){let u=this.locationViews$.value;m?.ids?.forEach(_=>{delete u?.[_]}),this.locationViews$.next(u)}}else Object.entries(d??{}).forEach(([u,_])=>{this.setLocationViewsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:u,locationViews:_})})}))}setViewsData(e){try{this.views$.next(h(h({},this.views$.getValue()),e||{}))}catch(t){this.loggingService.catch("Error in ViewsService setViewsData:",t)}}setCommentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,commentViews:i,queryHash:a}){try{if(i||(i={}),t){e||(e=N.NO_ORGANIZATION_ID),a||(a=N.DEFAULT_QUERY_HASH);let l=h(h({},this.commentViews$.value),i);this.commentViews$.next(l),this.commentViewsByOrganizationIdAndDocumentId$.next(y(h({},this.commentViewsByOrganizationIdAndDocumentId$.value),{[e]:y(h({},this.commentViewsByOrganizationIdAndDocumentId$.value[e]),{[t]:y(h({},this.commentViewsByOrganizationIdAndDocumentId$.value[e]?.[t]),{[a]:i})})}))}}catch(l){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",l)}}setDocumentViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,documentViews:i,queryHash:a}){try{if(i||(i={}),t){e||(e=N.NO_ORGANIZATION_ID),a||(a=N.DEFAULT_QUERY_HASH);let l=h(h({},this.documentViews$.value),i);this.documentViews$.next(l),this.documentViewsByOrganizationIdAndDocumentId$.next(y(h({},this.documentViewsByOrganizationIdAndDocumentId$.value),{[e]:y(h({},this.documentViewsByOrganizationIdAndDocumentId$.value[e]),{[t]:y(h({},this.documentViewsByOrganizationIdAndDocumentId$.value[e]?.[t]),{[a]:i})})}))}}catch(l){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",l)}}setLocationViewsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,locationViews:i,queryHash:a}){try{if(i||(i={}),t){e||(e=N.NO_ORGANIZATION_ID),a||(a=N.DEFAULT_QUERY_HASH);let l=h(h({},this.locationViews$.value),i);this.locationViews$.next(l),this.locationViewsByOrganizationIdAndLocationId$.next(y(h({},this.locationViewsByOrganizationIdAndLocationId$.value),{[e]:y(h({},this.locationViewsByOrganizationIdAndLocationId$.value[e]),{[t]:y(h({},this.locationViewsByOrganizationIdAndLocationId$.value[e]?.[t]),{[a]:i})})}))}}catch(l){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",l)}}getCommentFeatureViews$(){return this.commentViews$.pipe(_t((e,t)=>JSON.stringify(e||{})===JSON.stringify(t||{})))}setCommentAnnotationAsRead(e){return X(this,null,function*(){try{if(this.authService.getUser()&&e?.annotationId){if(e.annotationId.startsWith("TEMP_COMPOSER_"))return;this.updateCommentAnnotationViews(e);let i=e?.metadata?.organizationId??this.documentPaths?.organizationId??"",a=e?.metadata?.documentId??this.documentPaths?.documentId??"";if(e?.isDraft)return;yield this.commonDbService.setData({feature:"comment",properties:{id:e.annotationId,documentId:a,organizationId:i,metadata:{apiKey:this.configService.getApiKey(),organizationId:i,veltFolderId:e?.metadata?.veltFolderId,documentId:a}},data:JSON.parse(JSON.stringify(e))})}}catch(t){this.loggingService.catch("Error in ViewsService setCommentAnnotationAsRead:",t)}})}setCommentAnnotationAsUnread(e){return X(this,null,function*(){try{if(this.authService.getUser()&&e?.annotationId){if(e.annotationId.startsWith("TEMP_COMPOSER_"))return;this.removeCommentAnnotationViews(e);let i=e?.metadata?.organizationId??this.documentPaths?.organizationId??"",a=e?.metadata?.documentId??this.documentPaths?.documentId??"";if(e?.isDraft)return;yield this.commonDbService.setData({feature:"comment",properties:{id:e.annotationId,documentId:a,organizationId:i,metadata:{apiKey:this.configService.getApiKey(),organizationId:i,veltFolderId:e?.metadata?.veltFolderId,documentId:a}},data:JSON.parse(JSON.stringify(e))})}}catch(t){this.loggingService.catch("Error in ViewsService setCommentAnnotationAsRead:",t)}})}updateCommentAnnotationViews(e){try{let t=this.authService.getUser(),i={views:{},comments:{}};if(t){let a={},l=e?.views?.comments||{},c=new Date().getTime()+this.commonDbService.getOffset();e.comments?.forEach(m=>{l[m.commentId]||(l[m.commentId]={views:{}}),l[m.commentId].views||(l[m.commentId].views={}),l[m.commentId].views[t.userSnippylyId]||(l[m.commentId].views[t.userSnippylyId]={timestamp:c})});let d=new Set(e.comments?.map(m=>m.commentId+""));if(Object.keys(l??{}).forEach(m=>{d.has(m)||delete l[m]}),e.comments?.length){let m=l[e.comments[0].commentId]?.views||{},u=Object.keys(m??{}).filter(_=>e.comments?.every(I=>l[I.commentId]?.views?.[_]));u.forEach(_=>{a[_]={timestamp:m[_].timestamp}}),e.viewedByUserIds=u}i.views=a,i.comments=l,e.views=i}return i}catch(t){return this.loggingService.catch("Error in ViewsService updateCommentAnnotationViews:",t),{views:{},comments:{}}}}removeCommentAnnotationViews(e){try{let t=this.authService.getUser(),i={views:{},comments:{}};if(t){let a={},l=e?.views?.comments||{};e.comments?.forEach(d=>{l[d.commentId]?.views?.[t.userSnippylyId]&&delete l[d.commentId].views[t.userSnippylyId]});let c=new Set(e.comments?.map(d=>d.commentId+""));if(Object.keys(l??{}).forEach(d=>{c.has(d)||delete l[d]}),e.comments?.length){let d=l[e.comments[0].commentId]?.views||{},m=Object.keys(d??{}).filter(u=>e.comments?.every(_=>l[_.commentId]?.views?.[u]));m.forEach(u=>{a[u]={timestamp:d[u].timestamp}}),e.viewedByUserIds=m}else e.viewedByUserIds=[];i.views=a,i.comments=l,e.views=i}return i}catch(t){return this.loggingService.catch("Error in ViewsService removeCommentAnnotationViews:",t),{views:{},comments:{}}}}getNotificationFeatureViews$(){return this.views$.pipe(_t((e,t)=>JSON.stringify(e?.notification||{})===JSON.stringify(t?.notification||{})))}setNotificationsAsRead(e){try{let t=this.authService.getUser();if(t){let i=new Date().getTime()+this.commonDbService.getOffset();e.forEach(a=>{this.commonDbService.updateData({feature:"notificationViewsTimestamp",properties:{id:a,user:t.userSnippylyId,documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??""},data:{timestamp:i}})})}}catch(t){this.loggingService.catch("Error in ViewsService setNotificationAsRead:",t)}}getDocumentViews$(){return this.views$.pipe(_t((e,t)=>JSON.stringify(e?.documentViews||{})===JSON.stringify(t?.documentViews||{})))}getUniqueViewsByUser(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(Se(t=>(this.documentPaths=t,e?this.locationViews$.pipe(ue(i=>{let a=Object.keys(i||{}).find(l=>i?.[l]?.location?.id===e);return a?i?.[a]?.users||{}:{}})):this.documentViews$.pipe(ue(i=>{let a=this.documentPaths?.documentId;return a?i?.[a]?.users||{}:{}})))),_t(Kt))}catch(t){return this.loggingService.catch("Error in ViewsService getUniqueViewsByUser:",t),ce({})}}getUniqueViewsByDate(e){try{return this.enableDocumentViews(),this.docService.getDocumentPaths$().pipe(Se(t=>(this.documentPaths=t,e?this.locationViews$.pipe(ue(i=>{let a=Object.keys(i||{}).find(l=>i?.[l]?.location?.id===e);return a?i?.[a]?.day||{}:{}})):this.documentViews$.pipe(ue(i=>{let a=this.documentPaths?.documentId;return a?i?.[a]?.day||{}:{}})))))}catch(t){return this.loggingService.catch("Error in ViewsService getUniqueViewsByDate:",t),ce({})}}enableDocumentViews(){try{if(this.documentViewsEnabled$.value===!0)return;this.documentViewsEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in ViewsService enableDocumentViews:",e)}}disableDocumentViews(){try{if(this.documentViewsEnabled$.value===!1)return;this.documentViewsEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in ViewsService disableDocumentViews:",e)}}setDocumentAsRead(i){return X(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let a=this.authService.getUser();if(a&&e&&this.userPermissionService?.hasEditAccess({documentId:e??"",folderId:this.documentPaths?.allDocuments&&this.documentPaths?.veltFolderId?this.documentPaths?.veltFolderId:void 0})){if(this.documentViewsSetByDocumentId[e])return;this.documentViewsSetByDocumentId[e]=!0;let l=new Date().getTime()+this.commonDbService.getOffset(),c=new Date().toISOString().split("T")[0],d=this.getDocumentViewsById(e);if(d){let m=new Date().toISOString().split("T")[0];d?.users[a.userSnippylyId]||(d.users[a.userSnippylyId]={}),d.users[a.userSnippylyId][m]={timestamp:this.timestamp},d?.day[m]||(d.day[m]={}),d.day[m][a.userSnippylyId]={timestamp:this.timestamp},d.metadata=this.docService.getBaseMetadata("documentViews",{clientDocumentId:t}),this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:m,user:a.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??""},data:d})}else this.commonDbService.updateData({feature:"documentDayViews",properties:{id:e,date:c,user:a.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:l}}),this.commonDbService.updateData({feature:"documentUsersViews",properties:{id:e,user:a.userSnippylyId,date:c,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:l}}),this.commonDbService.updateData({feature:"documentMetadataViews",properties:{id:e,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:this.docService.getBaseMetadata("documentViews",{clientDocumentId:t})}),this.docService.getDocumentMetadata$(e).pipe(Ge(m=>m!==null),ut(1)).subscribe(()=>{let m={day:{[c]:{[a.userSnippylyId]:{timestamp:l}}},users:{[a.userSnippylyId]:{[c]:{timestamp:l}}},metadata:this.docService.getBaseMetadata("documentViews",{clientDocumentId:t})};this.commonDbService.updateData({feature:"documentViews",properties:{id:e,date:c,user:a.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipRtdb:!0},data:m})});this.checkAndTriggerNotification(a)}}catch(a){this.loggingService.catch("Error in ViewsService setDocumentAsRead:",a)}})}checkAndTriggerNotification(e){try{this.getUniqueViewsByUser().pipe(ut(1)).subscribe(t=>{if(Object.keys(t??{}).length===2){let i=this.docService.getDocumentMetadata();if(i?.creator?.email&&i?.creator?.email!==e.email){let a=[i.creator.email];this.updateNotificationsDatabase(VK.FIRST_VIEWED,{documentViews:{emails:a}})}}})}catch(t){this.loggingService.catch("Error in checkAndTriggerNotification:",t)}}setLocationAsRead(i){return X(this,arguments,function*({documentId:e,clientDocumentId:t}){try{let a=this.authService.getUser(),l=this.docService.getLocation(),c=l?.locationId,d=l?.location;if(a&&c&&d){let m=new Date().getTime()+this.commonDbService.getOffset(),u=new Date().toISOString().split("T")[0],_=this.getLocationViewsById(c);if(_){let I=new Date().toISOString().split("T")[0];_?.users[a.userSnippylyId]||(_.users[a.userSnippylyId]={}),_.users[a.userSnippylyId][I]={timestamp:this.timestamp},_?.day[I]||(_.day[I]={}),_.day[I][a.userSnippylyId]={timestamp:this.timestamp},_.metadata=this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),this.commonDbService.updateData({feature:"location",data:_,properties:{id:c,documentId:e,organizationId:this.documentPaths?.organizationId??""}})}else{this.commonDbService.updateData({feature:"locationViews",data:d,properties:{id:c,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0}}),this.commonDbService.updateData({feature:"locationUsersViews",properties:{id:c,user:a.userSnippylyId,date:u,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:m}}),this.commonDbService.updateData({feature:"locationDayViews",properties:{id:c,date:u,user:a.userSnippylyId,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:{timestamp:m}}),this.commonDbService.updateData({feature:"locationMetadataViews",properties:{id:c,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0},data:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t})});let I={day:{[u]:{[a.userSnippylyId]:{timestamp:m}}},users:{[a.userSnippylyId]:{[u]:{timestamp:m}}},metadata:this.docService.getBaseMetadata("locationViews",{clientDocumentId:t}),location:d};this.commonDbService.updateData({feature:"location",data:I,properties:{id:c,documentId:e,organizationId:this.documentPaths?.organizationId??"",skipRtdb:!0}})}}}catch(a){this.loggingService.catch("Error in ViewsService setLocationAsRead:",a)}})}updateNotificationsDatabase(e,t={}){try{let i=h({actionType:e,notificationSource:"documentViews"},t);this.notificationService.updateNotificationDatabase(i)}catch(i){this.loggingService.catch("Error in CommentService updateNotificationsDatabase: ",i)}}get timestamp(){return this.commonDbService.getServerTimestamp()}};o.\u0275fac=function(t){return new(t||o)(K(eo),K(qe),K(Ft),K($n),K(st),K(yn),K(Vn),K(k),K(mn),K(Ia))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ts=(()=>{let o=class o{constructor(e,t,i,a){this.docService=e,this.loggingService=t,this.authService=i,this.configService=a;try{this.loggingService.log("%c[WB] Creating CLASS: MetadataService","color: blue;")}catch(l){this.loggingService.catch("Error in MetadataService constructor: ",l)}}getGlobalMetadata(){return X(this,null,function*(){try{let e=this.authService.getUser();if(!e)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),{};let t=this.docService.getOrganizationMetadata(e?.organizationId),i=this.docService.getDocumentMetadataOfAvailableDocuments(),a=this.docService.getLocation();t&&(t=JSON.parse(JSON.stringify(t)),delete t?.organizationId,t.organizationId=t?.clientOrganizationId,delete t?.clientOrganizationId,delete t?.pageInfo),i&&(i=JSON.parse(JSON.stringify(i)),i.forEach(u=>{delete u?.locations,delete u?.location,delete u?.locationId,delete u?.pageInfo,delete u?.documentId,u.documentId=u?.clientDocumentId,delete u?.clientDocumentId,delete u?.veltFolderId,u?.clientOrganizationId&&(u.organizationId=u?.clientOrganizationId,delete u?.clientOrganizationId)}));let l=[];a&&(a=JSON.parse(JSON.stringify(a)),a?.location&&l.push(a?.location));let c=this.docService.getLocations();c&&Object.values(c).forEach(u=>{u?.location&&l.push(u?.location)});let d=this.docService.getDocumentPaths()?.folderId;return{organization:t,documents:i,locations:l,folderId:d}}catch(e){return this.loggingService.catch("Error in MetadataService getGlobalMetadata: ",e),{}}})}getDebugInfo(){return X(this,null,function*(){try{let e=this.authService.getUser();if(!e)return null;let t,i;e&&(t=Vo(e)??void 0,i=JSON.parse(JSON.stringify(e)),delete i?.contacts);let a=this.configService.getApiKey(),l=window?.Velt?.version,c=this.docService.getOrganizationMetadata(e?.organizationId),d,m;c&&(d=JSON.parse(JSON.stringify(c)),delete d?.organizationId,d.organizationId=d?.clientOrganizationId,delete d?.clientOrganizationId,delete d?.pageInfo,delete d?.apiKey,m=JSON.parse(JSON.stringify(c)),delete m?.clientOrganizationId,delete m?.pageInfo,delete m?.apiKey);let u=this.docService.getDocumentMetadataOfAvailableDocuments(),_=this.docService.getLocation(),I=[],A=[];_&&(I.push(_),_?.location&&A.push(_?.location));let M=this.docService.getLocations();M&&Object.values(M).forEach(he=>{I.push(he),he?.location&&A.push(he?.location)});let V=[],q=[];u&&(V=JSON.parse(JSON.stringify(u)),V.forEach(he=>{delete he?.apiKey,delete he?.locations,delete he?.location,delete he?.locationId,delete he?.pageInfo,delete he?.documentId,he.documentId=he?.clientDocumentId,delete he?.clientDocumentId,delete he?.veltFolderId,he?.clientOrganizationId&&(he.organizationId=he?.clientOrganizationId,delete he?.clientOrganizationId)}),q=JSON.parse(JSON.stringify(u)),q.forEach(he=>{delete he?.apiKey,delete he?.locations,delete he?.location,delete he?.locationId,delete he?.pageInfo,delete he?.clientDocumentId,he.folderId=he?.veltFolderId,delete he?.veltFolderId,delete he?.clientOrganizationId}));let ae,ye=this.docService.getDocumentPaths();ye?.folderId&&ye?.veltFolderId&&(ae={folderId:ye?.folderId,veltFolderId:ye?.veltFolderId});let ie,ge;ae&&(ie=JSON.parse(JSON.stringify(ae)),delete ie?.veltFolderId,ge=JSON.parse(JSON.stringify(ae)),ge.folderId=ge.veltFolderId,delete ge?.veltFolderId);let Ie={};return Ie.veltVersion=l,Ie.apiKey=a,Ie.serverMap={organization:m??void 0,documents:q,locations:I??void 0,folder:ge??void 0,user:i??void 0,accessFields:this.docService.getProcessedDocContext()??void 0},Ie.clientMap={organization:d??void 0,documents:V,locations:A??void 0,folder:ie??void 0,user:t??void 0,context:this.docService.getDocContext()??void 0},Ie}catch(e){return this.loggingService.catch("Error in MetadataService getDebugInfo: ",e),null}})}getDebugInfo$(){return gn([this.authService.getUser$(),this.docService.getOrganizationConfig$(),this.docService.getOrganizationMetadataMap$(),this.docService.getAllDocumentMetadataMap$(),this.docService.getDocContext$()]).pipe(Se(()=>X(this,null,function*(){return yield this.getDebugInfo()})),_t(Kt))}};o.\u0275fac=function(t){return new(t||o)(K(st),K(k),K(qe),K(Ft))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var CS=(()=>{let o=class o{constructor(e,t,i){this.coreActionsService=e,this.loggingService=t,this.metadataService=i,this.buttonClickSubject$=new at,this.buttonToggleMap$=new _e({}),this.contextDataMapping={commentAnnotation:{source:["componentConfigSignal","data","annotation"],target:"commentAnnotation"},unreadCommentsMap:{source:["componentConfigSignal","unreadCommentsMap"],target:"unreadCommentAnnotationsMap"},comment:{source:["commentObj"],target:"comment"},index:{source:["i"],target:"index"},allAnnotations:{source:["componentConfigSignal","annotations"],target:"commentAnnotations"},systemFilteredAnnotations:{source:["componentConfigSignal","filteredCommentPinAnnotations"],target:"systemFilteredAnnotations"},notification:{source:["notification"],target:"notification"},allNotifications:{source:["componentConfigSignal","notificationsInSession"],target:"notifications"}}}buttonClick(c){return X(this,arguments,function*({id:e,type:t,groupId:i,contextData:a,data:l}){try{this.buttonToggle(e,void 0,t,i);let m=this.extractButtonData(a),u=this.createButtonContext(e,t,i),_=yield this.metadataService.getGlobalMetadata(),I={};if(l){let d=l,{componentConfigSignal:M}=d,V=Uh(d,["componentConfigSignal"]);if(I=h({},V),M&&typeof M=="function")try{let q=M();q&&typeof q=="object"&&(I=h(h({},I),q))}catch(q){this.loggingService.catch("Error accessing componentConfigSignal: ",q)}}let A=y(h({buttonContext:u},m),{metadata:_,data:I});this.buttonClickSubject$.next(A),this.coreActionsService.triggerAction(tt.VELT_BUTTON_CLICK,A)}catch(m){this.loggingService.catch("Error in ButtonService buttonClick: ",m)}})}buttonActive({id:e,type:t,groupId:i,contextData:a}){try{let l=this.buttonToggleMap$.value?.[i||"ungrouped"]?.[e]||!0;this.buttonToggle(e,l,t,i)}catch(l){this.loggingService.catch("Error in ButtonService buttonClick: ",l)}}buttonToggle(e,t,i,a){try{let l=this.buttonToggleMap$.value,c=this.createNewToggleMap(l,e,t,i,a);this.buttonToggleMap$.next(c)}catch(l){this.loggingService.catch("Error in ButtonService buttonToggle: ",l)}}extractButtonData(e){try{let t={};return Object.entries(this.contextDataMapping).forEach(([i,a])=>{let l=this.getNestedValue(e,a.source);l!==void 0&&(t[a.target]=l)}),t}catch(t){return this.loggingService.catch("Error in ButtonService extractContextData: ",t),{}}}getNestedValue(e,t){try{let i=e;for(let a of t){if(i?.[a]===void 0)return;vo(i[a])?i=i[a]():i=i[a]}return i}catch(i){this.loggingService.catch("Error in ButtonService getNestedValue: ",i);return}}createButtonContext(e,t,i){try{let a={type:t,selections:this.buttonToggleMap$.value,clickedButtonId:e};return(t==="single-select"||t==="multi-select")&&i?y(h({},a),{groupId:i}):a}catch(a){return this.loggingService.catch("Error in ButtonService createButtonMetadata: ",a),{}}}createNewToggleMap(e,t,i,a,l){try{let c=h({},e);return a==="button-toggle"?y(h({},c),{ungrouped:y(h({},c.ungrouped),{[t]:i??!c.ungrouped?.[t]})}):a==="single-select"&&l?y(h({},c),{[l]:{[t]:i??!0}}):a==="multi-select"&&l?y(h({},c),{[l]:y(h({},c[l]),{[t]:i??!c[l]?.[t]})}):c}catch(c){return this.loggingService.catch("Error in ButtonService createNewToggleMap: ",c),{}}}buttonClickSubject(){return this.buttonClickSubject$.asObservable()}buttonToggleMap(){return this.buttonToggleMap$.asObservable()}resetVeltButtonState(e){return X(this,null,function*(){try{if(e){let{id:l,group:c}=e,d=JSON.parse(JSON.stringify(this.buttonToggleMap$.value||{}));c&&l?delete d?.[c]?.[l]:c?delete d?.[c]:l&&Object.keys(d).forEach(m=>{Object.keys(d[m]).forEach(u=>{u===l&&delete d?.[m]?.[u]})}),this.buttonToggleMap$.next(d)}else this.buttonToggleMap$.next({});let t={selections:this.buttonToggleMap$.value},i=yield this.metadataService.getGlobalMetadata(),a={buttonContext:t,metadata:i};this.coreActionsService.triggerAction(tt.VELT_BUTTON_CLICK,a)}catch(t){this.loggingService.catch("Error in ButtonService resetVeltButtonState: ",t)}})}buttonToggleMapValue(){return this.buttonToggleMap$.value}};o.\u0275fac=function(t){return new(t||o)(K(nr),K(k),K(ts))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var bS=(()=>{let o=class o{constructor(e,t){this.httpClient=e,this.loggingService=t,this.fileContentMap$=new _e({})}getFileContent(e){try{let t=er(e);return this.fileContentMap$.value[t]?ce(this.fileContentMap$.value[t]):this.httpClient.get(e,{responseType:"text"}).pipe(ue(i=>(this.fileContentMap$.next(y(h({},this.fileContentMap$.value),{[t]:i})),i)))}catch(t){return this.loggingService.catch("Error in TranscriptionService saveRecorderToDb: ",t),ce(null)}}getVttFileTextToArray(e){try{let c=[],d=e.split(`
500
- `);for(var t=0;t<d.length;t++)if(d[t].indexOf("-->")!==-1){var i=d[t].split(" --> ")[0],a=d[t].split(" --> ")[1],l=d[t+1];c.push({startTime:i,endTime:a,startTimeInSeconds:this.getTimeInSecondsFromVttTime(i),endTimeInSeconds:this.getTimeInSecondsFromVttTime(a),text:l})}return c}catch(c){return this.loggingService.catch("Error in TranscriptionService getVttFileTextToArray: ",c),[]}}getTimeInSecondsFromVttTime(e){try{let t=e.split(":"),i=0;t.length===3&&(i=parseInt(t[0]),t.shift());let a=parseInt(t[0]),l=parseInt(t[1].split(".")[0]),c=parseInt(t[1].split(".")[1]);return((i*60*60+a*60+l)*1e3+c)/1e3}catch(t){return this.loggingService.catch("Error in TranscriptionService getTimeInSecondsFromVttTime: ",t),0}}};o.\u0275fac=function(t){return new(t||o)(K(j9),K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ho=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A,M,V,q,ae,ye,ie,ge,Ie,he,Te){this.analyticsService=e,this.configService=t,this.docService=i,this.databaseService=a,this.commonDbService=l,this.authService=c,this.domService=d,this.afAuth=m,this.iamService=u,this.functions=_,this.avatarService=I,this.contactService=A,this.storageService=M,this.dialog=V,this.loggingService=q,this.notificationService=ae,this.transcriptionService=ye,this.recorderService=ie,this.recorderUtilsService=ge,this.userPermissionService=Ie,this.recorderAnnotationsResolverService=he,this.attachmentResolverService=Te,this.recorderAnnotationById$=new _e({}),this.documentPaths=null,this.allowedElementIds$=new _e([]),this.addRecorderMode$=new _e(!1),this.recorderContainerDarkMode$=new _e(!1),this.recordingTranscriptionEnabled$=new _e(!0),this.draftRecordings$=new _e([]),this.recorderNotesFound$=new _e(!1),this.recordedData=null,this.videoEditorAutoOpen$=new _e({}),this.commentService=null,this.getAllRecorderAnnotations().subscribe(Oe=>{}),this.loggingService.log("%c[WB] Creating CLASS: RecorderAnnotationService","color: blue;"),this.analyticsService.setRecorderAnnotationService(this),this.authService.setRecorderAnnotationService(this),this.databaseService.getDb().pipe(Ge(Oe=>!!Oe),ut(1)).subscribe(Oe=>{Oe&&this.getDocumentPaths()},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService getDb subscription: ",Oe)}),this.domService.onWindowPointerMove$().subscribe(Oe=>{if(this.addRecorderMode$.value){this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement);let Pe=this.domService.getBackgroundElement(Oe.clientX,Oe.clientY);Pe&&(this.isElementInsideAllowedElements(Pe)?tF(Oe.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement=Pe):this.domService.removeClassFromElement(document.body,"show-pin-cursor"))}},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowPointerMove$ subscription: ",Oe)}),this.domService.onWindowKeyupEsc$().subscribe(Oe=>{this.addRecorderMode$.value&&this.disableAddRecorderMode()},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupEsc$ subscription: ",Oe)}),this.domService.onDocumentClick$().subscribe(Oe=>{if(Oe&&this.addRecorderMode$.value){if(Oe.preventDefault(),Oe.stopPropagation(),!tF(Oe.target)){let Pe=this.domService.getBackgroundElement(Oe.clientX,Oe.clientY);Pe&&this.isElementInsideAllowedElements(Pe)}this.disableAddRecorderMode()}},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService onDocumentClick$ subscription: ",Oe)}),this.addRecorderMode$.subscribe(Oe=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),Oe?this.domService.addClassToElement(document.body,"snippyly-add-recorder-mode"):(this.domService.removeClassFromElement(document.body,"snippyly-add-recorder-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"))},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService addRecorderMode$ subscription: ",Oe)}),this.domService.onWindowKeyupBackspace$().subscribe(Oe=>{this.deleteRecorderPinAnnotations()},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupBackspace$ subscription: ",Oe)}),this.domService.onWindowKeyupDelete$().subscribe(Oe=>{this.deleteRecorderPinAnnotations()},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupDelete$ subscription: ",Oe)}),this.recorderService.onRecordedData().subscribe(Oe=>{this.recordedData=Oe},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService onRecordedData subscription: ",Oe)}),this.domService.getDeleteCommmentAnnotations$().subscribe(Oe=>{Oe?.length&&Oe.forEach(Pe=>X(this,null,function*(){}))},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupDelete$ subscription: ",Oe)})}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in RecorderAnnotationService","color: green;");try{this.recorderAnnotationById$.next({}),this.documentPaths=null,this.allowedElementIds$.next([]),this.addRecorderMode$.next(!1),this.highlightElement=null}catch(e){this.loggingService.catch("Error in RecorderAnnotationService clearCache: ",e)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;");try{this.docService.getDocumentPaths$().pipe(ln(e=>{this.documentPaths=e})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getDocumentPaths subscription: ",e)})}catch(e){this.loggingService.catch("Error in CursorService getDocumentPaths: ",e)}}setCommentService(e){this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;");try{this.commentService=e}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setCommentService: ",t)}}getAnonymousAvatarImage(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAnonymousAvatarImage","color: green;"),this.avatarService.generateUserImage()}setAllowedElementIds(e){this.allowedElementIds$.next(e||[])}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}getDraftRecordings$(){return this.draftRecordings$.asObservable()}getRecorderDataByRecorderId(e){try{return this.recorderAnnotationById$.pipe(ue(()=>this.getAnnotationById(e)),Se(t=>X(this,null,function*(){return t?yield this.createRecorderData(t,!0):void 0})))}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderDataByRecorderId: ",t),ce(void 0)}}getRecorderDataByRecorderIds(e){return X(this,null,function*(){try{let t={};return yield Promise.all(e.recorderIds.map(i=>X(this,null,function*(){let a=this.getAnnotationById(i);if(!a)return;let l=yield this.createRecorderData(a,!0);l&&(t[i]=l)}))),{data:Object.keys(t).length>0?t:null}}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderDataByRecorderIds: ",t),{data:null}}})}fetchRecorderDataByRecorderIds(e){return X(this,null,function*(){try{let t=this.recorderAnnotationById$.value,i=[],a=Object.values(t);return e?.recorderIds?.length&&(a=a.filter(l=>e.recorderIds.includes(l.annotationId))),a.length===0?[]:(yield Promise.all(a.map(l=>X(this,null,function*(){if(!l)return;let c=yield this.createRecorderData(l,!0);c&&i.push(c)}))),i)}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService fetchRecorderDataByRecorderIds: ",t),[]}})}deleteRecorderDataByRecorderIds(e){return X(this,null,function*(){try{let t=this.recorderAnnotationById$.value,i=[],a=Object.values(t),l=[];return e?.recorderIds?.length&&(l=a.filter(c=>e.recorderIds.includes(c.annotationId))),l.length===0?[]:(yield Promise.all(l.map(c=>X(this,null,function*(){if(!c)return;let d=yield this.createRecorderData(c,!0);yield this.deleteRecorderPinAnnotation(c),d&&i.push(d)}))),i)}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService deleteRecorderDataByRecorderIds: ",t),[]}})}getRecordings(e){try{return this.recorderAnnotationById$.pipe(Se(t=>X(this,null,function*(){let i=[],a=Object.values(t);return e?.recorderIds?.length&&(a=a.filter(l=>e.recorderIds.includes(l.annotationId))),a.length===0?[]:(yield Promise.all(a.map(l=>X(this,null,function*(){if(!l)return;let c=yield this.createRecorderData(l,!0);c&&i.push(c)}))),i)})),Xn(t=>(this.loggingService.catch("Error in RecorderAnnotationService getRecordings: ",t),ce([]))))}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService getRecordings: ",t),ce([])}}setRecorderActionsService(e){try{this.recorderActionsService=e}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setRecorderActionsService: ",t)}}getVttFileTextToArray(e){try{return this.transcriptionService.getVttFileTextToArray(e)}catch(t){this.loggingService.catch("Error in RecorderAnnotationService getVttFileTextToArray: ",t)}}getAllRecorderAnnotations(e,t,i){this.loggingService.log("%c[WB] Calling FUNCTION: getAllRecorderAnnotations","color: green;");let a,l;try{if(e&&(l=er(e)),t&&typeof t=="object"){let c=Oi(t);a=er(JSON.stringify(c))}}catch(c){this.loggingService.catch("Error in RecorderAnnotationService getAllRecorderAnnotations: ",c)}return _r(this.afAuth).pipe(Ge(c=>!!c),Se(c=>this.isFeatureAllowed({firebaseUser:c,annotations:[],filteredAnnotations:[]})),Se(c=>c.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(d=>(c.featureAllowed=d,c))):ce(c)),Se(c=>c.featureAllowed?this.authService.isPlanExpired$().pipe(ue(d=>(c.featureAllowed=!d,c))):ce(c)),Se(c=>c.featureAllowed?ce(c).pipe(Se(d=>this.docService.getDocumentPaths$().pipe(ue(m=>(this.documentPaths=m,d.documentPaths=m,d)))),Se(d=>l?this.getDataFromDocumentIds([l]).pipe(ue(m=>(d.annotations=m||[],h({},d)))):this.docService.getDocumentIds$().pipe(Se(m=>{let u=m?.length>0?m.map(_=>_.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(u).pipe(ue(_=>(d.annotations=_||[],h({},d))))}))),Se(d=>this.docService.getLocation$().pipe(ue(m=>(d.location=m,d)))),Se(d=>this.docService.getLocations$().pipe(ue(m=>(d.customLocations=m,d)))),ue(d=>{if(d.filteredAnnotations=[],l&&!a)return d.filteredAnnotations=d.annotations?.slice(),d;{let m=[];return a?m.push(a):(m.push(d?.location?.locationId),m.push(...Object.values(d?.customLocations||[]).map(u=>u.locationId))),d.filteredAnnotations=this.filterAnnotationsByLocationIds(d?.annotations,m),d}}),Se(d=>i?ce(d):d?.annotations?.length?this.domService.onWindowResize$().pipe(ue(()=>d)):ce(d)),Se(d=>i?ce(d):d?.annotations?.length?this.domService.onDomChange$("RecorderAnnotationService getAllRecorderAnnotations").pipe(ue(()=>d)):ce(d)),ue(d=>{let m=[];return d?.filteredAnnotations?.forEach(u=>{this.calculateRecorderAnnotationPosition(u),u?.targetElement||m.push(u)}),this.draftRecordings$.next(m),d}),Se(d=>d?.filteredAnnotations?ce(d?.filteredAnnotations||[]):ce([]))):ce([])),_t(Kt))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})),Se(t=>this.authService.getUser$().pipe(ue(i=>y(h({},t),{user:i})))),Se(t=>Ao(t.config,t.user,je.RECORDER)?ce(y(h({},t),{featureAllowed:!0})):(this.loggingService.warn("Recorder feature is not allowed."),ce(y(h({},t),{featureAllowed:!1})))),_t((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t,filters:i}=e;if(t?.some(d=>!d)||!this.documentPaths)return ce([]);let a=this.docService.getDocumentPaths()?.veltFolderId,l=ce([]),c={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(c.documentId=t?.length?t[0]:void 0,c.organizationId=this.documentPaths?.organizationId),this.userPermissionService?.getIsContextEnabled()){let d=[N.DEFAULT_VELT_CONTEXT,...this.docService.getProcessedDocContext()],m=[];for(let u=0;u<(d?.length??0);u+=N.LISTENER_CONTEXT_BATCH_SIZE)m.push(d?.slice(u,u+N.LISTENER_CONTEXT_BATCH_SIZE)??[]);l=gn(m.map(u=>this.commonDbService.dbListener({feature:"allRecorders",properties:y(h({},c),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",t),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[],...u?.length?[ft("context.accessFields","array-contains-any",u)]:[])]})}).pipe(la()))).pipe(ue(u=>Na(u)))}else{let d=[];for(let m=0;m<(t?.length??0);m+=N.LISTENER_BATCH_SIZE)d.push(t?.slice(m,m+N.LISTENER_BATCH_SIZE)??[]);l=gn(d.map(m=>this.commonDbService.dbListener({feature:"allRecorders",properties:y(h({},c),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",m),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[])]})}).pipe(la()))).pipe(ue(m=>Na(m)))}return l.pipe(ue(d=>({data:d?.data,operation:d?.operation})),ue(({data:d,operation:m})=>{let u=[];return d&&(u=Object.values(d).filter(_=>typeof _=="object")),{data:u,operation:m}}),ue(({data:d,operation:m})=>{if(!t)return{data:d,documentMap:{},operation:m};let u=d.reduce((_,I)=>{let A=I.metadata?.documentId;return A&&(_[A]||(_[A]=[]),_[A].push(I)),_},{});return{data:d,documentMap:u,operation:m}}),ue(({data:d,documentMap:m,operation:u})=>{if(!i)if(u?.type==="removed"){if(u?.ids?.length){let _=this.recorderAnnotationById$.value;u?.ids?.forEach(I=>{delete _?.[I]}),this.recorderAnnotationById$.next(_)}}else Object.entries(m).forEach(([_,I])=>{this.setRecorderAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:_,annotations:I})});return d}),Xn(d=>(this.loggingService.catch("Error in RecorderAnnotationService getDataFromDocumentId: ",d),ce([]))))}else return ce([])}setRecorderAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:i,queryHash:a}){try{if(t){e||(e=N.NO_ORGANIZATION_ID),a||(a=N.DEFAULT_QUERY_HASH);let l={};i?.forEach(d=>{d?.annotationId&&(l[d?.annotationId]=d)});let c=h(h({},this.recorderAnnotationById$.value),l);this.recorderAnnotationById$.next(c)}}catch(l){this.loggingService.catch("Error in RecorderAnnotationService setRecorderAnnotationsByOrganizationIdAndDocumentId:",l)}}filterAnnotationsByLocationIds(e,t){try{return e.filter(i=>t.includes(i.locationId))}catch(i){return this.loggingService.catch("Error in RecorderAnnotationService filterAnnotationsByLocations:",i),[]}}calculateRecorderAnnotationPosition(e){try{if(e.targetElement){let t=this.domService.getXPath(e.targetElement?.xpath);if(t){let i=t.iterateNext();if(i&&Kr(i)){let a=i.getBoundingClientRect();if(a&&a.width&&a.height){let{height:l,width:c}=np(i);e.position={top:l*e.targetElement.topPercentage/100,left:c*e.targetElement.leftPercentage/100}}else e.position=null}else e.position=null}else e.position=null}}catch(t){this.loggingService.catch("Error in RecorderAnnotationService calculateRecorderAnnotationPosition:",t)}}getAnnotationById(e,t){try{let i=this.recorderAnnotationById$.value?.[e];if(i){let{documentId:a,organizationId:l}=t||{};if(a&&i.metadata?.documentId!==a||l&&i.metadata?.organizationId!==l)return}return i}catch(i){this.loggingService.catch("Error in RecorderAnnotationService getAnnotationById: ",i);return}}getBaseMetadataFromRecorderAnnotationId(e){try{let t=this.recorderAnnotationById$.value?.[e];if(t)return t.metadata}catch(t){this.loggingService.catch("Error in RecorderAnnotationService getBaseMetadataFromRecorderAnnotationId: ",t)}}getRecorderAnnotationById(e,t){return this.recorderAnnotationById$.pipe(Se(()=>{let i=this.getAnnotationById(e,t);return i?ce(i):ce(null)}),Xn(i=>(this.loggingService.catch("Error in RecorderAnnotationService getCommentAnnotationById: ",i),ce(null))))}getRecorderAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let i={};return Object.values(this.recorderAnnotationById$.value).forEach(a=>{a?.metadata?.documentId==t&&a?.metadata?.organizationId==e&&(i[a?.annotationId]=a)}),Object.values(i)}catch(i){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderAnnotationsByOrganizationIdAndDocumentId:",i),[]}}setLocationToRecorderAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location);try{if(e.targetElement?.xpath){let i=this.domService.getElementFromXPath(e.targetElement.xpath),a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.addLocation({location:a,source:"internal"});l?.[0]&&(e.locationId=l[0].locationId,e.location=l[0].location)}}}catch{}}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setLocationToRecorderAnnotation:",t)}}addRecorder(e,t,i){this.loggingService.log("%c[WB] Calling FUNCTION: addRecorder","color: green;");try{let a=this.authService.getUser();if(a){if(a.isReadOnly||a.isAnonymous)return this.loggingService.catch("Anonymous/Readonly users cannot add recorders."),ce(null);{t.from=a,t.color=N.DEFAULT_ANNOTATION_COLOR,t.lastUpdated=this.timestamp;let{topPositionX:l,topPositionY:c}=this.domService.getTopLeftPosition();t.positionX=l,t.positionY=c;let d=this.domService.getCurrentWindowSizeValue();if(t.screenWidth=d.screenWidth,t.screenHeight=d.screenHeight,t.screenScrollHeight=d.screenScrollHeight,t.recorderedElementPath="",e&&(t.targetElement=this.domService.getTargetElementForCursorPosition(e)),t?.targetElement?.xpath){let m=this.domService.getXPath(t.targetElement.xpath);if(m){let u=m.iterateNext();u&&(Kr(u)||(t.targetElement=null))}}return this.setLocationToRecorderAnnotation(t),t.pageInfo=ro(),t.pageInfo&&(t.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth),this.saveRecorderToDb(t,i)}}else return ce(null)}catch(a){return this.loggingService.catch("Error in RecorderAnnotationService addRecorder: ",a),ce(null)}}saveRecorderToDb(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: saveRecorderToDb","color: green;");try{return this.authService.getUser()&&this.authService.isFeatureAllowed(je.RECORDER)?this.docService.getDocumentPaths$().pipe(Ge(i=>!!i),ut(1),Se(i=>(this.documentPaths=i,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Ge(a=>!!a),ut(1),Se(a=>X(this,null,function*(){if(this.documentPaths?.recorder){e.annotationId=this.commonDbService.generateDocumentId(),e.pageInfo&&(e.pageInfo.recorderUrl=this.generateRecorderUrl(e));let l=JSON.parse(JSON.stringify(e));if(l.position=null,this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||delete l?.isUrlAvailable,!l?.metadata?.documentId){l?.metadata||(l.metadata={});let u=this.docService.getBaseMetadata("recorder",{commentAnnotationId:e.commentAnnotationId});l.metadata=h(h({},l?.metadata),u)}let{documentId:c,organizationId:d}=l?.metadata||{};if(e.commentAnnotationId){let u=this.commentService?.getAnnotationById(e.commentAnnotationId??"");if(u?.context?.access&&u?.context?.accessFields){if(!this.userPermissionService?.hasUserContextAccess({userId:e.from?.userId,accessFields:u.context.accessFields}))return this.loggingService.catch("User does not have context access to add recorder annotation.",void 0,void 0,!0),null;l.context={access:u.context.access,accessFields:u.context.accessFields}}}let m={annotationData:l,actionType:Jl.ADDED,notificationSource:"recorder"};if(yield new Promise((u,_)=>X(this,null,function*(){yield this.commonDbService.setData({feature:"recorder",properties:{id:e.annotationId,documentId:c,organizationId:d},data:JSON.parse(JSON.stringify(l)),extraData:m,callback:()=>{u(!0)},errorCallback:I=>{_(I)}})})),this.analyticsService.trackEvent(Y.Events.Recording.RECORDING_ADDED,{annotationId:e.annotationId,recorderType:e.recordingType,recorderMode:e.mode,recorderTime:e?.recordedTime?.duration,recorderSize:e?.attachments?.length?e?.attachments[0]?.size:e?.attachment?.size,sourceFeature:t||"recording"}),this.setVideoEditorAutoOpen({[e.annotationId]:!0}),t==="recording"){let u=yield this.createRecorderData(l,!1);u&&this.recorderActionsService?.onRecordingDoneLocal(u)}return this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||this.processRecording(e,"recording","merge"),this.updateNotificationsDatabase(e,Jl.ADDED),e}else return null})))))):ce(null)}catch(i){return this.loggingService.catch("Error in RecorderAnnotationService saveRecorderToDb: ",i),ce(null)}}processRecording(e,t,i){return X(this,null,function*(){try{let a=Yr(this.functions,Zr({url:On?.cloudFunction?.processRecording,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:36e5}),l=this.docService.getDocumentPaths();e?.metadata?.documentId&&(l=new bm({apiKey:this.configService.getApiKey(),clientDocumentId:e.metadata.clientDocumentId,clientOrganizationId:e.metadata.clientOrganizationId,documentId:e.metadata.documentId,organizationId:e.metadata.organizationId}));let c={databaseUrl:this.authService.getFirebaseConfig()?.firebaseOptions?.databaseURL,entirePath:l?.recorder+e?.annotationId,fromUser:this.authService.getUser(),clientOrganizationId:l?.clientOrganizationId,clientDocumentId:l?.clientDocumentId,apiKey:this.configService.getApiKey(),sdkVersion:tl(),sdkType:this.configService.getSdkType(),useFirestore:this.commonDbService.shouldUseFirestore(),storageBucket:this.authService.getFirebaseConfig()?.firebaseOptions?.storageBucket,documentPath:l?.recorder,annotationId:e?.annotationId,sourceFeature:t||"recording",annotationData:e,skipMerge:!0,transcriptionEnabled:this.getRecordingTranscriptionEnabled(),type:i,returnType:"transcription",generatePreviewImages:this.recorderService.getVideoEditor()&&this.recorderService.getVideoEditorTimelinePreview()};if(c?.useFirestore){let M=yield this.recorderUtilsService.encryptRecorderAnnotation(e);c.annotationData=M}let d=this.documentPaths?.organizationId,m=this.documentPaths?.documentId;e?.metadata?.documentId&&(m=e.metadata.documentId,d=e.metadata.organizationId);let u=`${this.configService.getApiKey()}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${m}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`;d&&(u=`${this.configService.getApiKey()}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${d}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${m}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`),c.bucketPath=u;let _;try{_=yield a(c)}catch(M){M?.details?.type==="recording"&&this.recorderActionsService?.onError({type:"recordingFailed",message:"Recording failed",recorderId:M.details.recorderId}),M?.details?.type==="transcription"&&this.recorderActionsService?.onError({type:"transcriptionFailed",message:"Transcription failed",recorderId:M.details.recorderId}),this.loggingService.catch("Error in RecorderAnnotationService processRecording: ",M)}let I=this.getAnnotationById(e?.annotationId);if(!I)return;let A=yield this.createRecorderData(I,!1);if(A){if(_?.data?.transcriptedText&&(A.transcription.contentSummary=_.data.transcriptedText),_?.data?.vttUrl)try{let M=yield this.transcriptionService.getFileContent(_.data.vttUrl).toPromise();M&&(A.transcription.transcriptSegments=this.getVttFileTextToArray(M),A.transcription.vttFileUrl=_.data.vttUrl),A?.assets?.length&&A.assets.forEach(V=>{V.transcription=A.transcription}),A?.assetsAllVersions?.length&&(A.assetsAllVersions[0].transcription=A.transcription),this.recorderActionsService?.onTranscriptionDone(A)}catch(M){this.loggingService.catch("Error fetching VTT content: ",M)}I?.attachments?.length&&this.recordedData&&(this.recordedData.videoUrl=I.attachments[0].url),t==="recording"&&this.recorderActionsService?.onRecordingDone(A)}this.recordedData&&this.recorderService.setRecordedData(this.recordedData)}catch(a){this.loggingService.catch("Error in RecorderAnnotationService processRecording: ",a)}})}getDocumentIdAndOrganizationIdFromRecorderAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService getDocumentIdAndOrganizationIdFromRecorderAnnotation: ",t),{}}}createRecorderData(e,t=!1){return X(this,null,function*(){try{if(!e)return null;let i=oi(e.metadata||{}),a=Vo(e.from),l={recorderId:e.annotationId||"",from:a,assets:[],metadata:i,assetsAllVersions:[],transcription:{transcriptSegments:[],vttFileUrl:"",contentSummary:""}},c=e;e.latestVersion&&e.recordingEditVersions?.[e.latestVersion]&&(c=e.recordingEditVersions[e.latestVersion]);let d=u=>X(this,null,function*(){let _={transcriptSegments:[],vttFileUrl:"",contentSummary:u?.transcription?.transcriptedText||""};if(t&&u?.transcription?.vttUrl)try{let I=yield this.transcriptionService.getFileContent(u.transcription.vttUrl).toPromise();I&&(_.transcriptSegments=this.getVttFileTextToArray(I),_.vttFileUrl=u.transcription.vttUrl)}catch(I){this.loggingService.catch("Error fetching VTT content: ",I)}return _}),m=yield d(c);if(l.transcription=m,c?.attachments?.length)for(let u of c.attachments)u?.url&&l.assets.push({version:e.latestVersion||1,url:u.url,mimeType:u.mimeType,fileName:u.name,fileSizeInBytes:u.size,fileFormat:u.type,transcription:h({},m),thumbnailUrl:e.attachments?.[0]?.thumbnail});if(e.recordingEditVersions){let u=Object.entries(e.recordingEditVersions).map(M=>X(this,[M],function*([I,A]){let V=parseInt(I),q=yield d(A),ae=A?.attachments?.[0]||A?.attachment;return{version:V,url:ae?.url,mimeType:ae?.mimeType,fileName:ae?.name,fileSizeInBytes:ae?.size,fileFormat:ae?.type,transcription:q,thumbnailUrl:A?.attachments?.[0]?.thumbnail}})),_=yield Promise.all(u);l.assetsAllVersions=_.filter(I=>I.url)}else l.assetsAllVersions=[...l.assets];return l}catch(i){return this.loggingService.catch("Error in RecorderAnnotationService createRecorderData: ",i),null}})}updateRecorder(e,t=!1,i){try{i&&this.setLocationToRecorderAnnotation(e),t&&this.updateNotificationsDatabase(e,Jl.UPDATED),this.updateRecorderToDb(e)}catch(a){this.loggingService.catch("Error in RecorderAnnotationService updateRecorder: ",a)}}resolveRecorder(e){try{this.domService.resetSelectedAnnotationsMap(!1),this.updateNotificationsDatabase(e,Jl.RESOLVED),this.updateRecorderToDb(e),this.domService.updateSelectedAnnotationInMap([e])}catch(t){this.loggingService.catch("Error in RecorderAnnotationService resolveRecorder: ",t)}}updateRecorderToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateRecorderToDb","color: green;");try{if(e?.targetElement?.xpath){let t=this.domService.getXPath(e.targetElement.xpath);if(t){let i=t.iterateNext();i&&(Kr(i)||(e.targetElement=null))}}if(e.annotationId){let t=this.recorderAnnotationById$.value;this.recorderAnnotationById$.next(y(h({},t),{[e.annotationId]:h({},e)}))}if(this.domService.updateSelectedAnnotationInMap([e]),this.authService.getUser()&&this.authService.isFeatureAllowed(je.RECORDER)){let t=JSON.parse(JSON.stringify(e));if(t.position=null,this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||delete t?.isUrlAvailable,!t?.metadata?.documentId){t?.metadata||(t.metadata={});let l=this.docService.getBaseMetadata("recorder");t.metadata=h(h({},t?.metadata),l)}let{documentId:i,organizationId:a}=this.getDocumentIdAndOrganizationIdFromRecorderAnnotation(e);this.commonDbService.setData({feature:"recorder",properties:{id:e.annotationId,documentId:i,organizationId:a},data:JSON.parse(JSON.stringify(t)),extraData:{actionType:Jl.UPDATED}})}}catch(t){this.loggingService.catch("Error in RecorderAnnotationService updateRecorderToDb: ",t)}}deleteRecorderPinAnnotations(){try{let e=this.domService.getSelectedAnnotationsMap(),t=this.authService.getUser(),i=[];Object.keys(e).forEach(a=>X(this,null,function*(){let l=e[a];l.type==="recorder"&&t&&l.from&&(t?.isAdmin||l.from.userId===t.userId)&&i.push(l)})),i?.length&&(this.analyticsService.trackEvent(Y.Events.Recording.RECORDING_DELETE_TRIGGERED,{annotationId:i.map(a=>a.annotationId).join()}),this.dialog.open(al,{panelClass:"velt-mat-dialog-container",data:{title:"Delete recording?",message:"This selected recording will be deleted.",yesButton:"Delete",noButton:"Cancel",darkMode:this.recorderContainerDarkMode$.value,variant:"recorder"}}).afterClosed().pipe(ut(1)).subscribe(a=>{a&&(i.forEach(l=>X(this,null,function*(){yield this.deleteRecorderPinAnnotation(l)})),setTimeout(()=>{document.querySelectorAll(`[${N.SNIPPYLY_HIGHLIGHT}]`).forEach(c=>{this.domService.removeHighlightFromElement(c)})},100))}),this.domService.resetSelectedAnnotationsMap(!0,"recorder"))}catch(e){this.loggingService.catch("Error in RecorderAnnotationService deleteRecorderPinAnnotations: ",e)}}deleteRecorderPinAnnotation(e,t){if(this.authService.isFeatureAllowed(je.RECORDER)&&this.documentPaths?.recorder&&e?.annotationId){this.updateNotificationsDatabase(e,Jl.DELETED);let i=this.attachmentResolverService.attachmentDataProviderAvailable("recorder"),a=this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()?this.recorderUtilsService.mergeStrippedDataWithRecorderAnnotation(h({},e)):e,l=oi(e?.metadata??{});if(a?.attachments?.length)a.attachments.forEach(_=>{let I={organizationId:l?.organizationId??null,documentId:l?.documentId??null,folderId:l?.folderId??null,attachmentId:_.attachmentId,commentAnnotationId:null,apiKey:l?.apiKey??null};this.storageService.deleteAttachment({attachment:_,metadata:I,useAttachmentResolver:i,attachmentScope:"recorder"}).catch(A=>{this.loggingService.catch("Error in RecorderAnnotationService deleteRecorderPinAnnotation delete attachment: ",A)})});else if(a?.attachment){let _={organizationId:l?.organizationId??null,documentId:l?.documentId??null,folderId:l?.folderId??null,attachmentId:a.attachment.attachmentId,commentAnnotationId:null,apiKey:l?.apiKey??null};this.storageService.deleteAttachment({attachment:a.attachment,metadata:_,useAttachmentResolver:i,attachmentScope:"recorder"})}e?.transcription&&!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()&&(e?.transcription?.srtBucketPath&&this.storageService.deleteFileFromPath(e.transcription.srtBucketPath).catch(_=>{this.loggingService.catch("Error in RecorderAnnotationService deleteRecorderPinAnnotation delete srt file: ",_)}),e?.transcription?.vttBucketPath&&this.storageService.deleteFileFromPath(e.transcription.vttBucketPath).catch(_=>{this.loggingService.catch("Error in RecorderAnnotationService deleteRecorderPinAnnotation delete vtt file: ",_)})),this.analyticsService.trackEvent(Y.Events.Recording.RECORDING_DELETED,{annotationId:e.annotationId,recorderType:e.recordingType,recorderMode:e.mode,recorderTime:e?.recordedTime?.duration,recorderSize:e?.attachments?.length?e?.attachments[0]?.size:e.attachment?.size,sourceFeature:t||"recording"});let{documentId:c,organizationId:d}=this.getDocumentIdAndOrganizationIdFromRecorderAnnotation(e),m={annotationData:e,actionType:Jl.DELETED,notificationSource:"recorder"},u={apiKey:this.configService.getApiKey(),organizationId:d,documentId:c,veltFolderId:e?.metadata?.veltFolderId};return this.commonDbService.deleteData({feature:"recorder",properties:{id:e.annotationId,documentId:c,organizationId:d,metadata:u},extraData:m}).then(_=>X(this,null,function*(){let I=yield this.createRecorderData(e,!0);I&&this.recorderActionsService?.onDeleteRecording(I)}))}else return Promise.resolve()}enableAddRecorderMode(){this.authService.isFeatureAllowed(je.RECORDER)?this.addRecorderMode$.next(!0):this.loggingService.catch("Error in RecorderAnnotationService enableAddRecorderMode: ","Recorder feature is not enabled.")}disableAddRecorderMode(){this.addRecorderMode$.next(!1)}addRecorderModeChange(){return this.addRecorderMode$.asObservable()}setRecorderContainerDarkMode(e){try{if(this.recorderContainerDarkMode$.value===e)return;this.recorderContainerDarkMode$.next(e)}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setRecorderContainerDarkMode: ",t)}}getRecorderContainerDarkMode(){return this.recorderContainerDarkMode$.asObservable()}enableRecordingTranscription(){try{if(this.analyticsService.setFeatureConfig({feature:je.RECORDER,config:{recordingTranscription:!0}}),this.recordingTranscriptionEnabled$.value===!0)return;this.recordingTranscriptionEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderAnnotationService enableRecordingTranscription: ",e)}}disableRecordingTranscription(){try{if(this.analyticsService.setFeatureConfig({feature:je.RECORDER,config:{recordingTranscription:!1}}),this.recordingTranscriptionEnabled$.value===!1)return;this.recordingTranscriptionEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderAnnotationService disableRecordingTranscription: ",e)}}getRecordingTranscriptionEnabled(){return this.recordingTranscriptionEnabled$.value}getRecordingTranscriptionEnabled$(){return this.recordingTranscriptionEnabled$.asObservable()}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService isElementInsideAllowedElements: ",t),!1}}attachRecorder(e){let t=document.getElementById(e);if(t){let i=this.domService.getXPath(t),a=this.getRecorderPinAnnotationObject();a&&(a.targetElement={xpath:i,topPercentage:50,leftPercentage:90},this.saveRecorderToDb(a))}}getRecorderPinAnnotationObject(){let e=this.authService.getUser();if(e)if(e.isReadOnly||e.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add recorders.");else{let t=new Ku;t.from=e,t.color=N.DEFAULT_ANNOTATION_COLOR,t.lastUpdated=this.timestamp;let{topPositionX:i,topPositionY:a}=this.domService.getTopLeftPosition();t.positionX=i,t.positionY=a;let l=this.domService.getCurrentWindowSizeValue();t.screenWidth=l.screenWidth,t.screenHeight=l.screenHeight,t.screenScrollHeight=l.screenScrollHeight,t.recorderedElementPath="";let c=this.docService.getLocation();return c&&(t.locationId=c.locationId,t.location=c.location),t}return null}updateNotificationsDatabase(e,t,i={}){try{let a=e;this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()&&(a=JSON.parse(JSON.stringify(e)),a?.from?.userId&&(a.from={userId:a.from.userId}),delete a.transcription,a?.attachments?.length&&(a.attachments=a.attachments.map(c=>({attachmentId:c?.attachmentId,name:c?.name}))),a.attachment=null,a?.chunkUrls&&(a.chunkUrls={}));let l=h({annotationData:a,actionType:t,notificationSource:"recorder",recordingType:e?.recordingType},i);this.notificationService.updateNotificationDatabase(l)}catch(a){this.loggingService.catch("Error in RecorderAnnotationService updateNotificationsDatabase: ",a)}}getUserContacts$(){return this.contactService.getUserContacts$()}addUserContact(e){this.contactService.addUserContact(e)}getRecorderUrl(e){try{return e?.pageInfo?.recorderUrl?e.pageInfo.recorderUrl:e?.annotationId?(e?.pageInfo||(e.pageInfo=ro(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.recorderUrl=this.generateRecorderUrl(e),this.updateRecorder(e),e.pageInfo?.recorderUrl):""}catch(t){this.loggingService.catch("Error in RecorderAnnotationService getRecorderUrl: ",t);return}}uploadFile(e,t){let i=this.documentPaths?.organizationId,a=this.documentPaths?.documentId;t?.metadata?.documentId&&(a=t.metadata.documentId,i=t.metadata.organizationId);let l=`${N.FIREBASE_PARTIAL_PATH_DOCS}/${a}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`;if(i&&(l=`${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${i}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${a}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`),this.attachmentResolverService.attachmentDataProviderAvailable("recorder")){let c=this.docService.getBaseMetadata("recorder",{commentAnnotationId:t.commentAnnotationId});return this.storageService.uploadFile({path:l,file:e,useAttachmentResolver:!0,metadata:c,attachmentScope:"recorder"})}return this.storageService.uploadFile({path:l,file:e})}uploadFullRecordingAndUpdateAnnotation(e,t){try{if(!t?.annotationId)return;this.uploadFile(e,t).then(i=>{if(!i?.url)return;let l=this.getAnnotationById(t.annotationId)||t;l.attachments?.length&&(l.attachments[0].url=i.url,l.attachments[0].attachmentId=i.attachmentId,i.bucketPath&&(l.attachments[0].bucketPath=i.bucketPath)),l.attachment=l.attachments?.[0]??null,l.lastUpdated=new Date().getTime(),l.isUrlAvailable=!0,this.updateRecorder(l)}).catch(i=>{this.loggingService.catch("Error uploading full recording: ",i)})}catch(i){this.loggingService.catch("Error in RecorderAnnotationService uploadFullRecordingAndUpdateAnnotation: ",i)}}downloadAttachment(e){this.storageService.downloadAttachment(e)}deleteAttachment(e){return this.storageService.deleteAttachment({attachment:e})}generateRecorderUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(N.URL_PARAMS.RECORDER_ID),t.searchParams.append(N.URL_PARAMS.RECORDER_ID,e.annotationId),t.href}setRecorderNotesFound(e){try{this.recorderNotesFound$.next(e)}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setRecorderNotesFound: ",t)}}getRecorderNotesFound$(){try{return this.recorderNotesFound$.asObservable()}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderNotesFound: ",e),ce(!1)}}getRecorderNotesFound(){try{return this.recorderNotesFound$.value}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderNotesFound: ",e),!1}}editVideoRecording(e,t,i,a,l,c){return X(this,null,function*(){try{let d=Yr(this.functions,Zr({url:On?.cloudFunction?.videoBackend,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:36e5}),m=this.docService.getDocumentPaths();i?.metadata?.documentId&&(m=new bm({apiKey:this.configService.getApiKey(),clientDocumentId:i.metadata.clientDocumentId,clientOrganizationId:i.metadata.clientOrganizationId,documentId:i.metadata.documentId,organizationId:i.metadata.organizationId}));let u={databaseUrl:this.authService.getFirebaseConfig()?.firebaseOptions?.databaseURL,entirePath:m?.recorder+(i?.annotationId||""),fromUser:this.authService.getUser(),clientOrganizationId:m?.clientOrganizationId,clientDocumentId:m?.clientDocumentId,apiKey:this.configService.getApiKey(),sdkVersion:tl(),sdkType:this.configService.getSdkType(),useFirestore:this.commonDbService.shouldUseFirestore(),storageBucket:this.authService.getFirebaseConfig()?.firebaseOptions?.storageBucket,documentPath:m?.recorder,annotationId:i?.annotationId,annotationData:i,videoUrl:e,segments:t,zoomOptions:a,transcriptionEnabled:this.getRecordingTranscriptionEnabled(),type:l,backendUpload:!0};if(c){let V=yield c.arrayBuffer(),q=new Uint8Array(V),ae="";for(let ie=0;ie<q.length;ie++)ae+=String.fromCharCode(q[ie]);let ye=btoa(ae);u.videoBlobData=ye,u.videoBlobType=c.type,u.videoBlobSize=c.size}if(u?.useFirestore&&i){let V=yield this.recorderUtilsService.encryptRecorderAnnotation(i);u.annotationData=V}let _=this.documentPaths?.organizationId,I=this.documentPaths?.documentId;i?.metadata?.documentId&&(I=i.metadata.documentId,_=i.metadata.organizationId);let A=`${this.configService.getApiKey()}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${I}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`;_&&(A=`${this.configService.getApiKey()}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${_}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${I}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`),u.bucketPath=A;let M=yield d(u);if(l==="standalone"){let V=M?.data;if(V&&V?.videoData){let q=atob(V.videoData),ae=new ArrayBuffer(q.length),ye=new Uint8Array(ae);for(let Ie=0;Ie<q.length;Ie++)ye[Ie]=q.charCodeAt(Ie);let ie=new Blob([ye],{type:V.mimeType||"video/mp4"}),ge=document.createElement("a");ge.href=URL.createObjectURL(ie),ge.download="edited-video.mp4",document.body.appendChild(ge),ge.click(),document.body.removeChild(ge)}}return M}catch(d){throw this.loggingService.catch("Error in RecorderAnnotationService editVideoRecording: ",d),d}})}setVideoEditorAutoOpen(e){try{this.videoEditorAutoOpen$.next(h(h({},this.videoEditorAutoOpen$.value),e))}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setVideoEditorAutoOpen: ",t)}}getVideoEditorAutoOpen$(){try{return this.videoEditorAutoOpen$.asObservable()}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getVideoEditorAutoOpen: ",e),ce({})}}getVideoEditorAutoOpen(){try{return this.videoEditorAutoOpen$.value}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getVideoEditorAutoOpen: ",e),{}}}downloadLatestVideo(e){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: downloadLatestVideo","color: green;");let t=this.getAnnotationById(e);if(!t)return this.loggingService.catch("Recording not found with ID: "+e),!1;let i,a,l=t.latestVersion;if(l&&t.recordingEditVersions?.[l]?(i=t.recordingEditVersions[l].attachments?.[0]?.url,a=t.recordingEditVersions[l].attachments?.[0]?.name):(i=t.attachments?.[0]?.url||t.attachment?.url,a=t.attachments?.[0]?.name||t.attachment?.name),!i)return this.loggingService.catch("No video URL found for recording: "+e),!1;let c=yield fetch(i);if(!c.ok)return this.loggingService.catch("Failed to fetch video: "+c.statusText),!1;let d=yield c.blob(),m=document.createElement("a");return m.href=URL.createObjectURL(d),m.download=a||`recording-${e}.mp4`,document.body.appendChild(m),m.click(),document.body.removeChild(m),URL.revokeObjectURL(m.href),this.loggingService.log("Successfully downloaded video: "+a),!0}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService downloadLatestVideo: ",t),!1}})}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(Ft),K(st),K($n),K(yn),K(qe),K(Ve),K(eo),K(Vn),K(Do),K(fm),K(vn),K(Pp),K(Lo),K(k),K(mn),K(bS),K(Un),K(Dp),K(Ia),K(il),K(es))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var KWe=["access","accessFields"];function ZWe(n){return n?Object.keys(n).length>0:!1}var Re=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A,M,V,q,ae,ye,ie,ge,Ie,he,Te,Oe,Pe,$e,ze,We,gr){this.analyticsService=e,this.areaService=t,this.commonDbService=i,this.configService=a,this.docService=l,this.databaseService=c,this.authService=d,this.domService=m,this.afAuth=u,this.avatarService=_,this.contactService=I,this.storageService=A,this.functions=M,this.dialog=V,this.iamService=q,this.loggingService=ae,this.notificationService=ye,this.customFilterService=ie,this.reactionService=ge,this.hotkeyService=Ie,this.recorderService=he,this.viewsService=Te,this.buttonService=Oe,this.metadataService=Pe,this.commonDbUtilsService=$e,this.attachmentResolverService=ze,this.userPermissionService=We,this.recorderAnnotationService=gr,this.customPinsById=new Map,this.commentAdded$=new at,this.commentUpdated$=new at,this.commentAccepted$=new at,this.commentRejected$=new at,this.commentAnnotationDeleted$=new at,this.multiThreadCommentAnnotationDeleted$=new at,this.commentAnnotationById$=new _e(null),this.multiThreadCommentAnnotationById$=new _e(null),this.ghostCommentAnnotationMap$=new _e({}),this.unreadCommentsMap$=new _e(null),this.documentPaths=null,this.user=null,this.customCategoryMap=N.CommentCategoryMap,this.allowedElementIds$=new _e([]),this.allowedElementClassNames$=new _e([]),this.allowedElementQuerySelectors$=new _e([]),this.addCommentMode$=new _e(!1),this.persistentCommentMode$=new _e(!1),this.seenByUsers$=new _e(!0),this.deleteReplyConfirmation$=new _e(!1),this.persistentModeBanner$=new _e(!0),this.commentAddedEmitter=null,this.commentContextProvider=null,this.textCommentMode$=new _e(!0),this.sidebarVisible$=new _e(!1),this.sidebarOpenedByCustomTrigger$=new _e(!1),this.floatingCommentsEnabled$=new _e(!0),this.moderatorMode$=new _e(!1),this.streamMode$=new _e(!1),this.enableSignInButton$=new _e(!1),this.enableUpgradeButton$=new _e(!1),this.onSignInClick$=new at,this.onUpgradeClick$=new at,this.enableAttachment$=new _e(!0),this.enableAttachmentDownload$=new _e(!0),this.enableReactions$=new _e(!0),this.enableAnonymousEmail$=new _e(!0),this.enableFormatOptions$=new _e(!1),this.formatConfig$=new _e({bold:{enable:!0},italic:{enable:!0},underline:{enable:!0},strikethrough:{enable:!0}}),this.allowedRecordings$=new _e(["audio","video","screen"]),this.openSidebar$=new at,this.showScreenSizeInfo$=new _e(!1),this.showCommentIndex$=new _e(!1),this.popoverMode$=new _e(!1),this.popoverTriangleComponent$=new _e(!0),this.draftMode$=new _e(!0),this.enableDialogOnHover$=new _e(!0),this.enableDialogOnTargetElementClick$=new _e(!1),this.enablePriority$=new _e(!1),this.enableStatus$=new _e(!0),this.visibilityOptions$=new _e(!1),this.enableResolve$=new _e(!0),this.enableGhostComments$=new _e(!1),this.enableGhostCommentsMessage$=new _e(!0),this.inboxMode$=new _e(!1),this.enableAutoCategorize$=new _e(!1),this.commentContainerDarkMode$=new _e(!1),this.suggestionMode$=new _e(!1),this.mobileMode$=new _e(!0),this.inlineCommentMode$=new _e(!1),this.minimap$=new _e(!1),this.commentsOnDom$=new _e(!0),this.commentToolEnabled$=new _e(!0),this.totalMediaLength$=new _e(0),this.sidebarUrlNavigationEnabled$=new _e(!1),this.detectionStrategy$=new _e(wN.DEFAULT),this.sidebarButtonOnCommentDialogVisible$=new _e(!1),this.sidebarButtonOnCommentDialogClick$=new at,this.commentNavigationButtonClick$=new at,this.deviceIndicatorOnCommentPins$=new _e(!1),this.sidebarCommentClick$=new at,this.privateCommentMode$=new _e(!1),this.privateCommentAllowed$=new _e(!1),this.privateModeConfig$=new _e(null),this.scrollToComment$=new _e(!0),this.userMentions$=new _e(!0),this.paginatedContactList$=new _e(!1),this.deleteOnBackspace$=new _e(!0),this.hotkeyEnabled$=new _e(!1),this.recordingSummaryEnabled$=new _e(!0),this.unreadIndicatorMode$=new _e(p0.MINIMAL),this.composerMode$=new _e(BK.DEFAULT),this.enterKeyToSubmit$=new _e(!1),this.resolvedCommentsOnDom$=new _e(!1),this.bubbleOnPinEnabled$=new _e(!1),this.bubbleOnPinHoverEnabled$=new _e(!0),this.pinDragEnabled$=new _e(!0),this.excludeLocationIdsFromSidebar$=new _e([]),this.multiThread$=new _e(!1),this.groupMatchedComments$=new _e(!1),this.shortUserName$=new _e(!0),this.collapsedComments$=new _e(!1),this.fullExpanded$=new _e(!1),this.queryParamsComments$=new _e(!1),this.resolveStatusAccessAdminOnly$=new _e(!1),this.linkCallback$=new _e(!1),this.svgAsImg$=new _e(!1),this.commentToNearestAllowedElement$=new _e(!1),this.filterCommentsOnDom$=new _e(!1),this.maxReplyAvatars$=new _e(3),this.replyAvatars$=new _e(!1),this.commentplaceholder$=new _e(void 0),this.replyplaceholder$=new _e(void 0),this.editplaceholder$=new _e(void 0),this.editcommentplaceholder$=new _e(void 0),this.editreplyplaceholder$=new _e(void 0),this.screenshotEnabled$=new _e(!1),this.pinShadowDOM$=new _e(!0),this.dialogShadowDOM$=new _e(!0),this.dialogShadowDOMExplicit$=new _e(void 0),this.textCommentToolShadowDOM$=new _e(!0),this.pinDarkMode$=new _e(null),this.textCommentToolDarkMode$=new _e(null),this.textCommentToolbarDarkMode$=new _e(null),this.textCommentToolbarShadowDOM$=new _e(!0),this.sidebarShadowDOM$=new _e(!0),this.changeDetectionInCommentMode$=new _e(!1),this.commentSelectionChange$=new at,this.visibilityOptionClicked$=new at,this.submitComment$=new at,this.clearComposer$=new at,this.composerDataMap=new Map,this.commentsFromSidebarMap$=new _e(null),this.sidebarButtonCountType$=new _e("default"),this.filterGhostCommentsInSidebar$=new _e(!1),this.commentSidebarFilters$=new _e(null),this.effectiveSidebarFilters$=new _e({}),this.customSidebarDataAnnotationIds$=new _e(null),this.commentSidebarSystemFiltersOperator$=new _e(qc.AND),this.bubbleCommentAnnotationIds$=new _e([]),this.updateCommentDialogPositionTriggerSubject$=new _e(void 0),this.areaCommentEnabled$=new _e(!0),this.commentPinCursorImage$=new _e(""),this.commentAnnotationsFromCommentsContainer$=new _e([]),this.customChipDropdownData$=new _e(null),this.originalCommentAnnotationsByDocumentId$=new _e({}),this.draftCommentAnnotationsByAnnotationId$=new _e(null),this.draftMultiThreadCommentAnnotationsByAnnotationId$=new _e({}),this.pendingAddCommentAnnotationData=new Map,this.copyLink$=new _e(""),this.addCommentDragMode=!1,this.dragSubscriptions=[],this.hotkeySubscriptions=[],this.sidebarData$=new _e(null),this.sidebarCustomActionEventData$=new _e(null),this.sidebarCustomActionEventDataAllChanges$=new _e(null),this.sidebarCustomActionEventDataOnInit$=new _e(null),this.customActions$=new _e(!1),this.focusedThreadMode$=new _e(!1),this.openAnnotationInFocusMode$=new _e(!1),this.customStatusesShown$=new _e(!1),this.readOnly$=new _e(!1),this.customAutocompleteSearch$=new _e(!1),this.deleteThreadWithFirstComment$=new _e(!0),this.assignToType$=new _e("dropdown"),this.pageModeComposerContext$=new _e(null),this.contextInPageModeComposer$=new _e(!1),this.focusPageModeComposer$=new at,this.transformContext$=new _e(null),this.expandMentionGroups$=new _e(!1),this.showMentionGroupsFirst$=new _e(!1),this.showMentionGroupsOnly$=new _e(!1),this.fullScreenInSidebar$=new _e(!1),this.composerFileAttachments$=new _e(null),this.attachmentNameInMessage$=new _e(!1),this.allowedFileTypes$=new _e([]),this.forceCloseAllOnEsc$=new _e(!1),this.autoCompleteScrollConfig$=new _e({itemSize:55,minBufferPx:350,maxBufferPx:600,templateCacheSize:350}),this.commentAnnotationContextDraft=null,this.getCommentAnnotationForClient=nt=>{try{let Et=["commentCategories","color","resolved","inProgress","positionX","positionY","screenWidth","screenHeight","screenScrollHeight","screenScrollTop","taggedElementPath","taggedElementRect","targetElement","position","documentParamsId","documentParams","ghostComment","areaAnnotationId","iam","commentSource","involvedUserIds","mentionedUserIds","viewedByUserIds","views"],Je=JSON.parse(JSON.stringify(nt)),$t={};Object.keys(Je).forEach(Yn=>{Et.includes(Yn)||($t[Yn]=Je[Yn])}),$t?.comments?.forEach(Yn=>{let xr=[];Yn?.reactionAnnotationIds&&Yn?.reactionAnnotationIds?.forEach(Io=>{let Kn=this.reactionService.getAnnotationById(Io);if(Kn){let ao=this.reactionService.getReactionAnnotationForClient(Kn);xr.push(ao)}}),Yn.reactionAnnotations=xr}),Je?.viewedByUserIds?.forEach(Yn=>{let xr=this.contactService.getUserBySnippylyId(Yn);xr&&($t.viewedBy||($t.viewedBy=[]),$t.viewedBy.push(xr))}),this.user?.userSnippylyId&&($t.unread=!Je?.viewedByUserIds?.includes(this.user.userSnippylyId));let an=Je?.targetElement?.anchor?.fXPath||Je?.targetElement?.fXpath;return an&&($t.basicAnchorData={xpath:an,topPercentage:Je?.targetElement?.topPercentage||0,leftPercentage:Je?.targetElement?.leftPercentage||0}),JSON.parse(JSON.stringify($t))}catch{return null}},this.loggingService.log("%c[WB] Creating CLASS: CommentService","color: blue;"),this.analyticsService.setCommentService(this),this.contactService.setCommentService(this),this.notificationService.setCommentService(this),this.docService.setCommentService(this),this.authService.setCommentService(this),this.viewsService.setCommentService(this),this.reactionService.setCommentService(this),this.recorderAnnotationService.setCommentService(this),this.domService.getSelectedAnnotationsMap$().pipe(Qr(100),Fr()).subscribe(([nt,Et])=>{try{if(this.draftCommentAnnotationsByAnnotationId$.value){let Je=Object.keys(this.draftCommentAnnotationsByAnnotationId$.value||{}),$t=[];Object.keys(nt||{}).forEach(Yn=>{!Et?.[Yn]&&Je.includes(Yn)&&$t.push(Yn)});let an=JSON.parse(JSON.stringify(this.draftCommentAnnotationsByAnnotationId$.value||{}));$t.forEach(Yn=>{delete an[Yn]}),sr(an,this.draftCommentAnnotationsByAnnotationId$.value)||this.draftCommentAnnotationsByAnnotationId$.next(an)}}catch{}}),this.docService.getDocumentPaths$().pipe(Fr()).subscribe(([nt,Et])=>{nt?.documentId!==Et?.documentId&&this.unreadCommentsMap$.next(null),Et&&this.shouldEnableReadOnly()},nt=>{this.loggingService.catch("Error in CommentService getDocumentPaths$ subscription: ",nt)}),this.draftCommentAnnotationsByAnnotationId$.pipe(Fr()).subscribe(([nt,Et])=>{try{if(this.pendingAddCommentAnnotationData.size===0)return;let Je=Object.keys(nt||{});if(Je.length===0)return;let $t=new Set(Object.keys(Et||{}));Je.forEach(an=>{!$t.has(an)&&this.pendingAddCommentAnnotationData.has(an)&&this.pendingAddCommentAnnotationData.delete(an)})}catch(Je){this.loggingService.catch("Error in CommentService pendingAddCommentAnnotationData reconcile: ",Je)}}),this.authService.getUser$().subscribe(nt=>{nt||this.resetCacheData()},nt=>{this.loggingService.catch("Error in CommentService getUser$ subscription: ",nt)}),this.authService.getUser$().pipe(Se(nt=>nt?gn([this.iamService.isUserAdmin$(),this.contactService.getUserOrganizationContacts$()]).pipe(ue(([Et,Je])=>{let $t=!1;return Je?.find(an=>an.userId===nt?.userId)&&($t=!0),{isUserAdmin:Et,isOrgUser:$t}})):ce({isUserAdmin:!1,isOrgUser:!1}))).subscribe(({isUserAdmin:nt,isOrgUser:Et})=>{let Je=nt||Et;Je!==this.privateCommentAllowed$.value&&this.privateCommentAllowed$.next(Je)}),this.databaseService.getDb().pipe(Ge(nt=>!!nt),ut(1)).subscribe(nt=>{nt&&this.getDocumentPaths()},nt=>{this.loggingService.catch("Error in CommentService getDb subscription: ",nt)}),this.domService.onWindowPointerMove$().subscribe(nt=>{if(this.addCommentMode$.value){let Et=!0;if(this.addCommentDragMode)this.domService.removeClassFromElement(document.body,"show-pin-cursor");else{let Je=this.domService.getBackgroundElement(nt.clientX,nt.clientY,!0,!0);if(Je&&xhe(Je,{x:nt.clientX,y:nt.clientY})&&(Je=Je?.parentElement),Je)if(this.isElementInsideAllowedElements(Je))if(xg(nt.target))this.domService.removeClassFromElement(document.body,"show-pin-cursor");else{this.domService.addClassToElement(document.body,"show-pin-cursor"),this.hightlightElement&&this.hightlightElement!==Je&&this.domService.removeHighlightFromElement(this.hightlightElement),this.hightlightElement=Je;let $t=this.domService.getSelectedAnnotationsMap("comment")||{},an=this.commentPinCursorImage$.value||N.CURSOR.COMMENT_PIN;this.domService.highlightElement(this.hightlightElement,an,!!Object.keys($t)?.length),Et=!1}else this.domService.removeClassFromElement(document.body,"show-pin-cursor")}this.hightlightElement&&Et&&(this.domService.removeHighlightFromElement(this.hightlightElement),this.hightlightElement=null)}},nt=>{this.loggingService.catch("Error in CommentService onWindowPointerMove$ subscription: ",nt)}),this.domService.onWindowKeyupEsc$().subscribe(nt=>{if(this.addCommentMode$.value){let Et=this.domService.getSelectedAnnotationsMap("comment")||{};Object.keys(Et)?.length&&this.domService.resetSelectedAnnotationsMap(),this.disableAddCommentMode()}},nt=>{this.loggingService.catch("Error in CommentService onWindowKeyupEsc$ subscription: ",nt)}),this.domService.onDocumentClick$().subscribe(nt=>{if(nt&&!JN(nt)){let Et=this.domService.getSelectedAnnotationsMap("comment")||{};if(Et=h(h({},Et),this.domService.getSelectedAnnotationsMap("multiThread")||{}),Object.keys(Et)?.length&&(this.domService.resetSelectedAnnotationsMap(),this.persistentCommentMode$?.value)){this.addCommentMode$.value&&this.detectToAddAreaComment(),nt.preventDefault(),nt.stopPropagation();return}}if(nt&&this.addCommentMode$.value&&!xg(nt.target)){let Et=!1;if(this.addCommentDragMode)nt.preventDefault(),nt.stopPropagation(),this.addCommentDragMode=!1;else if(!this.domService.getDraftCommentAnnotationDialogs()?.length){let Je=this.domService.getBackgroundElement(nt.clientX,nt.clientY);if((this.persistentCommentMode$?.value&&this.domService.getBackgroundVeltElement(nt.clientX,nt.clientY)||nt&&JN(nt))&&(Je=null),Je&&(this.isElementInsideAllowedElements(Je)||this.getCommentToNearestAllowedElement()&&this.getNearestAllowedElement(Je))&&(Et=this.isElementInsideManualCommentContainer(Je),!Et)){nt.preventDefault(),nt.stopPropagation();let $t=this.freeStyleCommentContext&&typeof this.freeStyleCommentContext=="object"?JSON.parse(JSON.stringify(this.freeStyleCommentContext)):void 0;this.addComment(nt,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,$t)}}this.persistentCommentMode$?.value?this.detectToAddAreaComment():Et||this.disableAddCommentMode()}},nt=>{this.loggingService.catch("Error in CommentService onDocumentClick$ subscription: ",nt)}),this.addCommentMode$.subscribe(nt=>{this.hightlightElement&&this.domService.removeHighlightFromElement(this.hightlightElement),nt?(this.domService.addClassToElement(document.body,"snippyly-add-comment-mode"),this.detectToAddAreaComment(),this.addIframeContainerStaticAttribute()):(this.removeIframeContainerStaticAttribute(),this.domService.removeClassFromElement(document.body,"snippyly-add-comment-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"),this.dragSubscriptions.forEach(Et=>Et.unsubscribe()),this.clearFreeStyleCommentContext())},nt=>{this.loggingService.catch("Error in CommentService addCommentMode$ subscription: ",nt)}),this.domService.onWindowKeyupBackspace$().subscribe(nt=>{this.getDeleteOnBackspace()&&this.deleteCommentPinAnnotations("keyupBackspace")},nt=>{this.loggingService.catch("Error in CommentService onWindowKeyupBackspace$ subscription: ",nt)}),this.domService.onWindowKeyupDelete$().subscribe(nt=>{this.deleteCommentPinAnnotations("keyupDelete")},nt=>{this.loggingService.catch("Error in CommentService onWindowKeyupDelete$ subscription: ",nt)}),this.domService.getDeleteCommmentAnnotations$().subscribe(nt=>{nt?.length&&(nt?.filter(Je=>!["tag","recorder","rewriter","arrow","area","multiThread"].includes(Je.type))).forEach(Je=>X(this,null,function*(){yield this.deleteCommentPinAnnotation(Je)}))},nt=>{this.loggingService.catch("Error in CommentService onWindowKeyupDelete$ subscription: ",nt)}),this.getPopoverMode$().subscribe(nt=>{nt?document?.body?.setAttribute(N.ATTRIBUTES.VELT_POPOVER_MODE,"true"):document?.body?.removeAttribute(N.ATTRIBUTES.VELT_POPOVER_MODE)},nt=>{this.loggingService.catch("Error in CommentService getPopoverMode subscription: ",nt)}),this.customFilterService.customCategoryMap$.subscribe(nt=>{this.customCategoryMap=nt},nt=>{this.loggingService.catch("Error in CommentService customCategoryMap$ subscription: ",nt)}),this.hotkeyEnabled$.subscribe(nt=>{nt?this.subscribeHotkeyEvents():this.unsubscribeHotkeyEvents()},nt=>{this.loggingService.catch("Error in CommentService hotkeyEnabled$ subscription: ",nt)}),this.domService.getSelectedAnnotationsMap$().pipe(Fr()).subscribe(([nt,Et])=>{try{let Je=Object.values(nt||{}).filter(an=>!["tag","recorder","rewriter","arrow","area"].includes(an.type)),$t=Object.values(Et||{}).filter(an=>!["tag","recorder","rewriter","arrow","area"].includes(an.type));Je?.forEach(an=>{$t?.find(Yn=>Yn.annotationId===an.annotationId)||this.commentSelectionChange$.next({annotation:this.getCommentAnnotationForClient(an),selected:!1})}),$t?.forEach(an=>{Je?.find(Yn=>Yn.annotationId===an.annotationId)||this.commentSelectionChange$.next({annotation:this.getCommentAnnotationForClient(an),selected:!0})})}catch(Je){this.loggingService.catch("Error in CommentService getSelectedAnnotationsMap$: ",Je)}},nt=>{this.loggingService.catch("Error in CommentService getSelectedAnnotationsMap$ subscription: ",nt)})}clearCache(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in CommentService","color: green;"),this.commentAnnotationById$.next(null),this.draftCommentAnnotationsByAnnotationId$.next(null),this.multiThreadCommentAnnotationById$.next({}),this.draftMultiThreadCommentAnnotationsByAnnotationId$.next({}),this.pendingAddCommentAnnotationData.clear(),this.customAutocompleteSearch$.next(!1),this.hightlightElement=null,this.addCommentMode$.next(!1),this.unreadCommentsMap$.next(null),this.documentPaths=null,this.commentsFromSidebarMap$.next(null),this.customSidebarDataAnnotationIds$.next(null)}catch(e){this.loggingService.catch("Error in CommentService clearCache: ",e)}}setCommentActionsService(e){try{this.commentActionsService=e}catch(t){this.loggingService.catch("Error in CommentService setCommentActionsService: ",t)}}detectToAddAreaComment(){try{let e=this.areaService.getAreaEnabled(),t=this.getAreaCommentEnabled();if(e&&t){let i,a,l,c=null,d=null;this.dragSubscriptions.forEach(m=>m.unsubscribe()),this.dragSubscriptions.push(this.domService.onWindowMouseDown$().pipe(Ge(m=>!(m&&JN(m))),ut(1)).subscribe(m=>{c=null,d=null,this.dragSubscriptions.push(this.domService.getClickAndDragPointsObservable().subscribe(u=>{if(c===null){let _=u?.startPoint?.event?.target,I=Mo(_),A=xg(_),M=this.isElementInsideAllowedElements(_);c=!I&&!A&&M}if(c){this.addCommentDragMode=!0,i=u.startPoint,a=u.curPoint;let _=u?.curPoint?.event?.target,I=Mo(_),A=xg(_),M=this.isElementInsideAllowedElements(_);d=!I&&!A&&M,d?l=this.domService.drawRectangle(i,a):l?.remove()}})),this.domService.onWindowPointerUp$().pipe(Dd(1),ut(1)).subscribe(u=>{if(a={x:u.clientX,y:u.clientY},i&&a&&(l?.remove(),c&&d)){let _=[{x:i.x-window.scrollX,y:i.y-window.scrollY},{x:a.x,y:a.y}],I=this.freeStyleCommentContext&&typeof this.freeStyleCommentContext=="object"?JSON.parse(JSON.stringify(this.freeStyleCommentContext)):void 0;this.addComment(u,void 0,_,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,I)}this.dragSubscriptions.forEach(_=>_.unsubscribe())})}))}}catch(e){this.loggingService.catch("Error in CommentService detectToAddAreaComment: ",e)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling CommentService FUNCTION: resetCacheData","color: green;"),this.commentAnnotationById$.next(null),this.draftCommentAnnotationsByAnnotationId$.next(null),this.multiThreadCommentAnnotationById$.next({}),this.draftMultiThreadCommentAnnotationsByAnnotationId$.next({}),this.pendingAddCommentAnnotationData.clear()}catch(e){this.loggingService.catch("Error in CommentService resetCacheData: ",e)}}addAreaContainerTag(){try{if(!(document.querySelector(N.TAGS.VELT_AREAS)||document.querySelector(N.TAGS.SNIPPYLY_AREAS))){let t=document.createElement(N.TAGS.VELT_AREAS);document.body.appendChild(t)}}catch(e){this.loggingService.catch("Error in CommentService addAreaContainerTag: ",e)}}addIframeContainerStaticAttribute(){try{document.querySelectorAll(`[${N.ATTRIBUTES.VELT_IFRAME_CONTAINER}]`).forEach(t=>{window.getComputedStyle(t).position==="static"&&t.setAttribute(N.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC,"true")})}catch(e){this.loggingService.catch("Error in CommentService addIframeContainerStaticAttribute: ",e)}}removeIframeContainerStaticAttribute(){try{document.querySelectorAll(`[${N.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC}]`).forEach(t=>{t.removeAttribute(N.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC)})}catch(e){this.loggingService.catch("Error in CommentService removeIframeContainerStaticAttribute: ",e)}}subscribeHotkeyEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: subscribeHotkeyEvents","color: green;"),this.unsubscribeHotkeyEvents(),this.hotkeySubscriptions.push(this.hotkeyService.getKeyPressEvent("c").subscribe(e=>{e&&!this.addCommentMode$.value&&this.enableAddCommentMode()},e=>{this.loggingService.catch("Error in CommentService hotkeyService.getKeyPressEvent subscription: ",e)}))}catch(e){this.loggingService.catch("Error in CommentService subscribeHotkeyEvents: ",e)}}unsubscribeHotkeyEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribeHotkeyEvents","color: green;"),this.hotkeySubscriptions.forEach(e=>e?.unsubscribe())}catch(e){this.loggingService.catch("Error in CommentService unsubscribeHotkeyEvents: ",e)}}setCommentAddedEmitter(e){try{this.commentAddedEmitter=e}catch(t){this.loggingService.catch("Error in CommentService setCommentAddedEmitter: ",t)}}setContextProvider(e){try{this.commentContextProvider=e}catch(t){this.loggingService.catch("Error in CommentService setContextProvider: ",t)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$()}getAnonymousAvatarImage(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAnonymousAvatarImage","color: green;"),this.avatarService.generateUserImage()}setAllowedElementIds(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{allowedElementIds:e}}),this.allowedElementIds$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementIds: ",t)}}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}setAllowedElementClassNames(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{allowedElementClassNames:e}}),this.allowedElementClassNames$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementClassNames: ",t)}}getAllowedElementClassNames(){return this.allowedElementClassNames$.asObservable()}setAllowedElementQuerySelectors(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{allowedElementQuerySelectors:e}}),this.allowedElementQuerySelectors$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementQuerySelectors: ",t)}}getAllowedElementQuerySelectors(){return this.allowedElementQuerySelectors$.asObservable()}getAllCommentAnnotations({customClientDocumentId:e,params:t,excludeDomChanges:i,detectGhostComments:a,skipPositionCalculation:l,query:c,fromCommentSidebar:d,analytics:m,addFilterCommentsOnDomCheck:u}){this.loggingService.log("%c[WB] Calling FUNCTION: getAllCommentAnnotations","color: green;");let _,I,A;m?.enabled&&this.analyticsService.trackEvent(m?.eventName||Y.Events.Comments.GET_ALL_COMMENT_ANNOTATIONS_TRIGGERED_INTERNAL,m?.properties);try{if(e&&(A=`${er(e)}`),t&&typeof t=="object"){let M=Oi(t);I=M?.id,_=er(JSON.stringify(M))}}catch(M){this.loggingService.catch("Error in CommentService getAllCommentAnnotations: ",M)}return _r(this.afAuth).pipe(Ge(M=>!!M),Se(M=>this.isFeatureAllowed({firebaseUser:M,annotations:[],filteredAnnotations:[]})),Se(M=>M.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(V=>(M.featureAllowed=V,M))):ce(M)),Se(M=>M.featureAllowed?ce(M).pipe(Se(V=>this.docService.getDocumentPaths$().pipe(ue(q=>(this.documentPaths=q,V.documentPaths=q,V)))),Se(V=>c?.documentIds?.length||A?this.getDataFromDocumentIds({documentIds:A?[A]:c?.documentIds?.map(q=>`${er(q)}`),organizationId:this.documentPaths?.organizationId,query:c}).pipe(ue(q=>({res:V,data:q}))):this.docService.getDocumentIds$().pipe(Se(q=>{let ae=q?.length>0?q.map(ye=>ye.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds({documentIds:ae.length>0?ae:[A??""],organizationId:this.documentPaths?.organizationId,query:c}).pipe(ue(ye=>({res:V,data:ye})))}))),Se(V=>V?.data?(V.res.annotations=V.data||[],ce(V.res).pipe(Se(q=>this.docService.getLocation$().pipe(ue(ae=>(q.location=ae,q)))),Se(q=>this.docService.getLocations$().pipe(ue(ae=>(q.customLocations=ae,q)))),Se(q=>this.docService.getExcludedLocationIds$().pipe(ue(ae=>(q.excludedLocationIds=ae,q)))),ue(q=>{if(q.filteredAnnotations=[],c)return q.filteredAnnotations=q.annotations?.slice(),q;if(A&&!_||d)return q.filteredAnnotations=q.annotations?.slice(),q?.excludedLocationIds?.length&&(q.filteredAnnotations=q.filteredAnnotations?.filter(ae=>ae?.location?.id?!q.excludedLocationIds.includes(ae.location.id):!0)),q;{let ae=[],ye=[];return _?(ae.push(_),I&&ye.push(I)):(ae.push(q?.location?.locationId),ae.push(...Object.values(q?.customLocations||[]).map(ie=>ie.locationId)),q?.location?.location?.id&&ye.push(q?.location?.location?.id),ye.push(...Object.values(q?.customLocations||{}).map(ie=>ie.location?.id).filter(ie=>!!ie))),q.filteredAnnotations=this.filterAnnotationsByLocationIds(q?.annotations,ae,ye),q?.excludedLocationIds?.length&&(q.filteredAnnotations=q.filteredAnnotations?.filter(ie=>ie?.location?.id?!q.excludedLocationIds.includes(ie.location.id):!0)),q}}),Se(q=>this.isPrivateCommentAllowed$().pipe(ue(ae=>(ae||(q.filteredAnnotations=q.filteredAnnotations?.filter(ye=>!El(ye))),q)))),Se(q=>this.draftCommentAnnotationsByAnnotationId$.pipe(ue(ae=>(q.filteredAnnotations=q.filteredAnnotations?.filter(ye=>!ye.isDraft),ae&&q.filteredAnnotations.push(...Object.values(ae)),q)))),Se(q=>i?ce(q):q?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onWindowResize$().pipe(ue(()=>q)):ce(q)),Se(q=>i?ce(q):this.addCommentMode$.pipe(Se(ae=>ae&&!this.getChangeDetectionInCommentMode()?ce(q):q?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onDomChange$("CommentService getAllCommentAnnotations").pipe(ue(()=>q)):ce(q)))),ue(q=>{if(!l){(!this.getPopoverMode()||this.getPopoverTriangleComponent())&&(q.filteredAnnotations=q.filteredAnnotations?.map(ye=>{let ie=Object.assign({},ye);return this.calculateCommentAnnotationPosition(ie,a),ie}));let ae={};q.filteredAnnotations?.forEach(ye=>{if(ye?.targetTextRange){let ie=this.domService.getElementFromTargetTextRange(ye?.targetTextRange);ae[ye.annotationId]=!!ie}}),q.textAnnotationsElementMap=ae}return q}),Se(q=>q?.annotations?.length?this.viewsService.getCommentFeatureViews$().pipe(ue(ae=>(this.updateUnreadAnnotationsMap(q?.annotations,ae),q))):(ZWe(this.unreadCommentsMap$.value)&&this.unreadCommentsMap$.next({}),ce(q))))):ce(null))):ce(null)),ue(M=>{try{return typeof M=="object"&&M?JSON.parse(JSON.stringify(M)):M}catch{return M}}),_t((M,V)=>Kt(M?.filteredAnnotations,V?.filteredAnnotations)&&Kt(M?.textAnnotationsElementMap,V?.textAnnotationsElementMap)),Se(M=>M?M?.filteredAnnotations?ce(M?.filteredAnnotations||[]):ce([]):ce(null)),Se(M=>u?this.filterCommentsUsingSidebarSettings(M):ce(M)))}getAllMultiThreadCommentAnnotations(e,t,i,a,l,c){this.loggingService.log("%c[WB] Calling FUNCTION: getAllMultiThreadCommentAnnotations","color: green;");let d,m;try{if(e&&(m=er(e)),t&&typeof t=="object"){let u=Oi(t);d=er(JSON.stringify(u))}}catch(u){this.loggingService.catch("Error in CommentService getAllMultiThreadCommentAnnotations: ",u)}return _r(this.afAuth).pipe(Ge(u=>!!u),Se(u=>this.isFeatureAllowed({firebaseUser:u,annotations:[],filteredAnnotations:[]})),Se(u=>u.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(_=>(u.featureAllowed=_,u))):ce(u)),Se(u=>u.featureAllowed?ce(u).pipe(Se(_=>this.docService.getDocumentPaths$().pipe(ue(I=>(this.documentPaths=I,_.documentPaths=I,_)))),Se(_=>m?this.getMultiThreadDataFromDocumentIds([m]).pipe(ue(I=>({res:_,data:I}))):this.docService.getDocumentIds$().pipe(Se(I=>{let A=I?.length>0?I.map(M=>M.documentId):[this.documentPaths?.documentId??""];return this.getMultiThreadDataFromDocumentIds(A.length>0?A:[`${m}`]).pipe(ue(M=>({res:_,data:M})))}))),Se(({res:_,data:I})=>I?(_.annotations=I||[],ce(_).pipe(Se(A=>this.docService.getLocation$().pipe(ue(M=>(A.location=M,A)))),Se(A=>this.docService.getLocations$().pipe(ue(M=>(A.customLocations=M,A)))),Se(A=>this.docService.getExcludedLocationIds$().pipe(ue(M=>(A.excludedLocationIds=M,A)))),ue(A=>{if(A.filteredAnnotations=[],m&&!d)return A.filteredAnnotations=A.annotations?.slice(),A?.excludedLocationIds?.length&&(A.filteredAnnotations=A.filteredAnnotations?.filter(M=>M?.location?.id?!A.excludedLocationIds.includes(M.location.id):!0)),A;{let M=[],V=[];return d?M.push(d):(M.push(A?.location?.locationId),M.push(...Object.values(A?.customLocations||[]).map(q=>q.locationId)),A?.location?.location?.id&&V.push(A?.location?.location?.id),V.push(...Object.values(A?.customLocations||{}).map(q=>q.location?.id).filter(q=>!!q))),A.filteredAnnotations=this.filterAnnotationsByLocationIds(A?.annotations,M,V),A?.excludedLocationIds?.length&&(A.filteredAnnotations=A.filteredAnnotations?.filter(q=>q?.location?.id?!A.excludedLocationIds.includes(q.location.id):!0)),A}}),Se(A=>this.draftMultiThreadCommentAnnotationsByAnnotationId$.pipe(ue(M=>(A.filteredAnnotations=A.filteredAnnotations?.filter(V=>!V.isDraft),M&&A.filteredAnnotations.push(...Object.values(M)),A)))),Se(A=>i?ce(A):A?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onWindowResize$().pipe(ue(()=>A)):ce(A)),Se(A=>i?ce(A):this.addCommentMode$.pipe(Se(M=>M&&!this.getChangeDetectionInCommentMode()?ce(A):A?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onDomChange$("CommentService getAllMultiThreadCommentAnnotations").pipe(ue(()=>A)):ce(A)))),ue(A=>(l||(!this.getPopoverMode()||this.getPopoverTriangleComponent())&&(A.filteredAnnotations=A.filteredAnnotations?.map(M=>{let V=Object.assign({},M);return this.calculateCommentAnnotationPosition(V,a),V})),A)),Se(A=>A?.filteredAnnotations?ce(A?.filteredAnnotations||[]):ce([])))):ce(null))):ce(null)),_t(Kt),Se(u=>c?this.filterCommentsUsingSidebarSettings(u):ce(u)))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})),Se(t=>this.authService.getUser$().pipe(ue(i=>(this.user=i,y(h({},t),{user:i}))))),Se(t=>Ao(t.config,t.user,je.COMMENT)?ce(y(h({},t),{featureAllowed:!0})):(this.loggingService.warn("Comment feature is not allowed."),ce(y(h({},t),{featureAllowed:!1})))),_t((t,i)=>t?.featureAllowed===i?.featureAllowed))}buildVisibilityTokens(e,t,i){try{let a=It(t),l=[N.DEFAULT_VELT_CONTEXT,`${N.VISIBILITY_SELF_PREFIX}${a}`],c=e?.[t];return i&&c?.organization?.[i]?.accessRole&&l.push(`organizationPrivate:${i}`),l}catch(a){return this.loggingService.catch("Error in CommentService buildVisibilityTokens: ",a),[N.DEFAULT_VELT_CONTEXT]}}getDataFromDocuments(e){let{documentIds:t,organizationId:i,query:a}=e;if(!this.configService?.getApiKey())return ce(null);if(t?.some(A=>!A)||!this.documentPaths)return ce(null);let l,c,d=[];if(a)a?.folderId&&(l=Lr(a?.folderId)),a?.locationId&&(d=[...d,a?.locationId]),a?.locationIds?.length&&(d=[...d,...a?.locationIds]),c=a?.statusIds;else{l=this.docService.getDocumentPaths()?.veltFolderId;let A=this.docService.getDocumentPaths()?.locationId;A&&(d=[...d,A])}let m={useCollectionGroup:!0,isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(m.documentId=t?.length?t[0]:void 0,m.organizationId=this.documentPaths?.organizationId);let u=this.authService.getUser()?.userId;if(!u)return ce(null);let _=this.authService.getIsPrivateCommentsEnabled();return(_?this.userPermissionService.getCurrentUserPermissionsWithServerIds$().pipe(Ge(A=>A!==null&&!!A[u])):ce(null)).pipe(Se(A=>{let M=_?this.buildVisibilityTokens(A,u,i??this.documentPaths?.organizationId):[N.DEFAULT_VELT_CONTEXT],V=this.userPermissionService?.getIsContextEnabled()?this.docService.getProcessedDocContext():[],q=[...M,...V],ae=this.userPermissionService?.getIsContextEnabled(),ye;if(ae){let ie=[];for(let ge=0;ge<q.length;ge+=N.LISTENER_CONTEXT_BATCH_SIZE)ie.push(q.slice(ge,ge+N.LISTENER_CONTEXT_BATCH_SIZE));this.loggingService.logContext("[CONTEXT] getDataFromDocuments called with accessFields:",JSON.parse(JSON.stringify(q??"nil"))),ye=gn(ie.map(ge=>this.commonDbService.dbListener({feature:"allComments",properties:y(h({},m),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.organizationId","==",i??this.documentPaths?.organizationId),ft("metadata.documentId","in",t),...c?.length?[ft("status.id","in",c)]:[],...l?[ft("metadata.veltFolderId","==",l)]:[],...d?.length?[ft("location.id","in",d)]:[],...ge?.length?[ft("context.accessFields","array-contains-any",ge)]:[]),uo("lastUpdated","desc"),uo("createdAt","desc")]})}).pipe(la()))).pipe(ue(ge=>Na(JSON.parse(JSON.stringify(ge)))))}else{let ie=[];for(let ge=0;ge<(t?.length??0);ge+=N.LISTENER_BATCH_SIZE)ie.push(t?.slice(ge,ge+N.LISTENER_BATCH_SIZE)??[]);ye=gn(ie.map(ge=>this.commonDbService.dbListener({feature:"allComments",properties:y(h({},m),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.organizationId","==",i??this.documentPaths?.organizationId),ft("metadata.documentId","in",ge),...c?.length?[ft("status.id","in",c)]:[],...l?[ft("metadata.veltFolderId","==",l)]:[],...d?.length?[ft("location.id","in",d)]:[],...q?.length&&_?[ft("context.accessFields","array-contains-any",q)]:[]),uo("lastUpdated","desc"),uo("createdAt","desc")]})}).pipe(la()))).pipe(ue(ge=>Na(JSON.parse(JSON.stringify(ge)))))}return ye.pipe(Se(ie=>ie?.data?ce(ie).pipe(Se(ge=>this.commonDbUtilsService.mergeLocationMetadataWithData$({data:ge,feature:"allComments"}).pipe(ue(Ie=>({data:Object.values(Ie?.data||{}).filter(he=>typeof he=="object"),operation:Ie?.operation})))),ue(({data:ge,operation:Ie})=>{let he=ge.reduce((Te,Oe)=>{let Pe=Oe.metadata?.documentId;return Pe&&(Te[Pe]||(Te[Pe]=[]),Te[Pe].push(Oe)),Te},{});return{data:ge,documentMap:he,operation:Ie}}),ue(({data:ge,documentMap:Ie,operation:he})=>c?{data:ge,documentMap:Ie,operation:he}:(ge?.length&&(ge?.forEach(Te=>{this.sanitizeCommentAnnotation(Te)}),this.setAnnotationIndex(ge),this.updateAnnotationsForSelectAllContentMode(ge),ge.forEach(Te=>{this.customFilterService.convertLegacyAnnotationStatus(Te),this.customFilterService.convertLegacyPriority(Te),this.customFilterService.convertLegacyCategory(Te)})),{data:ge,documentMap:Ie,operation:he})),Xn(ge=>(this.loggingService.catch("Error in CommentService getDataFromDocuments: ",ge),ce([]))),ln(({documentMap:ge})=>{c||Object.entries(ge??{}).forEach(([Ie,he])=>{this.setOriginalCommentAnnotationsByAnnotationId(JSON.parse(JSON.stringify(he)))})}),ue(({data:ge,documentMap:Ie,operation:he})=>({data:this.filterUserDraftComments(ge),documentMap:Ie,operation:he})),ue(({data:ge,documentMap:Ie,operation:he})=>({data:this.removeDraftFlags(ge),documentMap:Ie,operation:he})),Se(({data:ge,documentMap:Ie,operation:he})=>c?ce({data:ge,documentMap:Ie,operation:he}):this.mergeDraftAnnotations(ge).pipe(ue(Te=>({data:Te,documentMap:Ie,operation:he})))),ue(({data:ge,documentMap:Ie,operation:he})=>{if(!c)if(he?.type==="removed"){if(he?.ids?.length){let Te=this.commentAnnotationById$.value??{};he?.ids?.forEach(Oe=>{delete Te?.[Oe]}),this.commentAnnotationById$.next(Te)}}else Object.entries(Ie??{}).length?Object.entries(Ie??{}).forEach(([Oe,Pe])=>{this.setCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:Oe,annotations:Pe})}):this.commentAnnotationById$.value||this.commentAnnotationById$.next({});return ge})):ce(null)))}))}fetchCommentAnnotations(e){return X(this,null,function*(){try{let t=this.authService.getUser();if(!t)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),{data:[],hasMore:!1};let i=this.configService?.getApiKey(),a=e?.organizationId??t?.clientOrganizationId,l=ba(a??""),c=[];e?.allDocuments||(c=e?.documentIds?.map(M=>mi(M??""))??this.docService.getDocumentIds()?.map(M=>M.documentId));let d=[];if(d.push(ft("metadata.organizationId","==",l)),d.push(ft("metadata.apiKey","==",i)),e?.folderId){let M=Lr(e?.folderId);d.push(ft("metadata.veltFolderId","==",M))}if(e?.locationId&&d.push(ft("location.id","==",e?.locationId)),c?.length&&d.push(ft("metadata.documentId","in",c)),e?.resolvedBy){if(e?.order==="asc")throw new Error("Order by resolvedBy is not supported in ascending order.");d.push(ft("resolvedByUserId","==",e?.resolvedBy))}if(e?.mentionedUserIds?.length){if(e?.order==="asc")throw new Error("Order by mentionedUserIds is not supported in ascending order.");d.push(ft("mentionedUserIds","array-contains-any",e?.mentionedUserIds))}if(e?.userIds?.length){if(e?.order==="asc")throw new Error("Order by userIds is not supported in ascending order.");d.push(ft("from.userId","in",e?.userIds))}if(e?.statusIds?.length){if(e?.order==="asc")throw new Error("Order by status id is not supported in ascending order.");d.push(ft("status.id","in",e?.statusIds))}let m=new Date().getTime();if(e?.createdAfter&&d.push(ft("createdAt",">=",e?.createdAfter)),e?.createdBefore&&d.push(ft("createdAt","<=",e?.createdBefore??m)),e?.updatedAfter&&d.push(ft("lastUpdated",">=",e?.updatedAfter??m)),e?.updatedBefore&&d.push(ft("lastUpdated","<=",e?.updatedBefore??m)),d.push(uo("lastUpdated",e?.order??"desc"),uo("createdAt",e?.order??"desc")),e?.pageToken){let M=yield WK(e?.pageToken??"","veltencrypttoken","veltencrypttoken");d.push(sbe(parseInt(M,10),"lastUpdated"))}let u=e?.pageSize??100;d.push(hm(u+1));let _=yield this.commonDbService.queryData({feature:"allComments",properties:{useCollectionGroup:!0,isCollection:!0,useQuery:!0,firestoreQuery:d,apiKey:i??"",organizationId:l}}),I=_.length>u;_=_.slice(0,u);let A=_?.reduce((M,V)=>(M[V?.annotationId]=V,M),{});return A=yield this.commonDbUtilsService.formatResponse({feature:"allComments",data:A,shouldAwait:!0}),A=this.commonDbUtilsService.mergeUsersWithData({feature:"allComments",data:A}),{data:Object.values(A??{}),hasMore:I}}catch(t){throw this.loggingService.catch("Error in CommentService fetchCommentAnnotations:",t),t}})}filterUserDraftComments(e){let t=this.authService.getUser();return e.filter(i=>(i.comments=i?.comments?.filter(a=>a?.from?.userId===t?.userId||!a?.isDraft),!!i?.comments?.length))}removeDraftFlags(e){return e.forEach(t=>delete t.isDraft),e}mergeDraftAnnotations(e){return this.draftCommentAnnotationsByAnnotationId$.pipe(ue(t=>{let i=t||{};return e?.filter(a=>{i?.[a?.annotationId]&&delete i[a?.annotationId]}),i}),ue(t=>{if(t){let i=e.slice();return i.push(...Object.values(t)),i}return e}))}getDataFromDocumentIds({documentIds:e,organizationId:t,query:i}){return this.getDataFromDocuments({documentIds:e,organizationId:t,query:i})}getMultiThreadDataFromDocumentIds(e){return this.getMultiThreadDataFromDocuments({documentIds:e})}getMultiThreadDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t}=e;if(t?.some(c=>!c)||!this.documentPaths)return ce(null);let i=this.docService.getDocumentPaths()?.veltFolderId,a=ce([]),l={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(l.documentId=t?.length?t[0]:void 0,l.organizationId=this.documentPaths?.organizationId),this.userPermissionService?.getIsContextEnabled()){let c=[N.DEFAULT_VELT_CONTEXT,...this.docService.getProcessedDocContext()],d=[];for(let m=0;m<(c?.length??0);m+=N.LISTENER_CONTEXT_BATCH_SIZE)d.push(c?.slice(m,m+N.LISTENER_CONTEXT_BATCH_SIZE)??[]);a=gn(d.map(m=>this.commonDbService.dbListener({feature:"allMultiThreads",properties:y(h({},l),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.organizationId","==",this.documentPaths?.organizationId),ft("metadata.documentId","in",t),...i?[ft("metadata.veltFolderId","==",i)]:[],...m?.length?[ft("context.accessFields","array-contains-any",m)]:[])]})}).pipe(la()))).pipe(ue(m=>Na(m)))}else{let c=[];for(let d=0;d<(t?.length??0);d+=N.LISTENER_BATCH_SIZE)c.push(t?.slice(d,d+N.LISTENER_BATCH_SIZE)??[]);a=gn(c.map(d=>this.commonDbService.dbListener({feature:"allMultiThreads",properties:y(h({},l),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.organizationId","==",this.documentPaths?.organizationId),ft("metadata.documentId","in",d),...i?[ft("metadata.veltFolderId","==",i)]:[])]})}).pipe(la()))).pipe(ue(d=>Na(d)))}return a.pipe(Se(c=>c?.data?ce(c).pipe(ue(d=>({data:d?.data,operation:d?.operation})),ue(({data:d,operation:m})=>{let u=[];return d&&(u=Object.values(d??{}).filter(_=>typeof _=="object")),{data:u,operation:m}}),Xn(d=>(this.loggingService.catch("Error in CommentService getMultiThreadDataFromDocumentId: ",d),ce({data:[],operation:null}))),ue(({data:d,operation:m})=>{d.forEach(_=>{delete _.isDraft});let u=d.reduce((_,I)=>{let A=I.metadata?.documentId;return A&&(_[A]||(_[A]=[]),_[A].push(I)),_},{});return{data:d,documentMap:u,operation:m}}),Se(({data:d,documentMap:m,operation:u})=>{let _=[];return this.commentAnnotationById$.pipe(Se(()=>this.domService.getSelectedAnnotationsMap$().pipe(ue(I=>({selectedAnnotationsMap:I})))),ue(({selectedAnnotationsMap:I})=>{let A={};return Object.keys(m??{}).forEach(M=>{let V=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:M});V&&V?.forEach(q=>{A[q?.annotationId]=q})}),_=d.filter(M=>{let V=!1;if(M?.commentAnnotations){for(let q in M?.commentAnnotations)if(A?.[q]&&A?.[q]?.status?.id!==this.customFilterService.resolvedStatus.id){V=!0;break}}return V}),_.forEach(M=>{Object.keys(M?.commentAnnotations||{}).forEach(V=>{M.commentAnnotationsMap||(M.commentAnnotationsMap={}),M.commentAnnotationsMap[V]=A?.[V]})}),{data:_,operation:u}}))}),Se(({data:d,operation:m})=>this.draftMultiThreadCommentAnnotationsByAnnotationId$.pipe(ue(u=>{let _=u||{};return d?.filter(I=>{_?.[I?.annotationId]&&delete _[I?.annotationId]}),_}),ue(u=>{if(u){let _=d.slice();return _.push(...Object.values(u)),{data:_,operation:m}}return{data:d,operation:m}}))),ue(({data:d,operation:m})=>{let u=d.reduce((_,I)=>{let A=I.metadata?.documentId;return A&&(_[A]||(_[A]=[]),_[A].push(I)),_},{});if(m?.type==="removed"){if(m?.ids?.length){let _=this.multiThreadCommentAnnotationById$.value;m?.ids?.forEach(I=>{delete _?.[I]}),this.multiThreadCommentAnnotationById$.next(_)}}else Object.keys(u??{}).forEach(_=>{this.setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:_,annotations:u[_]})});return d})):ce(null)))}else return ce(null)}updateUnreadAnnotationsMap(e,t){try{let i=new Date(N.UNREAD_COMMENTS_CHECK_FROM_DATE)?.getTime(),a=e.filter(l=>l?.lastUpdated>i);if(t){let l={},c=!1;a.forEach(d=>{let m=0,u=t?.[d?.annotationId];if(u){let _=u?.comments;_&&d?.comments?.forEach(I=>{_?.[I?.commentId]?.views?.[this.user?.userSnippylyId]||m++})}m?m!==l?.[d?.annotationId]&&(l[d?.annotationId]=m,c=!0):l?.[d?.annotationId]&&(delete l[d?.annotationId],c=!0)}),this.unreadCommentsMap$.next(l)}}catch(i){this.loggingService.catch("Error in CommentService updateUnreadAnnotationsMap:",i)}}updateAnnotationsForSelectAllContentMode(e){try{e.forEach(t=>{if(t?.selectAllContent&&t?.targetElementId){let i=nl(t.targetElementId,["id","data-id"]);if(i){let a=i.textContent;a&&(t.targetTextRange={commonAncestorContainer:this.domService.getXPath(i),text:a,occurrence:1,commonAncestorContainerAnchor:this.domService.generateAnchorRecord(i)??void 0},delete t?.targetElement)}}})}catch(t){this.loggingService.catch("Error in CommentService updateAnnotationsForSelectAllContentMode:",t)}}setCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:i,queryHash:a}){try{if(t){e||(e=N.NO_ORGANIZATION_ID),a||(a=N.DEFAULT_QUERY_HASH);let l={};i?.forEach(d=>{d?.annotationId&&(l[d?.annotationId]=d)});let c=h(h({},this.commentAnnotationById$.value??{}),l);this.commentAnnotationById$.next(c)}}catch(l){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",l)}}getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e,documentId:t}){try{return this.commentAnnotationById$.pipe(Se(()=>this.draftCommentAnnotationsByAnnotationId$),ue(()=>this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t})))}catch(i){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByOrganizationIdAndDocumentId$:",i),ce([])}}getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let i=null;this.commentAnnotationById$.value&&(i={},Object.values(this.commentAnnotationById$.value).forEach(l=>{l?.metadata?.documentId==t&&l?.metadata?.organizationId==e&&(i[l?.annotationId]=l)}));let a=this.draftCommentAnnotationsByAnnotationId$.value;return a&&(i===null&&(i={}),Object.values(a).forEach(l=>{l?.metadata?.documentId===t&&l?.metadata?.organizationId===e&&!i[l?.annotationId]&&(i[l?.annotationId]=l)})),i?Object.values(i):null}catch(i){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByOrganizationIdAndDocumentId:",i),[]}}getCommentAnnotationsByDocumentId$({clientDocumentId:e,documentId:t}){try{return e&&!t&&(t=this.docService.generateDocumentId(e)),t?this.docService.getDocumentPaths$().pipe(Se(i=>this.getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:i?.organizationId,documentId:t}))):ce(null)}catch(i){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByDocumentId$:",i),ce(null)}}getCommentAnnotationsOnCurrentOrganizationAndDocument$(){return this.docService.getDocumentPaths$().pipe(Se(e=>e?.documentId?this.getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e.organizationId,documentId:e.documentId}):ce([])))}getCommentAnnotationsOnCurrentOrganizationAndDocument(){try{let e=this.docService.getDocumentPaths();return e?.documentId?this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e?.organizationId,documentId:e?.documentId}):[]}catch(e){return this.loggingService.catch("Error in CommentService getCommentAnnotationsOnCurrentOrganizationAndDocument:",e),[]}}setOriginalCommentAnnotationsByAnnotationId(e){try{let t={};e?.forEach(i=>{i?.annotationId&&(t[i?.annotationId]=i)}),this.originalCommentAnnotationsByDocumentId$.next(h(h({},this.originalCommentAnnotationsByDocumentId$.value),t))}catch(t){this.loggingService.catch("Error in CommentService setOriginalCommentAnnotationsByAnnotationId:",t)}}setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:i,queryHash:a}){try{if(t){e||(e=N.NO_ORGANIZATION_ID),a||(a=N.DEFAULT_QUERY_HASH);let l={};i.forEach(d=>{d?.annotationId&&(l[d?.annotationId]=d)});let c=h(h({},this.multiThreadCommentAnnotationById$.value),l);this.multiThreadCommentAnnotationById$.next(c)}}catch(l){this.loggingService.catch("Error in CommentService setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId:",l)}}getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e,documentId:t}){return this.multiThreadCommentAnnotationById$.pipe(ue(()=>this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t})))}getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let i={};Object.values(this.multiThreadCommentAnnotationById$.value??{}).forEach(l=>{l?.metadata?.documentId==t&&l?.metadata?.organizationId==e&&(i[l?.annotationId]=l)});let a=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value;return a&&Object.values(a??{}).forEach(l=>{l?.metadata?.documentId===t&&l?.metadata?.organizationId===e&&!i[l?.annotationId]&&(i[l?.annotationId]=l)}),Object.values(i)}catch(i){return this.loggingService.catch("Error in CommentService getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId:",i),[]}}getMultiThreadCommentAnnotationsOnCurrentOrganizationAndDocument$(){return this.docService.getDocumentPaths$().pipe(Se(e=>e?.documentId?this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e.organizationId,documentId:e.documentId}):ce([])))}getMultiThreadCommentAnnotationsOnCurrentOrganizationAndDocument(){try{let e=this.docService.getDocumentPaths();return this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e?.organizationId,documentId:e?.documentId})}catch(e){return this.loggingService.catch("Error in CommentService getMultiThreadCommentAnnotationsOnCurrentOrganizationAndDocument:",e),[]}}getLocations$(){return this.docService.getLocation$().pipe(Se(e=>this.docService.getLocations$().pipe(ue(t=>({location:e,locations:t})))),ue(e=>{let t=[];return t.push(e?.location?.locationId),t.push(...Object.values(e.locations||[]).map(i=>i.locationId)),t||[]}))}filterAnnotationsByLocationIds(e,t,i){try{return e.filter(a=>t.includes(a.locationId)||i?.includes(a?.location?.id)||t?.find(l=>l==a?.location?.id)||i?.find(l=>l==a?.locationId+""))}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByLocations:",a),[]}}setAnnotationIndex(e){try{e.forEach((t,i)=>{t?.annotationId&&(t.annotationIndex=i+1)})}catch(t){this.loggingService.catch("Error in CommentService setAnnotationIndex:",t)}}calculateCommentAnnotationPosition(e,t){try{if(e.multiThreadAnnotationId)return;if(e.targetElementId){let i=nl(e.targetElementId,["id","data-id"]);if(i&&this.domService.isElementVisible(i)){let a=i.getAttribute(N.ATTRIBUTES.VELT_COMMENT_TYPE),l=!0;if(a)switch(a){case"popover":l=!0;break;default:l=!1;break}else{let c=document.querySelector(`${N.TAGS.VELT_INLINE_COMMENTS_SECTION}[${N.ATTRIBUTES.TARGET_INLINE_COMMENT_ELEMENT_ID}="${e.targetElementId}"], ${N.TAGS.VELT_INLINE_COMMENTS_SECTION}[${N.ATTRIBUTES.TARGET_COMMENT_ELEMENT_ID}="${e.targetElementId}"], ${N.TAGS.VELT_INLINE_COMMENTS_SECTION}[${N.ATTRIBUTES.TARGET_ELEMENT_ID}="${e.targetElementId}"]`);c&&i?.contains(c)&&(l=!1)}l?e.targetElement={xpath:this.domService.getXPath(i),fXpath:this.domService.getXPath(i,!0),cfXpath:this.domService.getXPath(i,!0,!0),topPercentage:e.targetElement?.topPercentage||50,leftPercentage:e.targetElement?.leftPercentage||90}:e.targetElement=null}else e.targetElement=null}if(e.targetElement){e.position=null,e.ghostComment=null;let i=e.targetElement?.xpath,a=null,l=e?.targetElement?.anchor;if(l){let d=this.domService.resolveAnchorRecord(l);d?.element&&this.domService.isElementVisible(d.element)&&Kr(d.element)&&(a=d.element)}else i&&(a=this.domService.getElementFromXPath(i),this.domService.isXpathWithId(i)||((!a||!this.domService.isElementVisible(a))&&e.targetElement?.cfXpath&&(i=e.targetElement?.cfXpath,a=this.domService.getElementFromXPath(i)),this.getDetectionStrategy()===wN.DYNAMIC_ID&&(!a||!this.domService.isElementVisible(a))&&(i=e.targetElement?.fXpath,i&&(a=this.domService.getElementFromXPath(i)))));(!a||!this.domService.isElementVisible(a))&&t&&(e.ghostComment={},this.setGhostCommentMessage(e),e.ghostComment.targetElement=this.getGhostCommentTargetElement(e),e?.ghostComment?.targetElement?.xpath&&(a=this.domService.getElementFromXPath(e?.ghostComment?.targetElement?.xpath)));let c=!1;if(e?.locationId){let d=this.docService.getLocation();if(!_0({location:d?.location,locationId:d?.locationId},{location:e?.location,locationId:e?.locationId})){let m=this.docService.getAdditionLocationFromElement(a),u=m?this.docService.genarateLocationId(m):void 0;e?.location?.id&&e?.location?.id===m?.id||u&&u===e?.locationId?c=!1:c=!0}}if(c&&(e.ghostComment=null),!c&&a&&Kr(a)&&!a?.closest(".cdk-overlay-container")&&a?.getBoundingClientRect()){let m=this.popoverMode$?.value?0:e.targetElement?.topPercentage,u=this.popoverMode$?.value?100:e.targetElement?.leftPercentage,{height:_,width:I}=np(a);e.position={top:_*(m||0)/100,left:I*(u||0)/100};let A=window.getComputedStyle(a).transform;if(A&&A!=="none")try{let M=new DOMMatrixReadOnly(A),V=Math.sqrt(M.a*M.a+M.b*M.b)||1,q=Math.sqrt(M.c*M.c+M.d*M.d)||1;(Math.abs(V-1)>.01||Math.abs(q-1)>.01)&&(e.position.parentScaleX=V,e.position.parentScaleY=q)}catch{}if(this.transformContext$.value){let{containerSelector:M,transforms:V}=this.transformContext$.value,q=document.querySelector(M);q&&q.contains(a)&&(e.position.transformContext=V)}}!c&&t&&!e?.position&&!e?.ghostComment&&(e.ghostComment={},this.setGhostCommentMessage(e),e.ghostComment.targetElement=e.targetElement)}t&&(e.ghostComment?this.addAnnotationToGhostCommentAnnotationMap(e):this.removeAnnotationFromGhostCommentAnnotationMap(e))}catch(i){this.loggingService.catch("Error in CommentService calculateCommentAnnotationPosition:",i)}}addComment($e,ze,We,gr,nt){return X(this,arguments,function*(e,t,i,a,l,c=[],d,m,u,_,I,A,M,V,q,ae,ye,ie,ge,Ie,he,Te,Oe,Pe){this.loggingService.log("%c[WB] Calling FUNCTION: addComment","color: green;");try{let Et=this.authService.getUser();if(Et)if(Et.isReadOnly||Et.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add comments.");else{yield this.triggerAddCommentAnnotationDraftEvent();let Je=new Nr;ye&&(Je=h(h({},Je),ye)),Je.comments=[],ye?.comments?.length&&(Je.comments=ye.comments.map(Pn=>{let bn=new Xl;return bn=h(h({},bn),Pn),bn.from=Et,bn.lastUpdated=new Date,bn.createdAt=this.timestamp,bn})),Je.from=Et,Je.color=Je?.color||N.DEFAULT_ANNOTATION_COLOR,Je.lastUpdated=this.timestamp,Je.createdAt=this.timestamp,Je.sourceId=q,Je.assignedTo=ye?.assignedTo||ae,Je.customList=ye?.customList||[],Te&&(Je.targetElementId=Te);let{topPositionX:$t,topPositionY:an}=this.domService.getTopLeftPosition();Je.positionX=$t,Je.positionY=an;let Yn=this.domService.getCurrentWindowSizeValue();if(Je.screenWidth=Yn.screenWidth,Je.screenHeight=Yn.screenHeight,Je.screenScrollHeight=Yn.screenScrollHeight,Je.taggedElementPath="",e&&(Je.targetElement=this.domService.getTargetElementForCursorPosition(e,!0,!0,!0,Pn=>{if(this.getSvgAsImg()){let bn=Pn?.closest(`[${N.ATTRIBUTES.VELT_COMMENT_CONTAINER}]`);bn&&bn instanceof HTMLElement&&(Pn=bn)}if(this.getPopoverMode()){let bn=Pn?.closest(`[${N.ATTRIBUTES.VELT_TARGET_COMMENT_ELEMENT_ID}]`);if(bn&&bn instanceof HTMLElement)return bn}return Pn}),this.getCommentToNearestAllowedElement()&&Je.targetElement?.xpath)){let Pn=this.domService.getElementFromXPath(Je.targetElement.xpath);if(Pn&&!this.isElementInsideAllowedElements(Pn)){let bn=this.getNearestAllowedElement(Pn);if(bn)Je.targetElement.xpath=this.domService.getXPath(bn),Je.targetElement.fXpath=this.domService.getXPath(bn,!0),Je.targetElement.cfXpath=this.domService.getXPath(bn,!0,!0),Je.targetElement.anchor=this.domService.generateAnchorRecord(bn);else return}}if(t&&(Je.targetTextRange=t),Je?.targetElement?.xpath){let Pn=this.domService.getXPath(Je.targetElement.xpath);if(Pn){let bn=Pn.iterateNext();bn&&(Kr(bn)||(Je.targetElement=null))}}this.customFilterService.defaultStatus&&!ye?.status&&(Je.status=this.customFilterService.defaultStatus),Je.pageInfo=ro(),Je.pageInfo&&(Je.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth);let xr=this.docService.getClientDocumentId(),Io=this.docService.getLocation()?.location;if(ge&&(Je.context=ge&&Es(ge),Je.contextId=this.generateContextId(Je.context)),this.commentContextProvider!==null){let Pn=this.commentContextProvider(xr,Io),bn=Pn instanceof Promise?yield Pn:Pn;bn&&(Je.context=bn&&Es(bn),Je.contextId=this.generateContextId(Je.context),bn?.commentType==="manual"&&(Je.commentType="manual",delete Je.targetElement))}if(a){Je.sourceId=a?.sourceId;let Pn=a?.targetElement,bn=a?.commentData;if(Pn?.targetText)Je.targetTextRange={commonAncestorContainer:"/html/body",text:Pn.targetText,occurrence:Pn?.occurrence||1,commonAncestorContainerAnchor:this.domService.generateAnchorRecord(document.body)??void 0};else if(Pn?.elementId)if(Je.targetElementId=Pn.elementId,Pn?.selectAllContent)Je.selectAllContent=!!Pn?.selectAllContent;else{let Ro=nl(Pn.elementId,["id","data-id"]);Ro?Je.targetElement={xpath:this.domService.getXPath(Ro),fXpath:this.domService.getXPath(Ro,!0),cfXpath:this.domService.getXPath(Ro,!0,!0),anchor:this.domService.generateAnchorRecord(Ro),topPercentage:50,leftPercentage:90}:Je.targetElement={xpath:"/html/body",fXpath:"/html/body",cfXpath:"/html/body",anchor:this.domService.generateAnchorRecord(document.body),topPercentage:50,leftPercentage:90}}a?.status&&(Je.status=a.status),a?.context&&(Je.context=a.context?Es(a.context):a.context,Je.contextId=this.generateContextId(Je.context)),Je.comments||(Je.comments=[]);let hi=this.authService.getUser();bn?.forEach(Ro=>{let aa=new Xl;aa.commentText=Ro.commentText,aa.commentHtml=Ro.commentHtml,aa.replaceContentHtml=Ro.replaceContentHtml,aa.replaceContentText=Ro.replaceContentText,aa.from=hi,Je.comments.push(aa)})}if(l&&(Je.isPageAnnotation=!0),c?.length&&(Je.comments=c),d&&(Je.commentType="chart",Je.metadata=d),u?.sourceId&&(Je.sourceId=u.sourceId),Je?.targetElement?.xpath&&!u){let Pn=this.domService.getElementFromXPath(Je.targetElement.xpath);Pn&&(u=this.getInlineCommentSectionConfig(Pn))}u?.targetInlineCommentElementId&&(Je.targetInlineCommentElementId=u?.targetInlineCommentElementId,Je.targetElementId=u.targetInlineCommentElementId,u?.config?.id&&(Je.inlineCommentSectionConfig=u?.config));let Kn=!Je?.comments?.length,ao=!!(a?.openComment===!1||Ie);this.getPrivateCommentMode()&&(Je?.iam||(Je.iam=new _3),Je.iam.accessMode=Ca.PRIVATE),_&&(Je.context=_.context?Es(_.context):_.context,Je.commentType="manual",delete Je.targetElement,Je.contextId=this.generateContextId(Je.context)),I&&(Je.targetElementId=I.targetElementId,Je.targetElement=I.targetElement);let Xr=this.getPrivateModeConfig();if(Xr)try{let Pn=h({},Xr);if(Pn.type==="restricted"){let hi=this.authService.getUser();hi?.userId&&(Pn=Ju(Pn,hi.userId))}if(Pn.type==="organizationPrivate"&&!Pn.organizationId){let hi=this.docService.getOrganizationConfig();hi?.clientOrganizationId&&(Pn.organizationId=hi.clientOrganizationId)}let bn=Xu(Pn);Je.context||(Je.context={}),Je.context._setAccessFields=bn,Je.visibilityConfig=h(h({type:Pn.type},Pn.organizationId&&{organizationId:Pn.organizationId}),Pn.userIds&&{userIds:Pn.userIds})}catch(Pn){this.loggingService.catch("Error building accessFields from privateModeConfig: ",Pn)}this.saveCommentToDb(Je,i,Kn,ao,m,A,M,ie,V,he,Oe,Pe)}}catch(Et){this.loggingService.catch("Error in CommentService addComment: ",Et)}})}triggerAddCommentAnnotationDraftEvent(){return X(this,null,function*(){try{this.commentAnnotationContextDraft=null;let e={addContext:i=>{this.commentAnnotationContextDraft=i}},t=yield this.commentActionsService?.getAddCommentAnnotationDraftEventFromCommentAddEventData(e);t&&this.commentActionsService?.triggerAddCommentAnnotationDraftEvent(t)}catch(e){this.loggingService.catch("Error in CommentService triggerAddCommentAnnotationDraftEvent: ",e)}})}triggerAddCommentDraftEventOnAbandon(e,t){return X(this,null,function*(){try{if(!e||!t)return;let i=this.getAnnotationById(e),a=!!i?.comments?.some(l=>l&&!l.isDraft);i&&a&&(yield this.commentActionsService?.triggerAddCommentDraftEventForAnnotation(i,t))}catch(i){this.loggingService.catch("Error in CommentService triggerAddCommentDraftEventOnAbandon: ",i)}})}willDeleteWholeAnnotation(e,t){try{if(!e?.comments?.length)return!1;let i=e.comments.findIndex(a=>a?.commentId===t);return i<0?!1:i===0&&this.deleteThreadWithFirstComment$.value!==!1||e.comments.length===1}catch(i){return this.loggingService.catch("Error in CommentService willDeleteWholeAnnotation: ",i),!1}}confirmDeleteCommentIfRequired(e,t){return X(this,null,function*(){try{if(!e?.comments?.length||!t)return!0;let i=e.comments.findIndex(d=>d?.commentId===t?.commentId);if(i<0||!(i===0&&this.deleteThreadWithFirstComment$.value!==!1||this.deleteReplyConfirmation$.value))return!0;let l;return this.deleteReplyConfirmation$.value&&(i!==0||this.deleteThreadWithFirstComment$.value===!1)?l={title:"Delete comment?",message:"This selected comment will be deleted.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"reply",type:"reply"}:l={title:"Delete thread?",message:"All replies to this thread will be lost.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"comment",type:"comment"},!!(yield this.dialog.open(al,{panelClass:["velt-confirm-dialog-overlay-pane","velt-mat-dialog-container"],data:l}).afterClosed().toPromise())}catch(i){return this.loggingService.catch("Error in CommentService confirmDeleteCommentIfRequired: ",i),!1}})}setLocationToCommentAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location);try{let i;e.targetElement?i=this.domService.getElementFromTargetElement(e.targetElement):e.targetElementId?i=nl(e.targetElementId,["id","data-id"]):e.targetTextRange&&(i=this.domService.getElementFromTargetTextRange(e.targetTextRange));let a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.addLocation({location:a,source:"internal"});l?.[0]&&(e.locationId=l[0].locationId,e.location=l[0].location)}}catch{}}catch(t){this.loggingService.catch("Error in CommentService setLocationToCommentAnnotation:",t)}}getElementForCommentAnnotation(e){try{let t;return e.targetElement?t=this.domService.getElementFromTargetElement(e.targetElement):e.targetElementId?t=nl(e.targetElementId,["id","data-id"]):e.targetTextRange&&(t=this.domService.getElementFromTargetTextRange(e.targetTextRange)),t}catch(t){return this.loggingService.catch("Error in CommentService getElementForCommentAnnotation: ",t),null}}saveCommentToDb(e,t,i=!1,a=!1,l,c,d,m,u,_,I,A){this.loggingService.log("%c[WB] Calling FUNCTION: saveCommentToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(je.COMMENT)&&this.docService.getDocumentPaths$().pipe(Ge(M=>!!M),ut(1),Se(M=>(this.documentPaths=M,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Ge(V=>!!V),ut(1),Se(V=>X(this,null,function*(){if(this.documentPaths?.comment){e.annotationId=this.commonDbService.generateDocumentId();let q=this.docService.getClientDocumentId(),ae=this.docService.getLocation()?.location;if(d)e.multiThreadAnnotationId=d;else if(this.getMultiThread()){let Pe=am();e.targetElementId&&(Pe=am(e.targetElementId),e?.location?.id?Pe=am([e?.location?.id,e.targetElementId]):e?.locationId&&(Pe=am([e?.locationId+"",e.targetElementId]))),e.multiThreadAnnotationId=Pe}let ye={addContext:Pe=>{Pe.access&&(Pe.accessFields=A3(Pe)),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ADD_CONTEXT_TRIGGERED,{annotationId:e.annotationId,commentType:this.getCommentType(e),commentMode:this.getCommentMode(),context:Pe}),e.context=Pe&&Es(Pe),e.contextId=this.generateContextId(e.context),Pe?.commentType==="manual"&&(e.commentType="manual",delete e.targetElement),e?.annotationId&&setTimeout(()=>{this.updateCommentAnnotationContext(e.annotationId,Pe)},200)},documentId:q,location:ae,annotation:this.getCommentAnnotationForClient(e),targetAnnotationId:e?.annotationId,targetCommentId:e?.comments?.length?e?.comments[0]?.commentId:void 0};e?.targetElement?.xpath?ye.elementRef={xpath:e.targetElement.xpath}:ye.elementRef=void 0,this.commentAddedEmitter!==null&&"emit"in this.commentAddedEmitter&&this.commentAddedEmitter.emit(ye),this.commentAdded$.next(ye),u&&u(ye),ye?.annotation?.annotationId&&this.pendingAddCommentAnnotationData.set(ye.annotation.annotationId,ye),this.setLocationToCommentAnnotation(e);let ie=this.getElementForCommentAnnotation(e),ge=this.docService.getBaseMetadata("comment",{element:ie,multiThreadAnnotationId:e.multiThreadAnnotationId});if(!ge?.apiKey)return;if(e?.metadata||(e.metadata={}),e.metadata=h(h({},e.metadata),ge),_&&(e.metadata=h(h({},e.metadata),_)),l&&typeof l=="object"&&(e.locationId=m||this.docService.genarateLocationId(l),e.location=l,A||this.docService.addLocation({location:l})),i)window.localStorage.setItem(N.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT,JSON.stringify(e));else{let Pe=window.localStorage.getItem(N.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);Pe&&JSON.parse(Pe).annotationId===e.annotationId&&e.comments!==void 0&&e.comments.length>0&&window.localStorage.removeItem(N.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT)}e.pageInfo&&(e.pageInfo.commentUrl=this.generateCommentUrl(e));let Ie=e.comments,he=JSON.parse(JSON.stringify(e));if(this.commentAnnotationContextDraft){let Pe=this.commentAnnotationContextDraft;this.commentAnnotationContextDraft=null,Pe.access&&(Pe.accessFields=A3(Pe)),he.context=Pe&&Es(Pe)}if(!this.handleDirectAccessFieldsAssignment(he?.context)&&!he?.context?.access&&(he?.context||(he.context={}),he.context.access={default:"velt"},he.context.accessFields=[...he.context.accessFields||[],N.DEFAULT_VELT_CONTEXT]),he.visibilityConfig||(he.visibilityConfig={type:"public"}),he.position=null,t){he.targetElement=null,he.targetTextRange=null;let Pe={annotationId:e.multiThreadAnnotationId?e.multiThreadAnnotationId:e.annotationId,type:e.multiThreadAnnotationId?je.MULTI_THREAD:je.COMMENT},$e=yield this.areaService.generateAreaAnnotationId();he.areaAnnotationId=$e;let ze=this.areaService.addArea(void 0,t,Pe,$e,{locationId:he.locationId,location:he.location},he.context);ze&&(he.metadata=h(h({},he.metadata),ze?.metadata||{}))}!a&&!he?.targetInlineCommentElementId&&!he?.isPageAnnotation&&this.domService.toggleAnnotationSelection(he,c),e.targetTextRange&&sessionStorage.setItem(N.SESSION_STORAGE.SNIPPYLY_AUTO_SELECT_ANNOTATION_ID,e?.multiThreadAnnotationId?e?.multiThreadAnnotationId:e.annotationId),he?.comments?.length?this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ADDED,{annotationId:e.annotationId,commentThreadId:he?.comments[0]?.commentId,commentThreadIndex:0,commentType:this.getCommentType(he),commentMode:this.getCommentMode(),source:I??"internal",commentAnnotationCreatedAt:e.createdAt,taggedClientUserIds:he?.comments[0]?.taggedUserContacts?.map(Pe=>Pe.contact?.userId).filter(Pe=>!!Pe),taggedSnippylyUserIds:he?.comments[0]?.taggedUserContacts?.filter(Pe=>!!he?.metadata?.apiKey&&!!Pe.contact?.userId).map(Pe=>cd(he.metadata.apiKey,Pe.contact.userId))}):this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_DRAFT_ADDED,{annotationId:e.annotationId,commentType:this.getCommentType(he),commentMode:this.getCommentMode()});let Oe=this.getAnnotationNumber(e);Oe&&(he.annotationNumber=Oe),he?.comments?.length?he.comments=[]:he.isDraft=!0,he?.multiThreadAnnotationId&&this.saveMultiThreadCommentAnnotation(he),he?.context&&(he.contextId=this.generateContextId(he.context),he.context?.commentType==="manual"&&(he.commentType="manual",delete he.targetElement)),Ie?.length&&!he?.isDraft?this.saveComment(he,{type:Ot.NEWLY_ADDED,updatedComment:Ie[0]}):(Ie?.length&&(he.comments=Ie),this.draftCommentAnnotationsByAnnotationId$.next(y(h({},this.draftCommentAnnotationsByAnnotationId$.value),{[e.annotationId]:he})))}})))))).subscribe(()=>{},M=>{this.loggingService.catch("Error in CommentService saveCommentToDb subscription: ",M)})}catch(M){this.loggingService.catch("Error in CommentService saveCommentToDb: ",M)}}saveMultiThreadCommentAnnotation(e){return X(this,null,function*(){try{if(e?.multiThreadAnnotationId){let t=this.docService.getDocumentPaths();if(this.databaseService.getDbValue()&&t?.multiThread){let i={annotationId:e.multiThreadAnnotationId,targetElement:e.targetElement,targetElementId:e.targetElementId,targetInlineCommentElementId:e.targetInlineCommentElementId,inlineCommentSectionConfig:e.inlineCommentSectionConfig,areaAnnotationId:e.areaAnnotationId,targetTextRange:e.targetTextRange,from:e.from,locationId:e.locationId,location:e.location,sourceId:e.sourceId,type:"multiThread",metadata:e.metadata,context:e.context};delete e?.targetElement,delete e?.areaAnnotationId,delete e?.targetTextRange;let a=this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:t?.organizationId,documentId:t?.documentId})?.find(l=>l.annotationId===e.multiThreadAnnotationId);if(a||(a=yield this.commonDbService?.getData({feature:"multiThread",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",id:e.multiThreadAnnotationId}})),a&&(a=JSON.parse(JSON.stringify(a)),delete a.from,i=h(h({},a),i)),i?.commentAnnotations||(i.commentAnnotations={}),i.commentAnnotations[e.annotationId]=!0,e?.isDraft)this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(y(h({},this.draftMultiThreadCommentAnnotationsByAnnotationId$.value),{[i.annotationId]:y(h({},i),{isDraft:!0})}));else{let c=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value[i.annotationId];if(c&&(i=h(h({},i),c)),delete i.isDraft,i.commentAnnotationsMap={},!i?.metadata?.documentId){i?.metadata||(i.metadata={});let u=this.docService.getBaseMetadata("multiThread");i.metadata=h(h({},i?.metadata),u)}let{documentId:d,organizationId:m}=i?.metadata||{};yield this.commonDbService.updateData({feature:"multiThread",properties:{id:i.annotationId,documentId:d,organizationId:m},data:JSON.parse(JSON.stringify(i)),callback:()=>{let u=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value;u[e.annotationId]&&(delete u[e.annotationId],this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(u))}})}return i}}return null}catch(t){return this.loggingService.catch("Error in CommentService saveMultiThreadCommentAnnotation: ",t),null}})}setCommentCategory(e){return X(this,null,function*(){try{if(e?.comments?.length){let t=e.comments[0].commentText?.trim();if(t){let i=yield this.getCommentCategory(t).toPromise();if(i){let a=this.docService.getDocumentPaths();if(a?.comment&&e?.annotationId){let l=this.getCommentAnnotationsOnCurrentOrganizationAndDocument()?.find(c=>c.annotationId===e.annotationId);if(l||(l=yield this.commonDbService?.getData({feature:"comment",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:e.annotationId}})),l?.annotationId){let c=l;c.commentCategories=[i];let{documentId:d,organizationId:m}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(c);yield this.commonDbService.updateData({feature:"comment",properties:{id:e.annotationId,documentId:d,organizationId:m,metadata:{apiKey:this.configService.getApiKey(),organizationId:m,veltFolderId:c?.metadata?.veltFolderId,documentId:d}},data:JSON.parse(JSON.stringify(c))})}}}}}}catch(t){this.loggingService.catch("Error in CommentService setCommentCategory: ",t)}})}getCommentCategory(e){try{let t=Yr(this.functions,Zr({url:On.cloudFunction.chatgptCompletion,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=[{role:"system",content:`Identify category of this sentence from these categories, ${Object.keys(this.customCategoryMap)?.join(", ")}:`},{role:"user",content:e}];return co(t({messages:a,apiKey:this.configService.getApiKey(),sdkVersion:tl(),sdkType:this.configService.getSdkType(),numResponse:1})).pipe(ue(l=>{if(l?.data){let c=l.data,d=c?.length?c[0]?.content?.trim():void 0;return d&&Object.keys(this.customCategoryMap).includes(d)?this.customCategoryMap[d]:void 0}else return}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentCategory: ",t),ce(void 0)}}handleDirectAccessFieldsAssignment(e){try{if(!e||typeof e!="object")return!1;if("_setAccessFields"in e||"_replaceAccessFields"in e){let t=e._setAccessFields??e._replaceAccessFields;return delete e.access,delete e.accessFields,Array.isArray(t)&&t.length>0?e.accessFields=t:t==null&&delete e.accessFields,delete e._setAccessFields,delete e._replaceAccessFields,!0}return!1}catch(t){return this.loggingService.catch("Error in CommentService handleDirectAccessFieldsAssignment: ",t),!1}}updateCommentAnnotationContext(e,t,i){return X(this,null,function*(){try{this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_UPDATE_CONTEXT_TRIGGERED,{annotationId:e,context:t,merge:i?.merge});let a=this.authService.getUser(),l=this.docService.getDocumentPaths();if(a&&l?.comment&&e){let c=this.getAnnotationById(e);if(typeof c=="object"&&(c=JSON.parse(JSON.stringify(c))),c||(c=yield this.commonDbService?.getData({feature:"comment",properties:{documentId:l?.documentId??"",organizationId:l?.organizationId??"",id:e}})),c?.annotationId){let d=t,m=JSON.parse(JSON.stringify(c.context||{}));i?.merge&&(d=h(h({},m),t));let u=this.handleDirectAccessFieldsAssignment(d);if(d&&"_setVisibilityConfig"in d&&(c.visibilityConfig=d._setVisibilityConfig,delete d._setVisibilityConfig),d&&typeof d=="object"&&!u)if("access"in t)t.access!==null&&t.access!==void 0?d.accessFields=A3(d):(delete d.access,delete d.accessFields);else{if(!i?.merge)for(let A of KWe)!(A in t)&&m?.[A]!==void 0&&(d[A]=m[A]);d.access!==null&&d.access!==void 0&&(d.accessFields=A3(d))}let _={context:JSON.parse(JSON.stringify(d||{}))},I=!1;if(_?.context?.commentType==="manual"&&(_.commentType="manual",_.targetElement=null,c?.targetElement&&(c.targetElement=null,I=!0)),c.context=_.context?Es(_.context):_.context,c.contextId=this.generateContextId(c.context),sr(m,d)&&!I)return Promise.resolve("Comment annotation context is already updated.");if(c?.comments?.length){c.lastUpdated=this.timestamp;let{documentId:A,organizationId:M}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(c);return this.commonDbService.setData({feature:"comment",properties:{id:e,documentId:A,organizationId:M,metadata:{apiKey:this.configService.getApiKey(),organizationId:M,veltFolderId:c?.metadata?.veltFolderId,documentId:A}},data:JSON.parse(JSON.stringify(c)),callback:()=>{this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_UPDATE_CONTEXT_SUCCESS,{annotationId:e,context:_?.context,merge:i?.merge})}})}else return this.draftCommentAnnotationsByAnnotationId$.value?.[e]?(this.draftCommentAnnotationsByAnnotationId$.next(y(h({},this.draftCommentAnnotationsByAnnotationId$.value),{[e]:c})),Promise.resolve("Draft comment annotation context updated.")):(this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_UPDATE_CONTEXT_FAILED,{annotationId:e,context:t,merge:i?.merge,error:"Draft comment annotation not found."}),Promise.resolve("Draft comment annotation not found."))}else return this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_UPDATE_CONTEXT_FAILED,{annotationId:e,context:t,merge:i?.merge,error:"Comment annotation not found in database."}),Promise.resolve("Comment annotation not found in database.")}}catch(a){return this.loggingService.catch("Error in CommentService updateCommentAnnotationContext: ",a),Promise.resolve("Error in CommentService updateCommentAnnotationContext.")}})}updateComment(e,t,i,a,l,c){this.loggingService.log("%c[WB] Calling FUNCTION: updateComment","color: green;");try{if(this.authService.getUser()&&this.authService.isFeatureAllowed(je.COMMENT)){if(t&&this.setLocationToCommentAnnotation(e),e?.targetElement?.xpath){let d=this.domService.getXPath(e.targetElement.xpath);if(d){let m=d.iterateNext();m&&(Kr(m)||(e.targetElement=null))}}if(e?.type==="multiThread"){let d=JSON.parse(JSON.stringify(e));if(d.position=null,d.ghostComment=null,d?.context&&this.handleDirectAccessFieldsAssignment(d.context),!d?.metadata?.documentId){d?.metadata||(d.metadata={});let _=this.docService.getBaseMetadata("multiThread");d.metadata=h(h({},d?.metadata),_)}let{documentId:m,organizationId:u}=d?.metadata||{};i?this.commonDbService.updateData({feature:"multiThread",properties:{id:d.annotationId,documentId:m,organizationId:u},data:JSON.parse(JSON.stringify(d))}):this.commonDbService.setData({feature:"multiThread",properties:{id:d.annotationId,documentId:m,organizationId:u},data:JSON.parse(JSON.stringify(d))})}else{this.setSubscribedUsersDataInCommentAnnotation(e);let d=JSON.parse(JSON.stringify(e));if(d.position=null,d.ghostComment=null,d.lastUpdated=this.timestamp,d.status||(d.status=this.customFilterService.defaultStatus),delete d.resolved,delete d.inProgress,this.setLocationFromDocumentParams(d),d?.context&&this.handleDirectAccessFieldsAssignment(d.context),d?.annotationId?.startsWith("TEMP_COMPOSER_"))return;let m=window.localStorage.getItem(N.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);if(m&&JSON.parse(m).annotationId===d.annotationId&&window.localStorage.removeItem(N.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT),d?.multiThreadAnnotationId&&!l&&this.saveMultiThreadCommentAnnotation(d).then(u=>{}),d?.comments?.length){if(delete d?.isDraft,d?.multiThreadAnnotationId&&this.draftMultiThreadCommentAnnotationsByAnnotationId$.value[d?.multiThreadAnnotationId]&&this.saveMultiThreadCommentAnnotation(d),!d?.metadata?.documentId){d?.metadata||(d.metadata={});let A=this.docService.getBaseMetadata("comment");d.metadata=h(h({},d?.metadata),A)}let{documentId:u,organizationId:_}=d?.metadata||{},I=a?h({annotationData:a?.commentAnnotation,targetAnnotationData:a?.targetComment,actionType:a?.actionType,notificationSource:"comment"},a?.otherFields||{}):null;this.viewsService.updateCommentAnnotationViews(d),this.commonDbService.setData({feature:"comment",properties:{id:d.annotationId,documentId:u,targetCommentId:c?.commentId,organizationId:_,metadata:{apiKey:this.configService.getApiKey(),organizationId:_,veltFolderId:d?.metadata?.veltFolderId,documentId:u}},extraData:I,data:JSON.parse(JSON.stringify(d)),callback:A=>X(this,null,function*(){if(a&&!A?.firestoreAvailable&&this.updateNotificationsDatabase(a.commentAnnotation,a.targetComment,a.actionType,a.otherFields||{}),this.getScreenshotEnabled()&&a?.actionType===Ot.NEWLY_ADDED&&this.captureScreenshot(e),a?.actionType===Ot.NEWLY_ADDED||a?.actionType===Ot.ADDED)try{let M=yield this.metadataService.getGlobalMetadata(),V={annotationId:d.annotationId,commentAnnotation:this.getCommentAnnotationForClient(d),metadata:M};this.commentActionsService?.triggerAction(ar.COMMENT_SAVED,V)}catch(M){this.loggingService.catch("Error triggering commentSaved event: ",M)}})})}else this.draftCommentAnnotationsByAnnotationId$.next(y(h({},this.draftCommentAnnotationsByAnnotationId$.value),{[e.annotationId]:d}))}}}catch(d){this.loggingService.catch("Error in CommentService updateComment: ",d)}}captureScreenshot(e){return X(this,null,function*(){try{if(this.getScreenshotEnabled()){let i=Yr(this.functions,Zr({url:On.cloudFunction.screenshot,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a,l={source:"velt",sourceData:{commentAnnotation:e},eventType:"screenshot"};e?.areaAnnotationId&&(a=this.areaService.getAnnotationById(e?.areaAnnotationId),a&&(l.sourceData||(l.sourceData={}),l.sourceData.areaAnnotation=a));let c=yield ws(l,this.authService.getUser()?.userId??"");yield i({veltData:c})}}catch(t){this.loggingService.catch("Error in CommentService captureScreenshot: ",t)}})}getDocumentIdAndOrganizationIdFromCommentAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIdAndOrganizationIdFromCommentAnnotation: ",t),{}}}getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation: ",t),{}}}setLocationFromDocumentParams(e){e?.documentParams&&(e.location=e.documentParams,delete e.documentParams),e?.documentParamsId&&(e.locationId=e.documentParamsId,delete e.documentParamsId)}deleteCommentPinAnnotations(e){return new Promise((t,i)=>X(this,null,function*(){try{let a=this.domService.getSelectedAnnotationsMap(),l=this.authService.getUser(),c=[];Object.keys(a).forEach(d=>{let m=a[d];["tag","recorder","rewriter","arrow","area","multiThread"].includes(m.type)||l&&m.from&&(l?.isAdmin||m.from.userId===l.userId)&&c.push(m)}),c?.length?(this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_DELETE_TRIGGERED,{triggerType:e,annotationId:c.map(d=>d.annotationId).join(),commentMode:this.getCommentMode()}),this.dialog.open(al,{panelClass:["velt-confirm-dialog-overlay-pane","velt-mat-dialog-container"],data:{title:"Delete thread?",message:"All replies to this thread will be lost.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"comment",type:"comment"}}).afterClosed().pipe(ut(1)).subscribe(d=>{try{d?(c.forEach(m=>X(this,null,function*(){yield this.deleteCommentPinAnnotation(m)})),setTimeout(()=>{document.querySelectorAll(`[${N.SNIPPYLY_HIGHLIGHT}]`).forEach(u=>{this.domService.removeHighlightFromElement(u)}),t()},100)):t()}catch(m){i(m)}},d=>{i(d)})):t(),this.domService.resetSelectedAnnotationsMap(!0,"comment")}catch(a){this.loggingService.catch("Error in CommentService deleteCommentPinAnnotations: ",a),i(a)}}))}deleteCommentPinAnnotation(e,t){return X(this,null,function*(){try{if(setTimeout(()=>{if(this.draftCommentAnnotationsByAnnotationId$?.value?.[e.annotationId]){let i=this.draftCommentAnnotationsByAnnotationId$.value;delete i[e.annotationId],this.draftCommentAnnotationsByAnnotationId$.next(i)}},50),e?.annotationId&&this.pendingAddCommentAnnotationData.delete(e.annotationId),this.authService.isFeatureAllowed(je.COMMENT))if((t||e.comments?.length)&&this.updateNotificationsDatabase(e,null,Ot.DELETED),e.comments?.forEach(i=>{i.reactionAnnotationIds&&i.reactionAnnotationIds.forEach(a=>{this.deleteReaction(a)})}),e?.annotationId){this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_DELETED,{annotationId:e.annotationId,commentType:this.getCommentType(e),commentMode:this.getCommentMode()});let i=window.localStorage.getItem(N.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);i&&JSON.parse(i).annotationId===e.annotationId&&window.localStorage.removeItem(N.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT),this.areaService.onDeleteTargetAnnotation(e?.annotationId,e?.areaAnnotationId);let a={type:"delete",annotation:null,targetAnnotationId:e.annotationId};this.commentUpdated$.next(a),e?.multiThreadAnnotationId&&(yield this.removeCommentAnnotationFromMultiThread(e)),this.commentAnnotationDeleted$.next(e);let{documentId:l,organizationId:c}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(e);if(e?.isDraft)return Promise.resolve();{let d={annotationData:e,targetAnnotationData:null,actionType:Ot.DELETED,notificationSource:"comment",isAnnotationDelete:!0};return this.commonDbService.deleteData({feature:"comment",properties:{id:e.annotationId,documentId:l,organizationId:c,metadata:{apiKey:this.configService.getApiKey(),organizationId:c,veltFolderId:e?.metadata?.veltFolderId,documentId:l}},extraData:d})}}else return Promise.resolve();return Promise.resolve()}catch(i){return this.loggingService.catch("Error in CommentService deleteCommentPinAnnotation: ",i),Promise.resolve()}})}removeCommentAnnotationFromMultiThread(e){return X(this,null,function*(){try{let t=e?.multiThreadAnnotationId;if(t){let i=this.docService.getDocumentPaths(),a=this.getMultiThreadAnnotationById(t);if(!a){let m=e?.metadata?.documentId||i?.documentId,u=e?.metadata?.organizationId||i?.organizationId;a=yield this.commonDbService?.getData({feature:"multiThread",properties:{documentId:m,organizationId:u,id:t}})}let l=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value?.[t];a&&delete a?.commentAnnotations?.[e.annotationId],l&&(delete l?.commentAnnotations?.[e.annotationId],Object.keys(l?.commentAnnotations||{}).length===0&&(delete this.draftMultiThreadCommentAnnotationsByAnnotationId$.value?.[t],this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(this.draftMultiThreadCommentAnnotationsByAnnotationId$.value))),delete a.commentAnnotationsMap;let{documentId:c,organizationId:d}=this.getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation(a);return Object.keys(a?.commentAnnotations||{}).length===0?(this.areaService.onDeleteTargetAnnotation(a?.annotationId,a?.areaAnnotationId),this.multiThreadCommentAnnotationDeleted$.next(a),this.commonDbService.deleteData({feature:"multiThread",properties:{id:a?.annotationId,documentId:c,organizationId:d}})):this.commonDbService.setData({feature:"multiThread",properties:{id:a?.annotationId,documentId:c,organizationId:d},data:JSON.parse(JSON.stringify(a))})}}catch(t){this.loggingService.catch("Error in CommentService removeCommentAnnotationFromMultiThread: ",t)}})}getAnnotationById(e,t){try{let i=this.commentAnnotationById$.value?.[e]||this.draftCommentAnnotationsByAnnotationId$?.value?.[e];if(i){let{documentId:a,organizationId:l}=t||{};if(a&&i.metadata?.documentId!==a||l&&i.metadata?.organizationId!==l)return}return i}catch(i){this.loggingService.catch("Error in CommentService getAnnotationById: ",i);return}}getBaseMetadataFromCommentAnnotationId(e){try{let t=this.commentAnnotationById$.value?.[e];if(t)return t.metadata}catch(t){this.loggingService.catch("Error in CommentService getBaseMetadataFromCommentAnnotationId: ",t)}}getMultiThreadAnnotationById(e,t){try{let i=this.multiThreadCommentAnnotationById$.value?.[e]||this.draftMultiThreadCommentAnnotationsByAnnotationId$?.value?.[e];if(i){let{documentId:a,organizationId:l}=t||{};if(a&&i.metadata?.documentId!==a||l&&i.metadata?.organizationId!==l)return}return i}catch(i){this.loggingService.catch("Error in CommentService getAnnotationById: ",i);return}}getBaseMetadataFromMultiThreadCommentAnnotationId(e){try{let t=this.multiThreadCommentAnnotationById$.value?.[e];if(t)return t.metadata}catch(t){this.loggingService.catch("Error in CommentService getBaseMetadataFromMultiThreadCommentAnnotationId: ",t)}}getElementRefByAnnotationId(e){try{let t=this.getAnnotationById(e);if(t){let i=t?.targetElement?.xpath;if(i)return{xpath:i}}return}catch(t){this.loggingService.catch("Error in CommentService getElementRefByAnnotationId: ",t);return}}scrollToCommentByAnnotationId(e){try{let t=this.getAnnotationById(e),i=document.getElementById(`comment-pin-container-${e}`);i||(i=document.querySelector(`[data-velt-id='${e}']`)),i||(i=document.querySelector(`${N.TAGS.VELT_COMMENT_TEXT}[${N.ATTRIBUTES.ANNOTATION_ID}="${e}"]`)),i&&(i.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"}),t&&(this.domService.getSelectedAnnotationsMap()[e]||this.domService.toggleAnnotationSelection(t)))}catch(t){this.loggingService.catch("Error in CommentService scrollToCommentByAnnotationId: ",t)}}selectCommentByAnnotationId(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: selectCommentByAnnotationId","color: green;");let i=e?this.getAnnotationById(e):void 0;i?this.domService.toggleAnnotationSelection(i,void 0,void 0,!0):this.domService.resetSelectedAnnotationsMap()}catch(i){this.loggingService.catch("Error in CommentService selectCommentByAnnotationId: ",i)}}enableAddCommentMode(){try{this.authService.isFeatureAllowed(je.COMMENT)?!this.authService.isPlanExpired()&&this.iamService.hasRoleAny([Uo.ADMIN,Uo.COMMENTER])?(this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ADD_MODE_ENABLED,{commentMode:this.getCommentMode()}),this.addCommentMode$.next(!0)):this.loggingService.catch("Error in CommentService enableAddCommentMode: ","User is not allowed to add comment."):this.loggingService.catch("Error in CommentService enableAddCommentMode: ","Comment feature is not enabled.")}catch(e){this.loggingService.catch("Error in CommentService enableAddCommentMode: ",e)}}disableAddCommentMode(){this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ADD_MODE_DISABLED,{commentMode:this.getCommentMode()}),this.addCommentMode$.next(!1)}addCommentModeChange(){return this.addCommentMode$.asObservable()}setFreeStyleCommentContext(e){try{this.freeStyleCommentContext=e}catch(t){this.loggingService.catch("Error in CommentService setFreeStyleCommentContext: ",t)}}clearFreeStyleCommentContext(){try{this.freeStyleCommentContext=void 0}catch(e){this.loggingService.catch("Error in CommentService resetFreeStyleCommentContext: ",e)}}enablePersistentCommentMode(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{persistentCommentMode:!0}}),this.persistentCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePersistentCommentMode: ",e)}}enableDeleteReplyConfirmation(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deleteReplyConfirmation:!0}}),this.deleteReplyConfirmation$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeleteReplyConfirmation: ",e)}}enableSeenByUsers(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{seenByUsers:!0}}),this.seenByUsers$.value===!0)return;this.seenByUsers$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSeenByUsers: ",e)}}disableSeenByUsers(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{seenByUsers:!1}}),this.seenByUsers$.value===!1)return;this.seenByUsers$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSeenByUsers: ",e)}}getSeenByUsers$(){return this.seenByUsers$.asObservable()}disableDeleteReplyConfirmation(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deleteReplyConfirmation:!1}}),this.deleteReplyConfirmation$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeleteReplyConfirmation: ",e)}}disablePersistentCommentMode(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{persistentCommentMode:!1}}),this.persistentCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePersistentCommentMode: ",e)}}persistentCommentModeChange(){return this.persistentCommentMode$.asObservable()}enablePersistentModeBanner(){this.persistentModeBanner$.next(!0)}disablePersistentModeBanner(){this.persistentModeBanner$.next(!1)}persistentModeBannerChange(){return this.persistentModeBanner$.asObservable()}setAssignToType(e){try{this.assignToType$.next(e.type)}catch(t){this.loggingService.catch("Error in CommentService setAssignToType: ",t)}}getAssignToType$(){return this.assignToType$.asObservable()}getAssignToType(){return this.assignToType$.value}setPageModeComposerContext(e){try{this.pageModeComposerContext$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setPageModeComposerContext: ",t)}}clearPageModeComposerContext(){try{this.pageModeComposerContext$.next(null)}catch(e){this.loggingService.catch("Error in CommentService clearPageModeComposerContext: ",e)}}getPageModeComposerContext$(){return this.pageModeComposerContext$.asObservable()}getPageModeComposerContext(){return this.pageModeComposerContext$.value}enableContextInPageModeComposer(){try{this.contextInPageModeComposer$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableContextInPageModeComposer: ",e)}}disableContextInPageModeComposer(){try{this.contextInPageModeComposer$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableContextInPageModeComposer: ",e)}}getContextInPageModeComposer$(){return this.contextInPageModeComposer$.asObservable()}getContextInPageModeComposer(){return this.contextInPageModeComposer$.value}focusPageModeComposer(){try{this.focusPageModeComposer$.next()}catch(e){this.loggingService.catch("Error in CommentService focusPageModeComposer: ",e)}}getFocusPageModeComposer$(){return this.focusPageModeComposer$.asObservable()}showCommentIndex(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentIndex:e}}),this.showCommentIndex$.value===e)return;this.showCommentIndex$.next(e)}catch(t){this.loggingService.catch("Error in CommentService showCommentIndex: ",t)}}getShowCommentIndex(){return this.showCommentIndex$.asObservable()}enablePopoverMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{popoverMode:!0}}),this.popoverMode$.value===!0)return;this.popoverMode$.next(!0),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_POPOVER_MODE_ENABLED,{commentMode:this.getCommentMode()})}catch(e){this.loggingService.catch("Error in CommentService enablePopoverMode: ",e)}}disablePopoverMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{popoverMode:!1}}),this.popoverMode$.value===!1)return;this.popoverMode$.next(!1),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_POPOVER_MODE_DISABLED,{commentMode:this.getCommentMode()})}catch(e){this.loggingService.catch("Error in CommentService disablePopoverMode: ",e)}}getPopoverMode(){try{return this.popoverMode$.value}catch(e){return this.loggingService.catch("Error in CommentService getPopoverMode: ",e),!1}}getPopoverMode$(){return this.popoverMode$.asObservable()}enablePopoverTriangleComponent(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{popoverTriangleComponent:!0}}),this.popoverTriangleComponent$.value===!0)return;this.popoverTriangleComponent$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePopoverTriangleComponent: ",e)}}disablePopoverTriangleComponent(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{popoverTriangleComponent:!1}}),this.popoverTriangleComponent$.value===!1)return;this.popoverTriangleComponent$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePopoverTriangleComponent: ",e)}}getPopoverTriangleComponent(){try{return this.popoverTriangleComponent$.value}catch(e){return this.loggingService.catch("Error in CommentService getPopoverTriangleComponent: ",e),!1}}getPopoverTriangleComponent$(){return this.popoverTriangleComponent$.asObservable()}enableDraftMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{draftMode:!0}}),this.draftMode$.value===!0)return;this.draftMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDraftMode: ",e)}}disableDraftMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{draftMode:!1}}),this.draftMode$.value===!1)return;this.draftMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDraftMode: ",e)}}getDraftMode$(){return this.draftMode$.asObservable()}getDraftMode(){return this.draftMode$.value}enableTextComments(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textMode:!0}}),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_TEXT_MODE_ENABLED,{commentMode:this.getCommentMode()}),this.textCommentMode$.value===!0)return;this.textCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextComments: ",e)}}disableTextComments(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textMode:!1}}),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_TEXT_MODE_DISABLED,{commentMode:this.getCommentMode()}),this.textCommentMode$.value===!1)return;this.textCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextComments: ",e)}}getTextCommentMode$(){return this.textCommentMode$.asObservable()}isUserGlobalContact$(){return this.contactService.isUserGlobalContact$()}isSidebarOpenedByCustomTrigger(){try{return this.sidebarOpenedByCustomTrigger$.value}catch(e){return this.loggingService.catch("Error in CommentService isSidebarOpenedByCustomTrigger: ",e),!1}}setSidebarVisibility(e,t=!1,i=!1){try{this.domService.resetSelectedAnnotationsMap(),e?(document.querySelector(N.TAGS.VELT_COMMENTS_SIDEBAR_V2)||document.querySelector(N.TAGS.VELT_COMMENTS_SIDEBAR)||document.querySelector(N.TAGS.SNIPPYLY_COMMENTS_SIDEBAR)?this.sidebarVisible$.next(e):this.loggingService.catch("Error in CommentService setSidebarVisibility: ",`<${N.TAGS.VELT_COMMENTS_SIDEBAR}> or <${N.TAGS.VELT_COMMENTS_SIDEBAR_V2}> tag is not added.`),t&&this.sidebarOpenedByCustomTrigger$.next(!0)):(!this.sidebarOpenedByCustomTrigger$.value||t||i)&&(this.sidebarVisible$.next(e),this.sidebarOpenedByCustomTrigger$.next(!1),this.clearPageModeComposerContext()),e?this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_SIDEBAR_OPENED,{commentMode:this.getCommentMode()}):this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_SIDEBAR_CLOSED,{commentMode:this.getCommentMode()})}catch{this.loggingService.catch("Error in CommentService setSidebarVisibility: ",`<${N.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`)}}toggleSidebarVisibility(e=!1,t=!1){try{this.domService.resetSelectedAnnotationsMap(),this.sidebarVisible$.value?(!this.sidebarOpenedByCustomTrigger$.value||e||t)&&(this.sidebarVisible$.next(!this.sidebarVisible$.value),this.sidebarOpenedByCustomTrigger$.next(!1),this.sidebarVisible$.value||this.clearPageModeComposerContext()):(document.querySelector(N.TAGS.VELT_COMMENTS_SIDEBAR_V2)||document.querySelector(N.TAGS.VELT_COMMENTS_SIDEBAR)||document.querySelector(N.TAGS.SNIPPYLY_COMMENTS_SIDEBAR)?(this.sidebarVisible$.next(!this.sidebarVisible$.value),this.sidebarVisible$.value?this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_SIDEBAR_TOGGLED,{commentMode:this.getCommentMode(),action:"closed"}):this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_SIDEBAR_TOGGLED,{commentMode:this.getCommentMode(),action:"opened"})):this.loggingService.catch("Error in CommentService toggleSidebarVisibility: ",`<${N.TAGS.VELT_COMMENTS_SIDEBAR}> or <${N.TAGS.VELT_COMMENTS_SIDEBAR_V2}> tag is not added.`),e&&this.sidebarOpenedByCustomTrigger$.next(!0))}catch{this.loggingService.catch("Error in CommentService toggleSidebarVisibility: ",`<${N.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`)}}getSidebarVisibility$(){return this.sidebarVisible$.asObservable()}disableFloatingComments(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{floatingCommentDialog:!e}}),this.floatingCommentsEnabled$.value===!e)return;this.floatingCommentsEnabled$.next(!e)}catch(t){this.loggingService.catch("Error in CommentService disableFloatingComments: ",t)}}showFloatingComments$(){return this.floatingCommentsEnabled$.asObservable()}showFloatingComments(){return this.floatingCommentsEnabled$.value}setModeratorMode(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{moderatorMode:e}}),this.moderatorMode$.value===e)return;this.moderatorMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setModeratorMode: ",t)}}getModeratorMode(){return this.moderatorMode$.value}getModeratorMode$(){return this.moderatorMode$.asObservable()}setStreamMode(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{streamMode:e}}),this.streamMode$.value===e)return;this.streamMode$.next(e),e?this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_STREAM_MODE_ENABLED,{commentMode:this.getCommentMode()}):this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_STREAM_MODE_DISABLED,{commentMode:this.getCommentMode()})}catch(t){this.loggingService.catch("Error in CommentService setStreamMode: ",t)}}getStreamMode(){return this.streamMode$.value}getStreamMode$(){return this.streamMode$.asObservable()}getEnableDialogOnHover(){return this.enableDialogOnHover$.value}getEnableDialogOnHover$(){return this.enableDialogOnHover$.asObservable()}setEnableDialogOnHover(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{dialogOnHover:e}}),this.enableDialogOnHover$.value===e)return;this.enableDialogOnHover$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableDialogOnHover: ",t)}}getEnableDialogOnTargetElementClick(){return this.enableDialogOnTargetElementClick$.value}getEnableDialogOnTargetElementClick$(){return this.enableDialogOnTargetElementClick$.asObservable()}setEnableDialogOnTargetElementClick(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{dialogOnTargetElementClick:e}}),this.enableDialogOnTargetElementClick$.value===e)return;this.enableDialogOnTargetElementClick$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableDialogOnTargetElementClick: ",t)}}getEnablePriority(){return this.enablePriority$.value}getEnablePriority$(){return this.enablePriority$.asObservable()}setEnablePriority(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{priority:e}}),this.enablePriority$.value===e)return;this.enablePriority$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnablePriority: ",t)}}getEnableStatus(){return this.enableStatus$.value}getEnableStatus$(){return this.enableStatus$.asObservable()}setEnableStatus(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{status:e}}),this.getEnableStatus()===e)return;this.enableStatus$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableStatus: ",t)}}getEnableVisibilityOptions(){return this.visibilityOptions$.value}getEnableVisibilityOptions$(){return this.visibilityOptions$.asObservable()}setEnableVisibilityOptions(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{visibilityOptions:e}}),this.visibilityOptions$.value===e)return;this.visibilityOptions$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableVisibilityOptions: ",t)}}getEnableResolve(){return this.enableResolve$.value}getEnableResolve$(){return this.enableResolve$.asObservable()}setEnableResolve(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{resolveButton:e}}),this.getEnableResolve()===e)return;this.enableResolve$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableResolve: ",t)}}getEnableGhostComments(){return this.enableGhostComments$.value}getEnableGhostComments$(){return this.enableGhostComments$.asObservable()}enableGhostComments(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{ghostComments:!0}}),this.enableGhostComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableGhostComments: ",e)}}disableGhostComments(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{ghostComments:!1}}),this.enableGhostComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableGhostComments: ",e)}}getEnableGhostCommentsMessage(){return this.enableGhostCommentsMessage$.value}getEnableGhostCommentsMessage$(){return this.enableGhostCommentsMessage$.asObservable()}enableGhostCommentsMessage(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{ghostCommentsIndicator:!0}}),this.enableGhostCommentsMessage$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShowGhostCommentsMessage: ",e)}}disableGhostCommentsMessage(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{ghostCommentsIndicator:!1}}),this.enableGhostCommentsMessage$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShowGhostCommentsMessage: ",e)}}enableInboxMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{inboxMode:!0}}),this.inboxMode$.value===!0)return;this.inboxMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableInboxMode: ",e)}}disableInboxMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{inboxMode:!1}}),this.inboxMode$.value===!1)return;this.inboxMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableInboxMode: ",e)}}getInboxMode(){return this.inboxMode$.value}getInboxMode$(){return this.inboxMode$.asObservable()}setEnableAutoCategorize(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{autoCategorize:e}}),this.enableAutoCategorize$.value===e)return;this.enableAutoCategorize$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableAutoCategorize: ",t)}}getEnableAutoCategorize(){return this.enableAutoCategorize$.value}getEnableAutoCategorize$(){return this.enableAutoCategorize$.asObservable()}setCommentContainerDarkMode(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{darkMode:e}}),this.commentContainerDarkMode$.value===e)return;this.commentContainerDarkMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentContainerDarkMode: ",t)}}getCommentContainerDarkMode(){return this.commentContainerDarkMode$.asObservable()}getSuggestionMode(){return this.suggestionMode$.value}getSuggestionMode$(){return this.suggestionMode$.asObservable()}setSuggestionMode(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{suggestionMode:e}}),this.getSuggestionMode()===e)return;this.suggestionMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setSuggestionMode: ",t)}}getMobileMode(){return this.mobileMode$.value}getMobileMode$(){return this.mobileMode$.asObservable()}setMobileMode(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{mobileMode:e}}),this.getMobileMode()===e)return;this.mobileMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setMobileMode: ",t)}}enableInlineCommentMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{inlineCommentMode:!0}}),this.inlineCommentMode$.value===!0)return;this.inlineCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableInlineCommentMode: ",e)}}disableInlineCommentMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{inlineCommentMode:!1}}),this.inlineCommentMode$.value===!1)return;this.inlineCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableInlineCommentMode: ",e)}}getInlineCommentMode(){return this.inlineCommentMode$.value}getInlineCommentMode$(){return this.inlineCommentMode$.asObservable()}enableMinimap(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{minimap:!0}}),this.minimap$.value===!0)return;this.minimap$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableMinimap: ",e)}}disableMinimap(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{minimap:!1}}),this.minimap$.value===!1)return;this.minimap$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableMinimap: ",e)}}getMinimap(){return this.minimap$.value}getMinimap$(){return this.minimap$.asObservable()}showCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentsOnDom:!0}}),this.commentsOnDom$.value===!0)return;this.commentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService showCommentsOnDom: ",e)}}hideCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentsOnDom:!1}}),this.commentsOnDom$.value===!1)return;this.commentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService hideCommentsOnDom: ",e)}}getCommentsOnDom(){return this.commentsOnDom$.value}getCommentsOnDom$(){return this.commentsOnDom$.asObservable()}enableCommentTool(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentTool:!0}}),this.commentToolEnabled$.value===!0)return;this.commentToolEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCommentTool: ",e)}}disableCommentTool(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentTool:!1}}),this.commentToolEnabled$.value===!1)return;this.commentToolEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCommentTool: ",e)}}getCommentTool(){return this.commentToolEnabled$.value}getCommentTool$(){return this.commentToolEnabled$.asObservable()}setTotalMediaLength(e){try{if(this.totalMediaLength$.value===e)return;this.totalMediaLength$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setTotalMediaLength: ",t)}}getTotalMediaLength(){return this.totalMediaLength$.value}getTotalMediaLength$(){return this.totalMediaLength$.asObservable()}enableSidebarUrlNavigation(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{sidebarUrlNavigation:!0}}),this.sidebarUrlNavigationEnabled$.value===!0)return;this.sidebarUrlNavigationEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarUrlNavigation: ",e)}}disableSidebarUrlNavigation(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{sidebarUrlNavigation:!1}}),this.sidebarUrlNavigationEnabled$.value===!1)return;this.sidebarUrlNavigationEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarUrlNavigation: ",e)}}getSidebarUrlNavigation(){return this.sidebarUrlNavigationEnabled$.value}getSidebarUrlNavigation$(){return this.sidebarUrlNavigationEnabled$.asObservable()}setDetectionStrategy(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{detectionStrategy:e}}),this.detectionStrategy$.value===e)return;this.detectionStrategy$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setDetectionStrategy: ",t)}}getDetectionStrategy(){return this.detectionStrategy$.value}getDetectionStrategy$(){return this.detectionStrategy$.asObservable()}enableSidebarButtonOnCommentDialog(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{sidebarButtonOnCommentDialog:!0}}),this.sidebarButtonOnCommentDialogVisible$.value===!0)return;this.sidebarButtonOnCommentDialogVisible$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarButtonOnCommentDialog: ",e)}}disableSidebarButtonOnCommentDialog(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{sidebarButtonOnCommentDialog:!1}}),this.sidebarButtonOnCommentDialogVisible$.value===!1)return;this.sidebarButtonOnCommentDialogVisible$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarButtonOnCommentDialog: ",e)}}getSidebarButtonOnCommentDialogVisibility(){return this.sidebarButtonOnCommentDialogVisible$.value}getSidebarButtonOnCommentDialogVisibility$(){return this.sidebarButtonOnCommentDialogVisible$.asObservable()}onSidebarButtonOnCommentDialogClick(){this.sidebarButtonOnCommentDialogClick$.next()}getSidebarButtonOnCommentDialogClick$(){return this.sidebarButtonOnCommentDialogClick$.asObservable()}enableDeviceIndicatorOnCommentPins(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deviceIndicatorOnCommentPins:!0}}),this.deviceIndicatorOnCommentPins$.value===!0)return;this.deviceIndicatorOnCommentPins$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeviceIndicatorOnCommentPins: ",e)}}disableDeviceIndicatorOnCommentPins(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deviceIndicatorOnCommentPins:!1}}),this.deviceIndicatorOnCommentPins$.value===!1)return;this.deviceIndicatorOnCommentPins$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeviceIndicatorOnCommentPins: ",e)}}getDeviceIndicatorOnCommentPins(){return this.deviceIndicatorOnCommentPins$.value}getDeviceIndicatorOnCommentPins$(){return this.deviceIndicatorOnCommentPins$.asObservable()}onSidebarCommentClick(e){this.sidebarCommentClick$.next(e)}getSidebarCommentClick$(){return this.sidebarCommentClick$.asObservable()}onCommentNavigationButtonClick(e){this.commentNavigationButtonClick$.next(e)}getCommentNavigationButtonClick$(){return this.commentNavigationButtonClick$.asObservable()}addBubbleCommentAnnotationIds(e){try{let i=[...this.bubbleCommentAnnotationIds$.value||[],...e],a=[...new Set(i)];this.bubbleCommentAnnotationIds$.next(a)}catch(t){this.loggingService.catch("Error in CommentService addBubbleCommentAnnotationIds: ",t)}}getBubbleCommentAnnotationIds(){return this.bubbleCommentAnnotationIds$.value}getBubbleCommentAnnotationIds$(){return this.bubbleCommentAnnotationIds$.asObservable()}removeBubbleCommentAnnotationIds(e){try{let i=(this.bubbleCommentAnnotationIds$.value||[]).filter(a=>!e.includes(a));this.bubbleCommentAnnotationIds$.next(i)}catch(t){this.loggingService.catch("Error in CommentService removeBubbleCommentAnnotationIds: ",t)}}enableSignInButton(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{signInButton:e}}),this.enableSignInButton$.next(e)}catch(t){this.loggingService.catch("Error in CommentService enableSignInButton: ",t)}}getSignInButton(){return this.enableSignInButton$.value}getSignInButton$(){return this.enableSignInButton$.asObservable()}onSignInClick(){this.onSignInClick$.next()}getSignInButtonClick$(){return this.onSignInClick$.asObservable()}enableUpgradeButton(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{upgradeButton:e}}),this.enableUpgradeButton$.next(e)}catch(t){this.loggingService.catch("Error in CommentService enableUpgradeButton: ",t)}}getUpgradeButton(){return this.enableUpgradeButton$.value}getUpgradeButton$(){return this.enableUpgradeButton$.asObservable()}onUpgradeClick(){this.onUpgradeClick$.next()}getUpgradeButtonClick$(){return this.onUpgradeClick$.asObservable()}openSidebar(){this.openSidebar$.next()}getOpenSidebar$(){return this.openSidebar$.asObservable()}enableAttachment(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{attachments:e}}),this.enableAttachment$.value===e)return;this.enableAttachment$.next(e)}catch(t){this.loggingService.catch("Error in CommentService enableAttachment: ",t)}}getEnableAttachment$(){return this.enableAttachment$.asObservable()}enableAttachmentDownload(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{attachmentDownload:!0}}),this.enableAttachmentDownload$.value===!0)return;this.enableAttachmentDownload$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAttachmentDownload: ",e)}}disableAttachmentDownload(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{attachmentDownload:!1}}),this.enableAttachmentDownload$.value===!1)return;this.enableAttachmentDownload$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAttachmentDownload: ",e)}}getEnableAttachmentDownload$(){return this.enableAttachmentDownload$.asObservable()}getEnableAttachmentDownload(){return this.enableAttachmentDownload$.value}enableFormatOptions(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{formatOptions:!0}}),this.enableFormatOptions$.value===!0)return;this.enableFormatOptions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFormatOptions: ",e)}}disableFormatOptions(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{formatOptions:!1}}),this.enableFormatOptions$.value===!1)return;this.enableFormatOptions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFormatOptions: ",e)}}getEnableFormatOptions$(){return this.enableFormatOptions$.asObservable()}setFormatConfig(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{formatConfig:e}}),this.formatConfig$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setFormatConfig: ",t)}}getFormatConfig$(){return this.formatConfig$.asObservable()}setAllowedRecordings(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{recordings:e}}),e?.includes("all")?this.allowedRecordings$.next(["audio","video","screen"]):e?.includes("none")?this.allowedRecordings$.next([]):this.allowedRecordings$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setAllowedRecordings: ",t)}}getAllowedRecordings(){return this.allowedRecordings$.value}getAllowedRecordings$(){return this.allowedRecordings$.asObservable()}enableReactions(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{reactions:!0}}),this.enableReactions$.value===!0)return;this.enableReactions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReactions: ",e)}}disableReactions(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{reactions:!1}}),this.enableReactions$.value===!1)return;this.enableReactions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReactions: ",e)}}getEnableReactions(){return this.enableReactions$.value}getEnableReactions$(){return this.enableReactions$.asObservable()}enableAnonymousEmail(){try{if(this.enableAnonymousEmail$.value===!0)return;this.enableAnonymousEmail$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAnonymousEmail: ",e)}}disableAnonymousEmail(){try{if(this.enableAnonymousEmail$.value===!1)return;this.enableAnonymousEmail$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAnonymousEmail: ",e)}}getEnableAnonymousEmail(){return this.enableAnonymousEmail$.value}getEnableAnonymousEmail$(){return this.enableAnonymousEmail$.asObservable()}addCommentOnElement(e){this.addComment(void 0,void 0,void 0,e)}enablePrivateCommentMode(){return X(this,null,function*(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{privateCommentMode:!0}}),this.privateCommentMode$.value===!0)return;this.isPrivateCommentAllowed$().pipe(ut(1)).subscribe(e=>{e?(this.privateCommentMode$.next(!0),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_PRIVATE_COMMENT_MODE_ENABLED)):this.loggingService.logsEnabled&&console.warn("You are not allowed to enable private comment mode.")})}catch(e){this.loggingService.catch("Error in CommentService enablePrivateCommentMode: ",e)}})}disablePrivateCommentMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{privateCommentMode:!1}}),this.privateCommentMode$.value===!1)return;this.privateCommentMode$.next(!1),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_PRIVATE_COMMENT_MODE_DISABLED)}catch(e){this.loggingService.catch("Error in CommentService disablePrivateCommentMode: ",e)}}getPrivateCommentMode(){return this.privateCommentMode$.value}getPrivateCommentMode$(){return this.privateCommentMode$.asObservable()}isPrivateCommentAllowed(){return this.privateCommentAllowed$.value}isPrivateCommentAllowed$(){return this.privateCommentAllowed$.asObservable()}enablePrivateMode(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{privateModeConfig:e}}),!e?.type){this.loggingService.catch("enablePrivateMode: type is required in config");return}let t=h({},e);if(t.type==="restricted"){let i=this.authService.getUser();if(!i?.userId){this.loggingService.catch("enablePrivateMode: Current user not found. Cannot set restricted visibility without userIds.");return}t=Ju(t,i.userId)}this.privateModeConfig$.next(t)}catch(t){this.loggingService.catch("Error in CommentService enablePrivateMode: ",t)}}disablePrivateMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{privateModeConfig:null}}),this.privateModeConfig$.value===null)return;this.privateModeConfig$.next(null)}catch(e){this.loggingService.catch("Error in CommentService disablePrivateMode: ",e)}}getPrivateModeConfig(){return this.privateModeConfig$.value}getPrivateModeConfig$(){return this.privateModeConfig$.asObservable()}enableScrollToComment(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{scrollToComment:!0}}),this.scrollToComment$.value===!0)return;this.scrollToComment$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableScrollToComment: ",e)}}disableScrollToComment(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{scrollToComment:!1}}),this.scrollToComment$.value===!1)return;this.scrollToComment$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableScrollToComment: ",e)}}getScrollToComment(){return this.scrollToComment$.value}getScrollToComment$(){return this.scrollToComment$.asObservable()}showScreenSizeInfo(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deviceInfo:e}}),this.showScreenSizeInfo$.value===e)return;this.showScreenSizeInfo$.next(e)}catch(t){this.loggingService.catch("Error in CommentService showScreenSizeInfo: ",t)}}getShowScreenSizeInfo$(){return this.showScreenSizeInfo$.asObservable()}enableUserMentions(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableUserMentions","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{userMentions:!0}}),this.userMentions$.value===!0)return;this.userMentions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableUserMentions: ",e)}}disableUserMentions(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableUserMentions","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{userMentions:!1}}),this.userMentions$.value===!1)return;this.userMentions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableUserMentions: ",e)}}getUserMentions(){return this.userMentions$.value}getUserMentions$(){return this.userMentions$.asObservable()}enablePaginatedContactList(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enablePaginatedContactList","color: green;"),this.paginatedContactList$.value===!0)return;this.paginatedContactList$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePaginatedContactList: ",e)}}disablePaginatedContactList(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disablePaginatedContactList","color: green;"),this.paginatedContactList$.value===!1)return;this.paginatedContactList$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePaginatedContactList: ",e)}}getPaginatedContactList(){return this.paginatedContactList$.value}getPaginatedContactList$(){return this.paginatedContactList$.asObservable()}enableDeleteOnBackspace(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDeleteOnBackspace","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deleteOnBackspace:!0}}),this.deleteOnBackspace$.value===!0)return;this.deleteOnBackspace$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeleteOnBackspace: ",e)}}disableDeleteOnBackspace(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDeleteOnBackspace","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deleteOnBackspace:!1}}),this.deleteOnBackspace$.value===!1)return;this.deleteOnBackspace$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeleteOnBackspace: ",e)}}getDeleteOnBackspace(){return this.deleteOnBackspace$.value}getDeleteOnBackspace$(){return this.deleteOnBackspace$.asObservable()}enableHotkey(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableHotkey","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{hotkey:!0}}),this.hotkeyEnabled$.value===!0)return;this.hotkeyEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableHotkey: ",e)}}disableHotkey(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableHotkey","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{hotkey:!1}}),this.hotkeyEnabled$.value===!1)return;this.hotkeyEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableHotkey: ",e)}}enableRecordingSummary(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableRecordingSummary","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{recordingSummary:!0}}),this.recordingSummaryEnabled$.value===!0)return;this.recordingSummaryEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableRecordingSummary: ",e)}}disableRecordingSummary(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableRecordingSummary","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{recordingSummary:!1}}),this.recordingSummaryEnabled$.value===!1)return;this.recordingSummaryEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableRecordingSummary: ",e)}}getRecordingSummaryEnabled(){return this.recordingSummaryEnabled$.value}getRecordingSummaryEnabled$(){return this.recordingSummaryEnabled$.asObservable()}setUnreadIndicatorMode(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setUnreadIndicatorMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{unreadIndicatorMode:e}}),this.unreadIndicatorMode$.value===e)return;this.unreadIndicatorMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setUnreadIndicatorMode: ",t)}}getUnreadIndicatorMode(){return this.unreadIndicatorMode$.value}getUnreadIndicatorMode$(){return this.unreadIndicatorMode$.asObservable()}setComposerMode(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setComposerMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{composerMode:e}}),this.composerMode$.value===e)return;this.composerMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setComposerMode: ",t)}}getComposerMode(){return this.composerMode$.value}getComposerMode$(){return this.composerMode$.asObservable()}enableEnterKeyToSubmit(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableEnterKeyToSubmit","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{enterKeyToSubmit:!0}}),this.enterKeyToSubmit$.value===!0)return;this.enterKeyToSubmit$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableEnterKeyToSubmit: ",e)}}disableEnterKeyToSubmit(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableEnterKeyToSubmit","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{enterKeyToSubmit:!1}}),this.enterKeyToSubmit$.value===!1)return;this.enterKeyToSubmit$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableEnterKeyToSubmit: ",e)}}getEnterKeyToSubmit(){return this.enterKeyToSubmit$.value}getEnterKeyToSubmit$(){return this.enterKeyToSubmit$.asObservable()}enablePinShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enablePinShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{pinShadowDom:!0}}),this.pinShadowDOM$.value===!0)return;this.pinShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePinShadowDOM: ",e)}}disablePinShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disablePinShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{pinShadowDom:!1}}),this.pinShadowDOM$.value===!1)return;this.pinShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePinShadowDOM: ",e)}}getPinShadowDOM(){return this.pinShadowDOM$.value}getPinDarkMode(){return this.pinDarkMode$.value}getPinDarkMode$(){return this.pinDarkMode$.asObservable()}getTextCommentToolDarkMode(){return this.textCommentToolDarkMode$.value}getTextCommentToolDarkMode$(){return this.textCommentToolDarkMode$.asObservable()}getTextCommentToolbarDarkMode(){return this.textCommentToolbarDarkMode$.value}getTextCommentToolbarDarkMode$(){return this.textCommentToolbarDarkMode$.asObservable()}getPinShadowDOM$(){return this.pinShadowDOM$.asObservable()}getTextCommentToolShadowDOM$(){return this.textCommentToolShadowDOM$.asObservable()}getTextCommentToolbarShadowDOM$(){return this.textCommentToolbarShadowDOM$.asObservable()}enableDialogShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDialogShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{dialogShadowDom:!0}}),this.dialogShadowDOM$.value===!0)return;this.dialogShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDialogShadowDOM: ",e)}}enableTextCommentToolbarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolbarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolbarShadowDom:!0}}),this.textCommentToolbarShadowDOM$.value===!0)return;this.textCommentToolbarShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolbarShadowDOM: ",e)}}disableTextCommentToolbarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolbarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolbarShadowDom:!1}}),this.textCommentToolbarShadowDOM$.value===!1)return;this.textCommentToolbarShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolbarShadowDOM: ",e)}}enableTextCommentToolShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolShadowDom:!0}}),this.textCommentToolShadowDOM$.value===!0)return;this.textCommentToolShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolShadowDOM: ",e)}}disableTextCommentToolShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolShadowDom:!1}}),this.textCommentToolShadowDOM$.value===!1)return;this.textCommentToolShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolShadowDOM: ",e)}}enableTextCommentToolDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolDarkMode:!0}}),this.textCommentToolDarkMode$.value===!0)return;this.textCommentToolDarkMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolDarkMode: ",e)}}disableTextCommentToolDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolDarkMode:!1}}),this.textCommentToolDarkMode$.value===!1)return;this.textCommentToolDarkMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolDarkMode: ",e)}}enableTextCommentToolbarDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolbarDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolbarDarkMode:!0}}),this.textCommentToolbarDarkMode$.value===!0)return;this.textCommentToolbarDarkMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolbarDarkMode: ",e)}}disableTextCommentToolbarDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolbarDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolbarDarkMode:!1}}),this.textCommentToolbarDarkMode$.value===!1)return;this.textCommentToolbarDarkMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolbarDarkMode: ",e)}}enablePinDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enablePinDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{pinDarkMode:!0}}),this.pinDarkMode$.value===!0)return;this.pinDarkMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePinDarkMode: ",e)}}disablePinDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disablePinDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{pinDarkMode:!1}}),this.pinDarkMode$.value===!1)return;this.pinDarkMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePinDarkMode: ",e)}}disableDialogShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDialogShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{dialogShadowDom:!1}}),this.dialogShadowDOM$.value===!1)return;this.dialogShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDialogShadowDOM: ",e)}}getDialogShadowDOM(){return this.dialogShadowDOM$.value}getDialogShadowDOM$(){return this.dialogShadowDOM$.asObservable()}setDialogShadowDOMExplicit(e){this.dialogShadowDOMExplicit$.next(e)}getDialogShadowDOMExplicit$(){return this.dialogShadowDOMExplicit$.asObservable()}enableSidebarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableSidebarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{sidebarShadowDOM:!0}}),this.sidebarShadowDOM$.value===!0)return;this.sidebarShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarShadowDOM: ",e)}}disableSidebarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableSidebarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{sidebarShadowDOM:!1}}),this.sidebarShadowDOM$.value===!1)return;this.sidebarShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarShadowDOM: ",e)}}getSidebarShadowDOM(){return this.sidebarShadowDOM$.value}getSidebarShadowDOM$(){return this.sidebarShadowDOM$.asObservable()}enableChangeDetectionInCommentMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableChangeDetectionInCommentMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{changeDetectionInCommentMode:!0}}),this.changeDetectionInCommentMode$.value===!0)return;this.changeDetectionInCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableChangeDetectionInCommentMode: ",e)}}disableChangeDetectionInCommentMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableChangeDetectionInCommentMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{changeDetectionInCommentMode:!1}}),this.changeDetectionInCommentMode$.value===!1)return;this.changeDetectionInCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableChangeDetectionInCommentMode: ",e)}}getChangeDetectionInCommentMode(){return this.changeDetectionInCommentMode$.value}getChangeDetectionInCommentMode$(){return this.changeDetectionInCommentMode$.asObservable()}showResolvedCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{resolvedCommentsOnDom:!0}}),this.resolvedCommentsOnDom$.value===!0)return;this.resolvedCommentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService showResolvedCommentsOnDom: ",e)}}hideResolvedCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{resolvedCommentsOnDom:!1}}),this.resolvedCommentsOnDom$.value===!1)return;this.resolvedCommentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService hideResolvedCommentsOnDom: ",e)}}getResolvedCommentsOnDom(){return this.resolvedCommentsOnDom$.value}getResolvedCommentsOnDom$(){return this.resolvedCommentsOnDom$.asObservable()}enableBubbleOnPin(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{bubbleOnPin:!0}}),this.bubbleOnPinEnabled$.value===!0)return;this.bubbleOnPinEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableBubbleOnPin: ",e)}}disableBubbleOnPin(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{bubbleOnPin:!1}}),this.bubbleOnPinEnabled$.value===!1)return;this.bubbleOnPinEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableBubbleOnPin: ",e)}}getBubbleOnPin(){return this.bubbleOnPinEnabled$.value}getBubbleOnPin$(){return this.bubbleOnPinEnabled$.asObservable()}enableBubbleOnPinHover(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{bubbleOnPinHover:!0}}),this.bubbleOnPinHoverEnabled$.value===!0)return;this.bubbleOnPinHoverEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableBubbleOnPinHover: ",e)}}disableBubbleOnPinHover(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{bubbleOnPinHover:!1}}),this.bubbleOnPinHoverEnabled$.value===!1)return;this.bubbleOnPinHoverEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableBubbleOnPinHover: ",e)}}getBubbleOnPinHover(){return this.bubbleOnPinHoverEnabled$.value}getBubbleOnPinHover$(){return this.bubbleOnPinHoverEnabled$.asObservable()}enablePinDrag(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{pinDrag:!0}}),this.pinDragEnabled$.value===!0)return;this.pinDragEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePinDrag: ",e)}}disablePinDrag(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{pinDrag:!1}}),this.pinDragEnabled$.value===!1)return;this.pinDragEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePinDrag: ",e)}}getPinDrag(){return this.pinDragEnabled$.value}getPinDrag$(){return this.pinDragEnabled$.asObservable()}setExcludeLocationIdsFromSidebar(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{excludeLocationIdsFromSidebar:e}}),this.excludeLocationIdsFromSidebar$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setExcludeLocationIdsFromSidebar: ",t)}}getExcludeLocationIdsFromSidebar(){return this.excludeLocationIdsFromSidebar$.value}getExcludeLocationIdsFromSidebar$(){return this.excludeLocationIdsFromSidebar$.asObservable()}enableMultiThread(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{multiThread:!0}}),this.multiThread$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableMultiThread: ",e)}}disableMultiThread(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{multiThread:!1}}),this.multiThread$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableMultiThread: ",e)}}getMultiThread(){return this.multiThread$.value}getMultiThread$(){return this.multiThread$.asObservable()}enableGroupMatchedComments(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{groupMatchedComments:!0}}),this.groupMatchedComments$.value===!0)return;this.groupMatchedComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableGroupMatchedComments: ",e)}}disableGroupMatchedComments(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{groupMatchedComments:!1}}),this.groupMatchedComments$.value===!1)return;this.groupMatchedComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableGroupMatchedComments: ",e)}}getGroupMatchedComments(){return this.groupMatchedComments$.value}getGroupMatchedComments$(){return this.groupMatchedComments$.asObservable()}enableShortUserName(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableShortUserName","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{shortUserName:!0}}),this.shortUserName$.value===!0)return;this.shortUserName$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShortUserName: ",e)}}disableShortUserName(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableShortUserName","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{shortUserName:!1}}),this.shortUserName$.value===!1)return;this.shortUserName$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShortUserName: ",e)}}getShortUserName(){return this.shortUserName$.value}getShortUserName$(){return this.shortUserName$.asObservable()}enableRecordingCountdown(){try{this.loggingService.log("%c[WB] Calling FUNCTION: enableRecordingCountdown","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{recordingCountdown:!0}}),this.recorderService.enableRecordingCountdown()}catch(e){this.loggingService.catch("Error in CommentService enableRecordingCountdown: ",e)}}disableRecordingCountdown(){try{this.loggingService.log("%c[WB] Calling FUNCTION: disableRecordingCountdown","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{recordingCountdown:!1}}),this.recorderService.disableRecordingCountdown()}catch(e){this.loggingService.catch("Error in CommentService disableRecordingCountdown: ",e)}}setCommentSidebarFilters(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentSidebarFilters","color: green;"),this.commentSidebarFilters$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentSidebarFilters: ",t)}}getCommentSidebarFilters(){return this.commentSidebarFilters$.value??{}}getCommentSidebarFilters$(){return this.commentSidebarFilters$.asObservable()}setEffectiveSidebarFilters(e){try{this.effectiveSidebarFilters$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEffectiveSidebarFilters: ",t)}}getEffectiveSidebarFilters$(){return this.effectiveSidebarFilters$.asObservable()}setCommentSidebarSystemFiltersOperator(e){try{this.commentSidebarSystemFiltersOperator$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentSidebarSystemFiltersOperator: ",t)}}getCommentSidebarSystemFiltersOperator(){return this.commentSidebarSystemFiltersOperator$.value}getCommentSidebarSystemFiltersOperator$(){return this.commentSidebarSystemFiltersOperator$.asObservable()}enableCommentPinHighlighter(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentPinHighlighter:!0}}),this.domService.enableCommentPinHighlighter()}catch(e){this.loggingService.catch("Error in CommentService enableCommentPinHighlighter: ",e)}}disableCommentPinHighlighter(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentPinHighlighter:!1}}),this.domService.disableCommentPinHighlighter()}catch(e){this.loggingService.catch("Error in CommentService disableCommentPinHighlighter: ",e)}}setCustomReactions(e){try{this.reactionService.setCustomReactions(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomReactions: ",t)}}onCommentSelectionChange$(){return this.commentSelectionChange$.asObservable()}onVisibilityOptionClicked$(){return this.visibilityOptionClicked$.asObservable()}emitVisibilityOptionClicked(e){this.visibilityOptionClicked$.next(e)}onCommentAdd$(){return this.commentAdded$.asObservable()}onCommentUpdate$(){return this.commentUpdated$.asObservable()}onCommentAnnotationDelete$(){return this.commentAnnotationDeleted$.asObservable()}onMultiThreadCommentAnnotationDelete$(){return this.multiThreadCommentAnnotationDeleted$.asObservable()}getCommentMode(){try{let e="freestyle";return this.getStreamMode()?e="stream":this.getPopoverMode()&&(e="popover"),e}catch(e){return this.loggingService.catch("Error in CommentService getCommentMode: ",e),"freestyle"}}getCommentType(e){try{return e.targetElement?"element":e.targetTextRange?"text":e.areaAnnotationId?"area":""}catch(t){return this.loggingService.catch("Error in CommentService getCommentType: ",t),""}}getCommentAnnotationAvailableOnXPath(e,t,i){try{return this.commentAnnotationById$.pipe(Se(()=>this.draftCommentAnnotationsByAnnotationId$),Se(a=>(!i&&t&&(i=nl(t,["id","data-id"])),ce(y(h({},a),{element:i})))),Se(a=>this.getLocations$().pipe(ue(l=>y(h({},a),{locationIds:l})))),ue(({locationIds:a,element:l})=>{let c=[],d=this.docService.getDocumentPaths();if(d?.documentId){let m=this.docService.getAdditionalDocumentIdFromElement(l),u=m?this.docService.generateDocumentId(m):d?.documentId,_=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:d?.organizationId,documentId:u||""});if(_)for(let I of _)(t&&I?.targetElementId===t||I?.targetElement?.xpath===e)&&a?.includes(I?.locationId)&&c.push(I)}return c.length?c:null}))}catch(a){return this.loggingService.catch("Error in CommentService isCommentAnnotationAvailableOnXPath: ",a),ce(null)}}getCommentAnnotationsByContext({context:e,contextOptions:t,element:i,clientDocumentId:a}){try{return this.commentAnnotationById$.pipe(Se(()=>this.draftCommentAnnotationsByAnnotationId$),Se(()=>this.docService.getDocumentPaths$()),ue(()=>{let l=null,c=this.docService.getDocumentPaths(),d=Es(e),m=this.generateContextId(d);if(c?.documentId){let u=a||this.docService.getAdditionalDocumentIdFromElement(i??null),_=u?this.docService.generateDocumentId(u):c?.documentId,I=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:c?.organizationId,documentId:_||""});if(I){l=[];for(let A of I)t?.partialMatch?WN(A?.context,d)&&l.push(A):m&&A?.contextId===m&&l.push(A)}}return l}))}catch(l){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByContext: ",l),ce(null)}}getCommentAnnotationByAnnotationId(e){try{return this.commentAnnotationById$.pipe(ue(()=>this.getAnnotationById(e)),Se(t=>t?t?.iam?.accessMode===Ca.PRIVATE?this.isPrivateCommentAllowed$().pipe(ue(i=>{if(i)return t})):ce(t):ce(t)),Se(t=>t?this.filterCommentsUsingSidebarSettings(t).pipe(ue(i=>{if(i)return i})):ce(t)))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationByAnnotationId: ",t),ce(void 0)}}getMultiThreadCommentAnnotationByAnnotationId(e){return this.multiThreadCommentAnnotationById$.pipe(ue(()=>this.getMultiThreadAnnotationById(e)))}getCommentBubbleElement(e){try{let t=document.querySelector(`${N.TAGS.VELT_COMMENT_BUBBLE}[${N.ATTRIBUTES.VELT_ANNOTATION_IDS}*="${e?.annotationId}"]`);return t||(t=document.querySelector(`${N.TAGS.SNIPPYLY_COMMENT_BUBBLE}[${N.ATTRIBUTES.VELT_ANNOTATION_IDS}*="${e?.annotationId}"]`)),t}catch(t){return this.loggingService.catch("Error in CommentService getCommentBubbleElement: ",t),null}}getCommentAnnotationsBySectionId(e){try{return this.commentAnnotationById$.pipe(Se(()=>this.docService.getDocumentPaths$().pipe(ue(t=>({documentPaths:t,sectionId:e})))),Se(t=>{let i=nl(e,["id","data-id"]);if(i){let a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.genarateLocationId(a);return this.docService.getLocations$().pipe(ue(c=>{let m=Object.values(c||{}).find(u=>u.locationId===l||a?.id&&u.location.id===a.id);return y(h({},t),{additionalLocation:m,locationOnElement:!!a})}))}}return ce(y(h({},t),{additionalLocation:null,element:i}))}),Se(t=>t?.locationOnElement?ce(t):this.docService.getLocation$().pipe(ue(i=>y(h({},t),{location:i})))),ue(({documentPaths:t,location:i,additionalLocation:a,locationOnElement:l,element:c})=>{let d=null;if(this.authService.getUser()&&t?.documentId){let u=this.docService.getAdditionalDocumentIdFromElement(c),_=u?this.docService.generateDocumentId(u):t?.documentId,I=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:t?.organizationId,documentId:_||""});if(I){d=[];let A=am(e);l?a?.location?.id?A=am([a?.location?.id,e]):a?.locationId&&(A=am([a?.locationId+"",e])):i&&(i?.location?.id?A=am([i?.location?.id,e]):i?.locationId&&(A=am([i?.locationId+"",e])));for(let M of I)M?.multiThreadAnnotationId===A?d.push(M):(M?.targetInlineCommentElementId===e||M?.targetElementId===e)&&(l?a&&_0({location:a?.location,locationId:a?.locationId},{location:M.location,locationId:M.locationId})&&d.push(M):i?_0({location:i?.location,locationId:i?.locationId},{location:M.location,locationId:M.locationId})&&d.push(M):M?.locationId||d.push(M))}}return d}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsBySectionId: ",t),ce(null)}}getCommentAnnotationsByMultiThreadAnnotationId(e){try{return this.commentAnnotationById$.pipe(Se(()=>this.multiThreadCommentAnnotationById$),Se(()=>this.docService.getDocumentPaths$().pipe(ue(t=>({documentPaths:t,multiThreadAnnotationId:e})))),ue(({documentPaths:t,location:i,additionalLocation:a,locationOnElement:l})=>{let c=null;if(t?.documentId){let d=this.getMultiThreadAnnotationById(e),{documentId:m,organizationId:u}=d?.metadata||{documentId:t?.documentId,organizationId:t?.organizationId},_=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:u,documentId:m||""});if(_){c=[];for(let I of _)I?.multiThreadAnnotationId===e&&d?.commentAnnotations?.[I?.annotationId]&&c.push(I)}}return c}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsBySectionId: ",t),ce(null)}}getCommentAnnotationsByAnnotationIds(e){try{return this.commentAnnotationById$.pipe(Se(()=>this.draftCommentAnnotationsByAnnotationId$),Se(()=>this.docService.getDocumentPaths$().pipe(ue(t=>({documentPaths:t,annotationIds:e})))),ue(({documentPaths:t})=>{let i=null;if(t?.documentId){let a=this.commentAnnotationById$.value?Object.values(this.commentAnnotationById$.value):[],l=this.draftCommentAnnotationsByAnnotationId$.value?Object.values(this.draftCommentAnnotationsByAnnotationId$.value):[];if(a=[...a,...l],a){i=[];for(let c of a)e.includes(c?.annotationId)&&i.push(c)}}return i}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByAnnotationIds: ",t),ce(null)}}getCommentAnnotationsByFolderId({folderId:e,veltFolderId:t}){try{return this.commentAnnotationById$.pipe(Se(()=>this.draftCommentAnnotationsByAnnotationId$),Se(()=>this.docService.getDocumentPaths$()),ue(()=>{e&&!t&&(t=Lr(e));let i=this.authService.getUser(),a=this.docService.getDocumentPaths(),l=null;if(i&&a?.documentId){this.commentAnnotationById$.value&&(l={},Object.values(this.commentAnnotationById$.value).forEach(d=>{d?.metadata?.folderId==e&&d?.metadata?.veltFolderId==t&&(l[d?.annotationId]=d)}));let c=this.draftCommentAnnotationsByAnnotationId$.value;c&&(l===null&&(l={}),Object.values(c).forEach(d=>{d?.metadata?.folderId==e&&d?.metadata?.veltFolderId==t&&!l[d?.annotationId]&&(l[d?.annotationId]=d)}))}return l?Object.values(l):null}))}catch(i){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByFolderId: ",i),ce(null)}}getCommentAnnotationsForCommentComponent(e){try{let{annotationId:t,folderId:i,veltFolderId:a,targetElementId:l,clientDocumentId:c,documentId:d,context:m,contextOptions:u,element:_,type:I,sectionId:A,locationId:M}=e||{};if(c&&!d&&(d=this.docService.generateDocumentId(c)),i&&!a&&(a=Lr(i)),t)return this.getCommentAnnotationByAnnotationId(t).pipe(ue(q=>q?[q]:null));let V=[];if(l&&(I==="pin"||I==="tool"||I==="bubble")){let q=nl(l,["id","data-id"]);if(q){let ae=q,ye=this.domService.getXPath(q);V.push(this.getCommentAnnotationAvailableOnXPath(ye,l,ae))}}return A&&V.push(this.getCommentAnnotationsBySectionId(A)),m&&V.push(this.getCommentAnnotationsByContext({context:m,contextOptions:u,element:_,clientDocumentId:c})),d&&V.push(this.getCommentAnnotationsByDocumentId$({documentId:d})),i&&V.push(this.getCommentAnnotationsByFolderId({folderId:i,veltFolderId:a})),V.length===0?ce(null):gn(V).pipe(ue(q=>{let ae=q.filter(ie=>ie!==null&&Array.isArray(ie));if(ae.length===0)return null;if(ae.length===1){let ie=ae[0];return M&&ie?.length?ie.filter(Ie=>Ie?.location?.id===M):ie}let ye=ae[0];for(let ie=1;ie<ae.length;ie++){let ge=ae[ie];ye=ye.filter(Ie=>ge.some(Te=>Te.annotationId===Ie.annotationId))}return M&&ye?.length&&(ye=ye.filter(ie=>ie?.location?.id===M)),ye}),_t(Kt))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsForCommentComponent: ",t),ce(null)}}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.allowedElementIds$.value?.length||this.allowedElementClassNames$.value?.length||this.allowedElementQuerySelectors$.value?.length?!!(this.allowedElementIds$.value?.length&&this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)||this.allowedElementClassNames$.value?.length&&this.domService.isElementInsideListedElementClassNames(e,this.allowedElementClassNames$.value)||this.allowedElementQuerySelectors$.value?.length&&this.domService.isElementInsideListedElementQuerySelectors(e,this.allowedElementQuerySelectors$.value)):!0}catch(t){return this.loggingService.catch("Error in CommentService isElementInsideAllowedElements: ",t),!1}}getNearestAllowedElement(e){try{let t=this.domService.getListedElements({elementIds:this.allowedElementIds$.value,elementClassNames:this.allowedElementClassNames$.value,elementQuerySelectors:this.allowedElementQuerySelectors$.value});if(t?.length){for(let i=0;i<t.length;i++){let a=t[i];if(e.contains(a))return a}return null}return null}catch(t){return this.loggingService.catch("Error in CommentService getNearestAllowedElement: ",t),null}}isElementInsideManualCommentContainer(e){try{return this.domService.isElementInsideParentWithAttribute(e,N.ATTRIBUTES.VELT_MANUAL_COMMENT_CONTAINER,"true")}catch(t){return this.loggingService.catch("Error in CommentService isElementInsideManualCommentContainer: ",t),!1}}saveComment(e,t){return X(this,null,function*(){try{t?.annotation&&(e=t.annotation),e&&(e=JSON.parse(JSON.stringify(e)));let i=this.originalCommentAnnotationsByDocumentId$.value[e.annotationId];if(i?.comments?.length){let u=JSON.parse(JSON.stringify(e.comments||[]));e.comments=[],i.comments?.forEach(_=>{let I=u.find(A=>A.commentId===_.commentId);I?e.comments.push(I):e.comments.push(_)})}e.comments||(e.comments=[]);let a=!1,l=!1,c;switch(t.type){case Ot.NEWLY_ADDED:case Ot.ADDED:if(!t.updatedComment)break;e?.comments?.length||(l=!0),e.comments.push(t.updatedComment);let u=t?.assigned||void 0;c={commentAnnotation:e,targetComment:t.updatedComment,actionType:t.type,otherFields:{assigned:u}};break;case Ot.PUBLISHED:e.isDraft=!1;break;case Ot.APPROVED:e.approved=!0,c={commentAnnotation:e,targetComment:null,actionType:Ot.APPROVED};break;case Ot.ASSIGNED:{let ae=i?.assignedTo;e.assignedTo=t.assignedTo,c={commentAnnotation:e,targetComment:null,actionType:Ot.ASSIGNED,otherFields:{oldAssignedTo:ae,newAssignedTo:t.assignedTo}};break}case Ot.UPDATED:if(!t.updatedComment)break;let _=e.comments.findIndex(ae=>ae.commentId===t.updatedComment.commentId);if(_>=0){let ae=e.comments[_]?.commentText;e.comments[_]=t.updatedComment,e.comments[_].status=Ot.UPDATED;let ye=t?.assigned||void 0;c={commentAnnotation:e,targetComment:t.updatedComment,actionType:Ot.UPDATED,otherFields:{assigned:ye,oldCommentText:ae}}}break;case Ot.REACTION_ADDED:if(!t.updatedComment)break;let I=e.comments.findIndex(ae=>ae.commentId===t.updatedComment.commentId);I>=0&&(e.comments[I]=t.updatedComment,e.comments[I].status=Ot.UPDATED,c={commentAnnotation:e,targetComment:t.updatedComment,actionType:Ot.REACTION_ADDED});break;case Ot.REACTION_DELETED:if(!t.updatedComment)break;let A=e.comments.findIndex(ae=>ae.commentId===t.updatedComment.commentId);A>=0&&(e.comments[A]=t.updatedComment,e.comments[A].status=Ot.UPDATED,c={commentAnnotation:e,targetComment:t.updatedComment,actionType:Ot.REACTION_DELETED});break;case Ot.STATUS_CHANGED:if(e.status.type==="terminal"){this.domService.resetSelectedAnnotationsMap(!1,"comment");let ae=this.authService.getUser();e.resolvedByUserId=ae?.userId,e.resolvedByUser=ae}c={commentAnnotation:e,targetComment:null,actionType:Ot.STATUS_CHANGED,otherFields:{oldStatus:t.oldStatus,newStatus:t.newStatus}};break;case Ot.PRIORITY_CHANGED:c={commentAnnotation:e,targetComment:null,actionType:Ot.PRIORITY_CHANGED,otherFields:{oldPriority:t.oldPriority,newPriority:t.newPriority}};break;case Ot.ACCESS_MODE_CHANGED:c={commentAnnotation:e,targetComment:null,actionType:Ot.ACCESS_MODE_CHANGED,otherFields:{oldAccessMode:t.oldAccessMode,newAccessMode:t.newAccessMode}};break;case Ot.CUSTOM_LIST_CHANGED:c={commentAnnotation:e,targetComment:null,actionType:Ot.CUSTOM_LIST_CHANGED,otherFields:{oldCustomList:t.oldCustomList,newCustomList:t.newCustomList}};break;case Ot.SUBSCRIBED:c={commentAnnotation:e,targetComment:null,actionType:Ot.SUBSCRIBED};break;case Ot.UNSUBSCRIBED:c={commentAnnotation:e,targetComment:null,actionType:Ot.UNSUBSCRIBED};break;case Ot.DELETED:if(!t.updatedComment)break;let M=e.comments.findIndex(ae=>ae.commentId===t.updatedComment.commentId);if(M>=0){if((M===0&&this.deleteThreadWithFirstComment$.value!==!1||this.deleteReplyConfirmation$.value)&&!t.skipDeleteThreadConfirmation){let ie={};if(this.deleteReplyConfirmation$.value&&(M!==0||this.deleteThreadWithFirstComment$.value===!1)?ie={title:"Delete comment?",message:"This selected comment will be deleted.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"reply",type:"reply"}:ie={title:"Delete thread?",message:"All replies to this thread will be lost.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"comment",type:"comment"},!(yield this.dialog.open(al,{panelClass:["velt-confirm-dialog-overlay-pane","velt-mat-dialog-container"],data:ie}).afterClosed().toPromise()))return}let ae=e.comments.splice(M,1),ye=e.metadata;ae?.length&&ae.forEach(ie=>{ie?.attachments&&ie.attachments.forEach(ge=>{let Ie={attachmentId:ge.attachmentId,organizationId:ye?.clientOrganizationId??ye?.organizationId??null,documentId:ye?.clientDocumentId??ye?.documentId??null,folderId:ye?.folderId??null,commentAnnotationId:e.annotationId,apiKey:ye?.apiKey??null};this.deleteAttachment({attachment:ge,metadata:Ie})}),ie?.reactionAnnotationIds&&ie.reactionAnnotationIds.forEach(ge=>{this.deleteReaction(ge)})})}e?.status?.type==="terminal"&&(e.status=this.customFilterService.defaultStatus),M===0&&this.deleteThreadWithFirstComment$.value!==!1||e.comments?.length===0?a=!0:(this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_THREAD_DELETED,{annotationId:e.annotationId,commentThreadId:t.updatedComment.commentId,commentMode:this.getCommentMode()}),c={commentAnnotation:e,targetComment:t.updatedComment,actionType:Ot.DELETED});break;case Ot.ACCEPTED:let V={annotationId:e.annotationId,actionUser:this.authService.getUser(),actionType:Ot.ACCEPTED,replaceContentHtml:e?.comments?.length?e?.comments[0]?.replaceContentHtml:void 0,replaceContentText:e?.comments?.length?e?.comments[0]?.replaceContentText:void 0,annotation:this.getCommentAnnotationForClient(e)};this.commentAccepted$.next(V),c={commentAnnotation:e,targetComment:null,actionType:Ot.ACCEPTED};break;case Ot.REJECTED:let q={annotationId:e.annotationId,actionUser:this.authService.getUser(),actionType:Ot.REJECTED,replaceContentHtml:e?.comments?.length?e?.comments[0]?.replaceContentHtml:void 0,replaceContentText:e?.comments?.length?e?.comments[0]?.replaceContentText:void 0,annotation:this.getCommentAnnotationForClient(e)};this.commentRejected$.next(q),this.domService.resetSelectedAnnotationsMap(),c={commentAnnotation:e,targetComment:null,actionType:Ot.REJECTED};break;default:break}if(e.resolvedByUserId&&e.status.type!=="terminal"&&(e.resolvedByUserId=null,e.resolvedByUser=null),t.visibility)try{let u=h({},t.visibility);if(u.type==="organizationPrivate"&&!u.organizationId){let I=this.docService.getOrganizationConfig();I?.clientOrganizationId&&(u.organizationId=I.clientOrganizationId)}let _=Xu(u);_.length>0&&(e.context||(e.context={}),e.context._setAccessFields=_)}catch(u){this.loggingService.catch("Error building accessFields from visibility in saveComment:",u)}if(t?.updatedComment?.isDraft&&(c=void 0),a)this.deleteCommentPinAnnotation(e,!0),this.domService.resetSelectedAnnotationsMap(!1,"comment");else{if(l&&e.comments?.length&&this.enableAutoCategorize$?.value&&this.setCommentCategory(e),e.context?.access&&e.context?.accessFields&&t.updatedComment?.from?.userId&&!this.userPermissionService?.hasUserContextAccess({userId:t.updatedComment?.from?.userId,accessFields:e.context.accessFields})){this.loggingService.catch("User does not have context access to update comment annotation.",void 0,void 0,!0);return}this.updateComment(e,!1,!1,c,!0,t.updatedComment),e?.multiThreadAnnotationId&&(t.type===Ot.ADDED||t.type===Ot.NEWLY_ADDED)&&e.comments?.length===1?setTimeout(()=>{this.domService.resetSelectedAnnotationsMap(!1,"comment")},100):this.domService.updateSelectedAnnotationInMap([e])}let d=this.getCustomPinById(e.annotationId),m={type:t.type,annotation:this.getCommentAnnotationForClient(e),targetAnnotationId:e.annotationId,targetCommentId:t.updatedComment?.commentId,updateContext:(u,_)=>{this.updateCommentAnnotationContext(e.annotationId,u,_)}};if(d!==void 0&&(m.element=d),delete m?.annotation?.pageInfo,delete m?.annotation?.targetElement,delete m?.annotation?.targetTextRange,m?.type===Ot.DELETED&&(e.comments?.length||(m.annotation=null)),a||this.commentUpdated$.next(m),t.type===Ot.NEWLY_ADDED&&!a&&e?.annotationId){let u=this.pendingAddCommentAnnotationData.get(e.annotationId);if(u){this.pendingAddCommentAnnotationData.delete(e.annotationId);let _=y(h({},u),{annotation:this.getCommentAnnotationForClient(e),targetCommentId:t.updatedComment?.commentId}),I=yield this.commentActionsService?.getAddCommentAnnotationEventFromCommentAddEventData(_);I&&this.commentActionsService?.triggerAddCommentAnnotationEvent(I),t.updatedComment&&(yield this.commentActionsService?.triggerAddCommentEvent({annotation:e,newComment:t.updatedComment}))}}t.type===Ot.ADDED&&t._dispatchAddCommentEvent&&!a&&e?.annotationId&&t.updatedComment&&(yield this.commentActionsService?.triggerAddCommentEvent({annotation:e,newComment:t.updatedComment}))}catch(i){this.loggingService.catch("Error in CommentService saveComment: ",i)}})}attachComment(e,t=[],i,a,l,c,d,m){try{this.loggingService.log("%c[WB] Calling FUNCTION: attachComment","color: green;");let u;if(e){let _=nl(e,t);_&&(u={targetElement:{xpath:this.domService.getXPath(_),topPercentage:50,leftPercentage:90},targetElementId:e})}(u||i||l)&&this.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,c,void 0,void 0,u,m,void 0,void 0,a,void 0,void 0,void 0,i,void 0,l,void 0,void 0,d)}catch(u){this.loggingService.catch("Error in CommentService attachComment: ",u)}}generateComponentIdFromObject(e){try{let t=Es(e||{});return It(JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CommentService generateComponentIdFromObject: ",t);return}}updateNotificationsDatabase(e,t,i,a={}){try{let l=h({annotationData:e,targetAnnotationData:t,actionType:i,notificationSource:"comment"},a);this.notificationService.updateNotificationDatabase(l)}catch(l){this.loggingService.catch("Error in CommentService updateNotificationsDatabase: ",l)}}getUserContacts$(){return this.contactService.getUserContacts$()}addUserContact(e){this.contactService.addUserContact(e)}getCustomUserContacts(){try{return this.contactService.getCustomUserContacts()}catch(e){return this.loggingService.catch("Error in CommentService getCustomUserContacts:",e),null}}getCustomUserContactsConfig(){try{return this.contactService.getCustomUserContactsConfig()}catch(e){this.loggingService.catch("Error in CommentService getCustomUserContactsConfig:",e);return}}getElementFromComment(e){try{let t=null;if(e?.ghostComment)!t&&e.ghostComment?.targetElement?.fXpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.fXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e.ghostComment?.targetElement?.cfXpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.cfXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e.ghostComment?.targetElement?.xpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.xpath),t&&!this.domService.isElementVisible(t)&&(t=null));else{let i=!1,a=e?.targetElement?.anchor;if(!t&&a){let l=this.domService.resolveAnchorRecord(a);l?.element&&this.domService.isElementVisible(l.element)&&Kr(l.element)&&(t=l.element)}!t&&e?.targetElement?.xpath&&(i=this.domService.isXpathWithId(e?.targetElement?.xpath),t=this.domService.getElementFromXPath(e?.targetElement?.xpath),t&&!this.domService.isElementVisible(t)&&(t=null)),i||(!t&&e?.targetElement?.cfXpath&&(t=this.domService.getElementFromXPath(e?.targetElement?.cfXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e?.targetElement?.fXpath&&(t=this.domService.getElementFromXPath(e?.targetElement?.fXpath),t&&!this.domService.isElementVisible(t)&&(t=null)))}return t&&!Kr(t)&&(t=null),t}catch(t){return this.loggingService.catch("Error in CommentService getElementFromComment: ",t),null}}getElementFromComments(e){try{let t=[],i=null;if(e?.ghostComment)!i&&e.ghostComment?.targetElement?.fXpath&&(i=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.fXpath),i&&!this.domService.isElementVisible(i)&&(i=null)),!i&&e.ghostComment?.targetElement?.cfXpath&&(i=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.cfXpath),i&&!this.domService.isElementVisible(i)&&(i=null)),!i&&e.ghostComment?.targetElement?.xpath&&(i=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.xpath),i&&!this.domService.isElementVisible(i)&&(i=null));else{let a=!1,l=e?.targetElement?.anchor;if(!i&&l){let c=this.domService.resolveAnchorRecord(l);c?.element&&this.domService.isElementVisible(c.element)&&Kr(c.element)&&(i=c.element)}!i&&e?.targetElement?.xpath&&(a=this.domService.isXpathWithId(e?.targetElement?.xpath),i=this.domService.getElementFromXPath(e?.targetElement?.xpath),i&&!this.domService.isElementVisible(i)&&(i=null)),a||(!i&&e?.targetElement?.cfXpath&&(i=this.domService.getElementFromXPath(e?.targetElement?.cfXpath),i&&!this.domService.isElementVisible(i)&&(i=null)),!i&&e?.targetElement?.fXpath&&(i=this.domService.getElementFromXPath(e?.targetElement?.fXpath),i&&!this.domService.isElementVisible(i)&&(i=null)))}return i&&!Kr(i)&&(i=null),e?.targetElementId&&(t=Array.from(ahe(e.targetElementId,["id","data-id"]))),i&&!t.includes(i)&&t.push(i),t}catch(t){return this.loggingService.catch("Error in CommentService getElementFromComment: ",t),[]}}getGhostCommentTargetElement(e){try{let t=e.targetElement?.fXpath||e.targetElement?.xpath,i=null;if(t)for(;!i&&t;)i=this.domService.getElementFromXPath(t),i&&(!this.domService.isElementVisible(i)||!Kr(i))&&(i=null),i||(t=t.substring(0,t.lastIndexOf("/")));return t==="/"&&(t=""),t?{xpath:t,topPercentage:e?.targetElement?.topPercentage||0,leftPercentage:e?.targetElement?.leftPercentage||0}:null}catch(t){return this.loggingService.catch("Error in CommentService getGhostCommentTargetElement: ",t),null}}setGhostCommentMessage(e){try{if(e?.ghostComment){e.ghostComment.message="Original content not found.",e.ghostComment.type=ys.ELEMENT_DELETED;let t=e?.pageInfo?.deviceInfo?.deviceType,i=new hr().getDeviceType();t&&t!==i&&(e.ghostComment.type=ys.DIFFERENT_DEVICE,e.ghostComment.message=`Original comment was added on ${t}.`,[$i.MOBILE,$i.TABLET].includes(t)&&[$i.MOBILE,$i.TABLET].includes(i)||[$i.DESKTOP,$i.MONITOR].includes(t)&&[$i.DESKTOP,$i.MONITOR].includes(i)?e.ghostComment.isSameGroup=!0:e.ghostComment.isSameGroup=!1)}}catch(t){this.loggingService.catch("Error in CommentService setGhostCommentMessage: ",t)}}addAnnotationToGhostCommentAnnotationMap(e){try{let t=this.ghostCommentAnnotationMap$.value||{},i=t[e?.annotationId]||{};sr(e.ghostComment,i)||(t[e?.annotationId]=e.ghostComment,this.ghostCommentAnnotationMap$.next(t))}catch(t){this.loggingService.catch("Error in CommentService addAnnotationToGhostCommentAnnotationMap: ",t)}}removeAnnotationFromGhostCommentAnnotationMap(e){try{let t=this.ghostCommentAnnotationMap$.value||{};t[e?.annotationId]&&(delete t[e?.annotationId],this.ghostCommentAnnotationMap$.next(t))}catch(t){this.loggingService.catch("Error in CommentService removeAnnotationFromGhostCommentAnnotationMap: ",t)}}getGhostCommentAnnotationMap$(){return this.ghostCommentAnnotationMap$.asObservable()}getGhostCommentAnnotationMap(){return this.ghostCommentAnnotationMap$.value||{}}getUnreadCommentsMap$(){return this.unreadCommentsMap$.asObservable().pipe(_t(Kt))}getUnreadCommentsMap(){return this.unreadCommentsMap$.value}getUnreadCommentCountByAnnotationId$(e){return this.getUnreadCommentsMap$().pipe(ue(t=>t?{count:t[e]||0}:null))}getUnreadCommentAnnotationCountOnCurrentDocument$(){return this.getUnreadCommentsMap$().pipe(ue(e=>e?{count:Object.keys(e??{}).length||0}:null))}getUnreadCommentCountOnCurrentDocument$(){return this.getUnreadCommentsMap$().pipe(ue(e=>e?{count:Object.values(e).reduce((i,a)=>i+a,0)}:null))}getUnreadCommentCountByLocationId$(e){return this.getUnreadCommentsMap$().pipe(ue(t=>{if(t){let i=this.docService.getDocumentPaths(),a=[],l=0;return i?.documentId&&(a=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:i?.organizationId,documentId:i?.documentId}),a&&Object.keys(t).forEach(c=>{a?.find(m=>m.annotationId===c)?.location?.id===e&&(l+=t[c])})),{count:l}}else return null}))}getUnreadCommentAnnotationCountByLocationId$(e){return this.getUnreadCommentsMap$().pipe(ue(t=>{if(t){let i=this.docService.getDocumentPaths(),a=[],l=0;return i?.documentId&&(a=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:i?.organizationId,documentId:i?.documentId}),Object.keys(t).forEach(c=>{t[c]&&a?.find(m=>m.annotationId===c)?.location?.id===e&&(l+=1)})),{count:l}}else return null}))}setCommentAnnotationsAsRead(e){try{for(let t of e)this.viewsService.setCommentAnnotationAsRead(t)}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsAsRead: ",t)}}setCommentAnnotationsAsResolved(e){try{let t=this.customFilterService.resolvedStatus;if(t){for(let i of e)if(t?.id!==i?.status?.id){let a=JSON.parse(JSON.stringify(i||{}));i.status=this.customFilterService.resolvedStatus;let l={annotation:i,type:Ot.STATUS_CHANGED,oldStatus:a.status,newStatus:this.customFilterService.resolvedStatus};this.saveComment(i,l)}}}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsAsResolved: ",t)}}isCommentAnnotationUnread(e){try{let t=this.authService.getUser();return!(t?.userSnippylyId&&e?.viewedByUserIds?.length&&e?.viewedByUserIds?.includes(t?.userSnippylyId))}catch(t){return this.loggingService.catch("Error in CommentService isCommentAnnotationUnread: ",t),!1}}updateCommentDialogPosition(){try{this.updateCommentDialogPositionTriggerSubject$.next()}catch(e){this.loggingService.catch("Error in CommentService updateCommentDialogPosition: ",e)}}updateCommentDialogPositionTrigger$(){return this.updateCommentDialogPositionTriggerSubject$.asObservable()}enableAreaComment(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{areaComment:!0}}),this.areaCommentEnabled$.value===!0)return;this.areaCommentEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAreaComment: ",e)}}disableAreaComment(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{areaComment:!1}}),this.areaCommentEnabled$.value===!1)return;this.areaCommentEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAreaComment: ",e)}}getAreaCommentEnabled$(){return this.areaCommentEnabled$.asObservable()}getAreaCommentEnabled(){return this.areaCommentEnabled$.value}setPinCursorImage(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setPinCursorImage","color: green;"),e&&(e=`url(${e}) 0 31, auto`),this.commentPinCursorImage$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setPinCursorImage: ",t)}}getPinCursorImage$(){return this.commentPinCursorImage$.asObservable()}getPinCursorImage(){return this.commentPinCursorImage$.value}setCommentAnnotationsFromCommentsContainer(e){try{this.commentAnnotationsFromCommentsContainer$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsFromCommentsContainer: ",t)}}getCommentAnnotationsFromCommentsContainer$(){return this.commentAnnotationsFromCommentsContainer$.asObservable()}getCommentAnnotationsFromCommentsContainer(){return this.commentAnnotationsFromCommentsContainer$.value}addManualComment(e){return X(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addManualComment","color: green;"),new Promise((t,i)=>{let a=this.domService.getLastDocumentClick()?.target,l=e?.location||this.docService.getAdditionLocationFromElement(a);if(l?.id){let c=this.docService.getLocationByClientLocationId(l.id);c&&(l=c)}this.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,l,void 0,e,void 0,void 0,void 0,c=>{t(c)}),this.addCommentMode$?.value&&!this.persistentCommentMode$?.value&&this.disableAddCommentMode()})}catch(t){return this.loggingService.catch("Error in CommentService addManualComment: ",t),null}})}getCommentUrl(e){try{return e?.pageInfo?.commentUrl?e.pageInfo.commentUrl:(e?.pageInfo||(e.pageInfo=ro(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.commentUrl=this.generateCommentUrl(e),this.updateComment(e),e.pageInfo?.commentUrl)}catch(t){this.loggingService.catch("Error in CommentService getCommentUrl: ",t);return}}uploadFile(e,t){let i=`${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentPaths?.documentId}/${N.FIREBASE_PARTIAL_PATH_COMMENT}/${t.annotationId}`;this.documentPaths?.organizationId&&(i=`${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentPaths?.documentId}/${N.FIREBASE_PARTIAL_PATH_COMMENT}/${t.annotationId}`);let a={organizationId:t.metadata?.clientOrganizationId??this.documentPaths?.clientOrganizationId??null,documentId:t.metadata?.clientDocumentId??this.documentPaths?.clientDocumentId??null,commentAnnotationId:t.annotationId,apiKey:t.metadata?.apiKey??this.configService?.getApiKey()??null,folderId:t.metadata?.folderId??this.documentPaths?.folderId??null,attachmentId:null};return this.storageService.uploadFile({path:i,file:e,metadata:a,useAttachmentResolver:this.attachmentResolverService.attachmentDataProviderAvailable()})}downloadAttachment(e){this.storageService.downloadAttachment(e)}deleteAttachment({attachment:e,metadata:t}){return this.storageService.deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:this.attachmentResolverService.attachmentDataProviderAvailable()})}deleteReaction(e){try{this.reactionService.deleteReactionPinAnnotation(e)}catch(t){this.loggingService.catch("Error in CommentService deleteReaction: ",t)}}generateCommentUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(N.URL_PARAMS.COMMENT_ID),t.searchParams.append(N.URL_PARAMS.COMMENT_ID,e.annotationId),t.href}getCustomPinById(e){if(this.customPinsById.has(e))return this.customPinsById.get(e)}setCustomStatuses(e){try{if(e===void 0)return;this.customStatusesShown$.next(!0),this.customFilterService.setCustomStatusFilters(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomStatuses: ",t)}}getCustomStatusesShown$(){return this.customStatusesShown$.asObservable()}getCustomStatusesShown(){return this.customStatusesShown$.value}setCustomPriorities(e){try{if(e===void 0)return;this.customFilterService.setCustomPriorityFilters(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomPriorities: ",t)}}setCustomCategories(e){try{if(e===void 0)return;this.customFilterService.setCustomCategories(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomCategories: ",t)}}addCommentOnSelectedText(){try{let e=this.authService.getUser();if(this.textCommentMode$.value&&e&&!(e?.isReadOnly||e?.isAnonymous)&&this.authService.isFeatureAllowed(je.COMMENT)){let t=this.domService.getRange();if(window.getSelection()?.toString()&&!O3()&&t?.commonAncestorContainer&&this.isElementInsideAllowedElements(t.commonAncestorContainer)&&!xg(t.commonAncestorContainer)){let i=t?this.domService.getTargetTextRangeFromSelectionRange(t):void 0;this.domService.clearTextSelection(),setTimeout(()=>{this.addComment(void 0,i)},100)}}}catch(e){this.loggingService.catch("Error in CommentService addCommentOnSelectedText: ",e)}}getInlineCommentSectionConfig(e){try{let t;if(e){let i=e?.closest(`[${N.ATTRIBUTES.VELT_TARGET_INLINE_COMMENT_ELEMENT_ID}]`);if(i){let a=i.getAttribute(N.ATTRIBUTES.VELT_TARGET_INLINE_COMMENT_ELEMENT_ID);a&&(t={},t.targetInlineCommentElementId=a,i.getAttribute(N.ATTRIBUTES.VELT_INLINE_COMMENT_SECTION_CONFIG)&&(t.config=JSON.parse(i.getAttribute(N.ATTRIBUTES.VELT_INLINE_COMMENT_SECTION_CONFIG)||"{}")))}}return t}catch(t){this.loggingService.catch("Error in CommentService getInlineCommentSectionConfig: ",t)}}createCustomListDataOnAnnotation(e){try{if(e===void 0)return;this.customChipDropdownData$.next(e)}catch(t){this.loggingService.catch("Error in CommentService createCustomListDataOnAnnotation: ",t)}}getCustomChipDropdownData$(){return this.customChipDropdownData$.asObservable()}getCustomChipDropdownData(){return this.customChipDropdownData$.value}setSubscribedUsersDataInCommentAnnotation(e){try{let t={},i=e?.unsubscribedUsers||{},a={};if(e?.subscribedUsers&&Object.keys(e.subscribedUsers||{}).forEach(l=>{let c=e.subscribedUsers?.[l];c?.type==="manual"&&(t[l]=c)}),e?.assignedTo?.userId){let l=It(e?.assignedTo?.userId);i[l]||t[l]?.type!=="manual"&&(t[l]={user:e?.assignedTo,type:"auto"})}e?.comments?.filter(l=>!l?.isDraft)?.forEach(l=>{if(l?.from?.userId){let c=It(l?.from?.userId);i[c]||t[c]?.type!=="manual"&&(t[c]={user:l?.from,type:"auto"})}l?.to?.forEach(c=>{if(c?.userId){let d=It(c.userId);i[d]||t[d]?.type!=="manual"&&(t[d]={user:c,type:"auto"})}}),l?.toOrganizationUserGroup?.forEach(c=>{if(c?.groupId)a[c?.groupId]={type:"auto"};else if(c?.clientGroupId){let d=It(c.clientGroupId);a[d]={type:"auto"}}})}),e.subscribedUsers=t,e.unsubscribedUsers=i,e.subscribedGroups=a}catch(t){this.loggingService.catch("Error in CommentService setSubscribeUsersDataInCommentAnnotation: ",t)}}getCopyLink$(){return this.copyLink$.asObservable()}setCopyLink(e){try{this.copyLink$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCopyLink: ",t)}}getCommentAnnotationById(e){return this.commentAnnotationById$.pipe(Se(()=>{let{annotationId:t,documentId:i}=e;if(i){let a=er(i).toString();return this.getDataCommentAnnotationsFromDocumentId(a).pipe(ue(l=>l.find(d=>d.annotationId===t)||null))}else{let a=this.docService.getDocumentPaths();if(a?.documentId){let l=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:a?.organizationId,documentId:a?.documentId});if(l){let c=l.find(d=>d.annotationId===t);return ce(c||null)}}}return ce(null)}),Xn(t=>(this.loggingService.catch("Error in CommentService getCommentAnnotationById: ",t),ce(null))))}getDataCommentAnnotationsFromDocumentId(e){return this.configService?.getApiKey()?this.commonDbService.dbListener({feature:"allComments",properties:{documentId:e||this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,isCollection:!0}}).pipe(ue(t=>t?.data),ue(t=>{let i=[];return t&&(i=Object.values(t??{}).filter(a=>typeof a=="object")),i})):ce([])}enableCollapsedComments(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{collapsedComments:!0}}),this.collapsedComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCollapsedComments: ",e)}}disableCollapsedComments(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{collapsedComments:!1}}),this.collapsedComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCollapsedComments: ",e)}}getCollapsedComments$(){return this.collapsedComments$.asObservable()}enableFullExpanded(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{fullExpanded:!0}}),this.fullExpanded$.value===!0)return;this.fullExpanded$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFullExpanded: ",e)}}disableFullExpanded(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{fullExpanded:!1}}),this.fullExpanded$.value===!1)return;this.fullExpanded$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFullExpanded: ",e)}}getFullExpanded$(){return this.fullExpanded$.asObservable()}getFullExpanded(){return this.fullExpanded$.value}setSidebarCustomActionEventData(e,t,i,a,l){try{this.sidebarCustomActionEventData$.next({actions:e,data:t,unreadDataMap:i,systemFilteredData:a,customFilters:l})}catch(c){this.loggingService.catch("Error in CommentService emitOnSidebarCustomAction: ",c)}}getSidebarCustomActionEventData(){return this.sidebarCustomActionEventData$.asObservable()}setCommentSidebarData(e,t){try{let i=new Set;(e||[]).forEach(l=>{(l?.annotations||[]).forEach(c=>{c?.annotationId&&i.add(c.annotationId)})});let a=this.customSidebarDataAnnotationIds$.value;this.areAnnotationIdSetsEqual(a,i)||this.customSidebarDataAnnotationIds$.next(i),this.sidebarData$.next({data:e,options:t})}catch(i){this.loggingService.catch("Error in CommentService setCommentSidebarData: ",i)}}areAnnotationIdSetsEqual(e,t){if(e===t)return!0;if(e===null||t===null||e.size!==t.size)return!1;for(let i of e)if(!t.has(i))return!1;return!0}getSidebarCustomData(){return this.sidebarData$.asObservable()}getCustomSidebarDataAnnotationIds$(){return this.customSidebarDataAnnotationIds$.asObservable()}getCustomSidebarDataAnnotationIds(){return this.customSidebarDataAnnotationIds$.value}setSidebarCustomActionEventDataAllChanges(e,t,i,a,l){return X(this,null,function*(){try{this.sidebarCustomActionEventDataAllChanges$.next({actions:e,data:t,unreadDataMap:i,systemFilteredData:a,customFilters:l});let c=yield this.metadataService.getGlobalMetadata(),d={buttonContext:{selections:this.buttonService.buttonToggleMapValue()},unreadCommentAnnotationsMap:i,commentAnnotations:t,systemFilteredAnnotations:a,metadata:c,customFilters:l};this.commentActionsService?.triggerAction(ar.COMMENT_SIDEBAR_DATA_UPDATE,d)}catch(c){this.loggingService.catch("Error in CommentService setSidebarCustomActionEventDataAllChanges: ",c)}})}setSidebarCustomActionEventDataOnInit(e,t,i,a,l){return X(this,null,function*(){try{this.sidebarCustomActionEventDataOnInit$.next({actions:e,data:t,unreadDataMap:i,systemFilteredData:a,customFilters:l});let d={metadata:yield this.metadataService.getGlobalMetadata(),unreadCommentAnnotationsMap:i,commentAnnotations:t,systemFilteredAnnotations:a,buttonContext:{selections:this.buttonService.buttonToggleMapValue()},customFilters:l};this.commentActionsService?.triggerAction(ar.COMMENT_SIDEBAR_DATA_INIT,d)}catch(c){this.loggingService.catch("Error in CommentService setSidebarCustomActionEventDataOnInit: ",c)}})}getSidebarCustomActionEventDataAllChanges(){return this.sidebarCustomActionEventDataAllChanges$.asObservable()}getSidebarCustomActionEventDataOnInit(){return this.sidebarCustomActionEventDataOnInit$.asObservable()}getSidebarCustomActionEventDataOnInitValue(){return this.sidebarCustomActionEventDataOnInit$.getValue()}setTransformContext(e){try{e?sr(this.transformContext$.value,e)||this.transformContext$.next(e):this.transformContext$.next(null)}catch(t){this.loggingService.catch("Error in CommentService setTransformContext: ",t)}}getTransformContext$(){return this.transformContext$.asObservable()}getTransformContext(){return this.transformContext$.value}enableSidebarCustomActions(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{customActions:!0}}),this.customActions$.value===!0)return;this.customActions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarCustomActions: ",e)}}disableSidebarCustomActions(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{customActions:!1}}),this.customActions$.value===!1)return;this.customActions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarCustomActions: ",e)}}getSidebarCustomActionsValue(){return this.customActions$.getValue()}enableQueryParamsComments(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{queryParamsComments:!0}}),this.queryParamsComments$.value===!0)return;this.queryParamsComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableQueryParamsComments: ",e)}}disableQueryParamsComments(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{queryParamsComments:!1}}),this.queryParamsComments$.value===!1)return;this.queryParamsComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableQueryParamsComments: ",e)}}getQueryParamsComments$(){return this.queryParamsComments$.asObservable()}getQueryParamsComments(){return this.queryParamsComments$.value}enableResolveStatusAccessAdminOnly(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{resolveStatusAccessAdminOnly:!0}}),this.resolveStatusAccessAdminOnly$.value===!0)return;this.resolveStatusAccessAdminOnly$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableResolveStatusAccessAdminOnly: ",e)}}disableResolveStatusAccessAdminOnly(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{resolveStatusAccessAdminOnly:!1}}),this.resolveStatusAccessAdminOnly$.value===!1)return;this.resolveStatusAccessAdminOnly$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableResolveStatusAccessAdminOnly: ",e)}}enableLinkCallback(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{linkCallback:!0}}),this.linkCallback$.value===!0)return;this.linkCallback$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableLinkCallback: ",e)}}disableLinkCallback(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{linkCallback:!1}}),this.linkCallback$.value===!1)return;this.linkCallback$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableLinkCallback: ",e)}}getResolveStatusAccessAdminOnly$(){return this.resolveStatusAccessAdminOnly$.asObservable()}getLinkCallback$(){return this.linkCallback$.asObservable()}getResolveStatusAccessAdminOnly(){return this.resolveStatusAccessAdminOnly$.value}getLinkCallback(){return this.linkCallback$.value}enableSvgAsImg(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{svgAsImg:!0}}),this.svgAsImg$.value===!0)return;this.svgAsImg$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSvgAsImg: ",e)}}disableSvgAsImg(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{svgAsImg:!1}}),this.svgAsImg$.value===!1)return;this.svgAsImg$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSvgAsImg: ",e)}}getSvgAsImg$(){return this.svgAsImg$.asObservable()}getSvgAsImg(){return this.svgAsImg$.value}enableCommentToNearestAllowedElement(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentToNearestAllowedElement:!0}}),this.commentToNearestAllowedElement$.value===!0)return;this.commentToNearestAllowedElement$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCommentToNearestAllowedElement: ",e)}}disableCommentToNearestAllowedElement(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentToNearestAllowedElement:!1}}),this.commentToNearestAllowedElement$.value===!1)return;this.commentToNearestAllowedElement$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCommentToNearestAllowedElement: ",e)}}getCommentToNearestAllowedElement$(){return this.commentToNearestAllowedElement$.asObservable()}getCommentToNearestAllowedElement(){return this.commentToNearestAllowedElement$.value}enableFilterCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{filterCommentsOnDom:!0}}),this.filterCommentsOnDom$.value===!0)return;this.filterCommentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFilterCommentsOnDom: ",e)}}disableFilterCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{filterCommentsOnDom:!1}}),this.filterCommentsOnDom$.value===!1)return;this.filterCommentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFilterCommentsOnDom: ",e)}}getFilterCommentsOnDom$(){return this.filterCommentsOnDom$.asObservable()}getFilterCommentsOnDom(){return this.filterCommentsOnDom$.value}setCommentsFromSidebarMap(e){try{let{comments:t,sidebarVisible:i}=e||{},a=null;t&&(a={},t.forEach(c=>{c?.annotationId&&a&&(a[c.annotationId]=c)}));let l={};t===void 0?l.data=this.commentsFromSidebarMap$.value?.data:l.data=a,i===void 0?l.sidebarVisible=this.commentsFromSidebarMap$.value?.sidebarVisible:l.sidebarVisible=i,sr(this.commentsFromSidebarMap$.value,l)||this.commentsFromSidebarMap$.next(l)}catch(t){this.loggingService.catch("Error in CommentService setCommentsFromSidebarMap: ",t)}}getCommentsFromSidebarMap$(){return this.commentsFromSidebarMap$.asObservable()}getCommentsFromSidebarMap(){return this.commentsFromSidebarMap$.value}hasActiveFilters(e){try{return e?!!(e.people?.length||e.assigned?.length||e.tagged?.length||e.involved?.length||e.priority?.length||e.status?.length||e.category?.length||e.location?.length||e.document?.length||e.version?.length||e.accessModes?.length||this.hasCustomContextFilters(e)):!1}catch(t){return this.loggingService.catch("Error in CommentService hasActiveFilters: ",t),!1}}hasCustomContextFilters(e){try{if(!e)return!1;let t=new Set(["people","assigned","tagged","involved","priority","status","category","version","document","location","accessModes"]);return Object.keys(e).some(i=>!t.has(i)&&Array.isArray(e[i])&&e[i]?.length>0)}catch(t){return this.loggingService.catch("Error in CommentService hasCustomContextFilters: ",t),!1}}applyDirectFilters(e,t){try{let i=this.commentSidebarSystemFiltersOperator$.value,a,l=!1,c=new Set;i===qc.AND?a=e.slice():a=[];let d=m=>{i===qc.AND?a=a.filter(u=>m.some(_=>_.annotationId===u.annotationId)):m.forEach(u=>c.add(u.annotationId)),l=!0};if(t.people?.length){let m=[];t.people.forEach(u=>{let _=u.userId||u.email;_&&(m=[...m,...this.filterAnnotationsByPeople({id:_,name:u.name},e)])}),d(m)}if(t.assigned?.length){let m=[];t.assigned.forEach(u=>{let _=u.userId||u.email;_&&(m=[...m,...this.filterAnnotationsByAssigned({id:_,name:u.name},e)])}),d(m)}if(t.tagged?.length){let m=[];t.tagged.forEach(u=>{let _=u.userId||u.email;_&&(m=[...m,...this.filterAnnotationsByTagged({id:_,name:u.name},e)])}),d(m)}if(t.involved?.length){let m=[];t.involved.forEach(u=>{let _=u.userId||u.email;_&&(m=[...m,...this.filterAnnotationsByInvolved({id:_,name:u.name},e)])}),d(m)}if(t.priority?.length){let m=[];t.priority.forEach(u=>m=[...m,...this.filterAnnotationsByPriority({id:u},e)]),d(m)}if(t.status?.length){let m=[];t.status.forEach(u=>m=[...m,...this.filterAnnotationsByStatus({id:u},e)]),d(m)}if(t.category?.length){let m=[];t.category.forEach(u=>m=[...m,...this.filterAnnotationsByCommentCategory({id:u},e)]),d(m)}if(t.version?.length){let m=[];t.version.forEach(u=>m=[...m,...this.filterAnnotationsByVersion(u,e)]),d(m)}if(t.document?.length){let m=[];t.document.forEach(u=>m=[...m,...this.filterAnnotationsByDocument(u,e)]),d(m)}if(t.location?.length){let m=[];t.location.forEach(u=>{u.id&&(m=[...m,...e.filter(_=>_.location?.id===u.id||_.documentParams?.id===u.id)])}),d(m)}if(t.accessModes?.length){let m=[];t.accessModes.forEach(u=>{u===Ca.PRIVATE?m=[...m,...e.filter(_=>El(_))]:u===Ca.PUBLIC&&(m=[...m,...e.filter(_=>!El(_))])}),d(m)}return this.getCustomContextFilterEntries(t).forEach(({key:m,values:u})=>{let _=this.matchAnnotationsByContext(e,m,u);d(_)}),i!==qc.AND&&(l?a=e.filter(m=>c.has(m.annotationId)):a=e),a}catch(i){return this.loggingService.catch("Error in CommentService applyDirectFilters: ",i),e}}getCustomContextFilterEntries(e){try{if(!e)return[];let t=new Set(["people","assigned","tagged","involved","priority","status","category","version","document","location","accessModes"]),i=[];return Object.keys(e).forEach(a=>{if(t.has(a))return;let l=e[a];!Array.isArray(l)||!l.length||i.push({key:a,values:l})}),i}catch(t){return this.loggingService.catch("Error in CommentService getCustomContextFilterEntries: ",t),[]}}matchAnnotationsByContext(e,t,i){try{return e.filter(a=>{let l=a.context?.[t];return l==null?!1:i.some(c=>{let d=typeof c=="string"?c:c?.id;return l===d||l?.toString()===d})})}catch(a){return this.loggingService.catch("Error in CommentService matchAnnotationsByContext: ",a),[]}}filterAnnotationsByPeople(e,t){try{return e.id?t.filter(i=>i?.from?.userId===e.id||i?.from?.email===e.id):t}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByPeople: ",i),[]}}filterAnnotationsByTagged(e,t){try{return t.filter(i=>i?.comments?.some(a=>a.taggedUserContacts?.some(l=>l?.contact?.userId===e.id)))}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByTagged: ",i),[]}}filterAnnotationsByAssigned(e,t){try{return t.filter(i=>i?.assignedTo?.userId===e.id)}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByAssigned: ",i),[]}}filterAnnotationsByInvolved(e,t){try{return t.filter(i=>{let a=i?.from?.userId===e.id||i?.from?.email===e.id,l=i?.assignedTo?.userId===e.id,c=i?.comments?.some(d=>d.taggedUserContacts?.some(m=>m?.contact?.userId===e.id));return a||l||c})}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByInvolved: ",i),[]}}filterAnnotationsByPriority(e,t){try{return e.id==="unset"?t.filter(i=>!i?.priority):t.filter(i=>i?.priority?.id===e.id)}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByPriority: ",i),[]}}filterAnnotationsByStatus(e,t){try{return t.filter(i=>i?.status?.id===e.id)}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByStatus: ",i),[]}}filterAnnotationsByCommentCategory(e,t){try{return e.id==="other"?t.filter(i=>!i?.commentCategories?.length||i?.commentCategories?.some(a=>a.id===e.id)):t.filter(i=>(i?.commentCategories||[]).some(a=>a.id===e.id))}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByCommentCategory: ",i),[]}}filterAnnotationsByVersion(e,t){try{return e.id==="unset"?t.filter(i=>!i?.location?.version):t.filter(i=>i?.location?.version?.id===e.id)}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByVersion: ",i),[]}}filterAnnotationsByDocument(e,t){try{return e?.id&&e.id!=="other"?t.filter(i=>i?.metadata?.clientDocumentId?.toString()===e.id):t.filter(i=>!i?.metadata?.clientDocumentId)}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByDocument: ",i),[]}}setSidebarButtonCountType(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{sidebarButtonCountType:e}}),this.sidebarButtonCountType$.value===e)return;this.sidebarButtonCountType$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setSidebarButtonCountType: ",t)}}getSidebarButtonCountType$(){return this.sidebarButtonCountType$.asObservable()}getSidebarButtonCountType(){return this.sidebarButtonCountType$.value}enableFilterGhostCommentsInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{filterGhostCommentsInSidebar:!0}}),this.filterGhostCommentsInSidebar$.value===!0)return;this.filterGhostCommentsInSidebar$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFilterGhostCommentsInSidebar: ",e)}}disableFilterGhostCommentsInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{filterGhostCommentsInSidebar:!1}}),this.filterGhostCommentsInSidebar$.value===!1)return;this.filterGhostCommentsInSidebar$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFilterGhostCommentsInSidebar: ",e)}}getFilterGhostCommentsInSidebar$(){return this.filterGhostCommentsInSidebar$.asObservable()}getFilterGhostCommentsInSidebar(){return this.filterGhostCommentsInSidebar$.value}filterCommentsUsingSidebarSettings(e){try{let t=Array.isArray(e),i;return t?i=e||[]:e?i=[e]:i=[],this.getFilterCommentsOnDom$().pipe(Se(a=>a?i.length===0?ce(e):gn([this.effectiveSidebarFilters$,this.customSidebarDataAnnotationIds$]).pipe(ue(([l,c])=>{let d=i,m=!1;if(this.hasActiveFilters(l)){let u=this.applyDirectFilters(i,l),_=new Set(u.map(I=>I.annotationId));d=d.filter(I=>I?.isDraft||_.has(I.annotationId)),m=!0}return c&&(d=d.filter(u=>u?.isDraft||u?.annotationId&&c.has(u.annotationId)),m=!0),m?t?d:d.length>0?d[0]:null:e})):ce(e)))}catch{return ce(e)}}enableFocusedThreadMode(){try{if(this.focusedThreadMode$.value===!0)return;this.focusedThreadMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFocusedThreadMode: ",e)}}disableFocusedThreadMode(){try{if(this.focusedThreadMode$.value===!1)return;this.focusedThreadMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFocusedThreadMode: ",e)}}getFocusedThreadMode$(){return this.focusedThreadMode$.asObservable()}enableOpenAnnotationInFocusMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{openAnnotationInFocusMode:!0}}),this.openAnnotationInFocusMode$.value===!0)return;this.openAnnotationInFocusMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableOpenAnnotationInFocusMode: ",e)}}disableOpenAnnotationInFocusMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{openAnnotationInFocusMode:!1}}),this.openAnnotationInFocusMode$.value===!1)return;this.openAnnotationInFocusMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableOpenAnnotationInFocusMode: ",e)}}getOpenAnnotationInFocusMode$(){return this.openAnnotationInFocusMode$.asObservable()}getOpenAnnotationInFocusMode(){return this.openAnnotationInFocusMode$.value}enableReadOnly(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{readOnly:!0}}),this.readOnly$.value===!0)return;this.readOnly$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReadOnly: ",e)}}disableReadOnly(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{readOnly:!1}}),this.readOnly$.value===!1)return;this.readOnly$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReadOnly: ",e)}}getReadOnly$(){return this.readOnly$.asObservable()}getReadOnly(){return this.readOnly$.value}shouldEnableReadOnly(){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentService FUNCTION: shouldEnableReadOnly","color: green;");let e=this.authService.getUser(),t=this.docService.getDocumentPaths()?.folderId,i=this.docService.getDocumentIds().map(a=>a.clientDocumentId);if(e){let a=this.userPermissionService.getCurrentUserPermissions();a?.[e.userId]?t&&a[e.userId]?.folders?.[t]?.accessRole==="viewer"?this.enableReadOnly():i.forEach(l=>{a[e.userId]?.documents?.[l]?.accessRole==="viewer"&&this.enableReadOnly()}):this.getReadOnly()||this.disableReadOnly()}}catch(e){this.loggingService.catch("Error in CommentService shouldEnableReadOnly:",e)}})}sanitizeCommentAnnotation(e){try{return e?.comments?.length&&e.comments.forEach(t=>{t?.commentHtml&&(t.commentHtml=this.domService.sanitizeHtml(t.commentHtml))}),e}catch(t){return this.loggingService.catch("Error in CommentService sanitizeCommentAnnotation: ",t),e}}enableCustomAutocompleteSearch(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{customAutocompleteSearch:!0}}),this.customAutocompleteSearch$.value===!0)return;this.customAutocompleteSearch$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCustomAutocompleteSearch: ",e)}}disableCustomAutocompleteSearch(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{customAutocompleteSearch:!1}}),this.customAutocompleteSearch$.value===!1)return;this.customAutocompleteSearch$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCustomAutocompleteSearch: ",e)}}getCustomAutocompleteSearch$(){return this.customAutocompleteSearch$.asObservable()}getCustomAutocompleteSearch(){return this.customAutocompleteSearch$.value}enableDeleteThreadWithFirstComment(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deleteThreadWithFirstComment:!0}}),this.deleteThreadWithFirstComment$.value===!0)return;this.deleteThreadWithFirstComment$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeleteThreadWithFirstComment: ",e)}}disableDeleteThreadWithFirstComment(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deleteThreadWithFirstComment:!1}}),this.deleteThreadWithFirstComment$.value===!1)return;this.deleteThreadWithFirstComment$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeleteThreadWithFirstComment: ",e)}}getDeleteThreadWithFirstComment$(){return this.deleteThreadWithFirstComment$.asObservable()}enableExpandMentionGroups(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{expandMentionGroups:!0}}),this.expandMentionGroups$.value===!0)return;this.expandMentionGroups$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableExpandMentionGroups: ",e)}}disableExpandMentionGroups(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{expandMentionGroups:!1}}),this.expandMentionGroups$.value===!1)return;this.expandMentionGroups$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableExpandMentionGroups: ",e)}}getExpandMentionGroups$(){return this.expandMentionGroups$.asObservable()}getExpandMentionGroups(){return this.expandMentionGroups$.value}enableShowMentionGroupsFirst(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{showMentionGroupsFirst:!0}}),this.showMentionGroupsFirst$.value===!0)return;this.showMentionGroupsFirst$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShowMentionGroupsFirst: ",e)}}disableShowMentionGroupsFirst(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{showMentionGroupsFirst:!1}}),this.showMentionGroupsFirst$.value===!1)return;this.showMentionGroupsFirst$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShowMentionGroupsFirst: ",e)}}getShowMentionGroupsFirst$(){return this.showMentionGroupsFirst$.asObservable()}getShowMentionGroupsFirst(){return this.showMentionGroupsFirst$.value}enableShowMentionGroupsOnly(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{showMentionGroupsOnly:!0}}),this.showMentionGroupsOnly$.value===!0)return;this.showMentionGroupsOnly$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShowMentionGroupsOnly: ",e)}}disableShowMentionGroupsOnly(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{showMentionGroupsOnly:!1}}),this.showMentionGroupsOnly$.value===!1)return;this.showMentionGroupsOnly$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShowMentionGroupsOnly: ",e)}}getShowMentionGroupsOnly$(){return this.showMentionGroupsOnly$.asObservable()}getShowMentionGroupsOnly(){return this.showMentionGroupsOnly$.value}setAnalyticsFeatureConfig({config:e,feature:t}){try{this.analyticsService.setFeatureConfig({feature:t||je.COMMENT,config:e})}catch(i){this.loggingService.catch("Error in CommentService setAnalyticsFeatureConfig: ",i)}}generateContextId(e){try{let t;if(e&&typeof e=="object"){let i=JSON.parse(JSON.stringify(e));if(delete i.accessFields,delete i.access,Object.keys(i).length){let a=Es(i),l=JSON.stringify(a);t=It(l)}}return t}catch{return}}setMaxReplyAvatars(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{maxReplyAvatars:e}}),this.maxReplyAvatars$.value===e)return;this.maxReplyAvatars$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setMaxReplyAvatars: ",t)}}getMaxReplyAvatars$(){return this.maxReplyAvatars$.asObservable()}getMaxReplyAvatars(){return this.maxReplyAvatars$.value}enableReplyAvatars(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{replyAvatars:!0}}),this.replyAvatars$.value===!0)return;this.replyAvatars$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReplyAvatars: ",e)}}disableReplyAvatars(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{replyAvatars:!1}}),this.replyAvatars$.value===!1)return;this.replyAvatars$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReplyAvatars: ",e)}}getReplyAvatars$(){return this.replyAvatars$.asObservable()}getReplyAvatars(){return this.replyAvatars$.value}setCommentplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentplaceholder:e}}),this.commentplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentplaceholder: ",t)}}getCommentplaceholder$(){return this.commentplaceholder$.asObservable()}getCommentplaceholder(){return this.commentplaceholder$.value}setReplyplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{replyplaceholder:e}}),this.replyplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setReplyplaceholder: ",t)}}getReplyplaceholder$(){return this.replyplaceholder$.asObservable()}getReplyplaceholder(){return this.replyplaceholder$.value}setEditplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{editplaceholder:e}}),this.editplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEditplaceholder: ",t)}}getEditplaceholder$(){return this.editplaceholder$.asObservable()}getEditplaceholder(){return this.editplaceholder$.value}setEditcommentplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{editcommentplaceholder:e}}),this.editcommentplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEditcommentplaceholder: ",t)}}getEditcommentplaceholder$(){return this.editcommentplaceholder$.asObservable()}getEditcommentplaceholder(){return this.editcommentplaceholder$.value}setEditreplyplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{editreplyplaceholder:e}}),this.editreplyplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEditreplyplaceholder: ",t)}}getEditreplyplaceholder$(){return this.editreplyplaceholder$.asObservable()}getEditreplyplaceholder(){return this.editreplyplaceholder$.value}enableScreenshot(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{screenshotEnabled:!0}}),this.screenshotEnabled$.value===!0)return;this.screenshotEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableScreenshot: ",e)}}disableScreenshot(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{screenshotEnabled:!1}}),this.screenshotEnabled$.value===!1)return;this.screenshotEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableScreenshot: ",e)}}getScreenshotEnabled$(){return this.screenshotEnabled$.asObservable()}getScreenshotEnabled(){return this.screenshotEnabled$.value}getAnnotationNumber(e){try{let t=this.commentAnnotationById$.value||{},i=-1,a=Object.values(t).filter(l=>{let c=l.metadata?.documentId===e.metadata?.documentId;return c&&l.annotationNumber&&(i=Math.max(i,l.annotationNumber)),c});return i===-1?a.length+1:i+1}catch(t){return this.loggingService.catch("Error in CommentService getAnnotationNumber: ",t),null}}enableFullScreenInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{fullScreen:!0}}),this.fullScreenInSidebar$.value===!0)return;this.fullScreenInSidebar$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFullScreenInSidebar: ",e)}}disableFullScreenInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{fullScreen:!1}}),this.fullScreenInSidebar$.value===!1)return;this.fullScreenInSidebar$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFullScreenInSidebar: ",e)}}getFullScreenInSidebar$(){return this.fullScreenInSidebar$.asObservable()}getFullScreenInSidebar(){return this.fullScreenInSidebar$.value}setComposerFileAttachments(e){try{this.composerFileAttachments$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setComposerFileAttachments: ",t)}}getComposerFileAttachments$(){return this.composerFileAttachments$.asObservable()}getComposerFileAttachments(){return this.composerFileAttachments$.value}clearComposerFileAttachments(){try{this.composerFileAttachments$.next(null)}catch(e){this.loggingService.catch("Error in CommentService clearComposerFileAttachments: ",e)}}enableAttachmentNameInMessage(){try{if(this.attachmentNameInMessage$.value===!0)return;this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{attachmentNameInMessage:!0}}),this.attachmentNameInMessage$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAttachmentNameInMessage: ",e)}}disableAttachmentNameInMessage(){try{if(this.attachmentNameInMessage$.value===!1)return;this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{attachmentNameInMessage:!1}}),this.attachmentNameInMessage$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAttachmentNameInMessage: ",e)}}getAttachmentNameInMessage$(){return this.attachmentNameInMessage$.asObservable()}getAttachmentNameInMessage(){return this.attachmentNameInMessage$.value}setAllowedFileTypes(e){try{this.allowedFileTypes$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setAllowedFileTypes: ",t)}}getAllowedFileTypes$(){return this.allowedFileTypes$.asObservable()}getAllowedFileTypes(){return this.allowedFileTypes$.value}enableForceCloseAllOnEsc(){try{if(this.forceCloseAllOnEsc$.value===!0)return;this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{forceCloseAllOnEsc:!0}}),this.forceCloseAllOnEsc$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableForceCloseAllOnEsc: ",e)}}disableForceCloseAllOnEsc(){try{if(this.forceCloseAllOnEsc$.value===!1)return;this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{forceCloseAllOnEsc:!1}}),this.forceCloseAllOnEsc$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableForceCloseAllOnEsc: ",e)}}getForceCloseAllOnEsc$(){return this.forceCloseAllOnEsc$.asObservable()}getForceCloseAllOnEsc(){return this.forceCloseAllOnEsc$.value}markAsRead(e){return X(this,null,function*(){try{let t;e&&(t=this.getAnnotationById(e)),t&&(yield this.viewsService.setCommentAnnotationAsRead(t))}catch(t){this.loggingService.catch("Error in ViewsService markAsRead:",t)}})}markAsUnread(e){return X(this,null,function*(){try{let t;e&&(t=this.getAnnotationById(e)),t&&(yield this.viewsService.setCommentAnnotationAsUnread(t))}catch(t){this.loggingService.catch("Error in ViewsService markAsUnread:",t)}})}setAutoCompleteScrollConfig(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{autoCompleteScrollConfig:e}});let t=this.autoCompleteScrollConfig$.value,i={itemSize:e.itemSize??t.itemSize,minBufferPx:e.minBufferPx??t.minBufferPx,maxBufferPx:e.maxBufferPx??t.maxBufferPx,templateCacheSize:e.templateCacheSize??t.templateCacheSize};this.autoCompleteScrollConfig$.next(i)}catch(t){this.loggingService.catch("Error in CommentService setAutoCompleteScrollConfig: ",t)}}getAutoCompleteScrollConfig(){return this.autoCompleteScrollConfig$.value}getAutoCompleteScrollConfig$(){return this.autoCompleteScrollConfig$.asObservable()}submitComment(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: submitComment","color: green;"),this.submitComment$.next(e.targetComposerElementId)}catch(t){this.loggingService.catch("Error in CommentService submitComment: ",t)}}onSubmitComment$(){return this.submitComment$.asObservable()}clearComposer(e){try{this.clearComposer$.next(e.targetComposerElementId),this.composerDataMap.delete(e.targetComposerElementId)}catch(t){this.loggingService.catch("Error in CommentService clearComposer: ",t)}}onClearComposer$(){return this.clearComposer$.asObservable()}emitComposerTextChange(e,t,i){try{this.commentActionsService?.onComposerTextChange({text:e,annotation:t,targetComposerElementId:i})}catch(a){this.loggingService.catch("Error in CommentService emitComposerTextChange: ",a)}}setComposerData(e,t){try{this.composerDataMap.set(e,t)}catch(i){this.loggingService.catch("Error in CommentService setComposerData: ",i)}}clearComposerData(e){try{this.composerDataMap.delete(e)}catch(t){this.loggingService.catch("Error in CommentService clearComposerData: ",t)}}getComposerData(e){try{return this.composerDataMap.get(e.targetComposerElementId)||null}catch(t){return this.loggingService.catch("Error in CommentService getComposerData: ",t),null}}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(uv),K(yn),K(Ft),K(st),K($n),K(qe),K(Ve),K(eo),K(fm),K(vn),K(Pp),K(Do),K(Lo),K(Vn),K(k),K(mn),K(po),K(zi),K(jbe),K(Un),K(Ol),K(CS),K(ts),K(vd),K(es),K(Ia),K(ho))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Hbe=(()=>{let o=class o{constructor(e,t,i){this.commentService=e,this.reactionService=t,this.loggingService=i}getActivityForClient(e){try{let t=JSON.parse(JSON.stringify(e));return t.metadata&&(t.metadata=oi(t.metadata)),t.actionUser&&(t.actionUser=Vo(t.actionUser)),t.entityData&&(t.entityData=this.transformEntityData(t.featureType,t.entityData),t.entityData?.metadata&&(t.entityData.metadata=oi(t.entityData.metadata))),t.entityTargetData&&(t.entityTargetData=this.transformEntityTargetData(t.featureType,t.entityTargetData)),t.changes&&(t.changes=this.transformChanges(t.changes)),t.displayMessageTemplateData&&(t.displayMessageTemplateData=this.transformTemplateData(t.displayMessageTemplateData)),t}catch(t){return this.loggingService.catch("Error in ActivityActionsService getActivityForClient:",t),e}}transformEntityData(e,t){try{switch(e){case"comment":return this.commentService.getCommentAnnotationForClient(t);case"reaction":return this.reactionService.getReactionAnnotationForClient(t);case"recorder":return bhe(t);default:return t}}catch(i){return this.loggingService.catch("Error in ActivityActionsService transformEntityData:",i),t}}transformEntityTargetData(e,t){try{return t}catch(i){return this.loggingService.catch("Error in ActivityActionsService transformEntityTargetData:",i),t}}transformChanges(e){try{let t={};for(let i of Object.keys(e)){let a=e[i];if(!a){t[i]=a;continue}t[i]=h({},a),this.isUserObject(a.from)&&(t[i].from=Vo(a.from)),this.isUserObject(a.to)&&(t[i].to=Vo(a.to))}return t}catch(t){return this.loggingService.catch("Error in ActivityActionsService transformChanges:",t),e}}transformTemplateData(e){try{let t={};for(let i of Object.keys(e)){let a=e[i];this.isUserObject(a)?t[i]=Vo(a):t[i]=a}return t}catch(t){return this.loggingService.catch("Error in ActivityActionsService transformTemplateData:",t),e}}isUserObject(e){return!!e&&typeof e=="object"&&"userId"in e}};o.\u0275fac=function(t){return new(t||o)(K(Re),K(zi),K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Lg=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A,M,V){this.activityResolverService=e,this.activityUtilsService=t,this.authService=i,this.commentAnnotationsResolverService=a,this.reactionAnnotationsResolverService=l,this.recorderAnnotationsResolverService=c,this.commonDbService=d,this.commonDbUtilsService=m,this.configService=u,this.docService=_,this.functions=I,this.loggingService=A,this.usersService=M,this.userPermissionService=V,this.isActivityFeatureEnabled$=new _e(!1),this.isActivityFeatureImmutable$=new _e(!1),this.allActivities$=new _e(null),this.subscriptions=new Map,this.fetchedEntityIds=new Set;try{this.commonDbService.setActivityService(this),this.authService.setActivityService(this),this.initializeService()}catch(q){this.loggingService.catch("Error in ActivityService constructor:",q)}}setActivityFeatureConfig(e){try{this.isActivityFeatureEnabled$.next(e?.isEnabled??!1),this.isActivityFeatureImmutable$.next(e?.immutable??!1)}catch(t){this.loggingService.catch("Error in setActivityFeatureConfig: ",t)}}getIsActivityFeatureEnabled(){return this.isActivityFeatureEnabled$.value}getIsActivityFeatureImmutable(){return this.isActivityFeatureImmutable$.value}getIsActivityFeatureEnabled$(){return this.isActivityFeatureEnabled$.asObservable().pipe(_t(Kt))}initializeService(){try{this.authSubscription=this.getIsActivityFeatureEnabled$().pipe(_t(),Ge(e=>e===!0)).subscribe(()=>{this.subscriptions.size>0&&!this.triggerListenerSubscription&&this.rebuildTriggerListener()},e=>{this.loggingService.catch("Error in ActivityService feature flag subscription:",e)})}catch(e){this.loggingService.catch("Error in ActivityService initializeService:",e)}}subscribe(e){let t=lt(),i=new _e(null);try{let a={id:t,config:e??{},activities$:i};this.subscriptions.set(t,a),this.getIsActivityFeatureEnabled()&&this.rebuildTriggerListener(),this.allActivities$.getValue()!==null&&this.distributeActivitiesToSubscription(a)}catch(a){this.loggingService.catch("Error in ActivityService subscribe:",a)}return{getActivities$:()=>i.asObservable(),unsubscribe:()=>{try{this.subscriptions.delete(t),i.complete(),this.getIsActivityFeatureEnabled()&&this.rebuildTriggerListener()}catch(a){this.loggingService.catch("Error in ActivityService unsubscribe:",a)}}}}getActivities$(){return this.allActivities$.asObservable().pipe(_t(Kt))}getActivitiesForDocument$(e){return this.allActivities$.pipe(ue(t=>t===null?null:t.filter(i=>i.metadata?.documentId===e)),_t(Kt))}getActivitiesForEntity$(e){return this.allActivities$.pipe(ue(t=>t===null?null:t.filter(i=>i.targetEntityId===e)),_t(Kt))}fetchActivitiesForEntity(e){return X(this,null,function*(){try{if(!this.getIsActivityFeatureEnabled())return;let{targetEntityId:t,documentId:i,organizationId:a}=e;if(!t||!i||this.fetchedEntityIds.has(t))return;this.fetchedEntityIds.add(t);let l=this.authService.getUser();if(!l?.userId){this.fetchedEntityIds.delete(t);return}let c=a||this.docService.getOrganizationConfig()?.clientOrganizationId;if(!c){this.fetchedEntityIds.delete(t);return}let d=Yr(this.functions,Zr({url:On.cloudFunction.sdkProxy,apiProxyDomain:this.configService.getApiProxyDomain()})),m=yield wl({methodName:"getActivitiesForEntity",data:{type:"getActivitiesForEntity",organizationId:c,documentId:i,targetEntityId:String(t),isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable()},getSdkProxy:d,userId:l.userId});if(m?.activities?.length){let u=m.activities;this.appendActivities(u),this.rehydrateActivities(u)}}catch(t){this.fetchedEntityIds.delete(e.targetEntityId),this.loggingService.catch("Error in ActivityService fetchActivitiesForEntity:",t)}})}createActivity(e){return X(this,null,function*(){try{if(!this.getIsActivityFeatureEnabled())return;let t=this.authService.getUser();if(!t?.userId){this.loggingService.warn("ActivityService createActivity: No user available");return}let i=this.docService.getBaseMetadata("activity");if(!i?.apiKey||!i?.organizationId){this.loggingService.warn("ActivityService createActivity: Missing metadata or organizationId");return}let a=this.getIsActivityFeatureImmutable(),l=lt(),c={id:l,featureType:e.featureType,actionType:e.actionType,eventType:e.eventType,actionUser:t,timestamp:this.commonDbService.getServerTimestamp(),metadata:i,targetEntityId:e.targetEntityId!=null?String(e.targetEntityId):void 0,targetSubEntityId:e.targetSubEntityId!=null?String(e.targetSubEntityId):void 0,changes:e.changes,entityData:e.entityData,entityTargetData:e.entityTargetData,actionIcon:e.actionIcon,displayMessageTemplate:e.displayMessageTemplate,displayMessageTemplateData:e.displayMessageTemplateData,immutable:a};this.appendActivities([c]);let{strippedActivity:d,activityResolverData:m}=yield this.activityUtilsService.stripActivityPII(c);m&&this.activityResolverService.activityDataProviderAvailable()&&this.activityResolverService.saveActivity({activity:{[m.id]:m},event:ko.ACTIVITY_SAVE});try{yield this.sendActivityToBackend(d)}catch{let u=this.allActivities$.getValue()??[];this.allActivities$.next(u.filter(_=>_.id!==l)),this.subscriptions.forEach(_=>this.distributeActivitiesToSubscription(_))}}catch(t){this.loggingService.catch("Error in ActivityService createActivity:",t)}})}rebuildTriggerListener(){try{if(this.triggerListenerSubscription&&(this.triggerListenerSubscription.unsubscribe(),this.triggerListenerSubscription=void 0),this.subscriptions.size===0)return;let e=this.getCombinedSubscriptionScope();this.triggerListenerSubscription=this.getLastActivityTimestamps$(e).pipe(_o(null),Fr(),ue(([t,i])=>{if(!i)return;if(i.length===0){this.allActivities$.getValue()===null&&!this.emptyStateTimeoutId&&(this.emptyStateTimeoutId=setTimeout(()=>{this.emptyStateTimeoutId=void 0,this.allActivities$.getValue()===null&&(this.allActivities$.next([]),this.subscriptions.forEach(d=>this.distributeActivitiesToSubscription(d)))},5e3));return}this.emptyStateTimeoutId&&(clearTimeout(this.emptyStateTimeoutId),this.emptyStateTimeoutId=void 0);let a=new Map;t?.forEach(d=>a.set(d.documentId,d.timestamp));let l=[],c=[];if(i.forEach(d=>{let m=a.get(d.documentId);m===void 0?l.push(d.documentId):m!==d.timestamp&&c.push({documentId:d.documentId,previousTimestamp:m})}),l.length>0){let d=this.getStartAtTimestamp(e.maxDays);this.fetchActivitiesForDocuments(l,e.organizationId,void 0,d)}c.length>0&&this.fetchActivitiesForDocuments(c.map(d=>d.documentId),e.organizationId,c)})).subscribe(()=>{},t=>this.loggingService.catch("Error in ActivityService trigger listener:",t))}catch(e){this.loggingService.catch("Error in ActivityService rebuildTriggerListener:",e)}}getLastActivityTimestamps$(e){try{return this.authService.getUser$().pipe(Ge(t=>!!t),Se(t=>this.docService.getOrganizationConfig$().pipe(Ge(i=>!!i),ue(i=>{let l=(e.organizationId?ba(e.organizationId):void 0)||i?.organizationId||t?.organizationId;return{user:t,organizationId:l}}))),Se(({user:t,organizationId:i})=>{if(!t||!i)return ce(null);if(e.type===Fg.CURRENT_DOCUMENT)return this.docService.getDocumentPaths$().pipe(Se(l=>{let c=l?.clientDocumentId;if(!c&&!e.documentIds?.length)return this.resetCurrentDocumentSubscriptions(),ce(null);let d=new Set(e.documentIds??[]);c&&d.add(c);let m=Array.from(d).slice(0,30).map(u=>mi(u));return m.length===1?this.buildTriggerQuery(i,[ft("metadata.documentId","==",m[0])],e.maxDays):this.buildTriggerQuery(i,[ft("metadata.documentId","in",m)],e.maxDays)}));let a=[];if(e.type===Fg.DOCUMENTS&&e.documentIds?.length){e.documentIds.length>30&&this.loggingService.catch("Error in ActivityService getLastActivityTimestamps$: Subscription includes more than 30 document IDs. Only the first 30 will be monitored.",new Error("Subscription includes more than 30 document IDs. Only the first 30 will be monitored."),void 0,!0);let l=e.documentIds.slice(0,30).map(c=>mi(c));a.push(ft("metadata.documentId","in",l))}return this.buildTriggerQuery(i,a,e.maxDays)}))}catch(t){return this.loggingService.catch("Error in ActivityService getLastActivityTimestamps$:",t),ce(null)}}buildTriggerQuery(e,t,i=XL){try{let a=this.getStartAtTimestamp(i);t.push(ft("timestamp",">=",a));let c=[t.length>1?yr(...t):t[0],uo("timestamp","desc")];return this.commonDbService.dbListener({feature:"allLastActivityTimestamp",properties:{organizationId:e,isCollection:!0,useQuery:!0,firestoreQuery:c}}).pipe(ue(d=>d?.data),ue(d=>{if(!d)return[];let m=[];return Object.keys(d).forEach(u=>{let _=this.commonDbService.shouldUseFirestore()?d[u]?.timestamp??0:d[u];m.push({documentId:u,timestamp:_})}),m}))}catch(a){return this.loggingService.catch("Error in ActivityService buildTriggerQuery:",a),ce([])}}fetchActivitiesForDocuments(e,t,i,a){return X(this,null,function*(){try{if(!e.length)return;let l=this.authService.getUser();if(!l?.userId)return;let c=t||this.docService.getOrganizationConfig()?.clientOrganizationId;if(!c)return;let d=Yr(this.functions,Zr({url:On.cloudFunction.sdkProxy,apiProxyDomain:this.configService.getApiProxyDomain()})),m={type:"getActivitiesForDocuments",organizationId:c,documentIds:e,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable()};a&&(m.startAtTimestamp=a),i?.length&&(m.documentTimestamps=i.map(_=>({documentId:_.documentId,timestamp:_.previousTimestamp})));let u=yield wl({methodName:"getActivitiesForDocuments",data:m,getSdkProxy:d,userId:l.userId});if(u?.activities?.length){let _=u.activities;this.appendActivities(_),this.rehydrateActivities(_)}else this.allActivities$.getValue()===null&&(this.allActivities$.next([]),this.subscriptions.forEach(_=>this.distributeActivitiesToSubscription(_)))}catch(l){this.loggingService.catch("Error in ActivityService fetchActivitiesForDocuments:",l)}})}sendActivityToBackend(e){return X(this,null,function*(){try{let t=this.authService.getUser();if(!t?.userId)return;let i=Yr(this.functions,Zr({url:On.cloudFunction.sdkProxy,apiProxyDomain:this.configService.getApiProxyDomain()}));yield wl({methodName:"createActivity",data:{type:"createActivity",activityData:e},getSdkProxy:i,userId:t.userId})}catch(t){throw this.loggingService.catch("Error in ActivityService sendActivityToBackend:",t),t}})}rehydrateActivities(e){try{let t=this.usersService.userDataProviderAvailable(),i=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),a=this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable(),l=this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable(),c=this.activityResolverService.activityDataProviderAvailable(),d=Promise.resolve();t&&(d=d.then(()=>this.commonDbUtilsService.formatResponse({feature:"allActivities",data:e,shouldAwait:!0,forceResolve:!0})).then(()=>{this.resolveAndUpdateActivities(e,"user")})),i&&(d=d.then(()=>this.commonDbUtilsService.formatResponse({feature:"allActivities",data:e,shouldCommentAnnotationsResolverAwait:!0})).then(()=>{this.resolveAndUpdateActivities(e,"comment")})),a&&(d=d.then(()=>this.commonDbUtilsService.formatResponse({feature:"allActivities",data:e,shouldReactionResolverAwait:!0})).then(()=>{this.resolveAndUpdateActivities(e,"reaction")})),l&&(d=d.then(()=>this.commonDbUtilsService.formatResponse({feature:"allActivities",data:e,shouldRecorderResolverAwait:!0})).then(()=>{this.resolveAndUpdateActivities(e,"recorder")})),c&&(d=d.then(()=>this.commonDbUtilsService.formatResponse({feature:"allActivities",data:e,shouldActivityResolverAwait:!0})).then(()=>{this.resolveAndUpdateActivities(e,"activity")}))}catch(t){this.loggingService.catch("Error in ActivityService rehydrateActivities:",t)}}resolveAndUpdateActivities(e,t){try{let i=this.allActivities$.getValue()??[],a=new Map(i.map(m=>[m.id,m])),l=e.map(m=>a.get(m.id)??m),c=JSON.parse(JSON.stringify(l)),d;switch(t){case"user":d=this.commonDbUtilsService.mergeUsersWithData({feature:"allActivities",data:c});break;case"comment":d=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allActivities",data:c});break;case"reaction":d=this.commonDbUtilsService.mergeReactionAnnotationsWithData({feature:"allActivities",data:c});break;case"recorder":d=this.commonDbUtilsService.mergeRecorderAnnotationsWithData({feature:"allActivities",data:c});break;case"activity":d=this.commonDbUtilsService.mergeActivityResolverWithData({feature:"allActivities",data:c});break}d?.length&&this.appendActivities(d)}catch(i){this.loggingService.catch("Error in ActivityService resolveAndUpdateActivities:",i)}}appendActivities(e){try{let t=this.allActivities$.getValue()??[],i=new Map;e.forEach(m=>{m.id&&i.set(m.id,m)});let a=t.map(m=>i.get(m.id)??m),l=new Set(t.map(m=>m.id)),d=[...e.filter(m=>!l.has(m.id)),...a].sort((m,u)=>(u.timestamp??0)-(m.timestamp??0));if(d.forEach(m=>{m.displayMessage=this.activityUtilsService.getActivityDisplayMessage(m)}),this.activitiesEqual(t,d))return;this.allActivities$.next(d),this.subscriptions.forEach(m=>{this.distributeActivitiesToSubscription(m)})}catch(t){this.loggingService.catch("Error in ActivityService appendActivities:",t)}}distributeActivitiesToSubscription(e){try{let t=this.allActivities$.getValue();if(t===null)return;let i=e.config,a;if(i.currentDocumentOnly){let c=this.docService.getDocumentPaths()?.documentId;a=c?t.filter(d=>d.metadata?.documentId===c):[]}else if(i.documentIds?.length){let c=new Set(i.documentIds.map(d=>mi(d)));a=t.filter(d=>d.metadata?.documentId&&c.has(d.metadata.documentId))}else a=t;if(i.featureTypes?.length){let c=new Set(i.featureTypes);a=a.filter(d=>c.has(d.featureType))}else if(i.excludeFeatureTypes?.length){let c=new Set(i.excludeFeatureTypes);a=a.filter(d=>!c.has(d.featureType))}if(i.actionTypes?.length){let c=new Set(i.actionTypes);a=a.filter(d=>c.has(d.actionType))}else if(i.excludeActionTypes?.length){let c=new Set(i.excludeActionTypes);a=a.filter(d=>!c.has(d.actionType))}if(i.userIds?.length){let c=new Set(i.userIds);a=a.filter(d=>d.actionUser?.userId&&c.has(d.actionUser.userId))}else if(i.excludeUserIds?.length){let c=new Set(i.excludeUserIds);a=a.filter(d=>!d.actionUser?.userId||!c.has(d.actionUser.userId))}let l=e.activities$.getValue();if(l!==null&&this.activitiesEqual(l,a))return;e.activities$.next(a)}catch(t){this.loggingService.catch("Error in ActivityService distributeActivitiesToSubscription:",t)}}resetCurrentDocumentSubscriptions(){try{this.subscriptions.forEach(e=>{e.config.currentDocumentOnly&&e.activities$.getValue()!==null&&e.activities$.next(null)})}catch(e){this.loggingService.catch("Error in ActivityService resetCurrentDocumentSubscriptions:",e)}}activitiesEqual(e,t){try{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i].id!==t[i].id)return!1;return JSON.stringify(e)===JSON.stringify(t)}catch(i){return this.loggingService.catch("Error in ActivityService activitiesEqual:",i),!1}}getCombinedSubscriptionScope(){try{let e=!1,t=!1,i,a=new Set,l=XL;this.subscriptions.forEach(d=>{let m=d.config;m.organizationId&&(i=m.organizationId),m.currentDocumentOnly?t=!0:m.documentIds?.length?m.documentIds.forEach(u=>a.add(u)):e=!0,m.maxDays&&m.maxDays>l&&(l=m.maxDays)});let c={organizationId:i,maxDays:l};return e?h({type:Fg.ORG_WIDE},c):t&&a.size>0?h({type:Fg.CURRENT_DOCUMENT,documentIds:Array.from(a)},c):t?h({type:Fg.CURRENT_DOCUMENT},c):a.size>0?h({type:Fg.DOCUMENTS,documentIds:Array.from(a)},c):h({type:Fg.ORG_WIDE},c)}catch(e){return this.loggingService.catch("Error in ActivityService getCombinedSubscriptionScope:",e),{type:Fg.ORG_WIDE,organizationId:void 0,maxDays:XL}}}getStartAtTimestamp(e){try{let t=new Date,i=e>0?e:XL;return t.setDate(t.getDate()-i),t.getTime()}catch(t){return this.loggingService.catch("Error in ActivityService getStartAtTimestamp:",t),0}}cleanup(){try{this.triggerListenerSubscription?.unsubscribe(),this.triggerListenerSubscription=void 0,this.emptyStateTimeoutId&&(clearTimeout(this.emptyStateTimeoutId),this.emptyStateTimeoutId=void 0),this.subscriptions.forEach(e=>e.activities$.complete()),this.subscriptions.clear(),this.allActivities$.next(null),this.fetchedEntityIds.clear()}catch(e){this.loggingService.catch("Error in ActivityService cleanup:",e)}}destroy(){try{this.cleanup(),this.authSubscription?.unsubscribe()}catch(e){this.loggingService.catch("Error in ActivityService destroy:",e)}}};o.\u0275fac=function(t){return new(t||o)(K(Op),K(uS),K(qe),K(ol),K(Qc),K(il),K(yn),K(vd),K(Ft),K(st),K(Do),K(k),K(An),K(Ia))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})(),Fg=(function(n){return n.ORG_WIDE="orgWide",n.DOCUMENTS="documents",n.CURRENT_DOCUMENT="currentDocument",n})(Fg||{}),XL=30;var Cr=class{constructor(o){this.injector=o,this.hideAnalytics=!1}ha(o){try{this.hideAnalytics=o}catch{}}getService(o){return this.injector.get(o)}trackEvent(o,r={},e=!0){try{this.hideAnalytics||(r||(r={}),r=y(h({},r),{source:"external"}),this.getService(ct).trackAuthenticatedEvent(o,r,e))}catch(t){this.getService(k).catch("Error in _trackEvent: ",t);return}}};var QL=class extends Cr{constructor(o){super(o),this.getService(k).log("%c[WB] Creating CLASS: ActivityElement","color: blue;"),this.getAllActivities=this._getAllActivities,this.createActivity=this._createActivity}_getAllActivities(o){this.getService(k).log("%c[WB] Calling FUNCTION: getAllActivities","color: green;");try{let r=this.getService(Hbe),e=this.getService(Lg).subscribe(o);return new Vt(t=>{let i=e.getActivities$().pipe(ue(a=>a?.map(l=>r.getActivityForClient(l))??null)).subscribe(t);return()=>{i.unsubscribe(),e.unsubscribe()}})}catch(r){return this.getService(k).catch("Error in _getAllActivities: ",r),ce(null)}}_createActivity(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: createActivity","color: green;");try{yield this.getService(Lg).createActivity(o)}catch(r){this.getService(k).catch("Error in _createActivity: ",r)}})}};var eU=class extends Cr{constructor(o){super(o),this.getService(k).log("%c[WB] Creating CLASS: AreaElement","color: blue;"),this.enableArea=this._enableAreaComment,this.disableArea=this._disableAreaComment,this.enableAreaComment=this._enableAreaComment,this.disableAreaComment=this._disableAreaComment}_enableAreaComment(){this.getService(k).log("%c[WB] Calling FUNCTION: enableAreaComment","color: green;");try{this.trackEvent(Y.Events.Area.ENABLE_AREA_COMMENT_TRIGGERED),this.getService(uv).enableArea()}catch(o){this.getService(k).catch("Error in _enableAreaComment: ",o)}}_disableAreaComment(){this.getService(k).log("%c[WB] Calling FUNCTION: disableAreaComment","color: green;");try{this.trackEvent(Y.Events.Area.DISABLE_AREA_COMMENT_TRIGGERED),this.getService(uv).disableArea()}catch(o){this.getService(k).catch("Error in _disableAreaComment: ",o)}}};var km=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A){this.analyticsService=e,this.configService=t,this.docService=i,this.databaseService=a,this.authService=l,this.domService=c,this.afAuth=d,this.iamService=m,this.dialog=u,this.loggingService=_,this.notificationService=I,this.commonDbService=A,this.arrowAnnotations$=new _e({}),this.arrowAnnotationsByDocumentId$=new _e({}),this.documentPaths=null,this.allowedElementIds$=new _e([]),this.addArrowMode$=new _e(!1),this.loggingService.log("%c[WB] Creating CLASS: ArrowService","color: blue;"),this.databaseService.getDb().pipe(Ge(M=>!!M),ut(1)).subscribe(M=>{M&&this.getDocumentPaths()},M=>{this.loggingService.catch("Error in ArrowService getDb subscription: ",M)}),this.domService.onWindowPointerMove$().subscribe(M=>{if(this.addArrowMode$.value){let V=!0,q=this.domService.getBackgroundElement(M.clientX,M.clientY);q&&(this.isElementInsideAllowedElements(q)?QN(M.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement&&this.highlightElement!==q&&this.domService.removeHighlightFromElement(this.highlightElement),this.highlightElement=q,this.domService.highlightElement(this.highlightElement,N.CURSOR.ARROW_PIN),V=!1):this.domService.removeClassFromElement(document.body,"show-pin-cursor")),this.highlightElement&&V&&(this.domService.removeHighlightFromElement(this.highlightElement),this.highlightElement=null)}},M=>{this.loggingService.catch("Error in ArrowService onWindowPointerMove$ subscription: ",M)}),this.domService.onWindowKeyupEsc$().subscribe(M=>{this.addArrowMode$.value&&this.disableAddArrowMode()},M=>{this.loggingService.catch("Error in ArrowService onWindowKeyupEsc$ subscription: ",M)}),this.domService.onDocumentClick$().subscribe(M=>{if(M&&this.addArrowMode$.value){if(!QN(M.target)){let V=this.domService.getBackgroundElement(M.clientX,M.clientY);V&&this.isElementInsideAllowedElements(V)&&(M.preventDefault(),M.stopPropagation(),this.addArrow(M))}this.disableAddArrowMode()}},M=>{this.loggingService.catch("Error in ArrowService onDocumentClick$ subscription: ",M)}),this.addArrowMode$.subscribe(M=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),M?this.domService.addClassToElement(document.body,"snippyly-add-arrow-mode"):(this.domService.removeClassFromElement(document.body,"snippyly-add-arrow-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"))},M=>{this.loggingService.catch("Error in ArrowService addArrowMode$ subscription: ",M)}),this.domService.onWindowKeyupBackspace$().subscribe(M=>{this.deleteArrowPinAnnotations("keyupBackspace")},M=>{this.loggingService.catch("Error in ArrowService onWindowKeyupBackspace$ subscription: ",M)}),this.domService.onWindowKeyupDelete$().subscribe(M=>{this.deleteArrowPinAnnotations("keyupDelete")},M=>{this.loggingService.catch("Error in ArrowService onWindowKeyupDelete$ subscription: ",M)})}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$()}setAllowedElementIds(e){this.allowedElementIds$.next(e||[])}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}getAllArrowAnnotations(e,t,i){this.loggingService.log("%c[WB] Calling FUNCTION: getAllArrowAnnotations","color: green;");let a,l;try{if(e&&(l=er(e)),t&&typeof t=="object"){let c=Oi(t);a=er(JSON.stringify(c))}}catch(c){this.loggingService.catch("Error in ArrowService getAllArrowAnnotations: ",c)}return _r(this.afAuth).pipe(Ge(c=>!!c),Se(c=>this.isFeatureAllowed({firebaseUser:c,annotations:[],filteredAnnotations:[]})),Se(c=>c.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(d=>(c.featureAllowed=d,c))):ce(c)),Se(c=>c.featureAllowed?this.authService.isPlanExpired$().pipe(ue(d=>(c.featureAllowed=!d,c))):ce(c)),Se(c=>c.featureAllowed?ce(c).pipe(Se(d=>this.docService.getDocumentPaths$().pipe(ue(m=>(this.documentPaths=m,d.documentPaths=m,d)))),Se(d=>this.getDataFromDocumentId(l).pipe(ue(m=>(d.annotations=m||[],h({},d))))),Se(d=>this.docService.getLocation$().pipe(ue(m=>(d.location=m,d)))),Se(d=>this.docService.getLocations$().pipe(ue(m=>(d.customLocations=m,d)))),ue(d=>{if(d.filteredAnnotations=[],l&&!a)return d.filteredAnnotations=d.annotations?.slice(),d;{let m=[];return a?m.push(a):(m.push(d?.location?.locationId),m.push(...Object.values(d?.customLocations||[]).map(u=>u.locationId))),d.filteredAnnotations=this.filterAnnotationsByLocationIds(d?.annotations,m),d}}),Se(d=>i?ce(d):d?.annotations?.length?this.domService.onWindowResize$().pipe(ue(()=>d)):ce(d)),Se(d=>i?ce(d):d?.annotations?.length?this.domService.onDomChange$("ArrowService getAllArrowAnnotations").pipe(ue(()=>d)):ce(d)),ue(d=>(d?.filteredAnnotations?.forEach(m=>{this.calculateArrowAnnotationPosition(m)}),d)),Se(d=>d?.filteredAnnotations?ce(d?.filteredAnnotations||[]):ce([]))):ce([])),_t(Kt))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})),Se(t=>this.authService.getUser$().pipe(ue(i=>y(h({},t),{user:i})))),Se(t=>Ao(t.config,t.user,je.ARROW)?ce(y(h({},t),{featureAllowed:!0})):(this.loggingService.warn("Arrow feature is not allowed."),ce(y(h({},t),{featureAllowed:!1})))),_t((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ge(t=>!!t),Se(t=>this.configService.getApiKey()&&this.documentPaths?.arrow&&this.documentPaths?this.commonDbService.dbListener({feature:"allArrows",properties:{documentId:e??this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ue(i=>({data:i?.data,operation:i?.operation})),ue(({data:i,operation:a})=>{let l=[];return i&&(l=Object.values(i).filter(c=>typeof c=="object")),{data:l,operation:a}}),Xn(i=>(this.loggingService.catch("Error in ArrowService getDataFromDocumentId: ",i),ce({data:[],operation:null}))),ue(({data:i,operation:a})=>{if(a?.type==="removed"){if(a?.ids?.length){let l=this.arrowAnnotationsByDocumentId$.value;a?.ids?.forEach(c=>{delete l?.[c]}),this.arrowAnnotationsByDocumentId$.next(l)}}else this.setArrowAnnotationsByDocumentId(e||this.documentPaths?.documentId,i);return i})):ce([])))}setArrowAnnotationsByDocumentId(e,t){try{if(e){let i=y(h({},this.arrowAnnotationsByDocumentId$.value),{[e]:t});this.arrowAnnotationsByDocumentId$.next(i)}}catch(i){this.loggingService.catch("Error in ArrowService setArrowAnnotationsByDocumentId:",i)}}filterAnnotationsByLocationIds(e,t){try{return e.filter(i=>t.includes(i.locationId))}catch(i){return this.loggingService.catch("Error in ArrowService filterAnnotationsByLocations:",i),[]}}calculateArrowAnnotationPosition(e){try{if(e.targetElement){let t=this.domService.getXPath(e.targetElement?.xpath);if(t){let i=t.iterateNext();if(i&&Kr(i)){let a=i.getBoundingClientRect();if(a&&a.width&&a.height){let{height:l,width:c}=np(i);e.position={top:l*e.targetElement.topPercentage/100,left:c*e.targetElement.leftPercentage/100}}else e.position=null}else e.position=null}else e.position=null}}catch(t){this.loggingService.catch("Error in ArrowService calculateArrowAnnotationPosition:",t)}}addArrow(e){this.loggingService.log("%c[WB] Calling FUNCTION: addArrow","color: green;");try{let t=this.authService.getUser();if(t)if(t.isReadOnly||t.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add arrows.");else{let i=new DN;i.from=t,i.color=t?.color||N.DEFAULT_ANNOTATION_COLOR,i.lastUpdated=this.timestamp,i.props=new ad;let a=this.domService.getCurrentWindowSizeValue();if(i.props.screenWidth=a.screenWidth,i.props.screenHeight=a.screenHeight,i.props.screenScrollHeight=a.screenScrollHeight,i.props.viewportWidth=window.innerWidth,i.props.viewportHeight=window.innerHeight,i.props.arrowLength=N.VELT_MIN_ARROW_LENGTH,(e?.clientX||0)>N.VELT_MIN_ARROW_LENGTH?i.props.arrowAngle=135:i.props.arrowAngle=45,e&&(i.targetElement=this.domService.getTargetElementForCursorPosition(e)),i?.targetElement?.xpath){let l=this.domService.getXPath(i.targetElement.xpath);if(l){let c=l.iterateNext();c&&(Kr(c)||(i.targetElement=null))}}this.setLocationToArrowAnnotation(i),i.pageInfo=ro(),i.pageInfo&&(i.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth),this.saveArrowToDb(i)}}catch(t){this.loggingService.catch("Error in ArrowService addArrow: ",t)}}setLocationToArrowAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location);try{if(e.targetElement?.xpath){let i=this.domService.getElementFromXPath(e.targetElement.xpath),a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.addLocation({location:a,source:"internal"});l?.[0]&&(e.locationId=l[0].locationId,e.location=l[0].location)}}}catch{}}catch(t){this.loggingService.catch("Error in ArrowService setLocationToArrowAnnotation:",t)}}saveArrowToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: saveArrowToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(je.ARROW)&&this.docService.getDocumentPaths$().pipe(Ge(t=>!!t),ut(1),Se(t=>(this.documentPaths=t,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Ge(i=>!!i),ut(1),Se(i=>{if(this.documentPaths?.arrow){e.annotationId=this.commonDbService.generateDocumentId(),e.pageInfo&&(e.pageInfo.arrowUrl=this.generateArrowUrl(e));let a=JSON.parse(JSON.stringify(e));return a.position=null,this.domService.toggleAnnotationSelection(a),this.analyticsService.trackEvent(Y.Events.Arrow.ARROW_DRAFT_ADDED,{annotationId:e.annotationId}),this.commonDbService.setData({feature:"arrow",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.annotationId,skipFirestore:!0},data:JSON.parse(JSON.stringify(a))})}else return ce(null)}))))).subscribe(()=>{},t=>{this.loggingService.catch("Error in ArrowService saveArrowToDb subscription: ",t)})}catch(t){this.loggingService.catch("Error in ArrowService saveArrowToDb: ",t)}}updateArrow(e,t=!1,i){try{i&&this.setLocationToArrowAnnotation(e),t&&this.updateNotificationsDatabase(e,IN.UPDATED),this.updateArrowToDb(e)}catch(a){this.loggingService.catch("Error in ArrowService updateArrow: ",a)}}updateArrowToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateArrowToDb","color: green;");try{if(e?.targetElement?.xpath){let t=this.domService.getXPath(e.targetElement.xpath);if(t){let i=t.iterateNext();i&&(Kr(i)||(e.targetElement=null))}}this.domService.updateSelectedAnnotationInMap([e]),this.authService.getUser()&&this.authService.isFeatureAllowed(je.ARROW)&&this.docService.getDocumentPaths$().pipe(Ge(t=>!!t),ut(1),Se(t=>(this.documentPaths=t,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Ge(i=>!!i),ut(1),Se(i=>{if(this.documentPaths?.arrow&&e?.annotationId){let a=JSON.parse(JSON.stringify(e));return a.position=null,this.commonDbService.setData({feature:"arrow",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.annotationId,skipFirestore:!0},data:JSON.parse(JSON.stringify(a))})}else return ce(null)}))))).subscribe(()=>{},t=>{this.loggingService.catch("Error in ArrowService updateArrowToDb subscription: ",t)})}catch(t){this.loggingService.catch("Error in ArrowService updateArrowToDb: ",t)}}deleteArrowPinAnnotations(e){try{let t=this.domService.getSelectedAnnotationsMap(),i=this.authService.getUser(),a=[];Object.keys(t).forEach(l=>X(this,null,function*(){let c=t[l];if(c.type==="arrow"){let d=i&&!i?.isAnonymous&&!i?.isGuest;i&&c.from&&(d||c.from.userId===i.userId)&&a.push(c)}})),a?.length&&(this.analyticsService.trackEvent(Y.Events.Arrow.ARROW_DELETE_TRIGGERED,{triggerType:e,annotationId:a.map(l=>l.annotationId).join()}),this.dialog.open(al,{panelClass:"velt-mat-dialog-container",data:{title:"Delete arrow?",message:"This selected arrow will be deleted.",yesButton:"Delete",noButton:"Cancel",variant:"arrow"}}).afterClosed().pipe(ut(1)).subscribe(l=>{l&&(a.forEach(c=>X(this,null,function*(){yield this.deleteArrowPinAnnotation(c)})),setTimeout(()=>{document.querySelectorAll(`[${N.SNIPPYLY_HIGHLIGHT}]`).forEach(d=>{this.domService.removeHighlightFromElement(d)})},100))})),this.domService.resetSelectedAnnotationsMap(!0,"arrow")}catch(t){this.loggingService.catch("Error in ArrowService deleteArrowPinAnnotations: ",t)}}deleteArrowPinAnnotation(e){return this.authService.isFeatureAllowed(je.ARROW)&&this.documentPaths?.arrow&&e?.annotationId?(this.updateNotificationsDatabase(e,IN.DELETED),this.analyticsService.trackEvent(Y.Events.Arrow.ARROW_DELETED,{annotationId:e.annotationId}),this.commonDbService.deleteData({feature:"arrow",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.annotationId,skipFirestore:!0}})):Promise.resolve()}enableAddArrowMode(){this.authService.isFeatureAllowed(je.ARROW)?(this.analyticsService.trackEvent(Y.Events.Arrow.ARROW_ADD_MODE_ENABLED),this.addArrowMode$.next(!0)):this.loggingService.catch("Error in ArrowService enableAddArrowMode: ","Arrow feature is not enabled.")}disableAddArrowMode(){this.analyticsService.trackEvent(Y.Events.Arrow.ARROW_ADD_MODE_DISABLED),this.addArrowMode$.next(!1)}addArrowModeChange(){return this.addArrowMode$.asObservable()}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(t){return this.loggingService.catch("Error in ArrowService isElementInsideAllowedElements: ",t),!1}}updateNotificationsDatabase(e,t){try{let i={annotationData:e,actionType:t,notificationSource:"arrow"};this.notificationService.updateNotificationDatabase(i)}catch(i){this.loggingService.catch("Error in ArrowService updateNotificationsDatabase: ",i)}}getArrowUrl(e){try{return e?.pageInfo?.arrowUrl?e.pageInfo.arrowUrl:(e?.pageInfo||(e.pageInfo=ro(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.arrowUrl=this.generateArrowUrl(e),this.updateArrow(e),e.pageInfo?.arrowUrl)}catch(t){this.loggingService.catch("Error in ArrowService getArrowUrl: ",t);return}}generateArrowUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(N.URL_PARAMS.TAG_ID),t.searchParams.append(N.URL_PARAMS.TAG_ID,e.annotationId),t.href}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(Ft),K(st),K($n),K(qe),K(Ve),K(eo),K(Vn),K(Lo),K(k),K(mn),K(yn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var nU=class extends Cr{constructor(o){super(o),this.getService(k).log("%c[WB] Creating CLASS: ArrowElement","color: blue;"),this.allowedElementIds=this._allowedElementIds}_allowedElementIds(o){this.getService(k).log("%c[WB] Calling FUNCTION: allowedElementIds","color: green;");try{this.trackEvent(Y.Events.Arrow.ALLOWED_ELEMENT_IDS_TRIGGERED,{payload:{elementIds:o}}),this.getService(km).setAllowedElementIds(o)}catch(r){this.getService(k).catch("Error in allowedElementIds: ",r)}}};var Ec=(()=>{let o=class o{constructor(e){this.loggingService=e,this.autocompleteDataMap$=new _e({}),this.onAutocompleteChipClick$=new at;try{this.loggingService.log("%c[WB] Creating CLASS: AutocompleteService","color: blue;"),this.create({hotkey:"@",type:"contact",data:[]})}catch(t){this.loggingService.catch("Error in AutocompleteService constructor: ",t)}}create(e){try{if(this.loggingService.log("%c[WB] Calling AutocompleteService FUNCTION: create","color: green;"),e?.hotkey){let t=this.autocompleteDataMap$.value;t[e.hotkey]=e,this.autocompleteDataMap$.next(t)}}catch(t){this.loggingService.catch("Error in AutocompleteService create: ",t)}}remove(e){try{this.loggingService.log("%c[WB] Calling AutocompleteService FUNCTION: remove","color: green;");let t=this.autocompleteDataMap$.value;delete t[e],this.autocompleteDataMap$.next(t)}catch(t){this.loggingService.catch("Error in AutocompleteService remove: ",t)}}getAutocompleteDataMap$(){return this.autocompleteDataMap$.asObservable()}getAutocompleteDataMap(){return this.autocompleteDataMap$.value}setOnAutocompleteChipClick(e){this.onAutocompleteChipClick$.next(e)}getOnAutocompleteChipClick$(){return this.onAutocompleteChipClick$.asObservable()}};o.\u0275fac=function(t){return new(t||o)(K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var rU=class extends Cr{constructor(o){super(o),this.getService(k).log("%c[WB] Creating CLASS: AutocompleteElement","color: blue;"),this.create=this._create,this.onAutocompleteChipClick=this._onAutocompleteChipClick}_create(o){this.getService(k).log("%c[WB] Calling FUNCTION: create","color: green;");try{return this.trackEvent(Y.Events.Autocomplete.CREATE_TRIGGERED,{payload:{data:o}}),this.getService(Ec).create(o)}catch(r){this.getService(k).catch("Error in _create: ",r)}}_onAutocompleteChipClick(){this.getService(k).log("%c[WB] Calling FUNCTION: onAutocompleteChipClick","color: green;");try{return this.trackEvent(Y.Events.Autocomplete.ON_AUTOCOMPLETE_CHIP_CLICK_TRIGGERED),this.getService(Ec).getOnAutocompleteChipClick$()}catch(o){return this.getService(k).catch("Error in _onAutocompleteChipClick: ",o),ce(null)}}};var zbe=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m){this.authService=e,this.iamService=t,this.docService=i,this.configService=a,this.commonDbService=l,this.loggingService=c,this.commentService=d,this.userPermissionService=m,this.documentPaths=null,this.LISTENER_BATCH_SIZE=5}getAnnotationsCount(e){try{return this.authService.getUser$().pipe(Ge(t=>!!t),Se(t=>this.docService.getOrganizationConfig$().pipe(Ge(i=>!!i),ue(()=>t))),Se(t=>this.commentService.isFeatureAllowed({firebaseUser:t,annotations:[],filteredAnnotations:[]})),Se(t=>t.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(i=>(t.featureAllowed=i,t))):ce(t)),Se(t=>t.featureAllowed?this.processRequest(t,e):ce(null)),ue(t=>t??{data:null}),_t(Kt))}catch(t){return this.loggingService.catch("Error in CommentService getAnnotationsCount: ",t),ce({data:null})}}processRequest(e,t){try{return ce(e).pipe(Se(()=>this.initializeDocumentPaths(t,e)),Se(()=>this.getDocumentIds$(t)),Se(i=>{let a=this.authService.getUser()?.userSnippylyId,l=this.buildRequestContext(t,i);if(!this.validateRequestContext(l,t))return ce({data:null,mode:l.mode,serverDocumentIds:l.serverDocumentIds});if(!l.organizationId)return ce({data:null,mode:l.mode,serverDocumentIds:l.serverDocumentIds});let c=this.setupTriggers$(l.mode,l.organizationId,l.clientOrganizationId,l.veltFolderId,l.serverDocumentIds);if(this.shouldUseAggregateMode(l.mode))return this.handleAggregateCounts$({triggers$:c,serverDocumentIds:l.serverDocumentIds,request:t,userId:a,organizationId:l.organizationId,clientOrganizationId:l.clientOrganizationId,veltFolderId:l.veltFolderId,folderId:l.folderId,mode:l.mode}).pipe(ue(d=>({data:d,mode:l.mode,serverDocumentIds:l.serverDocumentIds})));if(l.mode.isBatchedGroupedMode){let d=t?.debounceMs??5e3;return this.handleBatchedGroupedCounts$({triggers$:c,documentIds:i,request:t,userId:a,organizationId:l.organizationId,veltFolderId:l.veltFolderId,debounceMs:d}).pipe(ue(m=>({data:m,mode:l.mode,serverDocumentIds:l.serverDocumentIds})))}else return this.handleGroupedCounts$(c,i,t,a,l.organizationId,l.veltFolderId).pipe(ue(d=>({data:d,mode:l.mode,serverDocumentIds:l.serverDocumentIds})))}),Se(i=>{if(!i?.data)return ce(null);let{data:a,mode:l,serverDocumentIds:c}=i;return t?.filterGhostComments?this.filterGhostComments$(a,l,c):ce(a)}),Xn(i=>(this.loggingService.catch("Error processing request: ",i),ce(null))))}catch(i){return this.loggingService.catch("Error in CommentService getAnnotationsCount: ",i),ce(null)}}initializeDocumentPaths(e,t){try{return e?ce(t):this.docService.getDocumentPaths$().pipe(Ge(i=>!!i),ln(i=>{this.documentPaths=i,t.documentPaths=i}),ue(()=>{}))}catch(i){return this.loggingService.catch("Error in CommentService initializeDocumentPaths: ",i),ce(t)}}buildRequestContext(e,t){try{let i=this.docService.getOrganizationConfig(),a=this.documentPaths?.organizationId??i?.organizationId,l=this.documentPaths?.clientOrganizationId??i?.clientOrganizationId,c,d,m;if(e?.allDocuments||e?.documentIds||e?.folderId||e?.organizationId||e?.locationIds){if(e.organizationId&&(a=ba(e.organizationId),l=e.organizationId),!a)throw new Error("organizationId is required for this request type");e.folderId&&(c=Lr(e.folderId),d=e.folderId),e.allDocuments&&(m=!0)}else c=this.documentPaths?.veltFolderId,d=this.documentPaths?.folderId,m=this.documentPaths?.allDocuments;let u=this.determineMode(e,c,m,t),_=u.isOrgMode?[]:t.length>0?t.map(I=>I.documentId):[this.documentPaths?.documentId??""];return{organizationId:a,clientOrganizationId:l,veltFolderId:c,folderId:d,allDocuments:m,mode:u,serverDocumentIds:_}}catch(i){return this.loggingService.catch("Error in CommentService buildRequestContext: ",i),{organizationId:void 0,clientOrganizationId:void 0,veltFolderId:void 0,folderId:void 0,allDocuments:void 0,mode:{isOrgMode:!1,isFolderMode:!1,isBatchMode:!1,isBatchedGroupedMode:!1},serverDocumentIds:[]}}}validateRequestContext(e,t){try{if(t?.aggregateDocuments&&!e.serverDocumentIds.length)throw this.loggingService.catch("Error in CommentService getAnnotationsCount: documentIds is required when aggregateDocuments is true"),new Error("documentIds is required when aggregateDocuments is true");return!(!e.organizationId||!(e.mode.isOrgMode||e.mode.isFolderMode)&&e.serverDocumentIds.some(i=>!i))}catch(i){return this.loggingService.catch("Error in CommentService validateRequestContext: ",i),!1}}shouldUseAggregateMode(e){try{return e.isFolderMode||e.isOrgMode||e.isBatchMode}catch(t){return this.loggingService.catch("Error in CommentService shouldUseAggregateMode: ",t),!1}}getDocumentIds$(e){try{return e?.documentIds?.length?ce(e.documentIds.map(t=>({clientDocumentId:t,documentId:mi(t)}))):this.docService.getDocumentIds$().pipe(ue(t=>t.length>0?t:[{documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId||""}]))}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIds: ",t),ce([])}}determineMode(e,t,i,a){try{let l=!!e?.organizationId&&!e?.documentIds?.length&&!t&&!i,c=!!t&&!!i,d=!!e?.aggregateDocuments&&!i&&!!a?.length,m=(!!e?.batchedPerDocument||a.length>1)&&!!a?.length&&!e?.aggregateDocuments&&!i;return{isOrgMode:l,isFolderMode:c,isBatchMode:d,isBatchedGroupedMode:m}}catch(l){return this.loggingService.catch("Error in CommentService determineMode: ",l),{isOrgMode:!1,isFolderMode:!1,isBatchMode:!1,isBatchedGroupedMode:!1}}}setupTriggers$(e,t,i,a,l){try{if(e.isOrgMode){let c=this.authService.getUser()?.userId??"";return[co(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:i})??Promise.resolve({})).pipe(Se(m=>c&&m?.[c]?.organization?.[i]?.errorCode===mr.PERMISSION_DENIED?(this.loggingService.log(`%c[WB] commentViews org listener skipped \u2014 user does not have access to organization: ${i}`,"color: orange;"),Pc):this.commonDbService.dbListener({feature:"organizationMetadata",properties:{useCollectionGroup:!1,isCollection:!1,organizationId:t}}))).pipe(ue(m=>m?.data?.commentViewsUpdatedAt??null),Ge(m=>!!m),_t(Kt))]}else{if(e.isFolderMode)return[this.commonDbService.dbListener({feature:"folder",properties:{useCollectionGroup:!1,isCollection:!1,folderId:a,organizationId:t}}).pipe(ue(d=>d?.data?.commentViewsUpdatedAt??null),Ge(d=>!!d),_t(Kt))];if(e.isBatchMode||e.isBatchedGroupedMode){let c=[];for(let d=0;d<l.length;d+=this.LISTENER_BATCH_SIZE)c.push(l.slice(d,d+this.LISTENER_BATCH_SIZE));return c.map(d=>this.commonDbService.dbListener({feature:"allDocuments",properties:{useCollectionGroup:!0,isCollection:!0,useQuery:!0,firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.organizationId","==",t),ft("metadata.documentId","in",d))]}}).pipe(ue(u=>Object.values(u?.data||{}).map(I=>I?.commentViewsUpdatedAt??null).sort().join(",")),_t(Kt)))}else return l.map(c=>this.commonDbService.dbListener({feature:"documentMetadata",properties:{useCollectionGroup:!1,isCollection:!1,documentId:c,organizationId:t}}).pipe(ue(m=>m?.data?.commentViewsUpdatedAt??null),Ge(m=>!!m),_t(Kt)))}}catch(c){return this.loggingService.catch("Error in CommentService setupTriggers: ",c),[]}}handleGroupedCounts$(e,t,i,a,l,c){try{let d=t.map((m,u)=>e[u].pipe(_o(void 0),Se(()=>co(this.getCountsForDocument$(m.documentId,m.clientDocumentId,i,a,l,c)))));return gn(d).pipe(ue(m=>{let u={};return m.forEach(_=>{_&&(u[_.clientDocumentId]={total:_.total,unread:_.unread})}),{data:u}}),Xn(m=>(this.loggingService.catch("Error in grouped counts: ",m),ce(null))))}catch(d){return this.loggingService.catch("Error in CommentService handleGroupedCounts: ",d),ce(null)}}handleBatchedGroupedCounts$(e){try{let{triggers$:t,documentIds:i,request:a,userId:l,organizationId:c,veltFolderId:d,debounceMs:m}=e,u=this.LISTENER_BATCH_SIZE,_=new Td(1),I=t.map((q,ae)=>q.pipe(KB(_),ue(()=>ae))),A=No(...I).pipe(Qr(m)),M=ce(-1).pipe(Se(()=>co(this.fetchAllDocumentCounts$(i,a,l,c,d))),ue(q=>({batchIndex:-1,data:q?.data||{}})),ln(()=>{_.next()})),V=A.pipe(Se(q=>{let ae=q*u,ye=Math.min(ae+u,i.length),ie=i.slice(ae,ye);return co(this.fetchAllDocumentCounts$(ie,a,l,c,d)).pipe(ue(ge=>({batchIndex:q,data:ge?.data||{}})))}));return No(M,V).pipe(ub((q,ae)=>({data:h(h({},q.data),ae.data)}),{data:{}}),Xn(q=>(this.loggingService.catch("Error in batched grouped counts: ",q),ce(null))))}catch(t){return this.loggingService.catch("Error in CommentService handleBatchedGroupedCounts: ",t),ce(null)}}fetchAllDocumentCounts$(e,t,i,a,l){return X(this,null,function*(){try{let c=e.map(u=>this.getCountsForDocument$(u.documentId,u.clientDocumentId,t,i,a,l)),d=yield Promise.allSettled(c),m={};return d.forEach(u=>{if(u.status==="fulfilled"&&u.value){let{clientDocumentId:_,total:I,unread:A}=u.value;m[_]={total:I,unread:A}}}),{data:m}}catch(c){return this.loggingService.catch("Error in CommentService fetchAllDocumentCounts: ",c),null}})}handleAggregateCounts$(e){try{let{triggers$:t,serverDocumentIds:i,request:a,userId:l,organizationId:c,clientOrganizationId:d,veltFolderId:m,folderId:u,mode:_}=e;return gn(t).pipe(ue(()=>{})).pipe(_o(void 0),Se(()=>co(this.getAggregateCounts({serverDocumentIds:i,request:a,userId:l,organizationId:c,clientOrganizationId:d,veltFolderId:m,folderId:u,mode:_}))),Xn(A=>(this.loggingService.catch("Error in aggregate counts: ",A),ce(null))))}catch(t){return this.loggingService.catch("Error in CommentService handleAggregateCounts: ",t),ce(null)}}getCountsForDocument$(e,t,i,a,l,c){return X(this,null,function*(){try{let d=this.configService?.getApiKey(),m={useCollectionGroup:!0,isCollection:!0,useQuery:!0,getCount:!0},u=[ft("metadata.apiKey","==",d),ft("metadata.organizationId","==",l),ft("metadata.documentId","in",[e]),...c?[ft("metadata.veltFolderId","==",c)]:[],...i?.statusIds?.length?[ft("status.id","in",i.statusIds)]:[],...i?.locationIds?.length?[ft("location.id","in",i.locationIds)]:[],...i?.agentFields?.length?[ft("agent.agentFields","array-contains-any",i.agentFields)]:[]],_=[yr(...u),uo("lastUpdated","desc"),uo("createdAt","desc")],I=yield this.commonDbService.queryData({feature:"allComments",properties:y(h({},m),{firestoreQuery:_})}),A=0;if(!i?.agentFields?.length){let M=[...u,ft("viewedByUserIds","array-contains",a)],V=[yr(...M),uo("lastUpdated","desc"),uo("createdAt","desc")];A=yield this.commonDbService.queryData({feature:"allComments",properties:y(h({},m),{firestoreQuery:V})})}return{clientDocumentId:t,total:I,unread:I-A}}catch(d){return this.loggingService.catch("Error in CommentService getCountsForDocument: ",d),null}})}getAggregateCounts(e){return X(this,null,function*(){try{let t="",{serverDocumentIds:i,request:a,userId:l,organizationId:c,clientOrganizationId:d,veltFolderId:m,folderId:u,mode:_}=e,I=this.configService?.getApiKey(),A={useCollectionGroup:!0,isCollection:!0,useQuery:!0,getCount:!0},M=[ft("metadata.apiKey","==",I),ft("metadata.organizationId","==",c),...a?.statusIds?.length?[ft("status.id","in",a.statusIds)]:[],...a?.locationIds?.length?[ft("location.id","in",a.locationIds)]:[],...a?.agentFields?.length?[ft("agent.agentFields","array-contains-any",a.agentFields)]:[]],V,q=0;if(_.isFolderMode){t=u??"",M.push(ft("metadata.veltFolderId","==",m));let ae=[yr(...M),uo("lastUpdated","desc"),uo("createdAt","desc")];if(V=yield this.commonDbService.queryData({feature:"allComments",properties:y(h({},A),{firestoreQuery:ae})}),!a?.agentFields?.length){let ye=[...M,ft("viewedByUserIds","array-contains",l)],ie=[yr(...ye),uo("lastUpdated","desc"),uo("createdAt","desc")];q=yield this.commonDbService.queryData({feature:"allComments",properties:y(h({},A),{firestoreQuery:ie})})}}else if(_.isOrgMode){t=d??"";let ae=[yr(...M),uo("lastUpdated","desc"),uo("createdAt","desc")];if(V=yield this.commonDbService.queryData({feature:"allComments",properties:y(h({},A),{firestoreQuery:ae})}),!a?.agentFields?.length){let ye=[...M,ft("viewedByUserIds","array-contains",l)],ie=[yr(...ye),uo("lastUpdated","desc"),uo("createdAt","desc")];q=yield this.commonDbService.queryData({feature:"allComments",properties:y(h({},A),{firestoreQuery:ie})})}}else{t="result";let ae=[];for(let ge=0;ge<i.length;ge+=this.LISTENER_BATCH_SIZE)ae.push(i.slice(ge,ge+this.LISTENER_BATCH_SIZE));let ye=ae.map(ge=>X(this,null,function*(){let Ie=[...M,ft("metadata.documentId","in",ge),...m?[ft("metadata.veltFolderId","==",m)]:[]],he=[yr(...Ie),uo("lastUpdated","desc"),uo("createdAt","desc")];return this.commonDbService.queryData({feature:"allComments",properties:y(h({},A),{firestoreQuery:he})})}));if(V=(yield Promise.allSettled(ye)).reduce((ge,Ie)=>ge+(Ie.status==="fulfilled"&&Ie.value||0),0),!a?.agentFields?.length){let ge=ae.map(he=>X(this,null,function*(){let Te=[...M,ft("metadata.documentId","in",he),...m?[ft("metadata.veltFolderId","==",m)]:[],ft("viewedByUserIds","array-contains",l)],Oe=[yr(...Te),uo("lastUpdated","desc"),uo("createdAt","desc")];return this.commonDbService.queryData({feature:"allComments",properties:y(h({},A),{firestoreQuery:Oe})})}));q=(yield Promise.allSettled(ge)).reduce((he,Te)=>he+(Te.status==="fulfilled"&&Te.value||0),0)}}return{data:{[t]:{total:V,unread:V-q}}}}catch(t){return this.loggingService.catch("Error in CommentService getAggregateCounts: ",t),null}})}filterGhostComments$(e,t,i){try{return e?this.commentService.getGhostCommentAnnotationMap$().pipe(ue(a=>{if(!a)return e;let l=this.buildGhostCommentAnnotationMap(a),c=this.groupGhostCommentsByModeId(l,t,i);return this.adjustCountsForGhostComments(e,c),e})):ce(null)}catch(a){return this.loggingService.catch("Error in CommentService filterGhostComments: ",a),ce(null)}}buildGhostCommentAnnotationMap(e){let t={};return Object.keys(e).forEach(i=>{let a=this.commentService.getAnnotationById(i);a&&(t[i]=a)}),t}groupGhostCommentsByModeId(e,t,i){try{let a={};return Object.values(e).forEach(l=>{let c=this.getModeIdForAnnotation(l,t,i);c&&(a[c]||(a[c]=[]),a[c].push(l))}),a}catch(a){return this.loggingService.catch("Error in CommentService groupGhostCommentsByModeId: ",a),{}}}getModeIdForAnnotation(e,t,i){try{return t.isOrgMode?e?.metadata?.clientOrganizationId||null:t.isFolderMode?e?.metadata?.folderId||null:t.isBatchMode?i.includes(e?.metadata?.documentId??"")?"result":null:e?.metadata?.clientDocumentId||null}catch(a){return this.loggingService.catch("Error in CommentService getModeIdForAnnotation: ",a),null}}adjustCountsForGhostComments(e,t){try{if(typeof e?.data!="object")return;let a=this.authService.getUser()?.userSnippylyId;Object.keys(e.data||{}).forEach(l=>{let c=t[l];if(!(!c||!e?.data?.[l]?.total)&&(e.data[l].total=Math.max(0,e.data[l].total-c.length),a)){let d=c.filter(m=>m?.viewedByUserIds&&!m?.viewedByUserIds?.includes(a));d.length>0&&(e.data[l].unread=Math.max(0,e.data[l].unread-d.length))}})}catch(i){this.loggingService.catch("Error in CommentService adjustCountsForGhostComments: ",i)}}};o.\u0275fac=function(t){return new(t||o)(K(qe),K(Vn),K(st),K(Ft),K(yn),K(k),K(Re),K(Ia))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Mn=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A){this.analyticsService=e,this.authService=t,this.commentService=i,this.commentViewsService=a,this.contactService=l,this.customFilterService=c,this.docService=d,this.iamService=m,this.loggingService=u,this.metadataService=_,this.reactionService=I,this.commonDbService=A,this.actionSubjects=new Map,this.defaultSource="internal",this.isUserAdmin=!1,this.subscriptions=[],this.loggingService.log("%c[WB] Creating CLASS: CommentActionsService","color: blue;");try{this.commentService.setCommentActionsService(this),this.iamService.isUserAdmin$().subscribe(M=>{this.isUserAdmin=M})}catch(M){this.loggingService.catch("Error in CommentActionsService constructor: ",M)}}addCommentAnnotation(l,c){return X(this,arguments,function*({annotation:e,options:t,visibility:i},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addCommentAnnotation","color: green;"),i){if(i.type==="restricted"){let m=this.authService.getUser();m?.userId&&(i=Ju(i,m.userId))}if(i.type==="organizationPrivate"&&!i.organizationId){let m=this.docService.getOrganizationConfig();m?.clientOrganizationId&&(i=y(h({},i),{organizationId:m.clientOrganizationId}))}let d=Xu(i);d.length>0&&(e.context||(e.context={}),e.context._setAccessFields=d,e.visibilityConfig=h(h({type:i.type},i.organizationId&&{organizationId:i.organizationId}),i.userIds&&{userIds:i.userIds}))}return new Promise(d=>{this.commentService.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,m=>X(this,null,function*(){let u=yield this.getAddCommentAnnotationEventFromCommentAddEventData(m);d(u)}),void 0,void 0,e,void 0,void 0,void 0,void 0,void 0,a)})}catch(d){return this.loggingService.catch("Error in CommentActionsService addCommentAnnotation: ",d),null}})}publishCommentAnnotation(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: publishCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t);if(c){let d=JSON.parse(JSON.stringify(c));d.isDraft=!1,this.commentService.saveComment(d,{type:Ot.PUBLISHED}),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_PUBLISHED,{annotationId:e,commentType:this.commentService.getCommentType(d),commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource});let m=yield this.metadataService.getGlobalMetadata(),u={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(d),metadata:m};return this.triggerAction(ar.PUBLISH_COMMENT_ANNOTATION,u),u}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService publishCommentAnnotation: ",c),null}})}getAddCommentAnnotationEventFromCommentAddEventData(e){return X(this,null,function*(){try{let t=yield this.metadataService.getGlobalMetadata();return{commentAnnotation:this.commentService.getCommentAnnotationForClient(e?.annotation),annotationId:e?.annotation?.annotationId,metadata:t,addContext:e?.addContext,elementRef:e?.elementRef}}catch(t){return this.loggingService.catch("Error in CommentActionsService getAddCommentAnnotationEventFromData: ",t),null}})}triggerAddCommentAnnotationEvent(e){try{this.triggerAction(ar.ADD_COMMENT_ANNOTATION,e)}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAddCommentAnnotationEvent: ",t)}}getAddCommentAnnotationDraftEventFromCommentAddEventData(e){return X(this,null,function*(){try{return{metadata:yield this.metadataService.getGlobalMetadata(),addContext:e?.addContext}}catch(t){return this.loggingService.catch("Error in CommentActionsService getAddCommentAnnotationEventFromData: ",t),null}})}triggerAddCommentAnnotationDraftEvent(e){try{this.triggerAction(ar.ADD_COMMENT_ANNOTATION_DRAFT,e)}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAddCommentAnnotationDraftEvent: ",t)}}triggerAddCommentDraftEventForAnnotation(e,t){return X(this,null,function*(){try{if(!e?.annotationId||!t)return;let i=yield this.metadataService.getGlobalMetadata(),a={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),comment:t,metadata:i};this.triggerAction(ar.ADD_COMMENT_DRAFT,a)}catch(i){this.loggingService.catch("Error in CommentActionsService triggerAddCommentDraftEventForAnnotation: ",i)}})}triggerAnnotationNotFoundError(e){try{this.loggingService.catch("Annotation not found:","The annotation with the given id was not found.")}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAnnotationNotFoundError: ",t)}}deleteCommentAnnotation(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteCommentAnnotation","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let d=this.commentService.getAnnotationById(e,t);if(d){let m=this.authService.getUser();if(this.isUserAdmin||m?.userId===d?.from?.userId){this.commentService.deleteCommentPinAnnotation(d);let u=yield this.metadataService.getGlobalMetadata(),_={annotationId:d.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(d),metadata:u};return this.triggerAction(ar.DELETE_COMMENT_ANNOTATION,_),_}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete it.")}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService deleteCommentAnnotation: ",c),null}})}updatePriority(l,c){return X(this,arguments,function*({annotationId:e,priority:t,options:i},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updatePriority","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let m=this.commentService.getAnnotationById(e,i);if(m){m=JSON.parse(JSON.stringify(m));let u=m.priority?JSON.parse(JSON.stringify(m.priority)):null;u&&t&&u?.id===t?.id?m.priority=void 0:m.priority=t,this.commentService.saveComment(m,{type:Ot.PRIORITY_CHANGED,newPriority:t,oldPriority:u});let _=yield this.metadataService.getGlobalMetadata(),I={newPriority:t,oldPriority:u,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:_};return this.triggerAction(ar.UPDATE_PRIORITY,I),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_PRIORITY_CHANGED,{annotationId:e,commentType:this.commentService.getCommentType(m),oldPriority:m.priority,newPriority:t,commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource}),I}else this.triggerAnnotationNotFoundError(e);return null}catch(d){return this.loggingService.catch("Error in CommentActionsService updatePriority: ",d),null}})}updateStatus(l,c){return X(this,arguments,function*({annotationId:e,status:t,options:i},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateStatus","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let m=this.commentService.getAnnotationById(e,i);if(m){m=JSON.parse(JSON.stringify(m));let u=m.status?JSON.parse(JSON.stringify(m.status)):null;m.status=t,this.commentService.saveComment(m,{type:Ot.STATUS_CHANGED,newStatus:t,oldStatus:u});let _=yield this.metadataService.getGlobalMetadata(),I={newStatus:t,oldStatus:u,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:_};return this.triggerAction(ar.UPDATE_STATUS,I),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_STATUS_CHANGED,{annotationId:e,commentType:this.commentService.getCommentType(m),oldStatus:u,newStatus:t,commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource,commentAnnotationCreatedAt:m.createdAt}),I}else this.triggerAnnotationNotFoundError(e);return null}catch(d){return this.loggingService.catch("Error in CommentActionsService updateStatus: ",d),null}})}updateAccess(l,c){return X(this,arguments,function*({annotationId:e,accessMode:t,options:i},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateAccess","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let m=this.commentService.getAnnotationById(e,i);if(m)if(this.commentService.isPrivateCommentAllowed()){m=JSON.parse(JSON.stringify(m));let u=m.iam?.accessMode;m.iam.accessMode=t,this.commentService.saveComment(m,{type:Ot.ACCESS_MODE_CHANGED,newAccessMode:t,oldAccessMode:u});let _=yield this.metadataService.getGlobalMetadata(),I={newAccessMode:t,oldAccessMode:u,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:_};switch(this.triggerAction(ar.UPDATE_ACCESS,I),t){case Ca.PRIVATE:this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ACCESS_MODE_CHANGED,{type:Ca.PRIVATE,source:a??this.defaultSource});break;case Ca.PUBLIC:this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ACCESS_MODE_CHANGED,{type:Ca.PUBLIC,source:a??this.defaultSource});break;default:break}return I}else this.loggingService.catch("Access Denied","You must be an admin to update the access mode of the comment.");else this.triggerAnnotationNotFoundError(e);return null}catch(d){return this.loggingService.catch("Error in CommentActionsService updateAccess: ",d),null}})}resolveCommentAnnotation(i){return X(this,arguments,function*({annotationId:e,options:t}){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: resolveCommentAnnotation","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let l=this.commentService.getAnnotationById(e,t);if(l){l=JSON.parse(JSON.stringify(l));let c=this.customFilterService.resolvedStatus,d=l.status?JSON.parse(JSON.stringify(l.status)):null;c&&(l.status=c,this.commentService.saveComment(l,{type:Ot.STATUS_CHANGED,newStatus:c,oldStatus:d}));let m=yield this.metadataService.getGlobalMetadata(),u={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(l),metadata:m};return this.triggerAction(ar.RESOLVE_COMMENT,u),u}else this.triggerAnnotationNotFoundError(e);return null}catch(a){return this.loggingService.catch("Error in CommentActionsService resolveCommentAnnotation: ",a),null}})}getLink(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getLink","color: green;");let c=this.commentService.getAnnotationById(e,t);if(c){let d=this.commentService.getCommentUrl(c)??null,m=yield this.metadataService.getGlobalMetadata();return{link:d,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(c),metadata:m}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService getLink: ",c),null}})}copyLink(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: copyLink","color: green;");let c=yield this.getLink({annotationId:e,options:t},i);if(c?.link){Kc(c.link),this.commentService.setCopyLink(c.link),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_LINK_COPIED,{annotationId:e,commentType:this.commentService.getCommentType(c.commentAnnotation),commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource,link:c.link});let d=yield this.metadataService.getGlobalMetadata(),m={link:c.link,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(c.commentAnnotation),metadata:d};return this.triggerAction(ar.COPY_LINK,m),m}return null}catch(c){return this.loggingService.catch("Error in CommentActionsService copyLink: ",c),null}})}addComment(m,u){return X(this,arguments,function*({annotationId:e,comment:t,assignedTo:i,assigned:a,options:l,visibility:c},d){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addComment","color: green;");let _=this.authService.getUser();if(!_)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;if(_){let I=this.commentService.getAnnotationById(e,l),A=I?.comments?.length?Ot.ADDED:Ot.NEWLY_ADDED;if(I){I.status.type==="terminal"&&(I.status=this.customFilterService.defaultStatus);let M=new Xl;M=h(h({},M),t),M.lastUpdated=new Date,M.attachments||(M.attachments=[]),M.attachments=M.attachments.filter(ie=>ie?.attachmentId),M.createdAt=this.timestamp,M.from=_,i&&(I.assignedTo=i),this.commentService.saveComment(I,{type:A,updatedComment:M,assigned:a,visibility:c,_dispatchAddCommentEvent:!0});let V=y(h({},I),{comments:[...I.comments||[],M]}),q=yield this.buildAddCommentEvent({annotation:V,newComment:M});if(!q)return null;let ae=t?.commentId,ye=this.calculateCommentThreadIndex(t,I);return this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ADDED,{annotationId:e,commentThreadId:ae,commentThreadIndex:ye,commentType:this.commentService.getCommentType(I),commentMode:this.commentService.getCommentMode(),source:d??this.defaultSource,commentAnnotationCreatedAt:I.createdAt,taggedClientUserIds:M.taggedUserContacts?.map(ie=>ie.contact?.userId).filter(ie=>!!ie),taggedSnippylyUserIds:M.taggedUserContacts?.filter(ie=>!!I?.metadata?.apiKey&&!!ie.contact?.userId).map(ie=>cd(I.metadata.apiKey,ie.contact.userId))}),q}else this.triggerAnnotationNotFoundError(e)}return null}catch(_){return this.loggingService.catch("Error in CommentActionsService addComment: ",_),null}})}buildAddCommentEvent(i){return X(this,arguments,function*({annotation:e,newComment:t}){try{let a=yield this.metadataService.getGlobalMetadata();return{annotationId:e.annotationId,commentId:t?.commentId,comment:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:a}}catch(a){return this.loggingService.catch("Error in CommentActionsService buildAddCommentEvent: ",a),null}})}triggerAddCommentEvent(i){return X(this,arguments,function*({annotation:e,newComment:t}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: triggerAddCommentEvent","color: green;");let a=yield this.buildAddCommentEvent({annotation:e,newComment:t});return a&&this.triggerAction(ar.ADD_COMMENT,a),a}catch(a){return this.loggingService.catch("Error in CommentActionsService triggerAddCommentEvent: ",a),null}})}approveCommentAnnotation(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: approveCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t);if(c){c.approved=!0,this.commentService.saveComment(c,{type:Ot.APPROVED}),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_APPROVED,{annotationId:e,commentType:this.commentService.getCommentType(c),commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource});let d=yield this.metadataService.getGlobalMetadata(),m={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(c),metadata:d};return this.triggerAction(ar.APPROVE_COMMENT_ANNOTATION,m),m}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService approveComment: ",c),null}})}acceptCommentAnnotation(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: acceptCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t),d=this.authService.getUser();if(c&&d){let m=c.status?JSON.parse(JSON.stringify(c.status)):null;c.status=N.CommentAcceptStatus,this.commentService.saveComment(c,{type:Ot.ACCEPTED,oldStatus:m,newStatus:N.CommentAcceptStatus});let u=yield this.metadataService.getGlobalMetadata(),_={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(c),metadata:u,actionUser:d,replaceContentHtml:c?.comments?.length?c?.comments[0]?.replaceContentHtml:void 0,replaceContentText:c?.comments?.length?c?.comments[0]?.replaceContentText:void 0};return this.triggerAction(ar.ACCEPT_COMMENT_ANNOTATION,_),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ACCEPTED,{annotationId:e,commentType:this.commentService.getCommentType(c),commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource}),_}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService acceptCommentAnnotation: ",c),null}})}rejectCommentAnnotation(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: rejectCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t),d=this.authService.getUser();if(c&&d){let m=c.status?JSON.parse(JSON.stringify(c.status)):null;c.status=N.CommentRejectStatus,this.commentService.saveComment(c,{type:Ot.REJECTED,oldStatus:m,newStatus:N.CommentRejectStatus});let u=yield this.metadataService.getGlobalMetadata(),_={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(c),metadata:u,actionUser:d,replaceContentHtml:c?.comments?.length?c?.comments[0]?.replaceContentHtml:void 0,replaceContentText:c?.comments?.length?c?.comments[0]?.replaceContentText:void 0};return this.triggerAction(ar.REJECT_COMMENT_ANNOTATION,_),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_REJECTED,{annotationId:e,commentType:this.commentService.getCommentType(c),commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource}),_}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService rejectCommentAnnotation: ",c),null}})}toggleNotificationSubscription(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: toggleNotificationSubscription","color: green;");let c=this.commentService.getAnnotationById(e,t),d=this.authService.getUser();if(c&&d){let m=It(d.userId);if(m){c.subscribedUsers||(c.subscribedUsers={}),c.unsubscribedUsers||(c.unsubscribedUsers={});let u,_=!1;if(c?.unsubscribedUsers?.[m])_=!1;else if(c?.subscribedUsers?.[m])_=!0;else{let M=this.contactService.getCurrentOrganizationUserIAM();if(M){let V=M.groups||{};Object.keys(V).forEach(q=>{c?.subscribedGroups?.[q]&&(_=!0)})}}if(i==="subscribe"||!i&&!_)delete c.unsubscribedUsers[m],c.subscribedUsers[m]={user:d,type:"manual"},u=Ot.SUBSCRIBED;else if(i==="unsubscribe"||!i&&_)delete c.subscribedUsers[m],c.unsubscribedUsers[m]={user:d,type:"manual"},u=Ot.UNSUBSCRIBED;else return null;this.commentService.saveComment(c,{type:u});let I=yield this.metadataService.getGlobalMetadata(),A={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(c),metadata:I};return u===Ot.SUBSCRIBED?this.triggerAction(ar.SUBSCRIBE_COMMENT_ANNOTATION,A):this.triggerAction(ar.UNSUBSCRIBE_COMMENT_ANNOTATION,A),A}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService toggleNotificationSubscription: ",c),null}})}assignUser(l,c){return X(this,arguments,function*({annotationId:e,assignedTo:t,options:i},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: assignUser","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let m=this.commentService.getAnnotationById(e,i);if(m){m.assignedTo=t,this.commentService.saveComment(m,{type:Ot.ASSIGNED,assignedTo:t});let u=yield this.metadataService.getGlobalMetadata(),_={annotationId:e,assignedTo:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:u};return this.triggerAction(ar.ASSIGN_USER,_),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ASSIGNED,{annotationId:e,commentType:this.commentService.getCommentType(m),commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource,assignedToUserId:t?.userId}),_}else this.triggerAnnotationNotFoundError(e);return null}catch(d){return this.loggingService.catch("Error in CommentActionsService assignUser: ",d),null}})}getComment(i){return X(this,arguments,function*({annotationId:e,options:t}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getComment","color: green;");let a=this.commentService.getAnnotationById(e,t);return a?a.comments||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(a){return this.loggingService.catch("Error in CommentActionsService getComment: ",a),[]}})}updateOrDeleteComment(e,t,i,a,l){return X(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateOrDeleteComment","color: green;"),t?.commentText?.trim()||t?.attachments?.length||t?.recorders?.length){let c=this.authService.getUser();if(this.isUserAdmin||c?.userId===t?.from?.userId){t.lastUpdated=new Date,t.status=Ot.UPDATED,t.isEdited||(t.isEdited=!0,t.editedAt=new Date),this.commentService.saveComment(e,{type:Ot.UPDATED,updatedComment:t});let d=yield this.metadataService.getGlobalMetadata(),m={annotationId:e?.annotationId,commentId:t?.commentId,comment:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:d};return this.triggerAction(ar.UPDATE_COMMENT,m),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_EDITED,{annotationId:e?.annotationId,commentThreadId:t?.commentId,commentType:this.commentService.getCommentType(e),commentMode:this.commentService.getCommentMode(),source:l??this.defaultSource}),m}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to update it.")}else yield this.deleteComment({annotationId:e?.annotationId,commentId:t.commentId,skipDeleteThreadConfirmation:i,options:a});return null}catch(c){return this.loggingService.catch("Error in CommentActionsService updateOrDeleteComment: ",c),null}})}updateComment(d,m){return X(this,arguments,function*({annotationId:e,comment:t,skipDeleteThreadConfirmation:i,merge:a,options:l},c){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateComment","color: green;");let u=this.commentService.getAnnotationById(e,l),_=this.authService.getUser();if(!_)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;if(u&&_){let I=t,A=u.comments?.find(M=>M.commentId===t.commentId);if(A){if(this.isUserAdmin||_?.userId===A?.from?.userId)return u?.status.type==="terminal"&&(u.status=this.customFilterService.defaultStatus),a&&(I=h(h({},A),t)),I.from=A.from,I.createdAt=A.createdAt,I.lastUpdated=new Date,yield this.updateOrDeleteComment(u,I,i,l,c);this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to update it.")}}else this.triggerAnnotationNotFoundError(e);return null}catch(u){return this.loggingService.catch("Error in CommentActionsService updateComment: ",u),null}})}deleteComment(c,d){return X(this,arguments,function*({annotationId:e,commentId:t,skipDeleteThreadConfirmation:i,options:a},l){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteComment","color: green;");let m=this.commentService.getAnnotationById(e,a),u=this.authService.getUser();if(!m)return this.triggerAnnotationNotFoundError(e),null;let _=m.comments?.find(q=>q?.commentId===t);if(!_)return null;if(!(this.isUserAdmin||u?.userId===_?.from?.userId))return this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete it."),null;let I=this.commentService.willDeleteWholeAnnotation(m,t),A=this.commentService.getCommentAnnotationForClient(m);if(!i&&!(yield this.commentService.confirmDeleteCommentIfRequired(m,_)))return null;this.commentService.saveComment(m,{type:Ot.DELETED,updatedComment:_,skipDeleteThreadConfirmation:!0});let M=yield this.metadataService.getGlobalMetadata(),V={annotationId:e,commentId:t,commentAnnotation:A,comment:_,metadata:M};if(I){let q={annotationId:e,commentAnnotation:A,metadata:M};this.triggerAction(ar.DELETE_COMMENT_ANNOTATION,q)}else this.triggerAction(ar.DELETE_COMMENT,V);return V}catch(m){return this.loggingService.catch("Error in CommentActionsService deleteComment: ",m),null}})}addAttachment(l,c){return X(this,arguments,function*({annotationId:e,files:t,options:i},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addAttachment","color: green;");let d=[],m=this.commentService.getAnnotationById(e,i);if(m||a==="internal"){let I=[];t.forEach(A=>{let{valid:M,file:V,maxAllowedSize:q,error:ae}=this.validateFile(A);M&&V?I.push(this.uploadFile(V,m||{}).then(ye=>({valid:M,file:V,maxAllowedSize:q,error:ae,attachment:ye||void 0}))):I.push(Promise.resolve({valid:M,file:V,maxAllowedSize:q,error:ae,attachment:void 0}))}),d=yield Promise.all(I)}else this.triggerAnnotationNotFoundError(e);let u=yield this.metadataService.getGlobalMetadata(),_={annotationId:e,commentAnnotation:m?this.commentService.getCommentAnnotationForClient(m):void 0,attachments:d,metadata:u};return this.triggerAction(ar.ADD_ATTACHMENT,_),d}catch(d){return this.loggingService.catch("Error in CommentActionsService addAttachment: ",d),[]}})}validateFile(e){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: validateFile","color: green;");let t=100*1024*1024;(e?.type?.includes("image")||e?.type?.includes("pdf"))&&(t=15*1024*1024);let i=e.size<=t;return{valid:i,file:e,maxAllowedSize:t,maxAllowedSizeInMB:t/1024/1024,error:i?void 0:`File size should be less than ${t/1024/1024} MB`}}catch(t){return this.loggingService.catch("Error in CommentActionsService validateFile: ",t),{valid:!1,maxAllowedSize:0,maxAllowedSizeInMB:0,error:"Error in validating file"}}}deleteAttachment(l){return X(this,arguments,function*({annotationId:e,commentId:t,attachmentId:i,options:a}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteAttachment","color: green;");let c=this.commentService.getAnnotationById(e,a);if(c){let d=c.comments?.find(u=>u?.commentId===t),m=c.metadata;if(d){let u=this.authService.getUser();if(this.isUserAdmin||u?.userId===d?.from?.userId){let _=d.attachments?.find(I=>I?.attachmentId===i);if(_){d.attachments=d.attachments?.filter(V=>V?.attachmentId!==i);let I={attachmentId:_.attachmentId,organizationId:m?.clientOrganizationId??m?.organizationId??null,documentId:m?.clientDocumentId??m?.documentId??null,folderId:m?.folderId??null,commentAnnotationId:c.annotationId,apiKey:m?.apiKey??null};yield this.commentService.deleteAttachment({attachment:_,metadata:I});let A=yield this.metadataService.getGlobalMetadata(),M={attachment:_,annotationId:e,commentId:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(c),metadata:A};return this.triggerAction(ar.DELETE_ATTACHMENT,M),this.updateComment({annotationId:e,comment:d,options:a}),M}}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete the attachment.")}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService deleteAttachment: ",c),null}})}getAttachment(a){return X(this,arguments,function*({annotationId:e,commentId:t,options:i}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getAttachment","color: green;");let l=this.commentService.getAnnotationById(e,i);return l?l.comments?.find(d=>d?.commentId===t)?.attachments||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(l){return this.loggingService.catch("Error in CommentActionsService getAttachment: ",l),[]}})}uploadFile(e,t){return X(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: uploadFile","color: green;"),this.commentService.uploadFile(e,t)}catch(i){return this.loggingService.catch("Error in CommentActionsService uploadFile: ",i),null}})}getRecording(a){return X(this,arguments,function*({annotationId:e,commentId:t,options:i}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getRecording","color: green;");let l=this.commentService.getAnnotationById(e,i);return l?l.comments?.find(d=>d?.commentId===t)?.recorders||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(l){return this.loggingService.catch("Error in CommentActionsService getRecording: ",l),[]}})}deleteRecording(l){return X(this,arguments,function*({annotationId:e,commentId:t,recorderId:i,options:a}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteRecording","color: green;");let c=this.commentService.getAnnotationById(e,a);if(c){let d=c.comments?.find(m=>m?.commentId===t);if(d){let m=this.authService.getUser();if(this.isUserAdmin||m?.userId===d?.from?.userId){let u=d.recorders?.find(_=>_?.id===i);if(u){d.recorders=d.recorders?.filter(A=>A?.id!==i);let _=yield this.metadataService.getGlobalMetadata(),I={annotationId:e,commentId:t,recording:u,commentAnnotation:this.commentService.getCommentAnnotationForClient(c),metadata:_};return this.triggerAction(ar.DELETE_RECORDING,I),this.updateComment({annotationId:e,comment:d,skipDeleteThreadConfirmation:!0,options:a}),I}}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete the recording.")}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService deleteRecording: ",c),null}})}fetchCommentAnnotations(e){return X(this,null,function*(){try{let t=yield this.commentService.fetchCommentAnnotations(e),i;if(t?.hasMore){let l=t?.data[t?.data?.length-1];i=yield zK(l?.lastUpdated?.toString()??"","veltencrypttoken","veltencrypttoken")}let a=t?.data?.reduce((l,c)=>(l[c.metadata.clientDocumentId??c.metadata.documentId]=l[c.metadata.clientDocumentId??c.metadata.documentId]||[],l[c.metadata.clientDocumentId??c.metadata.documentId].push(this.commentService.getCommentAnnotationForClient(c)),l),{});return h({data:a},t?.hasMore?{nextPageToken:i}:{})}catch(t){return this.loggingService.catch("Error in CommentActionsService fetchCommentAnnotations: ",t),{data:null}}})}toggleReaction(c,d){return X(this,arguments,function*({annotationId:e,commentId:t,reaction:i,options:a},l){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: toggleReaction","color: green;");let m=this.commentService.getAnnotationById(e,a),u=this.authService.getUser();if(m&&u){let _=m.comments?.find(I=>I?.commentId===t);if(_){let I=yield this.reactionService.addOrUpdateReaction(i.reactionId,_?.reactionAnnotationIds||[],void 0,void 0,m?.annotationId,i.customReaction,l),A=Ot.REACTION_ADDED;if(I){I?.reactions?.find(q=>q.from?.userId===u?.userId)||(A=Ot.REACTION_DELETED),_.reactionAnnotationIds||(_.reactionAnnotationIds=[]),_.reactionAnnotationIds.includes(I.annotationId)||_.reactionAnnotationIds.push(I.annotationId),I?.reactions?.length||(_.reactionAnnotationIds=_.reactionAnnotationIds.filter(q=>q!==I.annotationId)),this.commentService.saveComment(m,{type:A,updatedComment:_});let M=yield this.metadataService.getGlobalMetadata(),V={annotationId:e,commentId:t,reaction:I,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:M};return l==="add"?this.triggerAction(ar.ADD_REACTION,V):l==="delete"?this.triggerAction(ar.DELETE_REACTION,V):this.triggerAction(ar.TOGGLE_REACTION,V),A===Ot.REACTION_ADDED?this.analyticsService.trackEvent(Y.Events.Comments.REACTION_ADDED,{annotationId:e,commentId:t,reactionId:i.reactionId,commentMode:this.commentService.getCommentMode()}):A===Ot.REACTION_DELETED&&this.analyticsService.trackEvent(Y.Events.Comments.REACTION_DELETED,{annotationId:e,commentId:t,reactionId:i.reactionId,commentMode:this.commentService.getCommentMode()}),V}}}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService toggleReaction: ",m),null}})}onComposerClick(t){return X(this,arguments,function*({commentAnnotation:e}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onComposerClick","color: green;");let i=yield this.metadataService.getGlobalMetadata(),a={commentAnnotation:e?.annotationId?this.commentService.getCommentAnnotationForClient(e):void 0,metadata:i};this.triggerAction(ar.COMPOSER_CLICKED,a)}catch(i){this.loggingService.catch("Error in CommentActionsService onComposerClick: ",i)}})}onComposerTextChange(e){return X(this,null,function*(){try{let t=yield this.metadataService.getGlobalMetadata(),i={text:e.text,annotation:e.annotation,targetComposerElementId:e.targetComposerElementId,metadata:t};this.commentService.setComposerData(e.targetComposerElementId,i),this.triggerAction(ar.COMPOSER_TEXT_CHANGE,i)}catch(t){this.loggingService.catch("Error in CommentActionsService onComposerTextChange: ",t)}})}autocompleteSearch(e){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: autocompleteSearch","color: green;");let t=yield this.metadataService.getGlobalMetadata();e.metadata=t,this.triggerAction(ar.AUTOCOMPLETE_SEARCH,e)}catch(t){this.loggingService.catch("Error in CommentActionsService autocompleteSearch: ",t)}})}onCommentPinClick(e){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentPinClick","color: green;");let t=yield this.metadataService.getGlobalMetadata(),i={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:t};return this.triggerAction(ar.COMMENT_PIN_CLICKED,i),i}catch(t){return this.loggingService.catch("Error in CommentActionsService onCommentPinClick: ",t),null}})}onCommentBubbleClick(e){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentBubbleClick","color: green;");let t=yield this.metadataService.getGlobalMetadata(),i={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:t};return this.triggerAction(ar.COMMENT_BUBBLE_CLICKED,i),i}catch(t){return this.loggingService.catch("Error in CommentActionsService onCommentBubbleClick: ",t),null}})}onCommentToolClick(e,t){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentToolClick","color: green;");let i=yield this.metadataService.getGlobalMetadata(),a={context:e,targetElementId:t,metadata:i},l={context:e,targetElementId:t,metadata:i};return this.triggerAction(ar.COMMENT_TOOL_CLICK,a),this.triggerAction(ar.COMMENT_TOOL_CLICKED,l),a}catch(i){return this.loggingService.catch("Error in CommentActionsService onCommentToolClick: ",i),null}})}onSidebarButtonClick(){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onSidebarButtonClick","color: green;");let e=yield this.metadataService.getGlobalMetadata(),t={metadata:e},i={metadata:e};return this.triggerAction(ar.SIDEBAR_BUTTON_CLICK,t),this.triggerAction(ar.SIDEBAR_BUTTON_CLICKED,i),t}catch(e){return this.loggingService.catch("Error in CommentActionsService onSidebarButtonClick: ",e),null}})}onAttachmentDownloadClick(e,t){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onAttachmentDownloadClick","color: green;");let i=yield this.metadataService.getGlobalMetadata(),a={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),attachment:t,metadata:i};return this.triggerAction(ar.ATTACHMENT_DOWNLOAD_CLICKED,a),a}catch(i){return this.loggingService.catch("Error in CommentActionsService onAttachmentDownloadClick: ",i),null}})}onCommentSaveTriggered(e,t){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentSaveTriggered","color: green;");let i=yield this.metadataService.getGlobalMetadata(),a={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(t),metadata:i};return this.triggerAction(ar.COMMENT_SAVE_TRIGGERED,a),a}catch(i){return this.loggingService.catch("Error in CommentActionsService onCommentSaveTriggered: ",i),null}})}onVisibilityOptionClick(e,t,i){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onVisibilityOptionClick","color: green;");let a=yield this.metadataService.getGlobalMetadata(),l={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),visibility:t,users:i?.map(c=>Vo(c)).filter(Boolean),metadata:a};return this.triggerAction(ar.VISIBILITY_OPTION_CLICKED,l),l}catch(a){return this.loggingService.catch("Error in CommentActionsService onVisibilityOptionClick: ",a),null}})}convert(e){try{if(e?.options){let{documentId:t,organizationId:i}=this.docService.getServerId(e?.options);e.options=y(h({},e?.options),{documentId:t,organizationId:i})}return this}catch(t){return this.loggingService.catch("Error in CommentActionsService convert: ",t),this}}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new at),this.actionSubjects.get(e)?.next(t)}catch(i){this.loggingService.catch("Error in CommentActionsService triggerAction: ",i)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new at),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in CommentActionsService onAction: ",t),ce(null)}}get timestamp(){return this.commonDbService.getServerTimestamp()}getCommentAnnotations(e){try{if(e){if(e?.allDocuments&&!e?.folderId)return this.loggingService.catch("folderId is required when allDocuments is true."),ce({data:null});if(!e?.allDocuments&&!e?.documentIds?.length)return this.loggingService.catch("documentIds is required."),ce({data:null})}return this.commentService.getAllCommentAnnotations({excludeDomChanges:!0,skipPositionCalculation:!0,query:e,addFilterCommentsOnDomCheck:!0}).pipe(ue(t=>t?t.reduce((i,a)=>{let l=a.metadata?.clientDocumentId;return!l||e?.documentIds&&!e?.documentIds?.includes(l)||(i[l]||(i[l]=[]),i[l].push(a)),i},{}):null),ue(t=>({data:t})))}catch(t){return this.loggingService.catch("Error in CommentActionsService getCommentAnnotation: ",t),ce({data:null})}}getCommentAnnotationsCount$(e){try{return this.commentViewsService.getAnnotationsCount(e).pipe(ue(t=>t||{data:null}))}catch(t){return this.loggingService.catch("Error in CommentActionsService getCommentAnnotation: ",t),ce({data:null})}}updateVisibility(e){this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateVisibility","color: green;");try{let t=e.annotationId;if(!t)throw new Error("annotationId is required in visibility config");if(e.type==="restricted"){let l=this.authService.getUser();if(!l?.userId)throw new Error("Current user not found. Cannot set restricted visibility without userIds.");e=Ju(e,l.userId)}if(e.type==="organizationPrivate"&&!e.organizationId){let l=this.docService.getOrganizationConfig();if(!l?.clientOrganizationId)throw new Error("No organizationId found. Cannot set organizationPrivate visibility without organizationId.");e=y(h({},e),{organizationId:l.clientOrganizationId})}this.analyticsService.trackEvent(Y.Events.Comments.UPDATE_VISIBILITY_TRIGGERED,{payload:{annotationId:t,visibility:e}});let i=Xu(e),a=h(h({type:e.type},e.organizationId&&{organizationId:e.organizationId}),e.userIds&&{userIds:e.userIds});return this.commentService.updateCommentAnnotationContext(t,{_setAccessFields:i,_setVisibilityConfig:a},{merge:!0})}catch(t){return this.loggingService.catch("Error in updateVisibility: ",t),Promise.resolve()}}calculateCommentThreadIndex(e,t){try{let i=e?.commentId,a;return i&&(a=t?.comments?.findIndex(l=>l.commentId===i)),a===-1&&(a=t?.comments?.length),a}catch(i){this.loggingService.catch("Error in calculateCommentThreadIndex: ",i);return}}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(qe),K(Re),K(zbe),K(vn),K(po),K(st),K(Vn),K(k),K(ts),K(zi),K(yn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var oU=class extends Cr{constructor(o){super(o),this._submitComment=r=>{this.getService(k).log("%c[WB] Calling FUNCTION: submitComment","color: green;");try{this.trackEvent(Y.Events.Comments.SUBMIT_COMMENT_TRIGGERED,{payload:{referenceId:r.targetComposerElementId}}),this.getService(Re).submitComment(r)}catch(e){this.getService(k).catch("Error in _submitComment: ",e)}},this._clearComposer=r=>{this.getService(k).log("%c[WB] Calling FUNCTION: clearComposer","color: green;");try{this.trackEvent(Y.Events.Comments.CLEAR_COMPOSER_TRIGGERED),this.getService(Re).clearComposer(r)}catch(e){this.getService(k).catch("Error in _clearComposer: ",e)}},this._enableFormatOptions=()=>{this.getService(k).log("%c[WB] Calling FUNCTION: enableFormatOptions","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_FORMAT_OPTIONS_TRIGGERED),this.getService(Re).enableFormatOptions()}catch(r){this.getService(k).catch("Error in _enableFormatOptions: ",r)}},this._disableFormatOptions=()=>{this.getService(k).log("%c[WB] Calling FUNCTION: disableFormatOptions","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_FORMAT_OPTIONS_TRIGGERED),this.getService(Re).disableFormatOptions()}catch(r){this.getService(k).catch("Error in _disableFormatOptions: ",r)}},this._setFormatConfig=r=>{this.getService(k).log("%c[WB] Calling FUNCTION: setFormatConfig","color: green;");try{this.trackEvent(Y.Events.Comments.SET_FORMAT_CONFIG_TRIGGERED,{payload:{config:r}}),this.getService(Re).setFormatConfig(r)}catch(e){this.getService(k).catch("Error in _setFormatConfig: ",e)}},this._getComposerData=r=>{this.getService(k).log("%c[WB] Calling FUNCTION: getComposerData","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_COMPOSER_DATA_TRIGGERED),this.getService(Re).getComposerData(r)}catch(e){return this.getService(k).catch("Error in _getComposerData: ",e),null}},this.getService(k).log("%c[WB] Creating CLASS: CommentElement","color: blue;"),this.getAllCommentAnnotations=this._getAllCommentAnnotations,this.deleteSelectedComment=this._deleteSelectedComment,this.enableTextComments=this._enableTextComments,this.disableTextComments=this._disableTextComments,this.allowedElementIds=this._allowedElementIds,this.allowedElementClassNames=this._allowedElementClassNames,this.allowedElementQuerySelectors=this._allowedElementQuerySelectors,this.disableFloatingCommentDialog=this._disableFloatingComments,this.enableFloatingCommentDialog=this._enableFloatingComments,this.attachComment=this._attachComment,this.openCommentSidebar=this._openCommentSidebar,this.closeCommentSidebar=this._closeCommentSidebar,this.toggleCommentSidebar=this._toggleCommentSidebar,this.enableModeratorMode=this._enableModeratorMode,this.disableModeratorMode=this._disableModeratorMode,this.enableStreamMode=this._enableStreamMode,this.disableStreamMode=this._disableStreamMode,this.enableSignInButton=this._enableSignInButton,this.disableSignInButton=this._disableSignInButton,this.enableUpgradeButton=this._enableUpgradeButton,this.disableUpgradeButton=this._disableUpgradeButton,this.onCommentModeChange=this._onCommentModeChange,this.enableAttachments=this._enableAttachment,this.disableAttachments=this._disableAttachment,this.enableAttachmentDownload=this._enableAttachmentDownload,this.disableAttachmentDownload=this._disableAttachmentDownload,this.isUserGlobalContact=this._isUserGlobalContact,this.enableDeviceInfo=this._enableDeviceInfo,this.disableDeviceInfo=this._disableDeviceInfo,this.enableCommentMode=this._enableCommentMode,this.disableCommentMode=this._disableCommentMode,this.enablePersistentCommentMode=this._enablePersistentCommentMode,this.disablePersistentCommentMode=this._disablePersistentCommentMode,this.enableCommentIndex=this._enableCommentIndex,this.disableCommentIndex=this._disableCommentIndex,this.enablePopoverMode=this._enablePopoverMode,this.disablePopoverMode=this._disablePopoverMode,this.enableDialogOnHover=this._enableDialogOnHover,this.enablePopoverTriangleComponent=this._enablePopoverTriangleComponent,this.disablePopoverTriangleComponent=this._disablePopoverTriangleComponent,this.disableDialogOnHover=this._disableDialogOnHover,this.enableDialogOnTargetElementClick=this._enableDialogOnTargetElementClick,this.disableDialogOnTargetElementClick=this._disableDialogOnTargetElementClick,this.enablePriority=this._enablePriority,this.disablePriority=this._disablePriority,this.enableStatus=this._enableStatus,this.disableStatus=this._disableStatus,this.enableVisibilityOptions=this._enableVisibilityOptions,this.disableVisibilityOptions=this._disableVisibilityOptions,this.enableResolveButton=this._enableResolveButton,this.disableResolveButton=this._disableResolveButton,this.enableGhostComments=this._enableGhostComments,this.disableGhostComments=this._disableGhostComments,this.enableGhostCommentsIndicator=this._enableGhostCommentsIndicator,this.disableGhostCommentsIndicator=this._disableGhostCommentsIndicator,this.setCustomStatus=this._setCustomStatus,this.setCustomPriority=this._setCustomPriority,this.setCustomCategory=this._setCustomCategory,this.enableInboxMode=this._enableInboxMode,this.disableInboxMode=this._disableInboxMode,this.enableAutoCategorize=this._enableAutoCategorize,this.disableAutoCategorize=this._disableAutoCategorize,this.enableDarkMode=this._enableDarkMode,this.disableDarkMode=this._disableDarkMode,this.setContextProvider=this._setContextProvider,this.enableSuggestionMode=this._enableSuggestionMode,this.disableSuggestionMode=this._disableSuggestionMode,this.enableMobileMode=this._enableMobileMode,this.disableMobileMode=this._disableMobileMode,this.enableInlineCommentMode=this._enableInlineCommentMode,this.disableInlineCommentMode=this._disableInlineCommentMode,this.enableMinimap=this._enableMinimap,this.disableMinimap=this._disableMinimap,this.showCommentsOnDom=this._showCommentsOnDom,this.hideCommentsOnDom=this._hideCommentsOnDom,this.enableCommentTool=this._enableCommentTool,this.disableCommentTool=this._disableCommentTool,this.setTotalMediaLength=this._setTotalMediaLength,this.onCommentAdd=this._onCommentAdd,this.onCommentUpdate=this._onCommentUpdate,this.addCommentOnSelectedText=this._addCommentOnSelectedText,this.enableSidebarUrlNavigation=this._enableSidebarUrlNavigation,this.disableSidebarUrlNavigation=this._disableSidebarUrlNavigation,this.setDStrategy=this._setDStrategy,this.enableSidebarButtonOnCommentDialog=this._enableSidebarButtonOnCommentDialog,this.disableSidebarButtonOnCommentDialog=this._disableSidebarButtonOnCommentDialog,this.onSidebarButtonOnCommentDialogClick=this._onSidebarButtonOnCommentDialogClick,this.enableReactions=this._enableReactions,this.disableReactions=this._disableReactions,this.enableAnonymousEmail=this._enableAnonymousEmail,this.disableAnonymousEmail=this._disableAnonymousEmail,this.setRecordings=this._setRecordings,this.addCommentOnElement=this._addCommentOnElement,this.enablePrivateCommentMode=this._enablePrivateCommentMode,this.disablePrivateCommentMode=this._disablePrivateCommentMode,this.enablePrivateMode=this._enablePrivateMode,this.disablePrivateMode=this._disablePrivateMode,this.enableScrollToComment=this._enableScrollToComment,this.disableScrollToComment=this._disableScrollToComment,this.enableUserMentions=this._enableUserMentions,this.disableUserMentions=this._disableUserMentions,this.setCommentSidebarFilters=this._setCommentSidebarFilters,this.setSystemFiltersOperator=this._setSystemFiltersOperator,this.enableCommentPinHighlighter=this._enableCommentPinHighlighter,this.disableCommentPinHighlighter=this._disableCommentPinHighlighter,this.enableDeleteOnBackspace=this._enableDeleteOnBackspace,this.disableDeleteOnBackspace=this._disableDeleteOnBackspace,this.enableHotkey=this._enableHotkey,this.disableHotkey=this._disableHotkey,this.enableDeviceIndicatorOnCommentPins=this._enableDeviceIndicatorOnCommentPins,this.disableDeviceIndicatorOnCommentPins=this._disableDeviceIndicatorOnCommentPins,this.getElementRefByAnnotationId=this._getElementRefByAnnotationId,this.scrollToCommentByAnnotationId=this._scrollToCommentByAnnotationId,this.selectCommentByAnnotationId=this._selectCommentByAnnotationId,this.enableRecordingSummary=this._enableRecordingSummary,this.disableRecordingSummary=this._disableRecordingSummary,this.enableRecordingTranscription=this._enableRecordingTranscription,this.disableRecordingTranscription=this._disableRecordingTranscription,this.enableRecordingCountdown=this._enableRecordingCountdown,this.disableRecordingCountdown=this._disableRecordingCountdown,this.setUnreadIndicatorMode=this._setUnreadIndicatorMode,this.enableEnterKeyToSubmit=this._enableEnterKeyToSubmit,this.disableEnterKeyToSubmit=this._disableEnterKeyToSubmit,this.enablePinShadowDOM=this._enablePinShadowDOM,this.disablePinShadowDOM=this._disablePinShadowDOM,this.enableDialogShadowDOM=this._enableDialogShadowDOM,this.disableDialogShadowDOM=this._disableDialogShadowDOM,this.enableSidebarShadowDOM=this._enableSidebarShadowDOM,this.disableSidebarShadowDOM=this._disableSidebarShadowDOM,this.enableChangeDetectionInCommentMode=this._enableChangeDetectionInCommentMode,this.disableChangeDetectionInCommentMode=this._disableChangeDetectionInCommentMode,this.showResolvedCommentsOnDom=this._showResolvedCommentsOnDom,this.hideResolvedCommentsOnDom=this._hideResolvedCommentsOnDom,this.setCustomReactions=this._setCustomReactions,this.onCommentSelectionChange=this._onCommentSelectionChange,this.getUnreadCommentCountByAnnotationId=this._getUnreadCommentCountByAnnotationId,this.getUnreadCommentAnnotationCountOnCurrentDocument=this._getUnreadCommentAnnotationCountOnCurrentDocument,this.getUnreadCommentCountOnCurrentDocument=this._getUnreadCommentCountOnCurrentDocument,this.getUnreadCommentAnnotationCountByLocationId=this._getUnreadCommentAnnotationCountByLocationId,this.getUnreadCommentCountByLocationId=this._getUnreadCommentCountByLocationId,this.updateCommentDialogPosition=this._updateCommentDialogPosition,this.enableAreaComment=this._enableAreaComment,this.disableAreaComment=this._disableAreaComment,this.setPinCursorImage=this._setPinCursorImage,this.addManualComment=this._addManualComment,this.createCustomListDataOnAnnotation=this._createCustomListDataOnAnnotation,this.createCustomListDataOnComment=this._createCustomListDataOnComment,this.excludeLocationIdsFromSidebar=this._excludeLocationIdsFromSidebar,this.enableBubbleOnPin=this._enableBubbleOnPin,this.disableBubbleOnPin=this._disableBubbleOnPin,this.enableBubbleOnPinHover=this._enableBubbleOnPinHover,this.disableBubbleOnPinHover=this._disableBubbleOnPinHover,this.enablePinDrag=this._enablePinDrag,this.disablePinDrag=this._disablePinDrag,this.enableMultiThreadMode=this._enableMultiThread,this.disableMultiThreadMode=this._disableMultiThread,this.enableMultiThread=this._enableMultiThread,this.disableMultiThread=this._disableMultiThread,this.enableGroupMultipleMatch=this._enableGroupMatchedComments,this.disableGroupMultipleMatch=this._disableGroupMatchedComments,this.enableGroupMatchedComments=this._enableGroupMatchedComments,this.disableGroupMatchedComments=this._disableGroupMatchedComments,this.updateContext=this._updateContext,this.updateVisibility=this._updateVisibility,this.getSelectedComments=this._getSelectedComments,this.enableDeleteReplyConfirmation=this._enableDeleteReplyConfirmation,this.disableDeleteReplyConfirmation=this._disableDeleteReplyConfirmation,this.onCopyLink=this._onCopyLink,this.getCommentAnnotationById=this._getCommentAnnotationById,this.enableCollapsedComments=this._enableCollapsedComments,this.disableCollapsedComments=this._disableCollapsedComments,this.onCommentSidebarActionButtonClick=this._onCommentSidebarActionButtonClick,this.setCommentSidebarData=this._setCommentSidebarData,this.onCommentSidebarInit=this._onCommentSidebarInit,this.onCommentSidebarData=this._onCommentSidebarData,this.setCommentSidebarDefaultCustomActions=this._setCommentSidebarDefaultCustomActions,this.enableSidebarCustomActions=this._enableSidebarCustomActions,this.disableSidebarCustomActions=this._disableSidebarCustomActions,this.enableQueryParamsComments=this._enableQueryParamsComments,this.disableQueryParamsComments=this._disableQueryParamsComments,this.enableResolveStatusAccessAdminOnly=this._enableResolveStatusAccessAdminOnly,this.disableResolveStatusAccessAdminOnly=this._disableResolveStatusAccessAdminOnly,this.enableLinkCallback=this._enableLinkCallback,this.disableLinkCallback=this._disableLinkCallback,this.enableSeenByUsers=this._enableSeenByUsers,this.disableSeenByUsers=this._disableSeenByUsers,this.enableShortUserName=this._enableShortUserName,this.disableShortUserName=this._disableShortUserName,this.addCommentAnnotation=this._addCommentAnnotation,this.publishCommentAnnotation=this._publishCommentAnnotation,this.approveCommentAnnotation=this._approveCommentAnnotation,this.acceptCommentAnnotation=this._acceptCommentAnnotation,this.rejectCommentAnnotation=this._rejectCommentAnnotation,this.subscribeCommentAnnotation=this._subscribeCommentAnnotation,this.unsubscribeCommentAnnotation=this._unsubscribeCommentAnnotation,this.deleteCommentAnnotation=this._deleteCommentAnnotation,this.getCommentAnnotations=this._getCommentAnnotations,this.getCommentAnnotationsCount=this._getCommentAnnotationsCount,this.assignUser=this._assignUser,this.updatePriority=this._updatePriority,this.updateStatus=this._updateStatus,this.updateAccess=this._updateAccess,this.resolveCommentAnnotation=this._resolveCommentAnnotation,this.getLink=this._getLink,this.copyLink=this._copyLink,this.addComment=this._addComment,this.updateComment=this._updateComment,this.deleteComment=this._deleteComment,this.getComment=this._getComment,this.addAttachment=this._addAttachment,this.deleteAttachment=this._deleteAttachment,this.getAttachment=this._getAttachment,this.deleteRecording=this._deleteRecording,this.getRecording=this._getRecording,this.addReaction=this._addReaction,this.deleteReaction=this._deleteReaction,this.toggleReaction=this._toggleReaction,this.enableReadOnly=this._enableReadOnly,this.disableReadOnly=this._disableReadOnly,this.setAssignToType=this._setAssignToType,this.enableContextInPageModeComposer=this._enableContextInPageModeComposer,this.disableContextInPageModeComposer=this._disableContextInPageModeComposer,this.clearPageModeComposerContext=this._clearPageModeComposerContext,this.setContextInPageModeComposer=this._setContextInPageModeComposer,this.focusPageModeComposer=this._focusPageModeComposer,this.enableCustomAutocompleteSearch=this._enableCustomAutocompleteSearch,this.disableCustomAutocompleteSearch=this._disableCustomAutocompleteSearch,this.fetchCommentAnnotations=this._fetchCommentAnnotations,this.setTransformContext=this._setTransformContext,this.enableSvgAsImg=this._enableSvgAsImg,this.disableSvgAsImg=this._disableSvgAsImg,this.enableFullExpanded=this._enableFullExpanded,this.disableFullExpanded=this._disableFullExpanded,this.enableCommentToNearestAllowedElement=this._enableCommentToNearestAllowedElement,this.disableCommentToNearestAllowedElement=this._disableCommentToNearestAllowedElement,this.enableDraftMode=this._enableDraftMode,this.disableDraftMode=this._disableDraftMode,this.enableFilterCommentsOnDom=this._enableFilterCommentsOnDom,this.disableFilterCommentsOnDom=this._disableFilterCommentsOnDom,this.enableReplyAvatars=this._enableReplyAvatars,this.disableReplyAvatars=this._disableReplyAvatars,this.setMaxReplyAvatars=this._setMaxReplyAvatars,this.setSidebarButtonCountType=this._setSidebarButtonCountType,this.enableFilterGhostCommentsInSidebar=this._enableFilterGhostCommentsInSidebar,this.disableFilterGhostCommentsInSidebar=this._disableFilterGhostCommentsInSidebar,this.enableFullScreenInSidebar=this._enableFullScreenInSidebar,this.disableFullScreenInSidebar=this._disableFullScreenInSidebar,this.setComposerFileAttachments=this._setComposerFileAttachments,this.setAllowedFileTypes=this._setAllowedFileTypes,this.enableForceCloseAllOnEsc=this._enableForceCloseAllOnEsc,this.disableForceCloseAllOnEsc=this._disableForceCloseAllOnEsc,this.markAsRead=this._markAsRead,this.markAsUnread=this._markAsUnread,this.enableScreenshot=this._enableScreenshot,this.disableScreenshot=this._disableScreenshot,this.enablePaginatedContactList=this._enablePaginatedContactList,this.disablePaginatedContactList=this._disablePaginatedContactList,this.enableFormatOptions=this._enableFormatOptions,this.disableFormatOptions=this._disableFormatOptions,this.setFormatConfig=this._setFormatConfig,this.submitComment=this._submitComment,this.clearComposer=this._clearComposer,this.on=this._on,this.getComposerData=this._getComposerData}_getAllCommentAnnotations(o,r){this.getService(k).log("%c[WB] Calling FUNCTION: getOnlineUsers","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_ALL_COMMENT_ANNOTATIONS_TRIGGERED,{payload:{documentId:o,location:r}}),this.getService(Re).getAllCommentAnnotations({customClientDocumentId:o,params:r,excludeDomChanges:!0,skipPositionCalculation:!0,addFilterCommentsOnDomCheck:!0}).pipe(ue(e=>e?.length?e?.map(t=>this.getService(Re).getCommentAnnotationForClient(t)):e))}catch(e){return this.getService(k).catch("Error in _getLiveCommentsOnCurrentDocument: ",e),ce(null)}}_deleteSelectedComment(){this.getService(k).log("%c[WB] Calling FUNCTION: deleteSelectedComment","color: green;");try{return this.trackEvent(Y.Events.Comments.DELETE_SELECTED_COMMENT_TRIGGERED),this.getService(Re).deleteCommentPinAnnotations("commentElement")}catch(o){return this.getService(k).catch("Error in _deleteSelectedComment: ",o),Promise.resolve(null)}}_enableTextComments(){this.getService(k).log("%c[WB] Calling FUNCTION: enableTextComments","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_TEXT_COMMENTS_TRIGGERED),this.getService(Re).enableTextComments()}catch(o){this.getService(k).catch("Error in _enableTextComments: ",o)}}_disableTextComments(){this.getService(k).log("%c[WB] Calling FUNCTION: disableTextComments","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_TEXT_COMMENTS_TRIGGERED),this.getService(Re).disableTextComments()}catch(o){this.getService(k).catch("Error in _disableTextComments: ",o)}}_allowedElementIds(o){this.getService(k).log("%c[WB] Calling FUNCTION: allowedElementIds","color: green;");try{this.trackEvent(Y.Events.Comments.ALLOWED_ELEMENT_IDS_TRIGGERED,{payload:{elementIds:o}}),this.getService(Re).setAllowedElementIds(o)}catch(r){this.getService(k).catch("Error in allowedElementIds: ",r)}}_allowedElementClassNames(o){this.getService(k).log("%c[WB] Calling FUNCTION: allowedElementClassNames","color: green;");try{this.trackEvent(Y.Events.Comments.ALLOWED_ELEMENT_CLASS_NAMES_TRIGGERED,{payload:{classNames:o}}),this.getService(Re).setAllowedElementClassNames(o)}catch(r){this.getService(k).catch("Error in allowedElementClassNames: ",r)}}_allowedElementQuerySelectors(o){this.getService(k).log("%c[WB] Calling FUNCTION: allowedElementQuerySelectors","color: green;");try{this.trackEvent(Y.Events.Comments.ALLOWED_ELEMENT_QUERY_SELECTORS_TRIGGERED,{payload:{querySelectors:o}}),this.getService(Re).setAllowedElementQuerySelectors(o)}catch(r){this.getService(k).catch("Error in allowedElementQuerySelectors: ",r)}}_disableFloatingComments(){this.getService(k).log("%c[WB] Calling FUNCTION: disableFloatingComments","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_FLOATING_COMMENT_DIALOG_TRIGGERED),this.getService(Re).disableFloatingComments(!0)}catch(o){this.getService(k).catch("Error in _disableFloatingComments: ",o)}}_enableFloatingComments(){this.getService(k).log("%c[WB] Calling FUNCTION: enableFloatingComments","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_FLOATING_COMMENT_DIALOG_TRIGGERED),this.getService(Re).disableFloatingComments(!1)}catch(o){this.getService(k).catch("Error in _enableFloatingComments: ",o)}}_attachComment(o){this.getService(k).log("%c[WB] Calling FUNCTION: attachComment","color: green;");try{this.trackEvent(Y.Events.Comments.ATTACH_COMMENT_TRIGGERED,{payload:{elementId:o}}),this.getService(Re).attachComment(o,["id","data-id"])}catch(r){this.getService(k).catch("Error in _attachComment: ",r)}}_openCommentSidebar(){this.getService(k).log("%c[WB] Calling FUNCTION: openCommentSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.OPEN_COMMENT_SIDEBAR_TRIGGERED),this.getService(Re).setSidebarVisibility(!0,!0)}catch(o){this.getService(k).catch("Error in _openCommentSidebar: ",o)}}_closeCommentSidebar(){this.getService(k).log("%c[WB] Calling FUNCTION: closeCommentSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.CLOSE_COMMENT_SIDEBAR_TRIGGERED),this.getService(Re).setSidebarVisibility(!1,!0)}catch(o){this.getService(k).catch("Error in _closeCommentSidebar: ",o)}}_toggleCommentSidebar(){this.getService(k).log("%c[WB] Calling FUNCTION: toggleCommentSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.TOGGLE_COMMENT_SIDEBAR_TRIGGERED),this.getService(Re).toggleSidebarVisibility(!0)}catch(o){this.getService(k).catch("Error in _toggleCommentSidebar: ",o)}}_enableModeratorMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableModeratorMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_MODERATOR_MODE_TRIGGERED),this.getService(Re).setModeratorMode(!0)}catch(o){this.getService(k).catch("Error in _enableModeratorMode: ",o)}}_disableModeratorMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableModeratorMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_MODERATOR_MODE_TRIGGERED),this.getService(Re).setModeratorMode(!1)}catch(o){this.getService(k).catch("Error in _disableModeratorMode: ",o)}}_enableStreamMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableStreamMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_STREAM_MODE_TRIGGERED),this.getService(Re).setStreamMode(!0)}catch(o){this.getService(k).catch("Error in _enableStreamMode: ",o)}}_disableStreamMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableStreamMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_STREAM_MODE_TRIGGERED),this.getService(Re).setStreamMode(!1)}catch(o){this.getService(k).catch("Error in _disableStreamMode: ",o)}}_enableSignInButton(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSignInButton","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SIGN_IN_BUTTON_TRIGGERED),this.getService(Re).enableSignInButton(!0)}catch(o){this.getService(k).catch("Error in _enableSignInButton: ",o)}}_disableSignInButton(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSignInButton","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SIGN_IN_BUTTON_TRIGGERED),this.getService(Re).enableSignInButton(!1)}catch(o){this.getService(k).catch("Error in _disableSignInButton: ",o)}}_enableUpgradeButton(){this.getService(k).log("%c[WB] Calling FUNCTION: enableUpgradeButton","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_UPGRADE_BUTTON_TRIGGERED),this.getService(Re).enableUpgradeButton(!0)}catch(o){this.getService(k).catch("Error in _enableUpgradeButton: ",o)}}_disableUpgradeButton(){this.getService(k).log("%c[WB] Calling FUNCTION: disableUpgradeButton","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_UPGRADE_BUTTON_TRIGGERED),this.getService(Re).enableUpgradeButton(!1)}catch(o){this.getService(k).catch("Error in _disableUpgradeButton: ",o)}}_onCommentModeChange(){this.getService(k).log("%c[WB] Calling FUNCTION: onCommentModeChange","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_COMMENT_MODE_CHANGE_TRIGGERED),this.getService(Re).addCommentModeChange()}catch(o){return this.getService(k).catch("Error in _onCommentModeChange: ",o),ce(!1)}}_enableAttachment(){this.getService(k).log("%c[WB] Calling FUNCTION: enableAttachment","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_ATTACHMENTS_TRIGGERED),this.getService(Re).enableAttachment(!0)}catch(o){this.getService(k).catch("Error in _enableAttachment: ",o)}}_disableAttachment(){this.getService(k).log("%c[WB] Calling FUNCTION: disableAttachment","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_ATTACHMENTS_TRIGGERED),this.getService(Re).enableAttachment(!1)}catch(o){this.getService(k).catch("Error in _disableAttachment: ",o)}}_enableAttachmentDownload(){this.getService(k).log("%c[WB] Calling FUNCTION: enableAttachmentDownload","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_ATTACHMENT_DOWNLOAD_TRIGGERED),this.getService(Re).enableAttachmentDownload()}catch(o){this.getService(k).catch("Error in _enableAttachmentDownload: ",o)}}_disableAttachmentDownload(){this.getService(k).log("%c[WB] Calling FUNCTION: disableAttachmentDownload","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_ATTACHMENT_DOWNLOAD_TRIGGERED),this.getService(Re).disableAttachmentDownload()}catch(o){this.getService(k).catch("Error in _disableAttachmentDownload: ",o)}}_isUserGlobalContact(){this.getService(k).log("%c[WB] Calling FUNCTION: isUserGlobalContact","color: green;");try{return this.trackEvent(Y.Events.Comments.IS_USER_GLOBAL_CONTACT_TRIGGERED),this.getService(Re).isUserGlobalContact$()}catch(o){return this.getService(k).catch("Error in _isUserGlobalContact: ",o),ce(!1)}}_enableDeviceInfo(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDeviceInfo","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DEVICE_INFO_TRIGGERED),this.getService(Re).showScreenSizeInfo(!0)}catch(o){this.getService(k).catch("Error in _enableDeviceInfo: ",o)}}_disableDeviceInfo(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDeviceInfo","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DEVICE_INFO_TRIGGERED),this.getService(Re).showScreenSizeInfo(!1)}catch(o){this.getService(k).catch("Error in _disableDeviceInfo: ",o)}}_enableCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_COMMENT_MODE_TRIGGERED),this.getService(Re).enableAddCommentMode()}catch(o){this.getService(k).catch("Error in _enableCommentMode: ",o)}}_disableCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_COMMENT_MODE_TRIGGERED),this.getService(Re).disableAddCommentMode()}catch(o){this.getService(k).catch("Error in _disableCommentMode: ",o)}}_enablePersistentCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePersistentCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_PERSISTENT_COMMENT_MODE_TRIGGERED),this.getService(Re).enablePersistentCommentMode()}catch(o){this.getService(k).catch("Error in _enablePersistentCommentMode: ",o)}}_disablePersistentCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePersistentCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_PERSISTENT_COMMENT_MODE_TRIGGERED),this.getService(Re).disablePersistentCommentMode()}catch(o){this.getService(k).catch("Error in _disablePersistentCommentMode: ",o)}}_showCommentIndex(o){this.getService(k).log("%c[WB] Calling FUNCTION: showCommentIndex","color: green;");try{this.trackEvent(Y.Events.Comments.SHOW_COMMENT_INDEX_TRIGGERED,{payload:{show:o}}),this.getService(Re).showCommentIndex(o)}catch(r){this.getService(k).catch("Error in _showCommentIndex: ",r)}}_enableCommentIndex(){this.getService(k).log("%c[WB] Calling FUNCTION: enableCommentIndex","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_COMMENT_INDEX_TRIGGERED),this.getService(Re).showCommentIndex(!0)}catch(o){this.getService(k).catch("Error in _enableCommentIndex: ",o)}}_disableCommentIndex(){this.getService(k).log("%c[WB] Calling FUNCTION: disableCommentIndex","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_COMMENT_INDEX_TRIGGERED),this.getService(Re).showCommentIndex(!1)}catch(o){this.getService(k).catch("Error in _disableCommentIndex: ",o)}}_enablePopoverMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePopoverMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_POPOVER_MODE_TRIGGERED),this.getService(Re).enablePopoverMode()}catch(o){this.getService(k).catch("Error in _enablePopoverMode: ",o)}}_disablePopoverMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePopoverMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_POPOVER_MODE_TRIGGERED),this.getService(Re).disablePopoverMode()}catch(o){this.getService(k).catch("Error in _disablePopoverMode: ",o)}}_enableDialogOnHover(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDialogOnHover","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DIALOG_ON_HOVER_TRIGGERED),this.getService(Re).setEnableDialogOnHover(!0)}catch(o){this.getService(k).catch("Error in _enableDialogOnHover: ",o)}}_disableDialogOnHover(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDialogOnHover","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DIALOG_ON_HOVER_TRIGGERED),this.getService(Re).setEnableDialogOnHover(!1)}catch(o){this.getService(k).catch("Error in _disableDialogOnHover: ",o)}}_enablePopoverTriangleComponent(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePopoverTriangleComponent","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_POPOVER_TRIANGLE_COMPONENT_TRIGGERED),this.getService(Re).enablePopoverTriangleComponent()}catch(o){this.getService(k).catch("Error in _enablePopoverTriangleComponent: ",o)}}_disablePopoverTriangleComponent(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePopoverTriangleComponent","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_POPOVER_TRIANGLE_COMPONENT_TRIGGERED),this.getService(Re).disablePopoverTriangleComponent()}catch(o){this.getService(k).catch("Error in _disablePopoverTriangleComponent: ",o)}}_enableDialogOnTargetElementClick(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDialogOnTargetElementClick","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DIALOG_ON_TARGET_ELEMENT_CLICK_TRIGGERED),this.getService(Re).setEnableDialogOnTargetElementClick(!0)}catch(o){this.getService(k).catch("Error in _enableDialogOnTargetElementClick: ",o)}}_disableDialogOnTargetElementClick(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDialogOnTargetElementClick","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DIALOG_ON_TARGET_ELEMENT_CLICK_TRIGGERED),this.getService(Re).setEnableDialogOnTargetElementClick(!1)}catch(o){this.getService(k).catch("Error in _disableDialogOnTargetElementClick: ",o)}}_enablePriority(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePriority","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_PRIORITY_TRIGGERED),this.getService(Re).setEnablePriority(!0)}catch(o){this.getService(k).catch("Error in _enablePriority: ",o)}}_disablePriority(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePriority","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_PRIORITY_TRIGGERED),this.getService(Re).setEnablePriority(!1)}catch(o){this.getService(k).catch("Error in _disablePriority: ",o)}}_enableStatus(){this.getService(k).log("%c[WB] Calling FUNCTION: enableStatus","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_STATUS_TRIGGERED),this.getService(Re).setEnableStatus(!0)}catch(o){this.getService(k).catch("Error in _enableStatus: ",o)}}_disableStatus(){this.getService(k).log("%c[WB] Calling FUNCTION: disableStatus","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_STATUS_TRIGGERED),this.getService(Re).setEnableStatus(!1)}catch(o){this.getService(k).catch("Error in _disableStatus: ",o)}}_enableVisibilityOptions(){this.getService(k).log("%c[WB] Calling FUNCTION: enableVisibilityOptions","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_VISIBILITY_OPTIONS_TRIGGERED),this.getService(Re).setEnableVisibilityOptions(!0)}catch(o){this.getService(k).catch("Error in _enableVisibilityOptions: ",o)}}_disableVisibilityOptions(){this.getService(k).log("%c[WB] Calling FUNCTION: disableVisibilityOptions","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_VISIBILITY_OPTIONS_TRIGGERED),this.getService(Re).setEnableVisibilityOptions(!1)}catch(o){this.getService(k).catch("Error in _disableVisibilityOptions: ",o)}}_enableResolveButton(){this.getService(k).log("%c[WB] Calling FUNCTION: enableResolveButton","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_RESOLVE_BUTTON_TRIGGERED),this.getService(Re).setEnableResolve(!0)}catch(o){this.getService(k).catch("Error in _enableResolveButton: ",o)}}_disableResolveButton(){this.getService(k).log("%c[WB] Calling FUNCTION: disableResolveButton","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_RESOLVE_BUTTON_TRIGGERED),this.getService(Re).setEnableResolve(!1)}catch(o){this.getService(k).catch("Error in _disableResolveButton: ",o)}}_enableGhostComments(){this.getService(k).log("%c[WB] Calling FUNCTION: enableGhostComments","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_GHOST_COMMENTS_TRIGGERED),this.getService(Re).enableGhostComments()}catch(o){this.getService(k).catch("Error in _enableGhostCommentsInDOM: ",o)}}_disableGhostComments(){this.getService(k).log("%c[WB] Calling FUNCTION: disableGhostComments","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_GHOST_COMMENTS_TRIGGERED),this.getService(Re).disableGhostComments()}catch(o){this.getService(k).catch("Error in _disableGhostComments: ",o)}}_enableGhostCommentsIndicator(){this.getService(k).log("%c[WB] Calling FUNCTION: enableGhostCommentsIndicator","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_GHOST_COMMENTS_INDICATOR_TRIGGERED),this.getService(Re).enableGhostCommentsMessage()}catch(o){this.getService(k).catch("Error in _enableGhostCommentsIndicator: ",o)}}_disableGhostCommentsIndicator(){this.getService(k).log("%c[WB] Calling FUNCTION: disableGhostCommentsIndicator","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_GHOST_COMMENTS_INDICATOR_TRIGGERED),this.getService(Re).disableGhostCommentsMessage()}catch(o){this.getService(k).catch("Error in _disableGhostCommentsIndicator: ",o)}}_setCustomStatus(o){this.getService(k).log("%c[WB] Calling FUNCTION: setCustomStatus","color: green;");try{this.trackEvent(Y.Events.Comments.SET_CUSTOM_STATUS_TRIGGERED,{payload:{customStatuses:o}}),this.getService(Re).setCustomStatuses(o)}catch(r){this.getService(k).catch("Error in _setCustomStatus: ",r)}}_enableInboxMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableInboxMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_INBOX_MODE_TRIGGERED),this.getService(Re).enableInboxMode()}catch(o){this.getService(k).catch("Error in _enableInboxMode: ",o)}}_setCustomPriority(o){this.getService(k).log("%c[WB] Calling FUNCTION: setCustomPriority","color: green;");try{this.trackEvent(Y.Events.Comments.SET_CUSTOM_PRIORITY_TRIGGERED,{payload:{customPriorities:o}}),this.getService(Re).setCustomPriorities(o)}catch(r){this.getService(k).catch("Error in _setCustomPriority: ",r)}}_setCustomCategory(o){this.getService(k).log("%c[WB] Calling FUNCTION: setCustomCategory","color: green;");try{this.trackEvent(Y.Events.Comments.SET_CUSTOM_CATEGORY_TRIGGERED,{payload:{customCategories:o}}),this.getService(Re).setCustomCategories(o)}catch(r){this.getService(k).catch("Error in _setCustomCategory: ",r)}}_disableInboxMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableInboxMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_INBOX_MODE_TRIGGERED),this.getService(Re).disableInboxMode()}catch(o){this.getService(k).catch("Error in _disableInboxMode: ",o)}}_enableAutoCategorize(){this.getService(k).log("%c[WB] Calling FUNCTION: enableAutoCategorize","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_AUTO_CATEGORIZE_TRIGGERED),this.getService(Re).setEnableAutoCategorize(!0)}catch(o){this.getService(k).catch("Error in _enableAutoCategorize: ",o)}}_disableAutoCategorize(){this.getService(k).log("%c[WB] Calling FUNCTION: disableAutoCategorize","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_AUTO_CATEGORIZE_TRIGGERED),this.getService(Re).setEnableAutoCategorize(!1)}catch(o){this.getService(k).catch("Error in _disableAutoCategorize: ",o)}}_enableDarkMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDarkMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DARK_MODE_TRIGGERED),this.getService(Re).setCommentContainerDarkMode(!0)}catch(o){this.getService(k).catch("Error in _enableDarkMode: ",o)}}_disableDarkMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDarkMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DARK_MODE_TRIGGERED),this.getService(Re).setCommentContainerDarkMode(!1)}catch(o){this.getService(k).catch("Error in _disableDarkMode: ",o)}}_setContextProvider(o){try{this.trackEvent(Y.Events.Comments.SET_CONTEXT_PROVIDER_TRIGGERED,{payload:{}}),this.getService(Re).setContextProvider(o)}catch(r){this.getService(k).catch("Error in _setContextProvider: ",r)}}_enableSuggestionMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSuggestionMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SUGGESTION_MODE_TRIGGERED),this.getService(Re).setSuggestionMode(!0)}catch(o){this.getService(k).catch("Error in _enableSuggestionMode: ",o)}}_disableSuggestionMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSuggestionMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SUGGESTION_MODE_TRIGGERED),this.getService(Re).setSuggestionMode(!1)}catch(o){this.getService(k).catch("Error in _disableSuggestionMode: ",o)}}_enableMobileMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableMobileMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_MOBILE_MODE_TRIGGERED),this.getService(Re).setMobileMode(!0)}catch(o){this.getService(k).catch("Error in _enableMobileMode: ",o)}}_disableMobileMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableMobileMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_MOBILE_MODE_TRIGGERED),this.getService(Re).setMobileMode(!1)}catch(o){this.getService(k).catch("Error in _disableMobileMode: ",o)}}_enableInlineCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableInlineCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_INLINE_COMMENT_MODE_TRIGGERED),this.getService(Re).enableInlineCommentMode()}catch(o){this.getService(k).catch("Error in _enableInlineCommentMode: ",o)}}_disableInlineCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableInlineCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_INLINE_COMMENT_MODE_TRIGGERED),this.getService(Re).disableInlineCommentMode()}catch(o){this.getService(k).catch("Error in _disableInlineCommentMode: ",o)}}_enableMinimap(){this.getService(k).log("%c[WB] Calling FUNCTION: enableMinimap","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_MINIMAP_TRIGGERED),this.getService(Re).enableMinimap()}catch(o){this.getService(k).catch("Error in _enableMinimap: ",o)}}_disableMinimap(){this.getService(k).log("%c[WB] Calling FUNCTION: disableMinimap","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_MINIMAP_TRIGGERED),this.getService(Re).disableMinimap()}catch(o){this.getService(k).catch("Error in _disableMinimap: ",o)}}_showCommentsOnDom(){this.getService(k).log("%c[WB] Calling FUNCTION: showCommentsOnDom","color: green;");try{this.trackEvent(Y.Events.Comments.SHOW_COMMENTS_ON_DOM_TRIGGERED),this.getService(Re).showCommentsOnDom()}catch(o){this.getService(k).catch("Error in _showCommentsOnDom: ",o)}}_hideCommentsOnDom(){this.getService(k).log("%c[WB] Calling FUNCTION: hideCommentsOnDom","color: green;");try{this.trackEvent(Y.Events.Comments.HIDE_COMMENTS_ON_DOM_TRIGGERED),this.getService(Re).hideCommentsOnDom()}catch(o){this.getService(k).catch("Error in _hideCommentsOnDom: ",o)}}_enableCommentTool(){this.getService(k).log("%c[WB] Calling FUNCTION: enableCommentTool","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_COMMENT_TOOL_TRIGGERED),this.getService(Re).enableCommentTool()}catch(o){this.getService(k).catch("Error in _enableCommentTool: ",o)}}_disableCommentTool(){this.getService(k).log("%c[WB] Calling FUNCTION: disableCommentTool","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_COMMENT_TOOL_TRIGGERED),this.getService(Re).disableCommentTool()}catch(o){this.getService(k).catch("Error in _disableCommentTool: ",o)}}_setTotalMediaLength(o){this.getService(k).log("%c[WB] Calling FUNCTION: setTotalMediaLength","color: green;");try{this.trackEvent(Y.Events.Comments.SET_TOTAL_MEDIA_LENGTH_TRIGGERED,{payload:{length:o}}),this.getService(Re).setTotalMediaLength(o)}catch(r){this.getService(k).catch("Error in _setTotalMediaLength: ",r)}}_onCommentAdd(){this.getService(k).log("%c[WB] Calling FUNCTION: onCommentAdd","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_COMMENT_ADD_TRIGGERED),this.getService(Re).onCommentAdd$()}catch(o){return this.getService(k).catch("Error in _onCommentAdd: ",o),ce()}}_onCommentUpdate(){this.getService(k).log("%c[WB] Calling FUNCTION: onCommentUpdate","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_COMMENT_UPDATE_TRIGGERED),this.getService(Re).onCommentUpdate$()}catch(o){return this.getService(k).catch("Error in _onCommentUpdate: ",o),ce()}}_addCommentOnSelectedText(){this.getService(k).log("%c[WB] Calling FUNCTION: addCommentOnSelectedText","color: green;");try{this.trackEvent(Y.Events.Comments.ADD_COMMENT_ON_SELECTED_TEXT_TRIGGERED),this.getService(Re).addCommentOnSelectedText()}catch(o){this.getService(k).catch("Error in _addCommentOnSelectedText: ",o)}}_enableSidebarUrlNavigation(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSidebarUrlNavigation","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SIDEBAR_URL_NAVIGATION_TRIGGERED),this.getService(Re).enableSidebarUrlNavigation()}catch(o){this.getService(k).catch("Error in _enableSidebarUrlNavigation: ",o)}}_disableSidebarUrlNavigation(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSidebarUrlNavigation","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SIDEBAR_URL_NAVIGATION_TRIGGERED),this.getService(Re).disableSidebarUrlNavigation()}catch(o){this.getService(k).catch("Error in _disableSidebarUrlNavigation: ",o)}}_setDStrategy(o){this.getService(k).log("%c[WB] Calling FUNCTION: setDStrategy","color: green;");try{this.trackEvent(Y.Events.Comments.SET_D_STRATEGY_TRIGGERED,{payload:{strategy:o}}),this.getService(Re).setDetectionStrategy(o)}catch(r){this.getService(k).catch("Error in _setDStrategy: ",r)}}_enableSidebarButtonOnCommentDialog(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSidebarButtonOnCommentDialog","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SIDEBAR_BUTTON_ON_COMMENT_DIALOG_TRIGGERED),this.getService(Re).enableSidebarButtonOnCommentDialog()}catch(o){this.getService(k).catch("Error in _enableSidebarButtonOnCommentDialog: ",o)}}_disableSidebarButtonOnCommentDialog(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSidebarButtonOnCommentDialog","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SIDEBAR_BUTTON_ON_COMMENT_DIALOG_TRIGGERED),this.getService(Re).disableSidebarButtonOnCommentDialog()}catch(o){this.getService(k).catch("Error in _disableSidebarButtonOnCommentDialog: ",o)}}_onSidebarButtonOnCommentDialogClick(){this.getService(k).log("%c[WB] Calling FUNCTION: onSidebarButtonOnCommentDialogClick","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_SIDEBAR_BUTTON_ON_COMMENT_DIALOG_CLICK_TRIGGERED),this.getService(Re).getSidebarButtonOnCommentDialogClick$()}catch(o){return this.getService(k).catch("Error in _onSidebarButtonOnCommentDialogClick: ",o),ce(null)}}_enableReactions(){this.getService(k).log("%c[WB] Calling FUNCTION: enableReactions","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_REACTIONS_TRIGGERED),this.getService(Re).enableReactions()}catch(o){this.getService(k).catch("Error in _enableReactions: ",o)}}_disableReactions(){this.getService(k).log("%c[WB] Calling FUNCTION: disableReactions","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_REACTIONS_TRIGGERED),this.getService(Re).disableReactions()}catch(o){this.getService(k).catch("Error in _disableReactions: ",o)}}_enableAnonymousEmail(){this.getService(k).log("%c[WB] Calling FUNCTION: enableAnonymousEmail","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_ANONYMOUS_EMAIL_TRIGGERED),this.getService(Re).enableAnonymousEmail()}catch(o){this.getService(k).catch("Error in _enableAnonymousEmail: ",o)}}_disableAnonymousEmail(){this.getService(k).log("%c[WB] Calling FUNCTION: disableAnonymousEmail","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_ANONYMOUS_EMAIL_TRIGGERED),this.getService(Re).disableAnonymousEmail()}catch(o){this.getService(k).catch("Error in _disableAnonymousEmail: ",o)}}_setRecordings(o){this.getService(k).log("%c[WB] Calling FUNCTION: setRecordings","color: green;");try{this.trackEvent(Y.Events.Comments.SET_RECORDINGS_TRIGGERED,{payload:{allowedRecordings:o}}),typeof o=="string"&&(o=o?.split(",")?.map(r=>r.trim())),this.getService(Re).setAllowedRecordings(o)}catch(r){this.getService(k).catch("Error in _setRecordings: ",r)}}_addCommentOnElement(o){this.getService(k).log("%c[WB] Calling FUNCTION: addCommentOnElement","color: green;");try{this.trackEvent(Y.Events.Comments.ADD_COMMENT_ON_ELEMENT_TRIGGERED,{payload:{data:o}}),this.getService(Re).addCommentOnElement(o)}catch(r){this.getService(k).catch("Error in _addCommentOnElement: ",r)}}_enablePrivateCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePrivateCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_PRIVATE_COMMENT_MODE_TRIGGERED),this.getService(Re).enablePrivateCommentMode()}catch(o){this.getService(k).catch("Error in _enablePrivateCommentMode: ",o)}}_disablePrivateCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePrivateCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_PRIVATE_COMMENT_MODE_TRIGGERED),this.getService(Re).disablePrivateCommentMode()}catch(o){this.getService(k).catch("Error in _disablePrivateCommentMode: ",o)}}_enablePrivateMode(o){this.getService(k).log("%c[WB] Calling FUNCTION: enablePrivateMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_PRIVATE_MODE_TRIGGERED,{payload:{config:o}}),this.getService(Re).enablePrivateMode(o)}catch(r){this.getService(k).catch("Error in _enablePrivateMode: ",r)}}_disablePrivateMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePrivateMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_PRIVATE_MODE_TRIGGERED),this.getService(Re).disablePrivateMode()}catch(o){this.getService(k).catch("Error in _disablePrivateMode: ",o)}}_enableScrollToComment(){this.getService(k).log("%c[WB] Calling FUNCTION: enableScrollToComment","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SCROLL_TO_COMMENT_TRIGGERED),this.getService(Re).enableScrollToComment()}catch(o){this.getService(k).catch("Error in _enableScrollToComment: ",o)}}_disableScrollToComment(){this.getService(k).log("%c[WB] Calling FUNCTION: disableScrollToComment","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SCROLL_TO_COMMENT_TRIGGERED),this.getService(Re).disableScrollToComment()}catch(o){this.getService(k).catch("Error in _disableScrollToComment: ",o)}}_enableUserMentions(){this.getService(k).log("%c[WB] Calling FUNCTION: enableUserMentions","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_USER_MENTIONS_TRIGGERED),this.getService(Re).enableUserMentions()}catch(o){this.getService(k).catch("Error in _enableUserMentions: ",o)}}_disableUserMentions(){this.getService(k).log("%c[WB] Calling FUNCTION: disableUserMentions","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_USER_MENTIONS_TRIGGERED),this.getService(Re).disableUserMentions()}catch(o){this.getService(k).catch("Error in _disableUserMentions: ",o)}}_setCommentSidebarFilters(o){this.getService(k).log("%c[WB] Calling FUNCTION: setCommentSidebarFilters","color: green;");try{this.trackEvent(Y.Events.Comments.SET_COMMENT_SIDEBAR_FILTERS_TRIGGERED,{payload:{filters:o}}),this.getService(Re).setCommentSidebarFilters(o)}catch(r){this.getService(k).catch("Error in _setCommentSidebarFilters: ",r)}}_setSystemFiltersOperator(o){this.getService(k).log("%c[WB] Calling FUNCTION: setSystemFiltersOperator","color: green;");try{this.trackEvent(Y.Events.Comments.SET_SYSTEM_FILTERS_OPERATOR_TRIGGERED,{payload:{operator:o}}),this.getService(Re).setCommentSidebarSystemFiltersOperator(o)}catch(r){this.getService(k).catch("Error in _setSystemFiltersOperator: ",r)}}_enableCommentPinHighlighter(){this.getService(k).log("%c[WB] Calling FUNCTION: enableCommentPinHighlighter","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_COMMENT_PIN_HIGHLIGHTER_TRIGGERED),this.getService(Re).enableCommentPinHighlighter()}catch(o){this.getService(k).catch("Error in _enableCommentPinHighlighter: ",o)}}_disableCommentPinHighlighter(){this.getService(k).log("%c[WB] Calling FUNCTION: disableCommentPinHighlighter","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_COMMENT_PIN_HIGHLIGHTER_TRIGGERED),this.getService(Re).disableCommentPinHighlighter()}catch(o){this.getService(k).catch("Error in _disableCommentPinHighlighter: ",o)}}_enableDeleteOnBackspace(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDeleteOnBackspace","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DELETE_ON_BACKSPACE_TRIGGERED),this.getService(Re).enableDeleteOnBackspace()}catch(o){this.getService(k).catch("Error in _enableDeleteOnBackspace: ",o)}}_disableDeleteOnBackspace(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDeleteOnBackspace","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DELETE_ON_BACKSPACE_TRIGGERED),this.getService(Re).disableDeleteOnBackspace()}catch(o){this.getService(k).catch("Error in _disableDeleteOnBackspace: ",o)}}_enableHotkey(){this.getService(k).log("%c[WB] Calling FUNCTION: enableHotkey","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_HOTKEY_TRIGGERED),this.getService(Re).enableHotkey()}catch(o){this.getService(k).catch("Error in _enableHotkey: ",o)}}_disableHotkey(){this.getService(k).log("%c[WB] Calling FUNCTION: disableHotkey","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_HOTKEY_TRIGGERED),this.getService(Re).disableHotkey()}catch(o){this.getService(k).catch("Error in _disableHotkey: ",o)}}_enableDeviceIndicatorOnCommentPins(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDeviceIndicatorOnCommentPins","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DEVICE_INDICATOR_ON_COMMENT_PINS_TRIGGERED),this.getService(Re).enableDeviceIndicatorOnCommentPins()}catch(o){this.getService(k).catch("Error in _enableDeviceIndicatorOnCommentPins: ",o)}}_disableDeviceIndicatorOnCommentPins(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDeviceIndicatorOnCommentPins","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DEVICE_INDICATOR_ON_COMMENT_PINS_TRIGGERED),this.getService(Re).disableDeviceIndicatorOnCommentPins()}catch(o){this.getService(k).catch("Error in _disableDeviceIndicatorOnCommentPins: ",o)}}_getElementRefByAnnotationId(o){this.getService(k).log("%c[WB] Calling FUNCTION: getElementRefByAnnotationId","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_ELEMENT_REF_BY_ANNOTATION_ID_TRIGGERED,{payload:{annotationId:o}}),this.getService(Re).getElementRefByAnnotationId(o)}catch(r){this.getService(k).catch("Error in _getElementRefByAnnotationId: ",r);return}}_scrollToCommentByAnnotationId(o){this.getService(k).log("%c[WB] Calling FUNCTION: scrollToCommentByAnnotationId","color: green;");try{this.trackEvent(Y.Events.Comments.SCROLL_TO_COMMENT_BY_ANNOTATION_ID_TRIGGERED,{payload:{annotationId:o}}),this.getService(Re).scrollToCommentByAnnotationId(o)}catch(r){this.getService(k).catch("Error in _scrollToCommentByAnnotationId: ",r)}}_selectCommentByAnnotationId(o){this.getService(k).log("%c[WB] Calling FUNCTION: selectCommentByAnnotationId","color: green;");try{this.trackEvent(Y.Events.Comments.SELECT_COMMENT_BY_ANNOTATION_ID_TRIGGERED,{payload:{annotationId:o}}),this.getService(Re).selectCommentByAnnotationId(o)}catch(r){this.getService(k).catch("Error in _selectCommentByAnnotationId: ",r)}}_enableRecordingSummary(){this.getService(k).log("%c[WB] Calling FUNCTION: enableRecordingSummary","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_RECORDING_SUMMARY_TRIGGERED),this.getService(Re).enableRecordingSummary()}catch(o){this.getService(k).catch("Error in _enableRecordingSummary: ",o)}}_disableRecordingSummary(){this.getService(k).log("%c[WB] Calling FUNCTION: disableRecordingSummary","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_RECORDING_SUMMARY_TRIGGERED),this.getService(Re).disableRecordingSummary()}catch(o){this.getService(k).catch("Error in _disableRecordingSummary: ",o)}}_enableRecordingTranscription(){this.getService(k).log("%c[WB] Calling FUNCTION: enableRecordingTranscription","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_RECORDING_TRANSCRIPTION_TRIGGERED),this.getService(ho).enableRecordingTranscription()}catch(o){this.getService(k).catch("Error in _enableRecordingTranscription: ",o)}}_disableRecordingTranscription(){this.getService(k).log("%c[WB] Calling FUNCTION: disableRecordingTranscription","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_RECORDING_TRANSCRIPTION_TRIGGERED),this.getService(ho).disableRecordingTranscription()}catch(o){this.getService(k).catch("Error in _disableRecordingTranscription: ",o)}}_enableRecordingCountdown(){this.getService(k).log("%c[WB] Calling FUNCTION: enableRecordingCountdown","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_RECORDING_COUNTDOWN_TRIGGERED),this.getService(Re).enableRecordingCountdown()}catch(o){this.getService(k).catch("Error in _enableRecordingCountdown: ",o)}}_disableRecordingCountdown(){this.getService(k).log("%c[WB] Calling FUNCTION: disableRecordingCountdown","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_RECORDING_COUNTDOWN_TRIGGERED),this.getService(Re).disableRecordingCountdown()}catch(o){this.getService(k).catch("Error in _disableRecordingCountdown: ",o)}}_setUnreadIndicatorMode(o){this.getService(k).log("%c[WB] Calling FUNCTION: setUnreadIndicatorMode","color: green;");try{this.trackEvent(Y.Events.Comments.SET_UNREAD_INDICATOR_MODE_TRIGGERED,{payload:{mode:o}}),this.getService(Re).setUnreadIndicatorMode(o)}catch(r){this.getService(k).catch("Error in _setUnreadIndicatorMode: ",r)}}_enableEnterKeyToSubmit(){this.getService(k).log("%c[WB] Calling FUNCTION: enableEnterKeyToSubmit","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_ENTER_KEY_TO_SUBMIT_TRIGGERED),this.getService(Re).enableEnterKeyToSubmit()}catch(o){this.getService(k).catch("Error in _enableEnterKeyToSubmit: ",o)}}_disableEnterKeyToSubmit(){this.getService(k).log("%c[WB] Calling FUNCTION: disableEnterKeyToSubmit","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_ENTER_KEY_TO_SUBMIT_TRIGGERED),this.getService(Re).disableEnterKeyToSubmit()}catch(o){this.getService(k).catch("Error in _disableEnterKeyToSubmit: ",o)}}_enablePinShadowDOM(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePinShadowDOM","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_PIN_SHADOW_DOM_TRIGGERED),this.getService(Re).enablePinShadowDOM()}catch(o){this.getService(k).catch("Error in _enablePinShadowDOM: ",o)}}_disablePinShadowDOM(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePinShadowDOM","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_PIN_SHADOW_DOM_TRIGGERED),this.getService(Re).disablePinShadowDOM()}catch(o){this.getService(k).catch("Error in _disablePinShadowDOM: ",o)}}_enableDialogShadowDOM(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDialogShadowDOM","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DIALOG_SHADOW_DOM_TRIGGERED),this.getService(Re).enableDialogShadowDOM()}catch(o){this.getService(k).catch("Error in _enableDialogShadowDOM: ",o)}}_disableDialogShadowDOM(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDialogShadowDOM","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DIALOG_SHADOW_DOM_TRIGGERED),this.getService(Re).disableDialogShadowDOM()}catch(o){this.getService(k).catch("Error in _disableDialogShadowDOM: ",o)}}_enableSidebarShadowDOM(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSidebarShadowDOM","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SIDEBAR_SHADOW_DOM_TRIGGERED),this.getService(Re).enableSidebarShadowDOM()}catch(o){this.getService(k).catch("Error in _enableSidebarShadowDOM: ",o)}}_disableSidebarShadowDOM(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSidebarShadowDOM","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SIDEBAR_SHADOW_DOM_TRIGGERED),this.getService(Re).disableSidebarShadowDOM()}catch(o){this.getService(k).catch("Error in _disableSidebarShadowDOM: ",o)}}_enableChangeDetectionInCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableChangeDetectionInCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_CHANGE_DETECTION_IN_COMMENT_MODE_TRIGGERED),this.getService(Re).enableChangeDetectionInCommentMode()}catch(o){this.getService(k).catch("Error in _enableChangeDetectionInCommentMode: ",o)}}_disableChangeDetectionInCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableChangeDetectionInCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_CHANGE_DETECTION_IN_COMMENT_MODE_TRIGGERED),this.getService(Re).disableChangeDetectionInCommentMode()}catch(o){this.getService(k).catch("Error in _disableChangeDetectionInCommentMode: ",o)}}_showResolvedCommentsOnDom(){this.getService(k).log("%c[WB] Calling FUNCTION: showResolvedCommentsOnDom","color: green;");try{this.trackEvent(Y.Events.Comments.SHOW_RESOLVED_COMMENTS_ON_DOM_TRIGGERED),this.getService(Re).showResolvedCommentsOnDom()}catch(o){this.getService(k).catch("Error in _showResolvedCommentsOnDom: ",o)}}_hideResolvedCommentsOnDom(){this.getService(k).log("%c[WB] Calling FUNCTION: hideResolvedCommentsOnDom","color: green;");try{this.trackEvent(Y.Events.Comments.HIDE_RESOLVED_COMMENTS_ON_DOM_TRIGGERED),this.getService(Re).hideResolvedCommentsOnDom()}catch(o){this.getService(k).catch("Error in _hideResolvedCommentsOnDom: ",o)}}_setCustomReactions(o){this.getService(k).log("%c[WB] Calling FUNCTION: setCustomReactions","color: green;");try{this.trackEvent(Y.Events.Comments.SET_CUSTOM_REACTIONS_TRIGGERED,{payload:{reactions:o}}),this.getService(Re).setCustomReactions(o)}catch(r){this.getService(k).catch("Error in _setCustomReactions: ",r)}}_onCommentSelectionChange(){this.getService(k).log("%c[WB] Calling FUNCTION: onCommentSelectionChange","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_COMMENT_SELECTION_CHANGE_TRIGGERED),this.getService(Re).onCommentSelectionChange$()}catch(o){return this.getService(k).catch("Error in _onCommentSelectionChange: ",o),ce(null)}}_getUnreadCommentCountByAnnotationId(o){this.getService(k).log("%c[WB] Calling FUNCTION: getUnreadCommentCountByAnnotationId","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_UNREAD_COMMENT_COUNT_BY_ANNOTATION_ID_TRIGGERED,{payload:{commentAnnotationId:o}}),this.getService(Re).getUnreadCommentCountByAnnotationId$(o)}catch(r){return this.getService(k).catch("Error in _getUnreadCommentCountByAnnotationId: ",r),ce(null)}}_getUnreadCommentAnnotationCountOnCurrentDocument(){this.getService(k).log("%c[WB] Calling FUNCTION: getUnreadCommentAnnotationCountOnCurrentDocument","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_UNREAD_COMMENT_ANNOTATION_COUNT_ON_CURRENT_DOCUMENT_TRIGGERED),this.getService(Re).getUnreadCommentAnnotationCountOnCurrentDocument$()}catch(o){return this.getService(k).catch("Error in _getUnreadCommentAnnotationCountOnCurrentDocument: ",o),ce(null)}}_getUnreadCommentCountOnCurrentDocument(){this.getService(k).log("%c[WB] Calling FUNCTION: getUnreadCommentCountOnCurrentDocument","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_UNREAD_COMMENT_COUNT_ON_CURRENT_DOCUMENT_TRIGGERED),this.getService(Re).getUnreadCommentCountOnCurrentDocument$()}catch(o){return this.getService(k).catch("Error in _getUnreadCommentCountOnCurrentDocument: ",o),ce(null)}}_getUnreadCommentAnnotationCountByLocationId(o){this.getService(k).log("%c[WB] Calling FUNCTION: getUnreadCommentAnnotationCountByLocationId","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_UNREAD_COMMENT_ANNOTATION_COUNT_BY_LOCATION_ID_TRIGGERED,{payload:{locationId:o}}),this.getService(Re).getUnreadCommentAnnotationCountByLocationId$(o)}catch(r){return this.getService(k).catch("Error in _getUnreadCommentAnnotationCountByLocationId: ",r),ce(null)}}_getUnreadCommentCountByLocationId(o){this.getService(k).log("%c[WB] Calling FUNCTION: getUnreadCommentCountByLocationId","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_UNREAD_COMMENT_COUNT_BY_LOCATION_ID_TRIGGERED,{payload:{locationId:o}}),this.getService(Re).getUnreadCommentCountByLocationId$(o)}catch(r){return this.getService(k).catch("Error in _getUnreadCommentCountByLocationId: ",r),ce(null)}}_updateCommentDialogPosition(){this.getService(k).log("%c[WB] Calling FUNCTION: updateCommentDialogPosition","color: green;");try{this.trackEvent(Y.Events.Comments.UPDATE_COMMENT_DIALOG_POSITION_TRIGGERED),this.getService(Re).updateCommentDialogPosition()}catch(o){this.getService(k).catch("Error in _updateCommentDialogPosition: ",o)}}_enableAreaComment(){this.getService(k).log("%c[WB] Calling FUNCTION: enableAreaComment","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_AREA_COMMENT_TRIGGERED),this.getService(Re).enableAreaComment()}catch(o){this.getService(k).catch("Error in _enableAreaComment: ",o)}}_disableAreaComment(){this.getService(k).log("%c[WB] Calling FUNCTION: disableAreaComment","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_AREA_COMMENT_TRIGGERED),this.getService(Re).disableAreaComment()}catch(o){this.getService(k).catch("Error in _disableAreaComment: ",o)}}_setPinCursorImage(o){this.getService(k).log("%c[WB] Calling FUNCTION: setPinCursorImage","color: green;");try{this.trackEvent(Y.Events.Comments.SET_PIN_CURSOR_IMAGE_TRIGGERED,{payload:{image:o}}),this.getService(Re).setPinCursorImage(o)}catch(r){this.getService(k).catch("Error in _setPinCursorImage: ",r)}}_addManualComment(o){this.getService(k).log("%c[WB] Calling FUNCTION: addManualComment","color: green;");try{return this.trackEvent(Y.Events.Comments.ADD_MANUAL_COMMENT_TRIGGERED,{payload:{config:o}}),this.getService(Re).addManualComment(o)}catch(r){return this.getService(k).catch("Error in _addManualComment: ",r),Promise.resolve()}}_createCustomListDataOnAnnotation(o){this.getService(k).log("%c[WB] Calling FUNCTION: createCustomListDataOnAnnotation","color: green;");try{this.trackEvent(Y.Events.Comments.CREATE_CUSTOM_LIST_DATA_ON_ANNOTATION_TRIGGERED,{payload:{data:o}}),this.getService(Re).createCustomListDataOnAnnotation(o)}catch(r){this.getService(k).catch("Error in _createCustomListDataOnAnnotation: ",r)}}_createCustomListDataOnComment(o){this.getService(k).log("%c[WB] Calling FUNCTION: createCustomListDataOnComment","color: green;");try{return this.trackEvent(Y.Events.Comments.CREATE_CUSTOM_LIST_DATA_ON_COMMENT_TRIGGERED,{payload:{data:o}}),this.getService(Ec).create(o)}catch(r){this.getService(k).catch("Error in _createCustomListDataOnComment: ",r)}}_excludeLocationIdsFromSidebar(o){this.getService(k).log("%c[WB] Calling FUNCTION: excludeLocationIdsFromSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.EXCLUDE_LOCATION_IDS_FROM_SIDEBAR_TRIGGERED,{payload:{locationIds:o}}),this.getService(Re).setExcludeLocationIdsFromSidebar(o)}catch(r){this.getService(k).catch("Error in _excludeLocationIdsFromSidebar: ",r)}}_enableBubbleOnPin(){this.getService(k).log("%c[WB] Calling FUNCTION: enableBubbleOnPin","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_BUBBLE_ON_PIN_TRIGGERED),this.getService(Re).enableBubbleOnPin()}catch(o){this.getService(k).catch("Error in _enableBubbleOnPin: ",o)}}_disableBubbleOnPin(){this.getService(k).log("%c[WB] Calling FUNCTION: disableBubbleOnPin","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_BUBBLE_ON_PIN_TRIGGERED),this.getService(Re).disableBubbleOnPin()}catch(o){this.getService(k).catch("Error in _disableBubbleOnPin: ",o)}}_enableBubbleOnPinHover(){this.getService(k).log("%c[WB] Calling FUNCTION: enableBubbleOnPinHover","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_BUBBLE_ON_PIN_HOVER_TRIGGERED),this.getService(Re).enableBubbleOnPinHover()}catch(o){this.getService(k).catch("Error in _enableBubbleOnPinHover: ",o)}}_disableBubbleOnPinHover(){this.getService(k).log("%c[WB] Calling FUNCTION: disableBubbleOnPinHover","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_BUBBLE_ON_PIN_HOVER_TRIGGERED),this.getService(Re).disableBubbleOnPinHover()}catch(o){this.getService(k).catch("Error in _disableBubbleOnPinHover: ",o)}}_enablePinDrag(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePinDrag","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_PIN_DRAG_TRIGGERED),this.getService(Re).enablePinDrag()}catch(o){this.getService(k).catch("Error in _enablePinDrag: ",o)}}_disablePinDrag(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePinDrag","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_PIN_DRAG_TRIGGERED),this.getService(Re).disablePinDrag()}catch(o){this.getService(k).catch("Error in _disablePinDrag: ",o)}}_enableMultiThread(){this.getService(k).log("%c[WB] Calling FUNCTION: enableMultiThread","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_MULTI_THREAD_TRIGGERED),this.getService(Re).enableMultiThread()}catch(o){this.getService(k).catch("Error in _enableMultiThread: ",o)}}_disableMultiThread(){this.getService(k).log("%c[WB] Calling FUNCTION: disableMultiThread","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_MULTI_THREAD_TRIGGERED),this.getService(Re).disableMultiThread()}catch(o){this.getService(k).catch("Error in _disableMultiThread: ",o)}}_enableGroupMatchedComments(){this.getService(k).log("%c[WB] Calling FUNCTION: enableGroupMatchedComments","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_GROUP_MATCHED_COMMENTS_TRIGGERED),this.getService(Re).enableGroupMatchedComments()}catch(o){this.getService(k).catch("Error in _enableGroupMatchedComments: ",o)}}_disableGroupMatchedComments(){this.getService(k).log("%c[WB] Calling FUNCTION: disableGroupMatchedComments","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_GROUP_MATCHED_COMMENTS_TRIGGERED),this.getService(Re).disableGroupMatchedComments()}catch(o){this.getService(k).catch("Error in _disableGroupMatchedComments: ",o)}}_updateContext(o,r,e){this.getService(k).log("%c[WB] Calling FUNCTION: updateContext","color: green;");try{return this.trackEvent(Y.Events.Comments.UPDATE_CONTEXT_TRIGGERED,{payload:{annotationId:o,context:r,config:e}}),this.getService(Re).updateCommentAnnotationContext(o,r,e)}catch(t){return this.getService(k).catch("Error in _updateContext: ",t),Promise.resolve()}}_updateVisibility(o){this.getService(k).log("%c[WB] Calling FUNCTION: updateVisibility","color: green;");try{return this.trackEvent(Y.Events.Comments.UPDATE_VISIBILITY_TRIGGERED,{payload:{visibility:o}}),this.getService(Mn).updateVisibility(o)}catch(r){return this.getService(k).catch("Error in _updateVisibility: ",r),Promise.resolve()}}_getSelectedComments(){this.getService(k).log("%c[WB] Calling FUNCTION: getSelectedComments","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_SELECTED_COMMENTS_TRIGGERED),this.getService(Ve).getSelectedComments$()}catch(o){return this.getService(k).catch("Error in _getSelectedComments: ",o),ce([])}}_enableDeleteReplyConfirmation(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDeleteReplyConfirmation","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DELETE_REPLY_CONFIRMATION_TRIGGERED),this.getService(Re).enableDeleteReplyConfirmation()}catch(o){this.getService(k).catch("Error in _enableDeleteReplyConfirmation: ",o)}}_disableDeleteReplyConfirmation(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDeleteReplyConfirmation","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DELETE_REPLY_CONFIRMATION_TRIGGERED),this.getService(Re).disableDeleteReplyConfirmation()}catch(o){this.getService(k).catch("Error in _disableDeleteReplyConfirmation: ",o)}}_onCopyLink(){this.getService(k).log("%c[WB] Calling FUNCTION: onCopyLink","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_COPY_LINK_TRIGGERED),this.getService(Re).getCopyLink$()}catch(o){return this.getService(k).catch("Error in _onCopyLink: ",o),ce("")}}_getCommentAnnotationById(o){this.getService(k).log("%c[WB] Calling FUNCTION: getCommentAnnotationById","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_COMMENT_ANNOTATION_BY_ID_TRIGGERED,{payload:{config:o}}),this.getService(Re).getCommentAnnotationById(o)}catch(r){return this.getService(k).catch("Error in _getCommentAnnotationById: ",r),ce(null)}}_enableCollapsedComments(){this.getService(k).log("%c[WB] Calling FUNCTION: enableCollapsedComments","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_COLLAPSED_COMMENTS_TRIGGERED),this.getService(Re).enableCollapsedComments()}catch(o){this.getService(k).catch("Error in _enableCollapsedComments: ",o)}}_disableCollapsedComments(){this.getService(k).log("%c[WB] Calling FUNCTION: disableCollapsedComments","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_COLLAPSED_COMMENTS_TRIGGERED),this.getService(Re).disableCollapsedComments()}catch(o){this.getService(k).catch("Error in _disableCollapsedComments: ",o)}}_onCommentSidebarActionButtonClick(){this.getService(k).log("%c[WB] Calling FUNCTION: onCommentSidebarActionButtonClick","color: green;");try{return this.getService(Re).getSidebarCustomActionEventData()}catch(o){return this.getService(k).catch("Error in _onCommentSidebarActionButtonClick: ",o),ce(null)}}_setCommentSidebarData(o,r){this.getService(k).log("%c[WB] Calling FUNCTION: setCommentSidebarData","color: green;");try{this.trackEvent(Y.Events.Comments.SET_COMMENT_SIDEBAR_DATA_TRIGGERED,{payload:{data:o,options:r}}),this.getService(Re).setCommentSidebarData(o,r)}catch(e){this.getService(k).catch("Error in _setCommentSidebarData: ",e)}}_onCommentSidebarInit(){this.getService(k).log("%c[WB] Calling FUNCTION: onCommentSidebarInit","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_COMMENT_SIDEBAR_INIT_TRIGGERED),this.getService(Re).getSidebarCustomActionEventDataOnInit()}catch(o){return this.getService(k).catch("Error in _onCommentSidebarInit: ",o),ce(null)}}_onCommentSidebarData(){this.getService(k).log("%c[WB] Calling FUNCTION: onCommentSidebarData","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_COMMENT_SIDEBAR_DATA_TRIGGERED),this.getService(Re).getSidebarCustomActionEventDataAllChanges()}catch(o){return this.getService(k).catch("Error in _onCommentSidebarData: ",o),ce(null)}}_setCommentSidebarDefaultCustomActions(o){this.getService(k).log("%c[WB] Calling FUNCTION: setCommentSidebarDefaultCustomActions","color: green;");try{this.trackEvent(Y.Events.Comments.SET_COMMENT_SIDEBAR_DEFAULT_CUSTOM_ACTIONS_TRIGGERED,{payload:{actions:o}}),this.getService(Re).setSidebarCustomActionEventData(o,[],{},[],{})}catch(r){this.getService(k).catch("Error in _setCommentSidebarDefaultCustomActions: ",r)}}_enableSidebarCustomActions(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSidebarCustomActions","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SIDEBAR_CUSTOM_ACTIONS_TRIGGERED),this.getService(Re).enableSidebarCustomActions()}catch(o){this.getService(k).catch("Error in _enableSidebarCustomActions: ",o)}}_disableSidebarCustomActions(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSidebarCustomActions","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SIDEBAR_CUSTOM_ACTIONS_TRIGGERED),this.getService(Re).disableSidebarCustomActions()}catch(o){this.getService(k).catch("Error in _disableSidebarCustomActions: ",o)}}_enableQueryParamsComments(){this.getService(k).log("%c[WB] Calling FUNCTION: enableQueryParamsComments","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_QUERY_PARAMS_COMMENTS_TRIGGERED),this.getService(Re).enableQueryParamsComments()}catch(o){this.getService(k).catch("Error in _enableQueryParamsComments: ",o)}}_disableQueryParamsComments(){this.getService(k).log("%c[WB] Calling FUNCTION: disableQueryParamsComments","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_QUERY_PARAMS_COMMENTS_TRIGGERED),this.getService(Re).disableQueryParamsComments()}catch(o){this.getService(k).catch("Error in _disableQueryParamsComments: ",o)}}_enableResolveStatusAccessAdminOnly(){this.getService(k).log("%c[WB] Calling FUNCTION: enableResolveStatusAccessAdminOnly","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_RESOLVE_STATUS_ACCESS_ADMIN_ONLY_TRIGGERED),this.getService(Re).enableResolveStatusAccessAdminOnly()}catch(o){this.getService(k).catch("Error in _enableResolveStatusAccessAdminOnly: ",o)}}_disableResolveStatusAccessAdminOnly(){this.getService(k).log("%c[WB] Calling FUNCTION: disableResolveStatusAccessAdminOnly","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_RESOLVE_STATUS_ACCESS_ADMIN_ONLY_TRIGGERED),this.getService(Re).disableResolveStatusAccessAdminOnly()}catch(o){this.getService(k).catch("Error in _disableResolveStatusAccessAdminOnly: ",o)}}_enableLinkCallback(){this.getService(k).log("%c[WB] Calling FUNCTION: enableLinkCallback","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_LINK_CALLBACK_TRIGGERED),this.getService(Re).enableLinkCallback()}catch(o){this.getService(k).catch("Error in _enableLinkCallback: ",o)}}_disableLinkCallback(){this.getService(k).log("%c[WB] Calling FUNCTION: disableLinkCallback","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_LINK_CALLBACK_TRIGGERED),this.getService(Re).disableLinkCallback()}catch(o){this.getService(k).catch("Error in _disableLinkCallback: ",o)}}_enableSeenByUsers(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSeenByUsers","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SEEN_BY_USERS_TRIGGERED),this.getService(Re).enableSeenByUsers()}catch(o){this.getService(k).catch("Error in _enableSeenByUsers: ",o)}}_disableSeenByUsers(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSeenByUsers","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SEEN_BY_USERS_TRIGGERED),this.getService(Re).disableSeenByUsers()}catch(o){this.getService(k).catch("Error in _disableSeenByUsers: ",o)}}_enableShortUserName(){this.getService(k).log("%c[WB] Calling FUNCTION: enableShortUserName","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SHORT_USER_NAME_TRIGGERED),this.getService(Re).enableShortUserName()}catch(o){this.getService(k).catch("Error in _enableShortUserName: ",o)}}_disableShortUserName(){this.getService(k).log("%c[WB] Calling FUNCTION: disableShortUserName","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SHORT_USER_NAME_TRIGGERED),this.getService(Re).disableShortUserName()}catch(o){this.getService(k).catch("Error in _disableShortUserName: ",o)}}_addCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: addCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.ADD_COMMENT_ANNOTATION_TRIGGERED,{payload:{addCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).addCommentAnnotation(o,"external")}catch(r){return this.getService(k).catch("Error in _addCommentAnnotation: ",r),null}})}_publishCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: publishCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.PUBLISH_COMMENT_ANNOTATION_TRIGGERED,{payload:{publishCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).publishCommentAnnotation(o,"external")}catch(r){return this.getService(k).catch("Error in _publishCommentAnnotation: ",r),null}})}_approveCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: approveCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.APPROVE_COMMENT_ANNOTATION_TRIGGERED,{payload:{approveCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).approveCommentAnnotation(o,"external")}catch(r){return this.getService(k).catch("Error in _approveCommentAnnotation: ",r),null}})}_acceptCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: acceptCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.ACCEPT_COMMENT_ANNOTATION_TRIGGERED,{payload:{acceptCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).acceptCommentAnnotation(o,"external")}catch(r){return this.getService(k).catch("Error in _acceptCommentAnnotation: ",r),null}})}_rejectCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: rejectCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.REJECT_COMMENT_ANNOTATION_TRIGGERED,{payload:{rejectCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).rejectCommentAnnotation(o,"external")}catch(r){return this.getService(k).catch("Error in _rejectCommentAnnotation: ",r),null}})}_subscribeCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: subscribeCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.SUBSCRIBE_COMMENT_ANNOTATION_TRIGGERED,{payload:{subscribeCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).toggleNotificationSubscription(o,"subscribe")}catch(r){return this.getService(k).catch("Error in _subscribeCommentAnnotation: ",r),null}})}_unsubscribeCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: unsubscribeCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.UNSUBSCRIBE_COMMENT_ANNOTATION_TRIGGERED,{payload:{unsubscribeCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).toggleNotificationSubscription(o,"unsubscribe")}catch(r){return this.getService(k).catch("Error in _unsubscribeCommentAnnotation: ",r),null}})}_deleteCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: deleteCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.DELETE_COMMENT_ANNOTATION_TRIGGERED,{payload:{deleteCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).deleteCommentAnnotation(o,"external")}catch(r){return this.getService(k).catch("Error in _deleteCommentAnnotation: ",r),null}})}_getCommentAnnotations(o){this.getService(k).log("%c[WB] Calling FUNCTION: getCommentAnnotations","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_COMMENT_ANNOTATIONS_TRIGGERED,{payload:{query:o}}),this.getService(Mn).getCommentAnnotations(o).pipe(ue(r=>(r.data&&Object.keys(r.data).forEach(e=>{if(r.data?.[e]?.length){let t=r.data[e];r.data[e]=t?.map(i=>this.getService(Re).getCommentAnnotationForClient(i))}}),r)))}catch(r){return this.getService(k).catch("Error in _getCommentAnnotations: ",r),ce({data:null})}}_getCommentAnnotationsCount(o){this.getService(k).log("%c[WB] Calling FUNCTION: getCommentAnnotationsCount","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_COMMENT_ANNOTATIONS_COUNT_TRIGGERED,{payload:{query:o}}),this.getService(Mn).getCommentAnnotationsCount$(o)}catch(r){return this.getService(k).catch("Error in _getCommentAnnotationsCount: ",r),ce({data:null})}}_assignUser(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: assignUser","color: green;");try{return this.trackEvent(Y.Events.Comments.ASSIGN_USER_TRIGGERED,{payload:{assignUserRequest:o}}),this.getService(Mn).convert(o).assignUser(o,"external")}catch(r){return this.getService(k).catch("Error in _assignUser: ",r),null}})}_updatePriority(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: updatePriority","color: green;");try{return this.trackEvent(Y.Events.Comments.UPDATE_PRIORITY_TRIGGERED,{payload:{updatePriorityRequest:o}}),this.getService(Mn).convert(o).updatePriority(o,"external")}catch(r){return this.getService(k).catch("Error in _updatePriority: ",r),null}})}_updateStatus(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: updateStatus","color: green;");try{return this.trackEvent(Y.Events.Comments.UPDATE_STATUS_TRIGGERED,{payload:{updateStatusRequest:o}}),this.getService(Mn).convert(o).updateStatus(o,"external")}catch(r){return this.getService(k).catch("Error in _updateStatus: ",r),null}})}_updateAccess(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: updateAccess","color: green;");try{return this.trackEvent(Y.Events.Comments.UPDATE_ACCESS_TRIGGERED,{payload:{updateAccessRequest:o}}),this.getService(Mn).convert(o).updateAccess(o,"external")}catch(r){return this.getService(k).catch("Error in _updateAccess: ",r),null}})}_resolveCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: resolveCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.RESOLVE_COMMENT_ANNOTATION_TRIGGERED,{payload:{resolveCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).resolveCommentAnnotation(o)}catch(r){return this.getService(k).catch("Error in _resolveCommentAnnotation: ",r),null}})}_getLink(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: getLink","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_LINK_TRIGGERED,{payload:{getLinkRequest:o}}),this.getService(Mn).convert(o).getLink(o,"external")}catch(r){return this.getService(k).catch("Error in _getLink: ",r),null}})}_copyLink(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: copyLink","color: green;");try{return this.trackEvent(Y.Events.Comments.COPY_LINK_TRIGGERED,{payload:{copyLinkRequest:o}}),this.getService(Mn).convert(o).copyLink(o,"external")}catch(r){return this.getService(k).catch("Error in _copyLink: ",r),null}})}_addComment(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: addComment","color: green;");try{return this.trackEvent(Y.Events.Comments.ADD_COMMENT_TRIGGERED,{payload:{addCommentRequest:o}}),this.getService(Mn).convert(o).addComment(o,"external")}catch(r){return this.getService(k).catch("Error in _addComment: ",r),null}})}_updateComment(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: updateComment","color: green;");try{return this.trackEvent(Y.Events.Comments.UPDATE_COMMENT_TRIGGERED,{payload:{updateCommentRequest:o}}),this.getService(Mn).convert(o).updateComment(o,"external")}catch(r){return this.getService(k).catch("Error in _updateComment: ",r),null}})}_deleteComment(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: deleteComment","color: green;");try{return this.trackEvent(Y.Events.Comments.DELETE_COMMENT_TRIGGERED,{payload:{deleteCommentRequest:o}}),this.getService(Mn).convert(o).deleteComment(o,"external")}catch(r){return this.getService(k).catch("Error in _deleteComment: ",r),null}})}_getComment(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: getComment","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_COMMENT_TRIGGERED,{payload:{getCommentRequest:o}}),this.getService(Mn).convert(o).getComment(o)}catch(r){return this.getService(k).catch("Error in _getComment: ",r),[]}})}_addAttachment(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: addAttachment","color: green;");try{return this.trackEvent(Y.Events.Comments.ADD_ATTACHMENT_TRIGGERED,{payload:{addAttachmentRequest:o}}),this.getService(Mn).convert(o).addAttachment(o)}catch(r){return this.getService(k).catch("Error in _addAttachment: ",r),Promise.resolve([])}})}_deleteAttachment(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: deleteAttachment","color: green;");try{return this.trackEvent(Y.Events.Comments.DELETE_ATTACHMENT_TRIGGERED,{payload:{deleteAttachmentRequest:o}}),this.getService(Mn).convert(o).deleteAttachment(o)}catch(r){return this.getService(k).catch("Error in _deleteAttachment: ",r),null}})}_getAttachment(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: getAttachment","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_ATTACHMENT_TRIGGERED,{payload:{getAttachmentRequest:o}}),this.getService(Mn).convert(o).getAttachment(o)}catch(r){return this.getService(k).catch("Error in _getAttachment: ",r),[]}})}_getRecording(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: getRecording","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_RECORDING_TRIGGERED,{payload:{getRecordingRequest:o}}),this.getService(Mn).convert(o).getRecording(o)}catch(r){return this.getService(k).catch("Error in _getRecording: ",r),[]}})}_deleteRecording(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: deleteRecording","color: green;");try{return this.trackEvent(Y.Events.Comments.DELETE_RECORDING_TRIGGERED,{payload:{deleteRecordingRequest:o}}),this.getService(Mn).convert(o).deleteRecording(o)}catch(r){return this.getService(k).catch("Error in _deleteRecording: ",r),null}})}_fetchCommentAnnotations(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: fetchCommentAnnotations","color: green;");try{return this.trackEvent(Y.Events.Comments.FETCH_COMMENT_ANNOTATIONS_TRIGGERED,{payload:{fetchCommentAnnotationsRequest:o}}),this.getService(Mn).fetchCommentAnnotations(o)}catch(r){return this.getService(k).catch("Error in _fetchCommentAnnotations: ",r),{data:null}}})}_addReaction(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: addReaction","color: green;");try{return this.trackEvent(Y.Events.Comments.ADD_REACTION_TRIGGERED,{payload:{addReactionRequest:o}}),this.getService(Mn).convert(o).toggleReaction(o,"add")}catch(r){return this.getService(k).catch("Error in _addReaction: ",r),null}})}_deleteReaction(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: deleteReaction","color: green;");try{return this.trackEvent(Y.Events.Comments.DELETE_REACTION_TRIGGERED,{payload:{deleteReactionRequest:o}}),this.getService(Mn).convert(o).toggleReaction(o,"delete")}catch(r){return this.getService(k).catch("Error in _deleteReaction: ",r),null}})}_toggleReaction(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: toggleReaction","color: green;");try{return this.trackEvent(Y.Events.Comments.TOGGLE_REACTION_TRIGGERED,{payload:{toggleReactionRequest:o}}),this.getService(Mn).convert(o).toggleReaction(o)}catch(r){return this.getService(k).catch("Error in _toggleReaction: ",r),null}})}_on(o){this.getService(k).log("%c[WB] Calling FUNCTION: on","color: green;");try{return this.getService(Mn).onAction(o)}catch(r){return this.getService(k).catch("Error in _on: ",r),ce(null)}}_enableReadOnly(){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: enableReadOnly","color: green;");try{return this.trackEvent(Y.Events.Comments.ENABLE_READ_ONLY_TRIGGERED),this.getService(Re).enableReadOnly()}catch(o){this.getService(k).catch("Error in _toggleReaction: ",o);return}})}_disableReadOnly(){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: disableReadOnly","color: green;");try{return this.trackEvent(Y.Events.Comments.DISABLE_READ_ONLY_TRIGGERED),this.getService(Re).disableReadOnly()}catch(o){this.getService(k).catch("Error in _disableReadOnly: ",o);return}})}_setAssignToType(o){this.getService(k).log("%c[WB] Calling FUNCTION: setAssignToType","color: green;");try{this.trackEvent(Y.Events.Comments.SET_ASSIGN_TO_TYPE_TRIGGERED,{payload:{type:o.type}}),this.getService(Re).setAssignToType(o)}catch(r){this.getService(k).catch("Error in _setAssignToType: ",r)}}_enableContextInPageModeComposer(){this.getService(k).log("%c[WB] Calling FUNCTION: enableContextInPageModeComposer","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_CONTEXT_IN_PAGE_MODE_COMPOSER_TRIGGERED),this.getService(Re).enableContextInPageModeComposer()}catch(o){this.getService(k).catch("Error in _enableContextInPageModeComposer: ",o)}}_disableContextInPageModeComposer(){this.getService(k).log("%c[WB] Calling FUNCTION: disableContextInPageModeComposer","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_CONTEXT_IN_PAGE_MODE_COMPOSER_TRIGGERED),this.getService(Re).disableContextInPageModeComposer()}catch(o){this.getService(k).catch("Error in _disableContextInPageModeComposer: ",o)}}_clearPageModeComposerContext(){this.getService(k).log("%c[WB] Calling FUNCTION: clearPageModeComposerContext","color: green;");try{this.trackEvent(Y.Events.Comments.CLEAR_PAGE_MODE_COMPOSER_CONTEXT_TRIGGERED),this.getService(Re).clearPageModeComposerContext()}catch(o){this.getService(k).catch("Error in _clearPageModeComposerContext: ",o)}}_setContextInPageModeComposer(o){this.getService(k).log("%c[WB] Calling FUNCTION: setContextInPageModeComposer","color: green;");try{this.trackEvent(Y.Events.Comments.SET_CONTEXT_IN_PAGE_MODE_COMPOSER_TRIGGERED),this.getService(Re).setPageModeComposerContext(o)}catch(r){this.getService(k).catch("Error in _setContextInPageModeComposer: ",r)}}_focusPageModeComposer(){this.getService(k).log("%c[WB] Calling FUNCTION: focusPageModeComposer","color: green;");try{this.trackEvent(Y.Events.Comments.FOCUS_PAGE_MODE_COMPOSER_TRIGGERED),this.getService(Re).focusPageModeComposer()}catch(o){this.getService(k).catch("Error in _focusPageModeComposer: ",o)}}_enableCustomAutocompleteSearch(){this.getService(k).log("%c[WB] Calling FUNCTION: enableCustomAutocompleteSearch","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_CUSTOM_AUTOCOMPLETE_SEARCH_TRIGGERED),this.getService(Re).enableCustomAutocompleteSearch()}catch(o){this.getService(k).catch("Error in _enableCustomAutocompleteSearch: ",o);return}}_disableCustomAutocompleteSearch(){this.getService(k).log("%c[WB] Calling FUNCTION: disableCustomAutocompleteSearch","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_CUSTOM_AUTOCOMPLETE_SEARCH_TRIGGERED),this.getService(Re).disableCustomAutocompleteSearch()}catch(o){this.getService(k).catch("Error in _disableCustomAutocompleteSearch: ",o);return}}_setTransformContext(o){this.getService(k).log("%c[WB] Calling FUNCTION: setTransformContext","color: green;");try{this.trackEvent(Y.Events.Comments.SET_TRANSFORM_CONTEXT_TRIGGERED,{payload:{transformContext:o}}),this.getService(Re).setTransformContext(o)}catch(r){this.getService(k).catch("Error in _setTransformContext: ",r);return}}_enableSvgAsImg(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSvgAsImg","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SVG_AS_IMG_TRIGGERED),this.getService(Re).enableSvgAsImg()}catch(o){this.getService(k).catch("Error in _enableSvgAsImg: ",o);return}}_disableSvgAsImg(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSvgAsImg","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SVG_AS_IMG_TRIGGERED),this.getService(Re).disableSvgAsImg()}catch(o){this.getService(k).catch("Error in _disableSvgAsImg: ",o);return}}_enableFullExpanded(){this.getService(k).log("%c[WB] Calling FUNCTION: enableFullExpanded","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_FULL_EXPANDED_TRIGGERED),this.getService(Re).enableFullExpanded()}catch(o){this.getService(k).catch("Error in _enableFullExpanded: ",o);return}}_disableFullExpanded(){this.getService(k).log("%c[WB] Calling FUNCTION: disableFullExpanded","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_FULL_EXPANDED_TRIGGERED),this.getService(Re).disableFullExpanded()}catch(o){this.getService(k).catch("Error in _disableFullExpanded: ",o);return}}_enableCommentToNearestAllowedElement(){this.getService(k).log("%c[WB] Calling FUNCTION: enableCommentToNearestAllowedElement","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_COMMENT_TO_NEAREST_ALLOWED_ELEMENT_TRIGGERED),this.getService(Re).enableCommentToNearestAllowedElement()}catch(o){this.getService(k).catch("Error in _enableCommentToNearestAllowedElement: ",o);return}}_disableCommentToNearestAllowedElement(){this.getService(k).log("%c[WB] Calling FUNCTION: disableCommentToNearestAllowedElement","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_COMMENT_TO_NEAREST_ALLOWED_ELEMENT_TRIGGERED),this.getService(Re).disableCommentToNearestAllowedElement()}catch(o){this.getService(k).catch("Error in _disableCommentToNearestAllowedElement: ",o);return}}_enableDraftMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDraftMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DRAFT_MODE_TRIGGERED),this.getService(Re).enableDraftMode()}catch(o){this.getService(k).catch("Error in _enableDraftMode: ",o);return}}_disableDraftMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDraftMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DRAFT_MODE_TRIGGERED),this.getService(Re).disableDraftMode()}catch(o){this.getService(k).catch("Error in _disableDraftMode: ",o);return}}_enableFilterCommentsOnDom(){this.getService(k).log("%c[WB] Calling FUNCTION: enableFilterCommentsOnDom","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_FILTER_COMMENTS_ON_DOM_TRIGGERED),this.getService(Re).enableFilterCommentsOnDom()}catch(o){this.getService(k).catch("Error in _enableFilterCommentsOnDom: ",o);return}}_disableFilterCommentsOnDom(){this.getService(k).log("%c[WB] Calling FUNCTION: disableFilterCommentsOnDom","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_FILTER_COMMENTS_ON_DOM_TRIGGERED),this.getService(Re).disableFilterCommentsOnDom()}catch(o){this.getService(k).catch("Error in _disableFilterCommentsOnDom: ",o);return}}_enableReplyAvatars(){this.getService(k).log("%c[WB] Calling FUNCTION: enableReplyAvatars","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_REPLY_AVATARS_TRIGGERED),this.getService(Re).enableReplyAvatars()}catch(o){this.getService(k).catch("Error in _enableReplyAvatars: ",o);return}}_disableReplyAvatars(){this.getService(k).log("%c[WB] Calling FUNCTION: disableReplyAvatars","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_REPLY_AVATARS_TRIGGERED),this.getService(Re).disableReplyAvatars()}catch(o){this.getService(k).catch("Error in _disableReplyAvatars: ",o);return}}_setMaxReplyAvatars(o){this.getService(k).log("%c[WB] Calling FUNCTION: setMaxReplyAvatars","color: green;");try{this.trackEvent(Y.Events.Comments.SET_MAX_REPLY_AVATARS_TRIGGERED,{payload:{maxReplyAvatars:o}}),this.getService(Re).setMaxReplyAvatars(o)}catch(r){this.getService(k).catch("Error in _setMaxReplyAvatars: ",r);return}}_setSidebarButtonCountType(o){this.getService(k).log("%c[WB] Calling FUNCTION: setSidebarButtonCountType","color: green;");try{this.trackEvent(Y.Events.Comments.SET_SIDEBAR_BUTTON_COUNT_TYPE_TRIGGERED,{payload:{type:o}}),this.getService(Re).setSidebarButtonCountType(o)}catch(r){this.getService(k).catch("Error in _setSidebarButtonCountType: ",r);return}}_enableFilterGhostCommentsInSidebar(){this.getService(k).log("%c[WB] Calling FUNCTION: enableFilterGhostCommentsInSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_FILTER_GHOST_COMMENTS_IN_SIDEBAR_TRIGGERED),this.getService(Re).enableFilterGhostCommentsInSidebar()}catch(o){this.getService(k).catch("Error in _enableFilterGhostCommentsInSidebar: ",o);return}}_disableFilterGhostCommentsInSidebar(){this.getService(k).log("%c[WB] Calling FUNCTION: disableFilterGhostCommentsInSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_FILTER_GHOST_COMMENTS_IN_SIDEBAR_TRIGGERED),this.getService(Re).disableFilterGhostCommentsInSidebar()}catch(o){this.getService(k).catch("Error in _disableFilterGhostCommentsInSidebar: ",o);return}}_enableFullScreenInSidebar(){this.getService(k).log("%c[WB] Calling FUNCTION: enableFullScreenInSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_FULL_SCREEN_IN_SIDEBAR_TRIGGERED),this.getService(Re).enableFullScreenInSidebar()}catch(o){this.getService(k).catch("Error in _enableFullScreenInSidebar: ",o);return}}_disableFullScreenInSidebar(){this.getService(k).log("%c[WB] Calling FUNCTION: disableFullScreenInSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_FULL_SCREEN_IN_SIDEBAR_TRIGGERED),this.getService(Re).disableFullScreenInSidebar()}catch(o){this.getService(k).catch("Error in _disableFullScreenInSidebar: ",o);return}}_setComposerFileAttachments(o){this.getService(k).log("%c[WB] Calling FUNCTION: setComposerFileAttachments","color: green;");try{this.getService(Re).setComposerFileAttachments(o),this.trackEvent(Y.Events.Comments.SET_COMPOSER_FILE_ATTACHMENTS_TRIGGERED,{payload:{data:o}})}catch(r){this.getService(k).catch("Error in _setComposerFileAttachments: ",r);return}}_setAllowedFileTypes(o){this.getService(k).log("%c[WB] Calling FUNCTION: setAllowedFileTypes","color: green;");try{this.trackEvent(Y.Events.Comments.COMMENT_ATTACHMENT_SET_ALLOWED_FILE_TYPES_TRIGGERED,{payload:{allowedFileTypes:o}}),this.getService(Re).setAllowedFileTypes(o)}catch(r){this.getService(k).catch("Error in _setAllowedFileTypes: ",r);return}}_enableForceCloseAllOnEsc(){this.getService(k).log("%c[WB] Calling FUNCTION: enableForceCloseAllOnEsc","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_FORCE_CLOSE_ALL_ON_ESC_TRIGGERED),this.getService(Re).enableForceCloseAllOnEsc()}catch(o){this.getService(k).catch("Error in _enableForceCloseAllOnEsc: ",o);return}}_disableForceCloseAllOnEsc(){this.getService(k).log("%c[WB] Calling FUNCTION: disableForceCloseAllOnEsc","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_FORCE_CLOSE_ALL_ON_ESC_TRIGGERED),this.getService(Re).disableForceCloseAllOnEsc()}catch(o){this.getService(k).catch("Error in _disableForceCloseAllOnEsc: ",o);return}}_markAsRead(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: markAsRead","color: green;");try{this.trackEvent(Y.Events.Comments.MARK_AS_READ_TRIGGERED,{payload:{annotationId:o}}),yield this.getService(Re).markAsRead(o);return}catch(r){this.getService(k).catch("Error in _markAsRead: ",r);return}})}_markAsUnread(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: markAsUnread","color: green;");try{this.trackEvent(Y.Events.Comments.MARK_AS_UNREAD_TRIGGERED,{payload:{annotationId:o}}),yield this.getService(Re).markAsUnread(o)}catch(r){this.getService(k).catch("Error in _markAsUnread: ",r);return}})}_enableScreenshot(){this.getService(k).log("%c[WB] Calling FUNCTION: enableScreenshot","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SCREENSHOT_TRIGGERED),this.getService(Re).enableScreenshot()}catch(o){this.getService(k).catch("Error in _enableScreenshot: ",o);return}}_disableScreenshot(){this.getService(k).log("%c[WB] Calling FUNCTION: disableScreenshot","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SCREENSHOT_TRIGGERED),this.getService(Re).disableScreenshot()}catch(o){this.getService(k).catch("Error in _disableScreenshot: ",o);return}}_enablePaginatedContactList(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePaginatedContactList","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_PAGINATED_CONTACT_LIST_TRIGGERED),this.getService(Re).enablePaginatedContactList()}catch(o){this.getService(k).catch("Error in _enablePaginatedContactList: ",o);return}}_disablePaginatedContactList(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePaginatedContactList","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_PAGINATED_CONTACT_LIST_TRIGGERED),this.getService(Re).disablePaginatedContactList()}catch(o){this.getService(k).catch("Error in _disablePaginatedContactList: ",o);return}}};var iU=class extends Cr{constructor(o){super(o),this.getService(k).log("%c[WB] Creating CLASS: ContactElement","color: blue;"),this.isUserGlobalContact=this._isUserGlobalContact,this.onContactSelected=this._onContactSelected,this.enableAtHere=this._enableAtHere,this.setAtHereLabel=this._setAtHereLabel,this.setAtHereDescription=this._setAtHereDescription,this.disableAtHere=this._disableAtHere,this.updateContactListScopeForOrganizationUsers=this._updateContactListScopeForOrganizationUsers,this.updateContactList=this._updateContactList,this.getContactList=this._getContactList}_isUserGlobalContact(){this.getService(k).log("%c[WB] Calling FUNCTION: isUserGlobalContact","color: green;");try{return this.trackEvent(Y.Events.Contact.IS_USER_GLOBAL_CONTACT_TRIGGERED),this.getService(vn).isUserGlobalContact$()}catch(o){return this.getService(k).catch("Error in _isUserGlobalContact: ",o),ce(!1)}}_onContactSelected(){this.getService(k).log("%c[WB] Calling FUNCTION: onContactSelected","color: green;");try{return this.trackEvent(Y.Events.Contact.ON_CONTACT_SELECTED_TRIGGERED),this.getService(vn).onContactSelected$()}catch(o){return this.getService(k).catch("Error in _onContactSelected: ",o),ce(null)}}_enableAtHere(){this.getService(k).log("%c[WB] Calling FUNCTION: enableAtHere","color: green;");try{this.trackEvent(Y.Events.Contact.ENABLE_AT_HERE_TRIGGERED),this.getService(vn).enableAtHere()}catch(o){this.getService(k).catch("Error in _enableAtHere: ",o)}}_setAtHereLabel(o){this.getService(k).log("%c[WB] Calling FUNCTION: setAtHereLabel","color: green;");try{this.trackEvent(Y.Events.Contact.SET_AT_HERE_LABEL_TRIGGERED,{payload:{label:o}}),this.getService(vn).setAtHereLabel(o)}catch(r){this.getService(k).catch("Error in setAtHereLabel: ",r)}}_setAtHereDescription(o){this.getService(k).log("%c[WB] Calling FUNCTION: setAtHereDescription","color: green;");try{this.trackEvent(Y.Events.Contact.SET_AT_HERE_DESCRIPTION_TRIGGERED,{payload:{description:o}}),this.getService(vn).setAtHereDescription(o)}catch(r){this.getService(k).catch("Error in setAtHereDescription: ",r)}}_disableAtHere(){this.getService(k).log("%c[WB] Calling FUNCTION: disableAtHere","color: green;");try{this.trackEvent(Y.Events.Contact.DISABLE_AT_HERE_TRIGGERED),this.getService(vn).disableAtHere()}catch(o){this.getService(k).catch("Error in _disableAtHere: ",o)}}_updateContactListScopeForOrganizationUsers(o){this.getService(k).log("%c[WB] Calling FUNCTION: updateContactListScopeForOrganizationUsers","color: green;");try{this.trackEvent(Y.Events.Contact.UPDATE_CONTACT_LIST_SCOPE_FOR_ORGANIZATION_USERS_TRIGGERED,{payload:{scope:o}}),this.getService(vn).updateContactListScopeForOrganizationUsers(o)}catch(r){this.getService(k).catch("Error in _updateContactListScopeForOrganizationUsers: ",r)}}_updateContactList(o,r){this.getService(k).log("%c[WB] Calling FUNCTION: _updateContactList","color: green;");try{this.trackEvent(Y.Events.Contact.UPDATE_CONTACT_LIST_TRIGGERED,{payload:{userContacts:o,config:r}}),typeof o=="object"&&o instanceof Array&&(!r||r&&typeof r=="object")&&(o=JSON.parse(JSON.stringify(o)),this.getService(vn).convert(r).updateContactList(o,r))}catch(e){this.getService(k).catch("Error in _updateContactList: ",e)}}_getContactList(){this.getService(k).log("%c[WB] Calling FUNCTION: getContactList","color: green;");try{return this.trackEvent(Y.Events.Contact.GET_CONTACT_LIST_TRIGGERED),this.getService(vn).getContactList$()}catch(o){return this.getService(k).catch("Error in _getContactList: ",o),ce(null)}}};var aU=(()=>{let o=class o{constructor(e){this.loggingService=e,this.actionSubjects=new Map,this.subscriptions=[]}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new at),this.actionSubjects.get(e)?.next(t)}catch(i){this.loggingService.catch("Error in CrdtActionsService triggerAction: ",i)}}onAction(e){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new at);let t=this.actionSubjects.get(e);return t?t.asObservable():ce(null)}catch(t){return this.loggingService.catch("Error in CrdtActionsService onAction: ",t),ce(null)}}};o.\u0275fac=function(t){return new(t||o)(K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Rs=(()=>{let o=class o{static generateKey(){return X(this,null,function*(){try{return yield window.crypto.subtle.generateKey({name:"AES-GCM",length:this.KEY_LENGTH},!1,["encrypt","decrypt"])}catch(e){return it.catch("Failed to generate key: ",e),null}})}static deriveKeyFromPassword(e,t){return X(this,null,function*(){try{if(!t){let c=yield window.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));t=new Uint8Array(c).slice(0,this.SALT_LENGTH)}let i=new TextEncoder().encode(e),a=yield window.crypto.subtle.importKey("raw",i,"PBKDF2",!1,["deriveBits","deriveKey"]);return{key:yield window.crypto.subtle.deriveKey({name:"PBKDF2",salt:t,iterations:this.PBKDF2_ITERATIONS,hash:"SHA-256"},a,{name:"AES-GCM",length:this.KEY_LENGTH},!1,["encrypt","decrypt"]),salt:t}}catch(i){return it.catch("Failed to derive key from password: ",i),null}})}static resolveKey(e){return X(this,null,function*(){try{if(e.customKey){if(e.customKey instanceof CryptoKey)return{key:e.customKey};if(typeof e.customKey=="string"){let i=yield this.deriveKeyFromPassword(e.customKey,e.customSalt);if(!i)return it.catch("Failed to derive key from password"),null;let{key:a,salt:l}=i;return{key:a,salt:l}}}let t=yield this.generateKey();return t?{key:t}:(it.catch("Failed to generate key"),null)}catch(t){return it.catch("Failed to resolve key: ",t),null}})}static encrypt(i){return X(this,arguments,function*(e,t={}){try{if(t.customEncryptCallback)try{return yield t.customEncryptCallback(e)}catch(_){return it.catch("Custom encryption callback failed: ",_),""}let a=yield this.resolveKey(t);if(!a)return it.catch("Failed to resolve key"),"";let{key:l,salt:c}=a,d;if(t.customIV){if(t.customIV.length!==this.IV_LENGTH)return it.catch(`Custom IV must be exactly ${this.IV_LENGTH} bytes`),"";d=t.customIV}else d=window.crypto.getRandomValues(new Uint8Array(this.IV_LENGTH));let m=new TextEncoder().encode(e),u={name:"AES-GCM",iv:d,tagLength:128};t.additionalData&&(u.additionalData=t.additionalData);try{let _=yield window.crypto.subtle.encrypt(u,l,m),I=new Uint8Array(d.length+_.byteLength);I.set(d,0),I.set(new Uint8Array(_),d.length);let A=8192,M=[];for(let V=0;V<I.length;V+=A){let q=I.slice(V,Math.min(V+A,I.length)),ae="";for(let ye=0;ye<q.length;ye++)ae+=String.fromCharCode(q[ye]);M.push(ae)}return btoa(M.join(""))}catch(_){return it.catch("Encryption failed: ",_),""}}catch(a){return it.catch("Failed to encrypt: ",a),null}})}static decrypt(i){return X(this,arguments,function*(e,t={}){try{if(t.customDecryptCallback)try{return yield t.customDecryptCallback(e)}catch(_){return it.catch("Custom decryption callback failed: ",_),""}let a=yield this.resolveKey(t);if(!a)return it.catch("Failed to resolve key"),"";let{key:l}=a,c=new Uint8Array(atob(e).split("").map(_=>_.charCodeAt(0)));if(c.length<this.IV_LENGTH)return it.catch("Invalid encrypted data: Too short"),"";let d;if(t.customIV){if(t.customIV.length!==this.IV_LENGTH)return it.catch(`Custom IV must be exactly ${this.IV_LENGTH} bytes`),"";d=t.customIV}else d=c.slice(0,this.IV_LENGTH);let m=c.slice(this.IV_LENGTH),u={name:"AES-GCM",iv:d,tagLength:128};t.additionalData&&(u.additionalData=t.additionalData);try{let _=yield window.crypto.subtle.decrypt(u,l,m);return new TextDecoder().decode(_)}catch(_){return it.catch("Decryption failed: ",_),""}}catch(a){return it.catch("Failed to decrypt: ",a),""}})}static encryptData(i){return X(this,arguments,function*(e,t={}){try{let a=JSON.stringify(e);return(yield this.encrypt(a,t))??""}catch(a){return it.catch("Failed to encrypt data: ",a),""}})}static decryptData(i){return X(this,arguments,function*(e,t={}){try{let a=yield this.decrypt(e,t);return JSON.parse(a)}catch(a){return it.catch("Failed to decrypt data: ",a),null}})}};o.IV_LENGTH=12,o.SALT_LENGTH=16,o.PBKDF2_ITERATIONS=1e5,o.KEY_LENGTH=256;let n=o;return n})();var Pi=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I){this.activityService=e,this.analyticsService=t,this.authService=i,this.commonDbService=a,this.commonDbUtilsService=l,this.configService=c,this.crdtActionsService=d,this.docService=m,this.domService=u,this.loggingService=_,this.notificationService=I,this.MIN_WEBHOOK_DEBOUNCE_TIME=5*1e3,this.webhookDebounceTime=this.MIN_WEBHOOK_DEBOUNCE_TIME,this.updateDataWebhookTrigger$=new at,this.updateDataWebhookDebounceSubscription=null,this.pendingWebhookEvent=null,this.webhookEnabled$=new _e(!1),this.lastCrdtDataUpdatedId=null,this.MIN_ACTIVITY_DEBOUNCE_TIME=10*1e3,this.activityDebounceTime=600*1e3,this.editorEditTrackers=new Map;try{this.loggingService.log("%c[WB] Creating CLASS: CrdtService","color: blue;"),this.authService.setCrdtService(this),this.setupUpdateDataWebhookDebounce(),this.docService.addPreDocumentIdChangeFunction("crdt-service",()=>(this.lastCrdtDataUpdatedId=null,Promise.resolve())),this.authService.addPreSignOutFuction("crdt-service",()=>(this.lastCrdtDataUpdatedId=null,Promise.resolve()))}catch(A){this.loggingService.catch("Error in CrdtService constructor: ",A)}}trackCrdtDataUpdated(e){try{if(this.lastCrdtDataUpdatedId===e)return;this.lastCrdtDataUpdatedId=e,this.analyticsService.trackEvent(Y.Events.Crdt.CRDT_DATA_UPDATED,{id:e})}catch(t){this.loggingService.catch("Error in CrdtService trackCrdtDataUpdated: ",t)}}setupUpdateDataWebhookDebounce(){try{this.updateDataWebhookDebounceSubscription&&(this.updateDataWebhookDebounceSubscription.unsubscribe(),this.updateDataWebhookDebounceSubscription=null,this.pendingWebhookEvent=null),this.updateDataWebhookDebounceSubscription=this.updateDataWebhookTrigger$.pipe(ln(e=>{this.pendingWebhookEvent=e}),Qr(this.webhookDebounceTime)).subscribe(e=>{this.pendingWebhookEvent=null,this.webhookEnabled$.value&&e&&this.triggerUpdateDataWebhook(e)},e=>{this.loggingService.catch("Error in CrdtService setupUpdateDataWebhookDebounce subscription: ",e)})}catch(e){this.loggingService.catch("Error in CrdtService setupUpdateDataWebhookDebounce: ",e)}}setWebhookDebounceTime(e){try{e<this.MIN_WEBHOOK_DEBOUNCE_TIME&&(this.loggingService.catch("Error in CrdtService setWebhookDebounceTime: Value must be at least "+this.MIN_WEBHOOK_DEBOUNCE_TIME/1e3+" seconds ("+this.MIN_WEBHOOK_DEBOUNCE_TIME+"ms). Using minimum value."),e=this.MIN_WEBHOOK_DEBOUNCE_TIME),this.pendingWebhookEvent&&this.webhookEnabled$.value&&(this.triggerUpdateDataWebhook(this.pendingWebhookEvent),this.pendingWebhookEvent=null),this.webhookDebounceTime=e,this.setupUpdateDataWebhookDebounce()}catch(t){this.loggingService.catch("Error in CrdtService setWebhookDebounceTime: ",t)}}updateData(a){return X(this,arguments,function*({id:e,state:t,data:i}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: updateData","color: green;");let l=this.docService.getDocumentPaths(),c=this.authService.getUser(),d=this.domService.getTabId();if(c?.userId&&l){let m=It(e),u=c.userId,_=It(c.userId),I=new Date().toISOString(),A=null,M=this.configService.getEncryptionProvider();if(M?.encrypt&&typeof M.encrypt=="function")A=yield M.encrypt({data:t});else{let ye={};ye.customKey=m,A=yield Rs.encryptData(t,ye)}let V={id:e,veltId:m,encryptedState:A,lastUpdate:I,lastUpdatedBy:u,lastUpdatedByVeltUserId:_,sessionId:d},q={methodName:HN.UPDATE_DATA,uniqueId:lt(),timestamp:new Date().getTime(),source:GN.INTERNAL,payload:{id:e,data:i,lastUpdatedBy:u,sessionId:d,lastUpdate:I}},ae=yield this.commonDbService.updateData({feature:"crdtData",properties:{documentId:l?.documentId??"",organizationId:l?.organizationId??"",id:m,skipFirestore:!0},data:V});return this.crdtActionsService.triggerAction(FK.UPDATE_DATA,q),this.trackCrdtDataUpdated(e),this.updateDataWebhookTrigger$.next(q?.payload),this.trackEditForActivity(e),ae}return Promise.resolve(null)}catch(l){return this.loggingService.catch("Error in CrdtService updateData: ",l),Promise.resolve(null)}})}triggerUpdateDataWebhook(e){try{this.updateNotificationsDatabase(e,UK.UPDATE_DATA)}catch(t){this.loggingService.catch("Error in CrdtService triggerUpdateDataWebhook: ",t)}}onDataChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onDataChange","color: green;");let i=It(e),a=this.docService.getDocumentPaths$().pipe(Se(l=>l?this.commonDbService.dbListener({feature:"crdtData",properties:{documentId:l?.documentId??"",organizationId:l?.organizationId??"",id:i,skipFirestore:!0}}).pipe(Se(c=>X(this,null,function*(){try{if(c?.data){if(c.data.encryptedState){let d=null,m=this.configService.getEncryptionProvider();if(m?.decrypt&&typeof m.decrypt=="function")d=yield m.decrypt({data:c.data.encryptedState});else{let u={};u.customKey=i,d=yield Rs.decryptData(c.data.encryptedState,u)}c.data.state=d,delete c.data?.encryptedState}return c}else{if(c?.encryptedState){let d=null,m=this.configService.getEncryptionProvider();if(m?.decrypt&&typeof m.decrypt=="function")d=yield m.decrypt({data:c.encryptedState});else{let u={};u.customKey=i,d=yield Rs.decryptData(c.encryptedState,u)}c.state=d,delete c?.encryptedState}return c}}catch(d){return this.loggingService.catch("Error in CrdtService onDataChange subscription: ",d),null}}))):ce(null))).subscribe(l=>{l&&(l.data?t(l.data):t(l))});return()=>a.unsubscribe()}catch(i){return this.loggingService.catch("Error in CrdtService onDataChange: ",i),()=>{}}}getData(t){return X(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getData","color: green;");let i=this.docService.getDocumentPaths();if(i){let a=It(e),l=yield this.commonDbService.getData({feature:"crdtData",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:a,skipFirestore:!0}});if(l?.encryptedState){let c=null,d=this.configService.getEncryptionProvider();if(d?.decrypt&&typeof d.decrypt=="function")c=yield d.decrypt({data:l.encryptedState});else{let m={};m.customKey=a,c=yield Rs.decryptData(l.encryptedState,m)}l.state=c,delete l?.encryptedState}return l}return Promise.resolve(null)}catch(i){return this.loggingService.catch("Error in CrdtService getData: ",i),Promise.resolve(null)}})}onStateChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onStateChange","color: green;");let i=It(e),a=this.docService.getDocumentPaths$().pipe(Se(l=>l?this.commonDbService.dbListener({feature:"crdtSyncState",properties:{documentId:l?.documentId??"",organizationId:l?.organizationId??"",id:i,skipFirestore:!0}}).pipe(Se(c=>X(this,null,function*(){try{if(c?.data){if(c.data.encryptedState){let d=null,m=this.configService.getEncryptionProvider();if(m?.decrypt&&typeof m.decrypt=="function")d=yield m.decrypt({data:c.data.encryptedState});else{let u={};u.customKey=i,d=yield Rs.decryptData(c.data.encryptedState,u)}c.data.state=d,delete c.data?.encryptedState}return c}else{if(c?.encryptedState){let d=null,m=this.configService.getEncryptionProvider();if(m?.decrypt&&typeof m.decrypt=="function")d=yield m.decrypt({data:c.encryptedState});else{let u={};u.customKey=i,d=yield Rs.decryptData(c.encryptedState,u)}c.state=d,delete c?.encryptedState}return c}}catch(d){return this.loggingService.catch("Error in CrdtService onStateChange subscription: ",d),null}}))):ce(null))).subscribe(l=>{l&&(l.data?t(l.data):t(l))});return()=>a.unsubscribe()}catch(i){return this.loggingService.catch("Error in CrdtService onStateChange: ",i),()=>{}}}updateState(i){return X(this,arguments,function*({id:e,state:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: updateState","color: green;");let a=this.docService.getDocumentPaths(),l=this.authService.getUser(),c=this.domService.getTabId();if(l?.userId&&a){let d=It(e),m=l.userId,u=It(m),_=null,I=this.configService.getEncryptionProvider();if(I?.encrypt&&typeof I.encrypt=="function")_=yield I.encrypt({data:t});else{let A={};A.customKey=d,_=yield Rs.encryptData(t,A)}return this.commonDbService.setData({feature:"crdtSyncState",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:d,skipFirestore:!0},data:{id:e,veltId:d,encryptedState:_,lastUpdate:new Date().toISOString(),lastUpdatedBy:m,lastUpdatedByVeltUserId:u,sessionId:c}})}return Promise.resolve(null)}catch(a){return this.loggingService.catch("Error in CrdtService updateState: ",a),Promise.resolve(null)}})}registerSyncUser(t){return X(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: registerSyncUser","color: green;");let i=this.authService.getUser(),a=this.docService.getDocumentPaths(),l=this.configService.getApiKey(),c=It(e),d=this.domService.getTabId();if(i?.userId&&a&&l){let m=i.userId,u=It(m),_={documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:c,userId:u,apiKey:l,skipFirestore:!0},I={userId:m,veltUserId:u,status:"online",lastSeen:Date.now(),sessionId:d};yield this.commonDbService.setData({feature:"crdtSyncPresence",properties:_,data:I});let A=this.commonDbUtilsService.getDocumentPath({feature:"crdtSyncPresence",properties:_,defaultDocumentPaths:a,apiKey:l});A&&(yield this.commonDbService.setupOnDisconnect(A,{status:"offline",lastSeen:new Date().getTime(),sessionId:d}))}}catch(i){this.loggingService.catch("Error in CrdtService registerSyncUser: ",i)}})}onRegisteredUserChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onRegisteredUserChange","color: green;");let i=It(e),a=this.docService.getDocumentPaths$().pipe(Se(l=>l?this.commonDbService.dbListener({feature:"allCrdtSyncPresence",properties:{documentId:l?.documentId??"",organizationId:l?.organizationId??"",id:i,skipFirestore:!0}}).pipe(ln(c=>{try{c?.data?t(c.data):t(c)}catch(d){this.loggingService.catch("Error in CrdtService onRegisteredUserChange subscription: ",d)}})):ce(null))).subscribe(()=>{});return()=>a.unsubscribe()}catch(i){return this.loggingService.catch("Error in CrdtService onRegisteredUserChange: ",i),()=>{}}}setPresence(t){return X(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: setPresence","color: green;");let i=this.authService.getUser(),a=this.docService.getDocumentPaths(),l=this.configService.getApiKey(),c=It(e),d=this.domService.getTabId();if(i?.userId&&a&&l){let m=i.userId,u=It(m),_={documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:c,userId:u,apiKey:l,skipFirestore:!0},I={userId:m,veltUserId:u,status:"online",lastSeen:Date.now(),sessionId:d};yield this.commonDbService.setData({feature:"crdtPresence",properties:_,data:I});let A=this.commonDbUtilsService.getDocumentPath({feature:"crdtPresence",properties:_,defaultDocumentPaths:a,apiKey:l});A&&(yield this.commonDbService.setupOnDisconnect(A,{status:"offline",lastSeen:new Date().getTime(),sessionId:d}))}}catch(i){this.loggingService.catch("Error in CrdtService setPresence: ",i)}})}onPresenceChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onPresenceChange","color: green;");let i=It(e),a=this.docService.getDocumentPaths$().pipe(Se(l=>l?this.commonDbService.dbListener({feature:"allCrdtPresence",properties:{documentId:l?.documentId??"",organizationId:l?.organizationId??"",id:i,skipFirestore:!0}}).pipe(ln(c=>{try{c?.data?t(c.data):t(c)}catch(d){this.loggingService.catch("Error in CrdtService onPresenceChange subscription: ",d)}})):ce(null))).subscribe(()=>{});return()=>a.unsubscribe()}catch(i){return this.loggingService.catch("Error in CrdtService onPresenceChange: ",i),()=>{}}}saveVersion(l){return X(this,arguments,function*({id:e,versionId:t,versionName:i,state:a}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: saveVersion","color: green;");let c=this.docService.getDocumentPaths();if(c){let d=It(e),m="",u=this.configService.getEncryptionProvider();if(u?.encrypt&&typeof u.encrypt=="function")m=yield u.encrypt({data:a});else{let I={};I.customKey=d,m=yield Rs.encryptData(a,I)}let _={versionId:t,versionName:i,encryptedState:m,timestamp:new Date().getTime()};return this.commonDbService.setData({feature:"crdtVersion",properties:{documentId:c?.documentId??"",organizationId:c?.organizationId??"",id:d,versionId:t,skipFirestore:!0},data:h({id:e},_)})}return Promise.resolve(null)}catch(c){return this.loggingService.catch("Error in CrdtService saveVersion: ",c),Promise.resolve(null)}})}getVersion(i){return X(this,arguments,function*({id:e,versionId:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getVersion","color: green;");let a=this.docService.getDocumentPaths();if(a){let l=It(e),c=yield this.commonDbService.getData({feature:"crdtVersion",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:l,versionId:t,skipFirestore:!0}});if(c?.encryptedState){let d=null,m=this.configService.getEncryptionProvider();if(m?.decrypt&&typeof m.decrypt=="function")d=yield m.decrypt({data:c.encryptedState});else{let u={};u.customKey=l,d=yield Rs.decryptData(c.encryptedState,u)}c.state=d,delete c.encryptedState}return c}return Promise.resolve(null)}catch(a){return this.loggingService.catch("Error in CrdtService getVersion: ",a),Promise.resolve(null)}})}getVersions(t){return X(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getVersions","color: green;");let i=this.docService.getDocumentPaths();if(i){let a=It(e),l=yield this.commonDbService.getData({feature:"crdtVersions",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:a,skipFirestore:!0}}),c=null;if(l){c=[];for(let d of Object.values(l))if(d?.encryptedState){let m=null,u=this.configService.getEncryptionProvider();if(u?.decrypt&&typeof u.decrypt=="function")m=yield u.decrypt({data:d.encryptedState});else{let I={};I.customKey=a,m=yield Rs.decryptData(d.encryptedState,I)}let _=y(h({},d),{state:m});delete _?.encryptedState,c.push(_)}else c.push(d)}return c}return Promise.resolve(null)}catch(i){return this.loggingService.catch("Error in CrdtService getVersions: ",i),Promise.resolve(null)}})}encryptCrdtData(e,t){return X(this,null,function*(){try{let i=this.configService.getEncryptionProvider();if(i?.encrypt&&typeof i.encrypt=="function")return yield i.encrypt({data:e});let a={};return a.customKey=t,yield Rs.encryptData(e,a)}catch(i){return this.loggingService.catch("Error in CrdtService encryptCrdtData: ",i),null}})}decryptCrdtData(e,t){return X(this,null,function*(){try{let i=this.configService.getEncryptionProvider();if(i?.decrypt&&typeof i.decrypt=="function")return yield i.decrypt({data:e});let a={};return a.customKey=t,yield Rs.decryptData(e,a)}catch(i){return this.loggingService.catch("Error in CrdtService decryptCrdtData: ",i),null}})}pushMessage(u){return X(this,arguments,function*({id:e,data:t,yjsClientId:i,messageType:a,eventData:l,type:c,contentKey:d,source:m}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: pushMessage","color: green;");let _=this.docService.getDocumentPaths(),I=this.authService.getUser();if(I?.userId&&_){let A=It(e),M=yield this.encryptCrdtData(t,A);if(M==null)return;let V=I.userId,q=It(I.userId),ae=this.domService.getTabId();if(yield this.commonDbService.pushData({feature:"crdtMessages",properties:{documentId:_?.documentId??"",organizationId:_?.organizationId??"",id:A,skipFirestore:!0},data:{id:e,veltId:A,encryptedData:M,yjsClientId:i,messageType:a??null,type:c??null,contentKey:d??null,source:m??"unknown",updatedByUserId:V,updatedByVeltUserId:q,sessionId:ae,timestamp:this.commonDbService.getServerTimestamp()}}),a==="sync"){let ye=new Date().toISOString(),ie={methodName:HN.UPDATE_DATA,uniqueId:lt(),timestamp:new Date().getTime(),source:GN.INTERNAL,payload:{id:e,data:l,lastUpdatedBy:V,sessionId:ae,lastUpdate:ye}};this.crdtActionsService.triggerAction(FK.UPDATE_DATA,ie),this.trackCrdtDataUpdated(e),this.updateDataWebhookTrigger$.next(ie?.payload),this.trackEditForActivity(e)}}}catch(_){this.loggingService.catch("Error in CrdtService pushMessage: ",_)}})}onMessage({id:e,callback:t,afterTs:i}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onMessage","color: green;");let a=It(e),l=this.docService.getDocumentPaths$().pipe(Se(c=>c?this.commonDbService.streamChildAdded({feature:"crdtMessages",properties:{documentId:c?.documentId??"",organizationId:c?.organizationId??"",id:a,skipFirestore:!0},afterTs:i}):ce(null))).pipe(Ge(c=>!!c),Dw(c=>X(this,null,function*(){try{if(c.encryptedData){let d=yield this.decryptCrdtData(c.encryptedData,a);if(d==null)return null;c.data=d,delete c.encryptedData}else if(!c.data)return null;return c}catch(d){return this.loggingService.catch("Error in CrdtService onMessage decryption: ",d),null}})),Ge(c=>!!c)).subscribe(c=>{try{t(c)}catch(d){this.loggingService.catch("Error in CrdtService onMessage subscription: ",d)}});return()=>l.unsubscribe()}catch(a){return this.loggingService.catch("Error in CrdtService onMessage: ",a),()=>{}}}getMessages(i){return X(this,arguments,function*({id:e,afterTs:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getMessages","color: green;");let a=this.docService.getDocumentPaths();if(a){let l=It(e),c=yield this.commonDbService.getData({feature:"crdtMessages",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:l,skipFirestore:!0}});if(!c||typeof c!="object"||c?.errorCode)return[];let d=[];for(let m of Object.keys(c)){let u=c[m];if(!(!u||typeof u!="object")&&!(t!=null&&u.timestamp!=null&&u.timestamp<=t))if(u.encryptedData){let _=yield this.decryptCrdtData(u.encryptedData,l);if(_==null)continue;d.push({data:_,yjsClientId:u.yjsClientId,timestamp:u.timestamp})}else u.data&&d.push({data:u.data,yjsClientId:u.yjsClientId,timestamp:u.timestamp})}return d.sort((m,u)=>m.timestamp-u.timestamp),d}return[]}catch(a){return this.loggingService.catch("Error in CrdtService getMessages: ",a),[]}})}getSnapshot(t){return X(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getSnapshot","color: green;");let i=this.docService.getDocumentPaths();if(i){let a=It(e),l=yield this.commonDbService.getData({feature:"crdtSnapshot",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:a,skipFirestore:!0}});if(!l||typeof l!="object"||Object.keys(l).length===0||l?.errorCode)return null;if(l?.encryptedState){let c=yield this.decryptCrdtData(l.encryptedState,a);if(c==null)return null;l.state=c,delete l?.encryptedState}if(l?.encryptedVector){let c=yield this.decryptCrdtData(l.encryptedVector,a);if(c==null)return null;l.vector=c,delete l?.encryptedVector}return l}return Promise.resolve(null)}catch(i){return this.loggingService.catch("Error in CrdtService getSnapshot: ",i),Promise.resolve(null)}})}saveSnapshot(d){return X(this,arguments,function*({id:e,state:t,vector:i,type:a,contentKey:l,source:c}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: saveSnapshot","color: green;");let m=this.docService.getDocumentPaths(),u=this.authService.getUser();if(u?.userId&&m){let _=It(e),I=yield this.encryptCrdtData(t,_),A=yield this.encryptCrdtData(i,_);if(I==null||A==null)return;let M=u.userId,V=It(u.userId),q=this.domService.getTabId();yield this.commonDbService.setData({feature:"crdtSnapshot",properties:{documentId:m?.documentId??"",organizationId:m?.organizationId??"",id:_,skipFirestore:!0},data:{id:e,veltId:_,encryptedState:I,encryptedVector:A,type:a??null,contentKey:l??null,source:c??"unknown",updatedByUserId:M,updatedByVeltUserId:V,sessionId:q,timestamp:this.commonDbService.getServerTimestamp()}})}}catch(m){this.loggingService.catch("Error in CrdtService saveSnapshot: ",m)}})}pruneMessages(i){return X(this,arguments,function*({id:e,beforeTs:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: pruneMessages","color: green;");let a=this.docService.getDocumentPaths();if(a){let l=It(e),c=yield this.commonDbService.getData({feature:"crdtMessages",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:l,skipFirestore:!0}});if(c&&typeof c=="object"&&!c?.errorCode){let d=[];for(let m of Object.keys(c)){let u=c[m];u?.timestamp!=null&&u.timestamp<t&&d.push(this.commonDbService.deleteData({feature:"crdtMessage",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:l,messageId:m,skipFirestore:!0}}))}yield Promise.all(d)}}}catch(a){this.loggingService.catch("Error in CrdtService pruneMessages: ",a)}})}updateNotificationsDatabase(e,t,i={}){try{let a=h({crdtData:e,actionType:t,notificationSource:"crdt"},i);this.notificationService.updateNotificationDatabase(a)}catch(a){this.loggingService.catch("Error in CrdtService updateNotificationsDatabase: ",a)}}enableWebhook(){try{if(this.webhookEnabled$.value===!0)return;this.webhookEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CrdtService enableWebhook: ",e)}}disableWebhook(){try{if(this.webhookEnabled$.value===!1)return;this.webhookEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CrdtService disableWebhook: ",e)}}trackEditForActivity(e){try{let t=this.editorEditTrackers.get(e);if(!t){let i=new at,a=i.pipe(Qr(this.activityDebounceTime)).subscribe(()=>{this.flushEditorActivity(e)});t={count:0,subject$:i,subscription:a},this.editorEditTrackers.set(e,t)}t.count++,t.subject$.next()}catch(t){this.loggingService.catch("Error in CrdtService trackEditForActivity: ",t)}}flushEditorActivity(e){try{let t=this.editorEditTrackers.get(e);if(!t||t.count===0)return;let i=t.count;t.count=0;let a={featureType:"crdt",actionType:zpe.EDITOR_EDIT,targetEntityId:e,entityData:{editCount:i}};this.activityService.createActivity(a)}catch(t){this.loggingService.catch("Error in CrdtService flushEditorActivity: ",t)}}setActivityDebounceTime(e){try{e<this.MIN_ACTIVITY_DEBOUNCE_TIME&&(this.loggingService.catch("Error in CrdtService setActivityDebounceTime: Value must be at least "+this.MIN_ACTIVITY_DEBOUNCE_TIME/1e3+" seconds ("+this.MIN_ACTIVITY_DEBOUNCE_TIME+"ms). Using minimum value."),e=this.MIN_ACTIVITY_DEBOUNCE_TIME),this.flushAllEditorActivities(),this.activityDebounceTime=e}catch(t){this.loggingService.catch("Error in CrdtService setActivityDebounceTime: ",t)}}flushAllEditorActivities(){try{for(let[e,t]of this.editorEditTrackers)t.count>0&&this.flushEditorActivity(e),t.subject$.complete(),t.subscription.unsubscribe();this.editorEditTrackers.clear()}catch(e){this.loggingService.catch("Error in CrdtService flushAllEditorActivities: ",e)}}};o.\u0275fac=function(t){return new(t||o)(K(Lg),K(ct),K(qe),K(yn),K(vd),K(Ft),K(aU),K(st),K(Ve),K(k),K(mn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var lU=class extends Cr{constructor(o){super(o),this.getService(k).log("%c[WB] Creating CLASS: CrdtElement","color: blue;"),this.updateData=this._updateData,this.onDataChange=this._onDataChange,this.getData=this._getData,this.onStateChange=this._onStateChange,this.updateState=this._updateState,this.registerSyncUser=this._registerSyncUser,this.onRegisteredUserChange=this._onRegisteredUserChange,this.setPresence=this._setPresence,this.onPresenceChange=this._onPresenceChange,this.saveVersion=this._saveVersion,this.getVersion=this._getVersion,this.getVersions=this._getVersions,this.pushMessage=this._pushMessage,this.onMessage=this._onMessage,this.getMessages=this._getMessages,this.getSnapshot=this._getSnapshot,this.saveSnapshot=this._saveSnapshot,this.pruneMessages=this._pruneMessages,this.enableWebhook=this._enableWebhook,this.disableWebhook=this._disableWebhook,this.setWebhookDebounceTime=this._setWebhookDebounceTime,this.setActivityDebounceTime=this._setActivityDebounceTime,this.on=this._on}_updateData(o){this.getService(k).log("%c[WB] Calling FUNCTION: updateData","color: green;");try{return this.getService(Pi).updateData(o)}catch(r){return this.getService(k).catch("Error in updateData: ",r),Promise.resolve(null)}}_onDataChange(o){this.getService(k).log("%c[WB] Calling FUNCTION: onDataChange","color: green;");try{return this.getService(Pi).onDataChange(o)}catch(r){return this.getService(k).catch("Error in onDataChange: ",r),()=>{}}}_getData(o){this.getService(k).log("%c[WB] Calling FUNCTION: getData","color: green;");try{return this.getService(Pi).getData(o)}catch(r){return this.getService(k).catch("Error in getData: ",r),Promise.resolve(null)}}_onStateChange(o){this.getService(k).log("%c[WB] Calling FUNCTION: onStateChange","color: green;");try{return this.getService(Pi).onStateChange(o)}catch(r){return this.getService(k).catch("Error in onStateChange: ",r),()=>{}}}_updateState(o){this.getService(k).log("%c[WB] Calling FUNCTION: updateState","color: green;");try{return this.getService(Pi).updateState(o)}catch(r){return this.getService(k).catch("Error in updateState: ",r),Promise.resolve(null)}}_registerSyncUser(o){this.getService(k).log("%c[WB] Calling FUNCTION: registerSyncUser","color: green;");try{return this.getService(Pi).registerSyncUser(o)}catch(r){return this.getService(k).catch("Error in registerSyncUser: ",r),Promise.resolve()}}_onRegisteredUserChange(o){this.getService(k).log("%c[WB] Calling FUNCTION: onRegisteredUserChange","color: green;");try{return this.getService(Pi).onRegisteredUserChange(o)}catch(r){return this.getService(k).catch("Error in onRegisteredUserChange: ",r),()=>{}}}_setPresence(o){this.getService(k).log("%c[WB] Calling FUNCTION: setPresence","color: green;");try{return this.getService(Pi).setPresence(o)}catch(r){return this.getService(k).catch("Error in setPresence: ",r),Promise.resolve()}}_onPresenceChange(o){this.getService(k).log("%c[WB] Calling FUNCTION: onPresenceChange","color: green;");try{return this.getService(Pi).onPresenceChange(o)}catch(r){return this.getService(k).catch("Error in onPresenceChange: ",r),()=>{}}}_saveVersion(o){this.getService(k).log("%c[WB] Calling FUNCTION: saveVersion","color: green;");try{return this.getService(Pi).saveVersion(o)}catch(r){return this.getService(k).catch("Error in saveVersion: ",r),Promise.resolve(null)}}_getVersion(o){this.getService(k).log("%c[WB] Calling FUNCTION: getVersion","color: green;");try{return this.getService(Pi).getVersion(o)}catch(r){return this.getService(k).catch("Error in getVersion: ",r),Promise.resolve(null)}}_getVersions(o){this.getService(k).log("%c[WB] Calling FUNCTION: getVersions","color: green;");try{return this.getService(Pi).getVersions(o)}catch(r){return this.getService(k).catch("Error in getVersions: ",r),Promise.resolve(null)}}_pushMessage(o){this.getService(k).log("%c[WB] Calling FUNCTION: pushMessage","color: green;");try{return this.getService(Pi).pushMessage(o)}catch(r){return this.getService(k).catch("Error in pushMessage: ",r),Promise.resolve()}}_onMessage(o){this.getService(k).log("%c[WB] Calling FUNCTION: onMessage","color: green;");try{return this.getService(Pi).onMessage(o)}catch(r){return this.getService(k).catch("Error in onMessage: ",r),()=>{}}}_getMessages(o){this.getService(k).log("%c[WB] Calling FUNCTION: getMessages","color: green;");try{return this.getService(Pi).getMessages(o)}catch(r){return this.getService(k).catch("Error in getMessages: ",r),Promise.resolve([])}}_getSnapshot(o){this.getService(k).log("%c[WB] Calling FUNCTION: getSnapshot","color: green;");try{return this.getService(Pi).getSnapshot(o)}catch(r){return this.getService(k).catch("Error in getSnapshot: ",r),Promise.resolve(null)}}_saveSnapshot(o){this.getService(k).log("%c[WB] Calling FUNCTION: saveSnapshot","color: green;");try{return this.getService(Pi).saveSnapshot(o)}catch(r){return this.getService(k).catch("Error in saveSnapshot: ",r),Promise.resolve()}}_pruneMessages(o){this.getService(k).log("%c[WB] Calling FUNCTION: pruneMessages","color: green;");try{return this.getService(Pi).pruneMessages(o)}catch(r){return this.getService(k).catch("Error in pruneMessages: ",r),Promise.resolve()}}_enableWebhook(){this.getService(k).log("%c[WB] Calling FUNCTION: enableWebhook","color: green;");try{return this.getService(Pi).enableWebhook()}catch(o){this.getService(k).catch("Error in enableWebhook: ",o);return}}_disableWebhook(){this.getService(k).log("%c[WB] Calling FUNCTION: disableWebhook","color: green;");try{return this.getService(Pi).disableWebhook()}catch(o){this.getService(k).catch("Error in disableWebhook: ",o);return}}_setWebhookDebounceTime(o){this.getService(k).log("%c[WB] Calling FUNCTION: setWebhookDebounceTime","color: green;");try{!isNaN(o)&&o>0?this.getService(Pi).setWebhookDebounceTime(o):this.getService(k).catch("Error in setWebhookDebounceTime: ","Provided value must be a positive number greater than zero.")}catch(r){this.getService(k).catch("Error in setWebhookDebounceTime: ",r)}}_setActivityDebounceTime(o){this.getService(k).log("%c[WB] Calling FUNCTION: setActivityDebounceTime","color: green;");try{!isNaN(o)&&o>=1e4?this.getService(Pi).setActivityDebounceTime(o):this.getService(k).catch("Error in setActivityDebounceTime: ","Provided value must be a number >= 10000ms (10 seconds).")}catch(r){this.getService(k).catch("Error in setActivityDebounceTime: ",r)}}_on(o){this.getService(k).log("%c[WB] Calling FUNCTION: on","color: green;");try{return this.getService(aU).onAction(o)}catch(r){return this.getService(k).catch("Error in on: ",r),ce(null)}}};var wc=(function(n){return n.CLICK="click",n.HOVER="hover",n.SCROLL="scroll",n.NAVIGATE="navigate",n})(wc||{}),Ug=class{constructor(){this.type=wc.HOVER,this.data=null,this.pageInfo=ro(),this.timestamp=Date.now()}},cU=class{constructor(o,r){this.targetXpath=o,this.xpath=r}};var sU=class{constructor(){this.sessionId=null,this.isLeader=!1,this.lastProcessedActionTimestamp=null}};var K0=class{constructor(o){this.snippylyId=o,this.joinTimestamp=Date.now()}};var dU=class{constructor(o,r,e){this.followers=[],this.actionStack=[],this.id=lt(),this.leaderId=o,this.leaderName=r,this.followers.push(new K0(e))}};var Wbe=(()=>{let o=class o{constructor(e,t,i,a,l){this.databaseService=e,this.docService=t,this.loggingService=i,this.authService=a,this.commonDbService=l,this.currentUser$=new _e(null),this.currentSession$=new _e(null);try{this.databaseService.getDb().pipe(Ge(c=>!!c),ut(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,i){try{let a=this.docService.getDocumentPaths();a&&this.db&&this.commonDbService.dbListener({feature:"flockUser",properties:{documentId:a?.documentId,organizationId:a?.organizationId,id:e,skipFirestore:!0}}).pipe(ut(1)).subscribe(l=>{l?.data&&l?.data?.sessionId?this.subscribeToCurrentSession(l?.data?.sessionId,i):this.createFlockSession(e,t,i)})}catch(a){this.loggingService.catch("Error in FlockSessionService provisionFlockSession: ",a)}return null}swapLeader(e,t,i){try{if(this.updateRemoteFlockUser(e,{isLeader:!1}),this.updateRemoteFlockUser(t,{isLeader:!0}),this.currentSession){this.currentSession.leaderId=t,this.currentSession.leaderName=i,this.currentSession.followers.push(new K0(e));let a=this.currentSession.followers.findIndex(l=>l.snippylyId===t);a>-1&&this.currentSession.followers.splice(a,1),this.updateSession(this.currentSession.id,this.currentSession)}}catch(a){this.loggingService.catch("Error in FlockSessionService swapLeader: ",a)}}createFlockSession(e,t,i){try{let a=new dU(e,t,i);return this.updateRemoteFlockUser(e,{snippylyId:e,sessionId:a.id,isLeader:!0}),this.updateSession(a.id,a),this.subscribeToCurrentSession(a.id),a.id}catch(a){this.loggingService.catch("Error in FlockSessionService createFlockSession: ",a)}return null}removeFollowerFromCurrentSession(e){try{if(this.currentSession){this.updateRemoteFlockUser(e,{sessionId:null,lastProcessedActionTimestamp:null});let t=this.currentSession.followers.findIndex(i=>i.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 i=this.docService.getDocumentPaths();for(let a in t)t.hasOwnProperty(a)&&t[a]===void 0&&delete t[a];i&&this.db&&this.commonDbService.updateData({feature:"flockUser",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:e,skipFirestore:!0},data:JSON.parse(JSON.stringify(t))})}catch(i){this.loggingService.catch("Error in FlockSessionService updateRemoteFlockUser: ",i)}}subscribeToCurrentSession(e,t=void 0){try{let i=this.docService.getDocumentPaths();i&&this.db&&(this.sessionSub&&this.sessionSub.unsubscribe(),this.sessionSub=this.commonDbService.dbListener({feature:"flockSession",properties:{documentId:i?.documentId,organizationId:i?.organizationId,id:e,skipFirestore:!0}}).subscribe(a=>{a?.data&&typeof a?.data=="object"&&Object.keys(a?.data)?.length>0?(this.currentSession=a?.data,t!==void 0&&this.currentSession?.followers.findIndex(l=>l.snippylyId===t)===-1&&(this.currentSession.followers.push(new K0(t)),this.updateSession(this.currentSession.id,this.currentSession)),this.currentSession$.next(this.currentSession??null)):(this.currentSession=void 0,this.currentSession$.next(null))}))}catch(i){this.loggingService.catch("Error in FlockSessionService subscribeToCurrentSession: ",i)}}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(Xn(i=>(this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser: ",i),ce(null)))).subscribe(i=>{i?.data&&typeof i?.data=="object"&&Object.keys(i?.data)?.length>0&&(this.currentUser$.next(i?.data),i?.data?.sessionId&&this.subscribeToCurrentSession(i?.data?.sessionId))},i=>{this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser subscription: ",i)}))}catch(t){this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser: ",t)}}updateSession(e,t={}){try{if(!e)return;let i=this.docService.getDocumentPaths();for(let a in t)t.hasOwnProperty(a)&&t[a]===void 0&&delete t[a];i&&this.db&&this.commonDbService.updateData({feature:"flockSession",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:e,skipFirestore:!0},data:JSON.parse(JSON.stringify(t))})}catch(i){this.loggingService.catch("Error in FlockSessionService updateSession: ",i)}}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(i=>{this.updateRemoteFlockUser(i.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 i=this.docService.getDocumentPaths();if(i&&this.db&&e){let a=jr(this.db,`${i.flock}/sessions/${e}/actionStack`);t0(a,l=>l?(l.unshift(t),l.slice(0,5)):[t]),t.type===wc.NAVIGATE&&this.updateSession(e,{pageInfo:t.pageInfo})}}catch(i){this.loggingService.catch("Error in FlockSessionService addActionToStack: ",i)}}};o.\u0275fac=function(t){return new(t||o)(K($n),K(st),K(k),K(qe),K(yn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();function eqe(n,o){if(n&1&&(f(0,"span",6),re(1),R(2,"translate"),S()),n&2){let r=s(2).ngIf;v(),Qi("",F(2,2,"You are following")," ",r.leaderName)}}function tqe(n,o){n&1&&(f(0,"span",6),re(1),R(2,"translate"),S()),n&2&&(v(),Ye(F(2,1,"You are leading.")))}function nqe(n,o){if(n&1){let r=Z();f(0,"div",2),z("click",function(){L(r);let t=s().ngIf,i=s();return U(t.type==="following"?i.closeOverlay():void 0)}),f(1,"div",3),p(2,eqe,3,4,"span",4)(3,tqe,3,3,"span",4),f(4,"button",5),z("click",function(){L(r);let t=s(2);return U(t.closeOverlay())}),re(5),R(6,"translate"),R(7,"translate"),S()()()}if(n&2){let r=s().ngIf;fe("no-pointer",r.type==="leading"),v(2),g("ngIf",r.type==="following"),v(),g("ngIf",r.type==="leading"),v(2),Qi("",F(6,6,"Stop")," ",F(7,8,r.type))}}function rqe(n,o){if(n&1&&(C(0),p(1,nqe,8,10,"div",1),b()),n&2){let r=o.ngIf;v(),g("ngIf",r.leaderName!==""||r.type==="leading")}}var BO=(()=>{let o=class o extends At{closeOverlay(){this.closeOverlayEvent.emit()}constructor(e,t,i,a){super(t,i),this.loggingService=e,this.elementRef=t,this.themeService=i,this.domService=a,this.closeOverlayEvent=new Ue,this.componentConfigSignal=De({leaderName:"",type:"following"})}ngOnInit(){}ngAfterViewInit(){try{this.customCssSubscription=this.domService.subscribeInjectCustomCss(this.elementRef)}catch(e){this.loggingService.catch("Error in FollowOverlayComponent ngAfterViewInit: ",e)}}setLeaderName(e){try{this.componentConfigSignal.update(t=>(t=y(h({},t),{leaderName:e}),t))}catch(t){this.loggingService.catch("Error in FollowOverlayComponent setLeaderName: ",t)}}getLeaderName(){return this.componentConfigSignal().leaderName}setType(e){try{this.componentConfigSignal.update(t=>(t=y(h({},t),{type:e}),t))}catch(t){this.loggingService.catch("Error in FollowOverlayComponent setType: ",t)}}ngOnDestroy(){try{super.ngOnDestroy(),this.customCssSubscription?.unsubscribe()}catch(e){this.loggingService.catch("Error in FollowOverlayComponent ngOnDestroy: ",e)}}};o.\u0275fac=function(t){return new(t||o)(x(k),x(Q),x(yt),x(Ve))},o.\u0275cmp=O({type:o,selectors:[["snippyly-follow-overlay"]],outputs:{closeOverlayEvent:"closeOverlayEvent"},standalone:!1,features:[P],decls:1,vars:1,consts:[[4,"ngIf"],["data-velt-ignore","","class","follow-overlay-container",3,"no-pointer","click",4,"ngIf"],["data-velt-ignore","",1,"follow-overlay-container",3,"click"],["data-velt-ignore","",1,"follow-dialog"],["data-velt-ignore","","class","follow-text",4,"ngIf"],["data-velt-ignore","",1,"follow-btn",3,"click"],["data-velt-ignore","",1,"follow-text"]],template:function(t,i){t&1&&p(0,rqe,2,1,"ng-container",0),t&2&&g("ngIf",i.componentConfigSignal())},styles:[`html{--velt-base-rem-unit: 1}*[data-snippyly-element=true],*[data-velt-element=true]{font-family:var(--velt-default-font-family)}velt-wireframe{display:none!important}body.velt-pin-dragging iframe{pointer-events:none!important}.follow-overlay-container{position:fixed;top:0;left:0;width:100%;height:100%;background-color:transparent;z-index:var(--velt-follow-mode-overlay-z-index);display:flex;justify-content:center;align-items:flex-end}.follow-overlay-container .follow-dialog{background-color:var(--legacy-velt-follow-overlay-bg-color);color:var(--legacy-velt-follow-overlay-text-color);font-size:12px;display:flex;justify-content:center;align-items:center;gap:calc((1.2rem + 0px) * var(--velt-base-rem-unit));padding:calc((.9rem + 0px) * var(--velt-base-rem-unit)) calc((1.1rem + 0px) * var(--velt-base-rem-unit));border-radius:90px;margin-bottom:calc((2rem + 0px) * var(--velt-base-rem-unit));box-shadow:0 8px 16px -8px #0f0f0f1a;border:1px solid var(--legacy-velt-follow-overlay-border-color)}.follow-overlay-container .follow-dialog .follow-btn{background-color:var(--legacy-velt-follow-overlay-btn-color);padding:8px 12px;border-radius:90px;display:inline-flex;justify-content:center;align-items:center;border:none;font-weight:600;font-size:14px;cursor:pointer;pointer-events:all}.follow-overlay-container .follow-dialog .follow-btn:hover{transition:background-color .5s;background-color:var(--legacy-velt-follow-overlay-btn-hover-color)}.follow-overlay-container.no-pointer{pointer-events:none}
500
+ `);for(var t=0;t<d.length;t++)if(d[t].indexOf("-->")!==-1){var i=d[t].split(" --> ")[0],a=d[t].split(" --> ")[1],l=d[t+1];c.push({startTime:i,endTime:a,startTimeInSeconds:this.getTimeInSecondsFromVttTime(i),endTimeInSeconds:this.getTimeInSecondsFromVttTime(a),text:l})}return c}catch(c){return this.loggingService.catch("Error in TranscriptionService getVttFileTextToArray: ",c),[]}}getTimeInSecondsFromVttTime(e){try{let t=e.split(":"),i=0;t.length===3&&(i=parseInt(t[0]),t.shift());let a=parseInt(t[0]),l=parseInt(t[1].split(".")[0]),c=parseInt(t[1].split(".")[1]);return((i*60*60+a*60+l)*1e3+c)/1e3}catch(t){return this.loggingService.catch("Error in TranscriptionService getTimeInSecondsFromVttTime: ",t),0}}};o.\u0275fac=function(t){return new(t||o)(K(j9),K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ho=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A,M,V,q,ae,ye,ie,ge,Ie,he,Te){this.analyticsService=e,this.configService=t,this.docService=i,this.databaseService=a,this.commonDbService=l,this.authService=c,this.domService=d,this.afAuth=m,this.iamService=u,this.functions=_,this.avatarService=I,this.contactService=A,this.storageService=M,this.dialog=V,this.loggingService=q,this.notificationService=ae,this.transcriptionService=ye,this.recorderService=ie,this.recorderUtilsService=ge,this.userPermissionService=Ie,this.recorderAnnotationsResolverService=he,this.attachmentResolverService=Te,this.recorderAnnotationById$=new _e({}),this.documentPaths=null,this.allowedElementIds$=new _e([]),this.addRecorderMode$=new _e(!1),this.recorderContainerDarkMode$=new _e(!1),this.recordingTranscriptionEnabled$=new _e(!0),this.draftRecordings$=new _e([]),this.recorderNotesFound$=new _e(!1),this.recordedData=null,this.videoEditorAutoOpen$=new _e({}),this.commentService=null,this.getAllRecorderAnnotations().subscribe(Oe=>{}),this.loggingService.log("%c[WB] Creating CLASS: RecorderAnnotationService","color: blue;"),this.analyticsService.setRecorderAnnotationService(this),this.authService.setRecorderAnnotationService(this),this.databaseService.getDb().pipe(Ge(Oe=>!!Oe),ut(1)).subscribe(Oe=>{Oe&&this.getDocumentPaths()},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService getDb subscription: ",Oe)}),this.domService.onWindowPointerMove$().subscribe(Oe=>{if(this.addRecorderMode$.value){this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement);let Pe=this.domService.getBackgroundElement(Oe.clientX,Oe.clientY);Pe&&(this.isElementInsideAllowedElements(Pe)?tF(Oe.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement=Pe):this.domService.removeClassFromElement(document.body,"show-pin-cursor"))}},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowPointerMove$ subscription: ",Oe)}),this.domService.onWindowKeyupEsc$().subscribe(Oe=>{this.addRecorderMode$.value&&this.disableAddRecorderMode()},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupEsc$ subscription: ",Oe)}),this.domService.onDocumentClick$().subscribe(Oe=>{if(Oe&&this.addRecorderMode$.value){if(Oe.preventDefault(),Oe.stopPropagation(),!tF(Oe.target)){let Pe=this.domService.getBackgroundElement(Oe.clientX,Oe.clientY);Pe&&this.isElementInsideAllowedElements(Pe)}this.disableAddRecorderMode()}},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService onDocumentClick$ subscription: ",Oe)}),this.addRecorderMode$.subscribe(Oe=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),Oe?this.domService.addClassToElement(document.body,"snippyly-add-recorder-mode"):(this.domService.removeClassFromElement(document.body,"snippyly-add-recorder-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"))},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService addRecorderMode$ subscription: ",Oe)}),this.domService.onWindowKeyupBackspace$().subscribe(Oe=>{this.deleteRecorderPinAnnotations()},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupBackspace$ subscription: ",Oe)}),this.domService.onWindowKeyupDelete$().subscribe(Oe=>{this.deleteRecorderPinAnnotations()},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupDelete$ subscription: ",Oe)}),this.recorderService.onRecordedData().subscribe(Oe=>{this.recordedData=Oe},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService onRecordedData subscription: ",Oe)}),this.domService.getDeleteCommmentAnnotations$().subscribe(Oe=>{Oe?.length&&Oe.forEach(Pe=>X(this,null,function*(){}))},Oe=>{this.loggingService.catch("Error in RecorderAnnotationService onWindowKeyupDelete$ subscription: ",Oe)})}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in RecorderAnnotationService","color: green;");try{this.recorderAnnotationById$.next({}),this.documentPaths=null,this.allowedElementIds$.next([]),this.addRecorderMode$.next(!1),this.highlightElement=null}catch(e){this.loggingService.catch("Error in RecorderAnnotationService clearCache: ",e)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;");try{this.docService.getDocumentPaths$().pipe(ln(e=>{this.documentPaths=e})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getDocumentPaths subscription: ",e)})}catch(e){this.loggingService.catch("Error in CursorService getDocumentPaths: ",e)}}setCommentService(e){this.loggingService.log("%c[WB] Calling FUNCTION: setCommentService","color: green;");try{this.commentService=e}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setCommentService: ",t)}}getAnonymousAvatarImage(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAnonymousAvatarImage","color: green;"),this.avatarService.generateUserImage()}setAllowedElementIds(e){this.allowedElementIds$.next(e||[])}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}getDraftRecordings$(){return this.draftRecordings$.asObservable()}getRecorderDataByRecorderId(e){try{return this.recorderAnnotationById$.pipe(ue(()=>this.getAnnotationById(e)),Se(t=>X(this,null,function*(){return t?yield this.createRecorderData(t,!0):void 0})))}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderDataByRecorderId: ",t),ce(void 0)}}getRecorderDataByRecorderIds(e){return X(this,null,function*(){try{let t={};return yield Promise.all(e.recorderIds.map(i=>X(this,null,function*(){let a=this.getAnnotationById(i);if(!a)return;let l=yield this.createRecorderData(a,!0);l&&(t[i]=l)}))),{data:Object.keys(t).length>0?t:null}}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderDataByRecorderIds: ",t),{data:null}}})}fetchRecorderDataByRecorderIds(e){return X(this,null,function*(){try{let t=this.recorderAnnotationById$.value,i=[],a=Object.values(t);return e?.recorderIds?.length&&(a=a.filter(l=>e.recorderIds.includes(l.annotationId))),a.length===0?[]:(yield Promise.all(a.map(l=>X(this,null,function*(){if(!l)return;let c=yield this.createRecorderData(l,!0);c&&i.push(c)}))),i)}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService fetchRecorderDataByRecorderIds: ",t),[]}})}deleteRecorderDataByRecorderIds(e){return X(this,null,function*(){try{let t=this.recorderAnnotationById$.value,i=[],a=Object.values(t),l=[];return e?.recorderIds?.length&&(l=a.filter(c=>e.recorderIds.includes(c.annotationId))),l.length===0?[]:(yield Promise.all(l.map(c=>X(this,null,function*(){if(!c)return;let d=yield this.createRecorderData(c,!0);yield this.deleteRecorderPinAnnotation(c),d&&i.push(d)}))),i)}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService deleteRecorderDataByRecorderIds: ",t),[]}})}getRecordings(e){try{return this.recorderAnnotationById$.pipe(Se(t=>X(this,null,function*(){let i=[],a=Object.values(t);return e?.recorderIds?.length&&(a=a.filter(l=>e.recorderIds.includes(l.annotationId))),a.length===0?[]:(yield Promise.all(a.map(l=>X(this,null,function*(){if(!l)return;let c=yield this.createRecorderData(l,!0);c&&i.push(c)}))),i)})),Xn(t=>(this.loggingService.catch("Error in RecorderAnnotationService getRecordings: ",t),ce([]))))}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService getRecordings: ",t),ce([])}}setRecorderActionsService(e){try{this.recorderActionsService=e}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setRecorderActionsService: ",t)}}getVttFileTextToArray(e){try{return this.transcriptionService.getVttFileTextToArray(e)}catch(t){this.loggingService.catch("Error in RecorderAnnotationService getVttFileTextToArray: ",t)}}getAllRecorderAnnotations(e,t,i){this.loggingService.log("%c[WB] Calling FUNCTION: getAllRecorderAnnotations","color: green;");let a,l;try{if(e&&(l=er(e)),t&&typeof t=="object"){let c=Oi(t);a=er(JSON.stringify(c))}}catch(c){this.loggingService.catch("Error in RecorderAnnotationService getAllRecorderAnnotations: ",c)}return _r(this.afAuth).pipe(Ge(c=>!!c),Se(c=>this.isFeatureAllowed({firebaseUser:c,annotations:[],filteredAnnotations:[]})),Se(c=>c.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(d=>(c.featureAllowed=d,c))):ce(c)),Se(c=>c.featureAllowed?this.authService.isPlanExpired$().pipe(ue(d=>(c.featureAllowed=!d,c))):ce(c)),Se(c=>c.featureAllowed?ce(c).pipe(Se(d=>this.docService.getDocumentPaths$().pipe(ue(m=>(this.documentPaths=m,d.documentPaths=m,d)))),Se(d=>l?this.getDataFromDocumentIds([l]).pipe(ue(m=>(d.annotations=m||[],h({},d)))):this.docService.getDocumentIds$().pipe(Se(m=>{let u=m?.length>0?m.map(_=>_.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds(u).pipe(ue(_=>(d.annotations=_||[],h({},d))))}))),Se(d=>this.docService.getLocation$().pipe(ue(m=>(d.location=m,d)))),Se(d=>this.docService.getLocations$().pipe(ue(m=>(d.customLocations=m,d)))),ue(d=>{if(d.filteredAnnotations=[],l&&!a)return d.filteredAnnotations=d.annotations?.slice(),d;{let m=[];return a?m.push(a):(m.push(d?.location?.locationId),m.push(...Object.values(d?.customLocations||[]).map(u=>u.locationId))),d.filteredAnnotations=this.filterAnnotationsByLocationIds(d?.annotations,m),d}}),Se(d=>i?ce(d):d?.annotations?.length?this.domService.onWindowResize$().pipe(ue(()=>d)):ce(d)),Se(d=>i?ce(d):d?.annotations?.length?this.domService.onDomChange$("RecorderAnnotationService getAllRecorderAnnotations").pipe(ue(()=>d)):ce(d)),ue(d=>{let m=[];return d?.filteredAnnotations?.forEach(u=>{this.calculateRecorderAnnotationPosition(u),u?.targetElement||m.push(u)}),this.draftRecordings$.next(m),d}),Se(d=>d?.filteredAnnotations?ce(d?.filteredAnnotations||[]):ce([]))):ce([])),_t(Kt))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})),Se(t=>this.authService.getUser$().pipe(ue(i=>y(h({},t),{user:i})))),Se(t=>Ao(t.config,t.user,je.RECORDER)?ce(y(h({},t),{featureAllowed:!0})):(this.loggingService.warn("Recorder feature is not allowed."),ce(y(h({},t),{featureAllowed:!1})))),_t((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentIds(e,t){return this.getDataFromDocuments({documentIds:e,filters:t})}getDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t,filters:i}=e;if(t?.some(d=>!d)||!this.documentPaths)return ce([]);let a=this.docService.getDocumentPaths()?.veltFolderId,l=ce([]),c={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(c.documentId=t?.length?t[0]:void 0,c.organizationId=this.documentPaths?.organizationId),this.userPermissionService?.getIsContextEnabled()){let d=[N.DEFAULT_VELT_CONTEXT,...this.docService.getProcessedDocContext()],m=[];for(let u=0;u<(d?.length??0);u+=N.LISTENER_CONTEXT_BATCH_SIZE)m.push(d?.slice(u,u+N.LISTENER_CONTEXT_BATCH_SIZE)??[]);l=gn(m.map(u=>this.commonDbService.dbListener({feature:"allRecorders",properties:y(h({},c),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",t),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[],...u?.length?[ft("context.accessFields","array-contains-any",u)]:[])]})}).pipe(la()))).pipe(ue(u=>Na(u)))}else{let d=[];for(let m=0;m<(t?.length??0);m+=N.LISTENER_BATCH_SIZE)d.push(t?.slice(m,m+N.LISTENER_BATCH_SIZE)??[]);l=gn(d.map(m=>this.commonDbService.dbListener({feature:"allRecorders",properties:y(h({},c),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.documentId","in",m),ft("metadata.organizationId","==",this.documentPaths?.organizationId),...a?[ft("metadata.veltFolderId","==",a)]:[])]})}).pipe(la()))).pipe(ue(m=>Na(m)))}return l.pipe(ue(d=>({data:d?.data,operation:d?.operation})),ue(({data:d,operation:m})=>{let u=[];return d&&(u=Object.values(d).filter(_=>typeof _=="object")),{data:u,operation:m}}),ue(({data:d,operation:m})=>{if(!t)return{data:d,documentMap:{},operation:m};let u=d.reduce((_,I)=>{let A=I.metadata?.documentId;return A&&(_[A]||(_[A]=[]),_[A].push(I)),_},{});return{data:d,documentMap:u,operation:m}}),ue(({data:d,documentMap:m,operation:u})=>{if(!i)if(u?.type==="removed"){if(u?.ids?.length){let _=this.recorderAnnotationById$.value;u?.ids?.forEach(I=>{delete _?.[I]}),this.recorderAnnotationById$.next(_)}}else Object.entries(m).forEach(([_,I])=>{this.setRecorderAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:_,annotations:I})});return d}),Xn(d=>(this.loggingService.catch("Error in RecorderAnnotationService getDataFromDocumentId: ",d),ce([]))))}else return ce([])}setRecorderAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:i,queryHash:a}){try{if(t){e||(e=N.NO_ORGANIZATION_ID),a||(a=N.DEFAULT_QUERY_HASH);let l={};i?.forEach(d=>{d?.annotationId&&(l[d?.annotationId]=d)});let c=h(h({},this.recorderAnnotationById$.value),l);this.recorderAnnotationById$.next(c)}}catch(l){this.loggingService.catch("Error in RecorderAnnotationService setRecorderAnnotationsByOrganizationIdAndDocumentId:",l)}}filterAnnotationsByLocationIds(e,t){try{return e.filter(i=>t.includes(i.locationId))}catch(i){return this.loggingService.catch("Error in RecorderAnnotationService filterAnnotationsByLocations:",i),[]}}calculateRecorderAnnotationPosition(e){try{if(e.targetElement){let t=this.domService.getXPath(e.targetElement?.xpath);if(t){let i=t.iterateNext();if(i&&Kr(i)){let a=i.getBoundingClientRect();if(a&&a.width&&a.height){let{height:l,width:c}=np(i);e.position={top:l*e.targetElement.topPercentage/100,left:c*e.targetElement.leftPercentage/100}}else e.position=null}else e.position=null}else e.position=null}}catch(t){this.loggingService.catch("Error in RecorderAnnotationService calculateRecorderAnnotationPosition:",t)}}getAnnotationById(e,t){try{let i=this.recorderAnnotationById$.value?.[e];if(i){let{documentId:a,organizationId:l}=t||{};if(a&&i.metadata?.documentId!==a||l&&i.metadata?.organizationId!==l)return}return i}catch(i){this.loggingService.catch("Error in RecorderAnnotationService getAnnotationById: ",i);return}}getBaseMetadataFromRecorderAnnotationId(e){try{let t=this.recorderAnnotationById$.value?.[e];if(t)return t.metadata}catch(t){this.loggingService.catch("Error in RecorderAnnotationService getBaseMetadataFromRecorderAnnotationId: ",t)}}getRecorderAnnotationById(e,t){return this.recorderAnnotationById$.pipe(Se(()=>{let i=this.getAnnotationById(e,t);return i?ce(i):ce(null)}),Xn(i=>(this.loggingService.catch("Error in RecorderAnnotationService getCommentAnnotationById: ",i),ce(null))))}getRecorderAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let i={};return Object.values(this.recorderAnnotationById$.value).forEach(a=>{a?.metadata?.documentId==t&&a?.metadata?.organizationId==e&&(i[a?.annotationId]=a)}),Object.values(i)}catch(i){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderAnnotationsByOrganizationIdAndDocumentId:",i),[]}}setLocationToRecorderAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location);try{if(e.targetElement?.xpath){let i=this.domService.getElementFromXPath(e.targetElement.xpath),a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.addLocation({location:a,source:"internal"});l?.[0]&&(e.locationId=l[0].locationId,e.location=l[0].location)}}}catch{}}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setLocationToRecorderAnnotation:",t)}}addRecorder(e,t,i){this.loggingService.log("%c[WB] Calling FUNCTION: addRecorder","color: green;");try{let a=this.authService.getUser();if(a){if(a.isReadOnly||a.isAnonymous)return this.loggingService.catch("Anonymous/Readonly users cannot add recorders."),ce(null);{t.from=a,t.color=N.DEFAULT_ANNOTATION_COLOR,t.lastUpdated=this.timestamp;let{topPositionX:l,topPositionY:c}=this.domService.getTopLeftPosition();t.positionX=l,t.positionY=c;let d=this.domService.getCurrentWindowSizeValue();if(t.screenWidth=d.screenWidth,t.screenHeight=d.screenHeight,t.screenScrollHeight=d.screenScrollHeight,t.recorderedElementPath="",e&&(t.targetElement=this.domService.getTargetElementForCursorPosition(e)),t?.targetElement?.xpath){let m=this.domService.getXPath(t.targetElement.xpath);if(m){let u=m.iterateNext();u&&(Kr(u)||(t.targetElement=null))}}return this.setLocationToRecorderAnnotation(t),t.pageInfo=ro(),t.pageInfo&&(t.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth),this.saveRecorderToDb(t,i)}}else return ce(null)}catch(a){return this.loggingService.catch("Error in RecorderAnnotationService addRecorder: ",a),ce(null)}}saveRecorderToDb(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: saveRecorderToDb","color: green;");try{return this.authService.getUser()&&this.authService.isFeatureAllowed(je.RECORDER)?this.docService.getDocumentPaths$().pipe(Ge(i=>!!i),ut(1),Se(i=>(this.documentPaths=i,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Ge(a=>!!a),ut(1),Se(a=>X(this,null,function*(){if(this.documentPaths?.recorder){e.annotationId=this.commonDbService.generateDocumentId(),e.pageInfo&&(e.pageInfo.recorderUrl=this.generateRecorderUrl(e));let l=JSON.parse(JSON.stringify(e));if(l.position=null,this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||delete l?.isUrlAvailable,!l?.metadata?.documentId){l?.metadata||(l.metadata={});let u=this.docService.getBaseMetadata("recorder",{commentAnnotationId:e.commentAnnotationId});l.metadata=h(h({},l?.metadata),u)}let{documentId:c,organizationId:d}=l?.metadata||{};if(e.commentAnnotationId){let u=this.commentService?.getAnnotationById(e.commentAnnotationId??"");if(u?.context?.accessFields){if(!this.userPermissionService?.hasUserContextAccess({userId:e.from?.userId,accessFields:u.context.accessFields}))return this.loggingService.catch("User does not have context access to add recorder annotation.",void 0,void 0,!0),null;l.context=y(h({},u.context.access?{access:u.context.access}:{}),{accessFields:u.context.accessFields})}}let m={annotationData:l,actionType:Jl.ADDED,notificationSource:"recorder"};if(yield new Promise((u,_)=>X(this,null,function*(){yield this.commonDbService.setData({feature:"recorder",properties:{id:e.annotationId,documentId:c,organizationId:d},data:JSON.parse(JSON.stringify(l)),extraData:m,callback:()=>{u(!0)},errorCallback:I=>{_(I)}})})),this.analyticsService.trackEvent(Y.Events.Recording.RECORDING_ADDED,{annotationId:e.annotationId,recorderType:e.recordingType,recorderMode:e.mode,recorderTime:e?.recordedTime?.duration,recorderSize:e?.attachments?.length?e?.attachments[0]?.size:e?.attachment?.size,sourceFeature:t||"recording"}),this.setVideoEditorAutoOpen({[e.annotationId]:!0}),t==="recording"){let u=yield this.createRecorderData(l,!1);u&&this.recorderActionsService?.onRecordingDoneLocal(u)}return this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||this.processRecording(e,"recording","merge"),this.updateNotificationsDatabase(e,Jl.ADDED),e}else return null})))))):ce(null)}catch(i){return this.loggingService.catch("Error in RecorderAnnotationService saveRecorderToDb: ",i),ce(null)}}processRecording(e,t,i){return X(this,null,function*(){try{let a=Yr(this.functions,Zr({url:On?.cloudFunction?.processRecording,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:36e5}),l=this.docService.getDocumentPaths();e?.metadata?.documentId&&(l=new bm({apiKey:this.configService.getApiKey(),clientDocumentId:e.metadata.clientDocumentId,clientOrganizationId:e.metadata.clientOrganizationId,documentId:e.metadata.documentId,organizationId:e.metadata.organizationId}));let c={databaseUrl:this.authService.getFirebaseConfig()?.firebaseOptions?.databaseURL,entirePath:l?.recorder+e?.annotationId,fromUser:this.authService.getUser(),clientOrganizationId:l?.clientOrganizationId,clientDocumentId:l?.clientDocumentId,apiKey:this.configService.getApiKey(),sdkVersion:tl(),sdkType:this.configService.getSdkType(),useFirestore:this.commonDbService.shouldUseFirestore(),storageBucket:this.authService.getFirebaseConfig()?.firebaseOptions?.storageBucket,documentPath:l?.recorder,annotationId:e?.annotationId,sourceFeature:t||"recording",annotationData:e,skipMerge:!0,transcriptionEnabled:this.getRecordingTranscriptionEnabled(),type:i,returnType:"transcription",generatePreviewImages:this.recorderService.getVideoEditor()&&this.recorderService.getVideoEditorTimelinePreview()};if(c?.useFirestore){let M=yield this.recorderUtilsService.encryptRecorderAnnotation(e);c.annotationData=M}let d=this.documentPaths?.organizationId,m=this.documentPaths?.documentId;e?.metadata?.documentId&&(m=e.metadata.documentId,d=e.metadata.organizationId);let u=`${this.configService.getApiKey()}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${m}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`;d&&(u=`${this.configService.getApiKey()}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${d}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${m}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`),c.bucketPath=u;let _;try{_=yield a(c)}catch(M){M?.details?.type==="recording"&&this.recorderActionsService?.onError({type:"recordingFailed",message:"Recording failed",recorderId:M.details.recorderId}),M?.details?.type==="transcription"&&this.recorderActionsService?.onError({type:"transcriptionFailed",message:"Transcription failed",recorderId:M.details.recorderId}),this.loggingService.catch("Error in RecorderAnnotationService processRecording: ",M)}let I=this.getAnnotationById(e?.annotationId);if(!I)return;let A=yield this.createRecorderData(I,!1);if(A){if(_?.data?.transcriptedText&&(A.transcription.contentSummary=_.data.transcriptedText),_?.data?.vttUrl)try{let M=yield this.transcriptionService.getFileContent(_.data.vttUrl).toPromise();M&&(A.transcription.transcriptSegments=this.getVttFileTextToArray(M),A.transcription.vttFileUrl=_.data.vttUrl),A?.assets?.length&&A.assets.forEach(V=>{V.transcription=A.transcription}),A?.assetsAllVersions?.length&&(A.assetsAllVersions[0].transcription=A.transcription),this.recorderActionsService?.onTranscriptionDone(A)}catch(M){this.loggingService.catch("Error fetching VTT content: ",M)}I?.attachments?.length&&this.recordedData&&(this.recordedData.videoUrl=I.attachments[0].url),t==="recording"&&this.recorderActionsService?.onRecordingDone(A)}this.recordedData&&this.recorderService.setRecordedData(this.recordedData)}catch(a){this.loggingService.catch("Error in RecorderAnnotationService processRecording: ",a)}})}getDocumentIdAndOrganizationIdFromRecorderAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService getDocumentIdAndOrganizationIdFromRecorderAnnotation: ",t),{}}}createRecorderData(e,t=!1){return X(this,null,function*(){try{if(!e)return null;let i=oi(e.metadata||{}),a=Vo(e.from),l={recorderId:e.annotationId||"",from:a,assets:[],metadata:i,assetsAllVersions:[],transcription:{transcriptSegments:[],vttFileUrl:"",contentSummary:""}},c=e;e.latestVersion&&e.recordingEditVersions?.[e.latestVersion]&&(c=e.recordingEditVersions[e.latestVersion]);let d=u=>X(this,null,function*(){let _={transcriptSegments:[],vttFileUrl:"",contentSummary:u?.transcription?.transcriptedText||""};if(t&&u?.transcription?.vttUrl)try{let I=yield this.transcriptionService.getFileContent(u.transcription.vttUrl).toPromise();I&&(_.transcriptSegments=this.getVttFileTextToArray(I),_.vttFileUrl=u.transcription.vttUrl)}catch(I){this.loggingService.catch("Error fetching VTT content: ",I)}return _}),m=yield d(c);if(l.transcription=m,c?.attachments?.length)for(let u of c.attachments)u?.url&&l.assets.push({version:e.latestVersion||1,url:u.url,mimeType:u.mimeType,fileName:u.name,fileSizeInBytes:u.size,fileFormat:u.type,transcription:h({},m),thumbnailUrl:e.attachments?.[0]?.thumbnail});if(e.recordingEditVersions){let u=Object.entries(e.recordingEditVersions).map(M=>X(this,[M],function*([I,A]){let V=parseInt(I),q=yield d(A),ae=A?.attachments?.[0]||A?.attachment;return{version:V,url:ae?.url,mimeType:ae?.mimeType,fileName:ae?.name,fileSizeInBytes:ae?.size,fileFormat:ae?.type,transcription:q,thumbnailUrl:A?.attachments?.[0]?.thumbnail}})),_=yield Promise.all(u);l.assetsAllVersions=_.filter(I=>I.url)}else l.assetsAllVersions=[...l.assets];return l}catch(i){return this.loggingService.catch("Error in RecorderAnnotationService createRecorderData: ",i),null}})}updateRecorder(e,t=!1,i){try{i&&this.setLocationToRecorderAnnotation(e),t&&this.updateNotificationsDatabase(e,Jl.UPDATED),this.updateRecorderToDb(e)}catch(a){this.loggingService.catch("Error in RecorderAnnotationService updateRecorder: ",a)}}resolveRecorder(e){try{this.domService.resetSelectedAnnotationsMap(!1),this.updateNotificationsDatabase(e,Jl.RESOLVED),this.updateRecorderToDb(e),this.domService.updateSelectedAnnotationInMap([e])}catch(t){this.loggingService.catch("Error in RecorderAnnotationService resolveRecorder: ",t)}}updateRecorderToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateRecorderToDb","color: green;");try{if(e?.targetElement?.xpath){let t=this.domService.getXPath(e.targetElement.xpath);if(t){let i=t.iterateNext();i&&(Kr(i)||(e.targetElement=null))}}if(e.annotationId){let t=this.recorderAnnotationById$.value;this.recorderAnnotationById$.next(y(h({},t),{[e.annotationId]:h({},e)}))}if(this.domService.updateSelectedAnnotationInMap([e]),this.authService.getUser()&&this.authService.isFeatureAllowed(je.RECORDER)){let t=JSON.parse(JSON.stringify(e));if(t.position=null,this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()||delete t?.isUrlAvailable,!t?.metadata?.documentId){t?.metadata||(t.metadata={});let l=this.docService.getBaseMetadata("recorder");t.metadata=h(h({},t?.metadata),l)}let{documentId:i,organizationId:a}=this.getDocumentIdAndOrganizationIdFromRecorderAnnotation(e);this.commonDbService.setData({feature:"recorder",properties:{id:e.annotationId,documentId:i,organizationId:a},data:JSON.parse(JSON.stringify(t)),extraData:{actionType:Jl.UPDATED}})}}catch(t){this.loggingService.catch("Error in RecorderAnnotationService updateRecorderToDb: ",t)}}deleteRecorderPinAnnotations(){try{let e=this.domService.getSelectedAnnotationsMap(),t=this.authService.getUser(),i=[];Object.keys(e).forEach(a=>X(this,null,function*(){let l=e[a];l.type==="recorder"&&t&&l.from&&(t?.isAdmin||l.from.userId===t.userId)&&i.push(l)})),i?.length&&(this.analyticsService.trackEvent(Y.Events.Recording.RECORDING_DELETE_TRIGGERED,{annotationId:i.map(a=>a.annotationId).join()}),this.dialog.open(al,{panelClass:"velt-mat-dialog-container",data:{title:"Delete recording?",message:"This selected recording will be deleted.",yesButton:"Delete",noButton:"Cancel",darkMode:this.recorderContainerDarkMode$.value,variant:"recorder"}}).afterClosed().pipe(ut(1)).subscribe(a=>{a&&(i.forEach(l=>X(this,null,function*(){yield this.deleteRecorderPinAnnotation(l)})),setTimeout(()=>{document.querySelectorAll(`[${N.SNIPPYLY_HIGHLIGHT}]`).forEach(c=>{this.domService.removeHighlightFromElement(c)})},100))}),this.domService.resetSelectedAnnotationsMap(!0,"recorder"))}catch(e){this.loggingService.catch("Error in RecorderAnnotationService deleteRecorderPinAnnotations: ",e)}}deleteRecorderPinAnnotation(e,t){if(this.authService.isFeatureAllowed(je.RECORDER)&&this.documentPaths?.recorder&&e?.annotationId){this.updateNotificationsDatabase(e,Jl.DELETED);let i=this.attachmentResolverService.attachmentDataProviderAvailable("recorder"),a=this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()?this.recorderUtilsService.mergeStrippedDataWithRecorderAnnotation(h({},e)):e,l=oi(e?.metadata??{});if(a?.attachments?.length)a.attachments.forEach(_=>{let I={organizationId:l?.organizationId??null,documentId:l?.documentId??null,folderId:l?.folderId??null,attachmentId:_.attachmentId,commentAnnotationId:null,apiKey:l?.apiKey??null};this.storageService.deleteAttachment({attachment:_,metadata:I,useAttachmentResolver:i,attachmentScope:"recorder"}).catch(A=>{this.loggingService.catch("Error in RecorderAnnotationService deleteRecorderPinAnnotation delete attachment: ",A)})});else if(a?.attachment){let _={organizationId:l?.organizationId??null,documentId:l?.documentId??null,folderId:l?.folderId??null,attachmentId:a.attachment.attachmentId,commentAnnotationId:null,apiKey:l?.apiKey??null};this.storageService.deleteAttachment({attachment:a.attachment,metadata:_,useAttachmentResolver:i,attachmentScope:"recorder"})}e?.transcription&&!this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()&&(e?.transcription?.srtBucketPath&&this.storageService.deleteFileFromPath(e.transcription.srtBucketPath).catch(_=>{this.loggingService.catch("Error in RecorderAnnotationService deleteRecorderPinAnnotation delete srt file: ",_)}),e?.transcription?.vttBucketPath&&this.storageService.deleteFileFromPath(e.transcription.vttBucketPath).catch(_=>{this.loggingService.catch("Error in RecorderAnnotationService deleteRecorderPinAnnotation delete vtt file: ",_)})),this.analyticsService.trackEvent(Y.Events.Recording.RECORDING_DELETED,{annotationId:e.annotationId,recorderType:e.recordingType,recorderMode:e.mode,recorderTime:e?.recordedTime?.duration,recorderSize:e?.attachments?.length?e?.attachments[0]?.size:e.attachment?.size,sourceFeature:t||"recording"});let{documentId:c,organizationId:d}=this.getDocumentIdAndOrganizationIdFromRecorderAnnotation(e),m={annotationData:e,actionType:Jl.DELETED,notificationSource:"recorder"},u={apiKey:this.configService.getApiKey(),organizationId:d,documentId:c,veltFolderId:e?.metadata?.veltFolderId};return this.commonDbService.deleteData({feature:"recorder",properties:{id:e.annotationId,documentId:c,organizationId:d,metadata:u},extraData:m}).then(_=>X(this,null,function*(){let I=yield this.createRecorderData(e,!0);I&&this.recorderActionsService?.onDeleteRecording(I)}))}else return Promise.resolve()}enableAddRecorderMode(){this.authService.isFeatureAllowed(je.RECORDER)?this.addRecorderMode$.next(!0):this.loggingService.catch("Error in RecorderAnnotationService enableAddRecorderMode: ","Recorder feature is not enabled.")}disableAddRecorderMode(){this.addRecorderMode$.next(!1)}addRecorderModeChange(){return this.addRecorderMode$.asObservable()}setRecorderContainerDarkMode(e){try{if(this.recorderContainerDarkMode$.value===e)return;this.recorderContainerDarkMode$.next(e)}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setRecorderContainerDarkMode: ",t)}}getRecorderContainerDarkMode(){return this.recorderContainerDarkMode$.asObservable()}enableRecordingTranscription(){try{if(this.analyticsService.setFeatureConfig({feature:je.RECORDER,config:{recordingTranscription:!0}}),this.recordingTranscriptionEnabled$.value===!0)return;this.recordingTranscriptionEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in RecorderAnnotationService enableRecordingTranscription: ",e)}}disableRecordingTranscription(){try{if(this.analyticsService.setFeatureConfig({feature:je.RECORDER,config:{recordingTranscription:!1}}),this.recordingTranscriptionEnabled$.value===!1)return;this.recordingTranscriptionEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in RecorderAnnotationService disableRecordingTranscription: ",e)}}getRecordingTranscriptionEnabled(){return this.recordingTranscriptionEnabled$.value}getRecordingTranscriptionEnabled$(){return this.recordingTranscriptionEnabled$.asObservable()}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService isElementInsideAllowedElements: ",t),!1}}attachRecorder(e){let t=document.getElementById(e);if(t){let i=this.domService.getXPath(t),a=this.getRecorderPinAnnotationObject();a&&(a.targetElement={xpath:i,topPercentage:50,leftPercentage:90},this.saveRecorderToDb(a))}}getRecorderPinAnnotationObject(){let e=this.authService.getUser();if(e)if(e.isReadOnly||e.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add recorders.");else{let t=new Ku;t.from=e,t.color=N.DEFAULT_ANNOTATION_COLOR,t.lastUpdated=this.timestamp;let{topPositionX:i,topPositionY:a}=this.domService.getTopLeftPosition();t.positionX=i,t.positionY=a;let l=this.domService.getCurrentWindowSizeValue();t.screenWidth=l.screenWidth,t.screenHeight=l.screenHeight,t.screenScrollHeight=l.screenScrollHeight,t.recorderedElementPath="";let c=this.docService.getLocation();return c&&(t.locationId=c.locationId,t.location=c.location),t}return null}updateNotificationsDatabase(e,t,i={}){try{let a=e;this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable()&&(a=JSON.parse(JSON.stringify(e)),a?.from?.userId&&(a.from={userId:a.from.userId}),delete a.transcription,a?.attachments?.length&&(a.attachments=a.attachments.map(c=>({attachmentId:c?.attachmentId,name:c?.name}))),a.attachment=null,a?.chunkUrls&&(a.chunkUrls={}));let l=h({annotationData:a,actionType:t,notificationSource:"recorder",recordingType:e?.recordingType},i);this.notificationService.updateNotificationDatabase(l)}catch(a){this.loggingService.catch("Error in RecorderAnnotationService updateNotificationsDatabase: ",a)}}getUserContacts$(){return this.contactService.getUserContacts$()}addUserContact(e){this.contactService.addUserContact(e)}getRecorderUrl(e){try{return e?.pageInfo?.recorderUrl?e.pageInfo.recorderUrl:e?.annotationId?(e?.pageInfo||(e.pageInfo=ro(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.recorderUrl=this.generateRecorderUrl(e),this.updateRecorder(e),e.pageInfo?.recorderUrl):""}catch(t){this.loggingService.catch("Error in RecorderAnnotationService getRecorderUrl: ",t);return}}uploadFile(e,t){let i=this.documentPaths?.organizationId,a=this.documentPaths?.documentId;t?.metadata?.documentId&&(a=t.metadata.documentId,i=t.metadata.organizationId);let l=`${N.FIREBASE_PARTIAL_PATH_DOCS}/${a}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`;if(i&&(l=`${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${i}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${a}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`),this.attachmentResolverService.attachmentDataProviderAvailable("recorder")){let c=this.docService.getBaseMetadata("recorder",{commentAnnotationId:t.commentAnnotationId});return this.storageService.uploadFile({path:l,file:e,useAttachmentResolver:!0,metadata:c,attachmentScope:"recorder"})}return this.storageService.uploadFile({path:l,file:e})}uploadFullRecordingAndUpdateAnnotation(e,t){try{if(!t?.annotationId)return;this.uploadFile(e,t).then(i=>{if(!i?.url)return;let l=this.getAnnotationById(t.annotationId)||t;l.attachments?.length&&(l.attachments[0].url=i.url,l.attachments[0].attachmentId=i.attachmentId,i.bucketPath&&(l.attachments[0].bucketPath=i.bucketPath)),l.attachment=l.attachments?.[0]??null,l.lastUpdated=new Date().getTime(),l.isUrlAvailable=!0,this.updateRecorder(l)}).catch(i=>{this.loggingService.catch("Error uploading full recording: ",i)})}catch(i){this.loggingService.catch("Error in RecorderAnnotationService uploadFullRecordingAndUpdateAnnotation: ",i)}}downloadAttachment(e){this.storageService.downloadAttachment(e)}deleteAttachment(e){return this.storageService.deleteAttachment({attachment:e})}generateRecorderUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(N.URL_PARAMS.RECORDER_ID),t.searchParams.append(N.URL_PARAMS.RECORDER_ID,e.annotationId),t.href}setRecorderNotesFound(e){try{this.recorderNotesFound$.next(e)}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setRecorderNotesFound: ",t)}}getRecorderNotesFound$(){try{return this.recorderNotesFound$.asObservable()}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderNotesFound: ",e),ce(!1)}}getRecorderNotesFound(){try{return this.recorderNotesFound$.value}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getRecorderNotesFound: ",e),!1}}editVideoRecording(e,t,i,a,l,c){return X(this,null,function*(){try{let d=Yr(this.functions,Zr({url:On?.cloudFunction?.videoBackend,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:36e5}),m=this.docService.getDocumentPaths();i?.metadata?.documentId&&(m=new bm({apiKey:this.configService.getApiKey(),clientDocumentId:i.metadata.clientDocumentId,clientOrganizationId:i.metadata.clientOrganizationId,documentId:i.metadata.documentId,organizationId:i.metadata.organizationId}));let u={databaseUrl:this.authService.getFirebaseConfig()?.firebaseOptions?.databaseURL,entirePath:m?.recorder+(i?.annotationId||""),fromUser:this.authService.getUser(),clientOrganizationId:m?.clientOrganizationId,clientDocumentId:m?.clientDocumentId,apiKey:this.configService.getApiKey(),sdkVersion:tl(),sdkType:this.configService.getSdkType(),useFirestore:this.commonDbService.shouldUseFirestore(),storageBucket:this.authService.getFirebaseConfig()?.firebaseOptions?.storageBucket,documentPath:m?.recorder,annotationId:i?.annotationId,annotationData:i,videoUrl:e,segments:t,zoomOptions:a,transcriptionEnabled:this.getRecordingTranscriptionEnabled(),type:l,backendUpload:!0};if(c){let V=yield c.arrayBuffer(),q=new Uint8Array(V),ae="";for(let ie=0;ie<q.length;ie++)ae+=String.fromCharCode(q[ie]);let ye=btoa(ae);u.videoBlobData=ye,u.videoBlobType=c.type,u.videoBlobSize=c.size}if(u?.useFirestore&&i){let V=yield this.recorderUtilsService.encryptRecorderAnnotation(i);u.annotationData=V}let _=this.documentPaths?.organizationId,I=this.documentPaths?.documentId;i?.metadata?.documentId&&(I=i.metadata.documentId,_=i.metadata.organizationId);let A=`${this.configService.getApiKey()}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${I}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`;_&&(A=`${this.configService.getApiKey()}/${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${_}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${I}/${N.FIREBASE_PARTIAL_PATH_RECORDER}`),u.bucketPath=A;let M=yield d(u);if(l==="standalone"){let V=M?.data;if(V&&V?.videoData){let q=atob(V.videoData),ae=new ArrayBuffer(q.length),ye=new Uint8Array(ae);for(let Ie=0;Ie<q.length;Ie++)ye[Ie]=q.charCodeAt(Ie);let ie=new Blob([ye],{type:V.mimeType||"video/mp4"}),ge=document.createElement("a");ge.href=URL.createObjectURL(ie),ge.download="edited-video.mp4",document.body.appendChild(ge),ge.click(),document.body.removeChild(ge)}}return M}catch(d){throw this.loggingService.catch("Error in RecorderAnnotationService editVideoRecording: ",d),d}})}setVideoEditorAutoOpen(e){try{this.videoEditorAutoOpen$.next(h(h({},this.videoEditorAutoOpen$.value),e))}catch(t){this.loggingService.catch("Error in RecorderAnnotationService setVideoEditorAutoOpen: ",t)}}getVideoEditorAutoOpen$(){try{return this.videoEditorAutoOpen$.asObservable()}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getVideoEditorAutoOpen: ",e),ce({})}}getVideoEditorAutoOpen(){try{return this.videoEditorAutoOpen$.value}catch(e){return this.loggingService.catch("Error in RecorderAnnotationService getVideoEditorAutoOpen: ",e),{}}}downloadLatestVideo(e){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: downloadLatestVideo","color: green;");let t=this.getAnnotationById(e);if(!t)return this.loggingService.catch("Recording not found with ID: "+e),!1;let i,a,l=t.latestVersion;if(l&&t.recordingEditVersions?.[l]?(i=t.recordingEditVersions[l].attachments?.[0]?.url,a=t.recordingEditVersions[l].attachments?.[0]?.name):(i=t.attachments?.[0]?.url||t.attachment?.url,a=t.attachments?.[0]?.name||t.attachment?.name),!i)return this.loggingService.catch("No video URL found for recording: "+e),!1;let c=yield fetch(i);if(!c.ok)return this.loggingService.catch("Failed to fetch video: "+c.statusText),!1;let d=yield c.blob(),m=document.createElement("a");return m.href=URL.createObjectURL(d),m.download=a||`recording-${e}.mp4`,document.body.appendChild(m),m.click(),document.body.removeChild(m),URL.revokeObjectURL(m.href),this.loggingService.log("Successfully downloaded video: "+a),!0}catch(t){return this.loggingService.catch("Error in RecorderAnnotationService downloadLatestVideo: ",t),!1}})}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(Ft),K(st),K($n),K(yn),K(qe),K(Ve),K(eo),K(Vn),K(Do),K(fm),K(vn),K(Pp),K(Lo),K(k),K(mn),K(bS),K(Un),K(Dp),K(Ia),K(il),K(es))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var KWe=["access","accessFields"];function ZWe(n){return n?Object.keys(n).length>0:!1}var Re=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A,M,V,q,ae,ye,ie,ge,Ie,he,Te,Oe,Pe,$e,ze,We,gr){this.analyticsService=e,this.areaService=t,this.commonDbService=i,this.configService=a,this.docService=l,this.databaseService=c,this.authService=d,this.domService=m,this.afAuth=u,this.avatarService=_,this.contactService=I,this.storageService=A,this.functions=M,this.dialog=V,this.iamService=q,this.loggingService=ae,this.notificationService=ye,this.customFilterService=ie,this.reactionService=ge,this.hotkeyService=Ie,this.recorderService=he,this.viewsService=Te,this.buttonService=Oe,this.metadataService=Pe,this.commonDbUtilsService=$e,this.attachmentResolverService=ze,this.userPermissionService=We,this.recorderAnnotationService=gr,this.customPinsById=new Map,this.commentAdded$=new at,this.commentUpdated$=new at,this.commentAccepted$=new at,this.commentRejected$=new at,this.commentAnnotationDeleted$=new at,this.multiThreadCommentAnnotationDeleted$=new at,this.commentAnnotationById$=new _e(null),this.multiThreadCommentAnnotationById$=new _e(null),this.ghostCommentAnnotationMap$=new _e({}),this.unreadCommentsMap$=new _e(null),this.documentPaths=null,this.user=null,this.customCategoryMap=N.CommentCategoryMap,this.allowedElementIds$=new _e([]),this.allowedElementClassNames$=new _e([]),this.allowedElementQuerySelectors$=new _e([]),this.addCommentMode$=new _e(!1),this.persistentCommentMode$=new _e(!1),this.seenByUsers$=new _e(!0),this.deleteReplyConfirmation$=new _e(!1),this.persistentModeBanner$=new _e(!0),this.commentAddedEmitter=null,this.commentContextProvider=null,this.textCommentMode$=new _e(!0),this.sidebarVisible$=new _e(!1),this.sidebarOpenedByCustomTrigger$=new _e(!1),this.floatingCommentsEnabled$=new _e(!0),this.moderatorMode$=new _e(!1),this.streamMode$=new _e(!1),this.enableSignInButton$=new _e(!1),this.enableUpgradeButton$=new _e(!1),this.onSignInClick$=new at,this.onUpgradeClick$=new at,this.enableAttachment$=new _e(!0),this.enableAttachmentDownload$=new _e(!0),this.enableReactions$=new _e(!0),this.enableAnonymousEmail$=new _e(!0),this.enableFormatOptions$=new _e(!1),this.formatConfig$=new _e({bold:{enable:!0},italic:{enable:!0},underline:{enable:!0},strikethrough:{enable:!0}}),this.allowedRecordings$=new _e(["audio","video","screen"]),this.openSidebar$=new at,this.showScreenSizeInfo$=new _e(!1),this.showCommentIndex$=new _e(!1),this.popoverMode$=new _e(!1),this.popoverTriangleComponent$=new _e(!0),this.draftMode$=new _e(!0),this.enableDialogOnHover$=new _e(!0),this.enableDialogOnTargetElementClick$=new _e(!1),this.enablePriority$=new _e(!1),this.enableStatus$=new _e(!0),this.visibilityOptions$=new _e(!1),this.enableResolve$=new _e(!0),this.enableGhostComments$=new _e(!1),this.enableGhostCommentsMessage$=new _e(!0),this.inboxMode$=new _e(!1),this.enableAutoCategorize$=new _e(!1),this.commentContainerDarkMode$=new _e(!1),this.suggestionMode$=new _e(!1),this.mobileMode$=new _e(!0),this.inlineCommentMode$=new _e(!1),this.minimap$=new _e(!1),this.commentsOnDom$=new _e(!0),this.commentToolEnabled$=new _e(!0),this.totalMediaLength$=new _e(0),this.sidebarUrlNavigationEnabled$=new _e(!1),this.detectionStrategy$=new _e(wN.DEFAULT),this.sidebarButtonOnCommentDialogVisible$=new _e(!1),this.sidebarButtonOnCommentDialogClick$=new at,this.commentNavigationButtonClick$=new at,this.deviceIndicatorOnCommentPins$=new _e(!1),this.sidebarCommentClick$=new at,this.privateCommentMode$=new _e(!1),this.privateCommentAllowed$=new _e(!1),this.privateModeConfig$=new _e(null),this.scrollToComment$=new _e(!0),this.userMentions$=new _e(!0),this.paginatedContactList$=new _e(!1),this.deleteOnBackspace$=new _e(!0),this.hotkeyEnabled$=new _e(!1),this.recordingSummaryEnabled$=new _e(!0),this.unreadIndicatorMode$=new _e(p0.MINIMAL),this.composerMode$=new _e(BK.DEFAULT),this.enterKeyToSubmit$=new _e(!1),this.resolvedCommentsOnDom$=new _e(!1),this.bubbleOnPinEnabled$=new _e(!1),this.bubbleOnPinHoverEnabled$=new _e(!0),this.pinDragEnabled$=new _e(!0),this.excludeLocationIdsFromSidebar$=new _e([]),this.multiThread$=new _e(!1),this.groupMatchedComments$=new _e(!1),this.shortUserName$=new _e(!0),this.collapsedComments$=new _e(!1),this.fullExpanded$=new _e(!1),this.queryParamsComments$=new _e(!1),this.resolveStatusAccessAdminOnly$=new _e(!1),this.linkCallback$=new _e(!1),this.svgAsImg$=new _e(!1),this.commentToNearestAllowedElement$=new _e(!1),this.filterCommentsOnDom$=new _e(!1),this.maxReplyAvatars$=new _e(3),this.replyAvatars$=new _e(!1),this.commentplaceholder$=new _e(void 0),this.replyplaceholder$=new _e(void 0),this.editplaceholder$=new _e(void 0),this.editcommentplaceholder$=new _e(void 0),this.editreplyplaceholder$=new _e(void 0),this.screenshotEnabled$=new _e(!1),this.pinShadowDOM$=new _e(!0),this.dialogShadowDOM$=new _e(!0),this.dialogShadowDOMExplicit$=new _e(void 0),this.textCommentToolShadowDOM$=new _e(!0),this.pinDarkMode$=new _e(null),this.textCommentToolDarkMode$=new _e(null),this.textCommentToolbarDarkMode$=new _e(null),this.textCommentToolbarShadowDOM$=new _e(!0),this.sidebarShadowDOM$=new _e(!0),this.changeDetectionInCommentMode$=new _e(!1),this.commentSelectionChange$=new at,this.visibilityOptionClicked$=new at,this.submitComment$=new at,this.clearComposer$=new at,this.composerDataMap=new Map,this.commentsFromSidebarMap$=new _e(null),this.sidebarButtonCountType$=new _e("default"),this.filterGhostCommentsInSidebar$=new _e(!1),this.commentSidebarFilters$=new _e(null),this.effectiveSidebarFilters$=new _e({}),this.customSidebarDataAnnotationIds$=new _e(null),this.commentSidebarSystemFiltersOperator$=new _e(qc.AND),this.bubbleCommentAnnotationIds$=new _e([]),this.updateCommentDialogPositionTriggerSubject$=new _e(void 0),this.areaCommentEnabled$=new _e(!0),this.commentPinCursorImage$=new _e(""),this.commentAnnotationsFromCommentsContainer$=new _e([]),this.customChipDropdownData$=new _e(null),this.originalCommentAnnotationsByDocumentId$=new _e({}),this.draftCommentAnnotationsByAnnotationId$=new _e(null),this.draftMultiThreadCommentAnnotationsByAnnotationId$=new _e({}),this.pendingAddCommentAnnotationData=new Map,this.copyLink$=new _e(""),this.addCommentDragMode=!1,this.dragSubscriptions=[],this.hotkeySubscriptions=[],this.sidebarData$=new _e(null),this.sidebarCustomActionEventData$=new _e(null),this.sidebarCustomActionEventDataAllChanges$=new _e(null),this.sidebarCustomActionEventDataOnInit$=new _e(null),this.customActions$=new _e(!1),this.focusedThreadMode$=new _e(!1),this.openAnnotationInFocusMode$=new _e(!1),this.customStatusesShown$=new _e(!1),this.readOnly$=new _e(!1),this.customAutocompleteSearch$=new _e(!1),this.deleteThreadWithFirstComment$=new _e(!0),this.assignToType$=new _e("dropdown"),this.pageModeComposerContext$=new _e(null),this.contextInPageModeComposer$=new _e(!1),this.focusPageModeComposer$=new at,this.transformContext$=new _e(null),this.expandMentionGroups$=new _e(!1),this.showMentionGroupsFirst$=new _e(!1),this.showMentionGroupsOnly$=new _e(!1),this.fullScreenInSidebar$=new _e(!1),this.composerFileAttachments$=new _e(null),this.attachmentNameInMessage$=new _e(!1),this.allowedFileTypes$=new _e([]),this.forceCloseAllOnEsc$=new _e(!1),this.autoCompleteScrollConfig$=new _e({itemSize:55,minBufferPx:350,maxBufferPx:600,templateCacheSize:350}),this.commentAnnotationContextDraft=null,this.getCommentAnnotationForClient=nt=>{try{let Et=["commentCategories","color","resolved","inProgress","positionX","positionY","screenWidth","screenHeight","screenScrollHeight","screenScrollTop","taggedElementPath","taggedElementRect","targetElement","position","documentParamsId","documentParams","ghostComment","areaAnnotationId","iam","commentSource","involvedUserIds","mentionedUserIds","viewedByUserIds","views"],Je=JSON.parse(JSON.stringify(nt)),$t={};Object.keys(Je).forEach(Yn=>{Et.includes(Yn)||($t[Yn]=Je[Yn])}),$t?.comments?.forEach(Yn=>{let xr=[];Yn?.reactionAnnotationIds&&Yn?.reactionAnnotationIds?.forEach(Io=>{let Kn=this.reactionService.getAnnotationById(Io);if(Kn){let ao=this.reactionService.getReactionAnnotationForClient(Kn);xr.push(ao)}}),Yn.reactionAnnotations=xr}),Je?.viewedByUserIds?.forEach(Yn=>{let xr=this.contactService.getUserBySnippylyId(Yn);xr&&($t.viewedBy||($t.viewedBy=[]),$t.viewedBy.push(xr))}),this.user?.userSnippylyId&&($t.unread=!Je?.viewedByUserIds?.includes(this.user.userSnippylyId));let an=Je?.targetElement?.anchor?.fXPath||Je?.targetElement?.fXpath;return an&&($t.basicAnchorData={xpath:an,topPercentage:Je?.targetElement?.topPercentage||0,leftPercentage:Je?.targetElement?.leftPercentage||0}),JSON.parse(JSON.stringify($t))}catch{return null}},this.loggingService.log("%c[WB] Creating CLASS: CommentService","color: blue;"),this.analyticsService.setCommentService(this),this.contactService.setCommentService(this),this.notificationService.setCommentService(this),this.docService.setCommentService(this),this.authService.setCommentService(this),this.viewsService.setCommentService(this),this.reactionService.setCommentService(this),this.recorderAnnotationService.setCommentService(this),this.domService.getSelectedAnnotationsMap$().pipe(Qr(100),Fr()).subscribe(([nt,Et])=>{try{if(this.draftCommentAnnotationsByAnnotationId$.value){let Je=Object.keys(this.draftCommentAnnotationsByAnnotationId$.value||{}),$t=[];Object.keys(nt||{}).forEach(Yn=>{!Et?.[Yn]&&Je.includes(Yn)&&$t.push(Yn)});let an=JSON.parse(JSON.stringify(this.draftCommentAnnotationsByAnnotationId$.value||{}));$t.forEach(Yn=>{delete an[Yn]}),sr(an,this.draftCommentAnnotationsByAnnotationId$.value)||this.draftCommentAnnotationsByAnnotationId$.next(an)}}catch{}}),this.docService.getDocumentPaths$().pipe(Fr()).subscribe(([nt,Et])=>{nt?.documentId!==Et?.documentId&&this.unreadCommentsMap$.next(null),Et&&this.shouldEnableReadOnly()},nt=>{this.loggingService.catch("Error in CommentService getDocumentPaths$ subscription: ",nt)}),this.draftCommentAnnotationsByAnnotationId$.pipe(Fr()).subscribe(([nt,Et])=>{try{if(this.pendingAddCommentAnnotationData.size===0)return;let Je=Object.keys(nt||{});if(Je.length===0)return;let $t=new Set(Object.keys(Et||{}));Je.forEach(an=>{!$t.has(an)&&this.pendingAddCommentAnnotationData.has(an)&&this.pendingAddCommentAnnotationData.delete(an)})}catch(Je){this.loggingService.catch("Error in CommentService pendingAddCommentAnnotationData reconcile: ",Je)}}),this.authService.getUser$().subscribe(nt=>{nt||this.resetCacheData()},nt=>{this.loggingService.catch("Error in CommentService getUser$ subscription: ",nt)}),this.authService.getUser$().pipe(Se(nt=>nt?gn([this.iamService.isUserAdmin$(),this.contactService.getUserOrganizationContacts$()]).pipe(ue(([Et,Je])=>{let $t=!1;return Je?.find(an=>an.userId===nt?.userId)&&($t=!0),{isUserAdmin:Et,isOrgUser:$t}})):ce({isUserAdmin:!1,isOrgUser:!1}))).subscribe(({isUserAdmin:nt,isOrgUser:Et})=>{let Je=nt||Et;Je!==this.privateCommentAllowed$.value&&this.privateCommentAllowed$.next(Je)}),this.databaseService.getDb().pipe(Ge(nt=>!!nt),ut(1)).subscribe(nt=>{nt&&this.getDocumentPaths()},nt=>{this.loggingService.catch("Error in CommentService getDb subscription: ",nt)}),this.domService.onWindowPointerMove$().subscribe(nt=>{if(this.addCommentMode$.value){let Et=!0;if(this.addCommentDragMode)this.domService.removeClassFromElement(document.body,"show-pin-cursor");else{let Je=this.domService.getBackgroundElement(nt.clientX,nt.clientY,!0,!0);if(Je&&xhe(Je,{x:nt.clientX,y:nt.clientY})&&(Je=Je?.parentElement),Je)if(this.isElementInsideAllowedElements(Je))if(xg(nt.target))this.domService.removeClassFromElement(document.body,"show-pin-cursor");else{this.domService.addClassToElement(document.body,"show-pin-cursor"),this.hightlightElement&&this.hightlightElement!==Je&&this.domService.removeHighlightFromElement(this.hightlightElement),this.hightlightElement=Je;let $t=this.domService.getSelectedAnnotationsMap("comment")||{},an=this.commentPinCursorImage$.value||N.CURSOR.COMMENT_PIN;this.domService.highlightElement(this.hightlightElement,an,!!Object.keys($t)?.length),Et=!1}else this.domService.removeClassFromElement(document.body,"show-pin-cursor")}this.hightlightElement&&Et&&(this.domService.removeHighlightFromElement(this.hightlightElement),this.hightlightElement=null)}},nt=>{this.loggingService.catch("Error in CommentService onWindowPointerMove$ subscription: ",nt)}),this.domService.onWindowKeyupEsc$().subscribe(nt=>{if(this.addCommentMode$.value){let Et=this.domService.getSelectedAnnotationsMap("comment")||{};Object.keys(Et)?.length&&this.domService.resetSelectedAnnotationsMap(),this.disableAddCommentMode()}},nt=>{this.loggingService.catch("Error in CommentService onWindowKeyupEsc$ subscription: ",nt)}),this.domService.onDocumentClick$().subscribe(nt=>{if(nt&&!JN(nt)){let Et=this.domService.getSelectedAnnotationsMap("comment")||{};if(Et=h(h({},Et),this.domService.getSelectedAnnotationsMap("multiThread")||{}),Object.keys(Et)?.length&&(this.domService.resetSelectedAnnotationsMap(),this.persistentCommentMode$?.value)){this.addCommentMode$.value&&this.detectToAddAreaComment(),nt.preventDefault(),nt.stopPropagation();return}}if(nt&&this.addCommentMode$.value&&!xg(nt.target)){let Et=!1;if(this.addCommentDragMode)nt.preventDefault(),nt.stopPropagation(),this.addCommentDragMode=!1;else if(!this.domService.getDraftCommentAnnotationDialogs()?.length){let Je=this.domService.getBackgroundElement(nt.clientX,nt.clientY);if((this.persistentCommentMode$?.value&&this.domService.getBackgroundVeltElement(nt.clientX,nt.clientY)||nt&&JN(nt))&&(Je=null),Je&&(this.isElementInsideAllowedElements(Je)||this.getCommentToNearestAllowedElement()&&this.getNearestAllowedElement(Je))&&(Et=this.isElementInsideManualCommentContainer(Je),!Et)){nt.preventDefault(),nt.stopPropagation();let $t=this.freeStyleCommentContext&&typeof this.freeStyleCommentContext=="object"?JSON.parse(JSON.stringify(this.freeStyleCommentContext)):void 0;this.addComment(nt,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,$t)}}this.persistentCommentMode$?.value?this.detectToAddAreaComment():Et||this.disableAddCommentMode()}},nt=>{this.loggingService.catch("Error in CommentService onDocumentClick$ subscription: ",nt)}),this.addCommentMode$.subscribe(nt=>{this.hightlightElement&&this.domService.removeHighlightFromElement(this.hightlightElement),nt?(this.domService.addClassToElement(document.body,"snippyly-add-comment-mode"),this.detectToAddAreaComment(),this.addIframeContainerStaticAttribute()):(this.removeIframeContainerStaticAttribute(),this.domService.removeClassFromElement(document.body,"snippyly-add-comment-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"),this.dragSubscriptions.forEach(Et=>Et.unsubscribe()),this.clearFreeStyleCommentContext())},nt=>{this.loggingService.catch("Error in CommentService addCommentMode$ subscription: ",nt)}),this.domService.onWindowKeyupBackspace$().subscribe(nt=>{this.getDeleteOnBackspace()&&this.deleteCommentPinAnnotations("keyupBackspace")},nt=>{this.loggingService.catch("Error in CommentService onWindowKeyupBackspace$ subscription: ",nt)}),this.domService.onWindowKeyupDelete$().subscribe(nt=>{this.deleteCommentPinAnnotations("keyupDelete")},nt=>{this.loggingService.catch("Error in CommentService onWindowKeyupDelete$ subscription: ",nt)}),this.domService.getDeleteCommmentAnnotations$().subscribe(nt=>{nt?.length&&(nt?.filter(Je=>!["tag","recorder","rewriter","arrow","area","multiThread"].includes(Je.type))).forEach(Je=>X(this,null,function*(){yield this.deleteCommentPinAnnotation(Je)}))},nt=>{this.loggingService.catch("Error in CommentService onWindowKeyupDelete$ subscription: ",nt)}),this.getPopoverMode$().subscribe(nt=>{nt?document?.body?.setAttribute(N.ATTRIBUTES.VELT_POPOVER_MODE,"true"):document?.body?.removeAttribute(N.ATTRIBUTES.VELT_POPOVER_MODE)},nt=>{this.loggingService.catch("Error in CommentService getPopoverMode subscription: ",nt)}),this.customFilterService.customCategoryMap$.subscribe(nt=>{this.customCategoryMap=nt},nt=>{this.loggingService.catch("Error in CommentService customCategoryMap$ subscription: ",nt)}),this.hotkeyEnabled$.subscribe(nt=>{nt?this.subscribeHotkeyEvents():this.unsubscribeHotkeyEvents()},nt=>{this.loggingService.catch("Error in CommentService hotkeyEnabled$ subscription: ",nt)}),this.domService.getSelectedAnnotationsMap$().pipe(Fr()).subscribe(([nt,Et])=>{try{let Je=Object.values(nt||{}).filter(an=>!["tag","recorder","rewriter","arrow","area"].includes(an.type)),$t=Object.values(Et||{}).filter(an=>!["tag","recorder","rewriter","arrow","area"].includes(an.type));Je?.forEach(an=>{$t?.find(Yn=>Yn.annotationId===an.annotationId)||this.commentSelectionChange$.next({annotation:this.getCommentAnnotationForClient(an),selected:!1})}),$t?.forEach(an=>{Je?.find(Yn=>Yn.annotationId===an.annotationId)||this.commentSelectionChange$.next({annotation:this.getCommentAnnotationForClient(an),selected:!0})})}catch(Je){this.loggingService.catch("Error in CommentService getSelectedAnnotationsMap$: ",Je)}},nt=>{this.loggingService.catch("Error in CommentService getSelectedAnnotationsMap$ subscription: ",nt)})}clearCache(){try{this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in CommentService","color: green;"),this.commentAnnotationById$.next(null),this.draftCommentAnnotationsByAnnotationId$.next(null),this.multiThreadCommentAnnotationById$.next({}),this.draftMultiThreadCommentAnnotationsByAnnotationId$.next({}),this.pendingAddCommentAnnotationData.clear(),this.customAutocompleteSearch$.next(!1),this.hightlightElement=null,this.addCommentMode$.next(!1),this.unreadCommentsMap$.next(null),this.documentPaths=null,this.commentsFromSidebarMap$.next(null),this.customSidebarDataAnnotationIds$.next(null)}catch(e){this.loggingService.catch("Error in CommentService clearCache: ",e)}}setCommentActionsService(e){try{this.commentActionsService=e}catch(t){this.loggingService.catch("Error in CommentService setCommentActionsService: ",t)}}detectToAddAreaComment(){try{let e=this.areaService.getAreaEnabled(),t=this.getAreaCommentEnabled();if(e&&t){let i,a,l,c=null,d=null;this.dragSubscriptions.forEach(m=>m.unsubscribe()),this.dragSubscriptions.push(this.domService.onWindowMouseDown$().pipe(Ge(m=>!(m&&JN(m))),ut(1)).subscribe(m=>{c=null,d=null,this.dragSubscriptions.push(this.domService.getClickAndDragPointsObservable().subscribe(u=>{if(c===null){let _=u?.startPoint?.event?.target,I=Mo(_),A=xg(_),M=this.isElementInsideAllowedElements(_);c=!I&&!A&&M}if(c){this.addCommentDragMode=!0,i=u.startPoint,a=u.curPoint;let _=u?.curPoint?.event?.target,I=Mo(_),A=xg(_),M=this.isElementInsideAllowedElements(_);d=!I&&!A&&M,d?l=this.domService.drawRectangle(i,a):l?.remove()}})),this.domService.onWindowPointerUp$().pipe(Dd(1),ut(1)).subscribe(u=>{if(a={x:u.clientX,y:u.clientY},i&&a&&(l?.remove(),c&&d)){let _=[{x:i.x-window.scrollX,y:i.y-window.scrollY},{x:a.x,y:a.y}],I=this.freeStyleCommentContext&&typeof this.freeStyleCommentContext=="object"?JSON.parse(JSON.stringify(this.freeStyleCommentContext)):void 0;this.addComment(u,void 0,_,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,I)}this.dragSubscriptions.forEach(_=>_.unsubscribe())})}))}}catch(e){this.loggingService.catch("Error in CommentService detectToAddAreaComment: ",e)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling CommentService FUNCTION: resetCacheData","color: green;"),this.commentAnnotationById$.next(null),this.draftCommentAnnotationsByAnnotationId$.next(null),this.multiThreadCommentAnnotationById$.next({}),this.draftMultiThreadCommentAnnotationsByAnnotationId$.next({}),this.pendingAddCommentAnnotationData.clear()}catch(e){this.loggingService.catch("Error in CommentService resetCacheData: ",e)}}addAreaContainerTag(){try{if(!(document.querySelector(N.TAGS.VELT_AREAS)||document.querySelector(N.TAGS.SNIPPYLY_AREAS))){let t=document.createElement(N.TAGS.VELT_AREAS);document.body.appendChild(t)}}catch(e){this.loggingService.catch("Error in CommentService addAreaContainerTag: ",e)}}addIframeContainerStaticAttribute(){try{document.querySelectorAll(`[${N.ATTRIBUTES.VELT_IFRAME_CONTAINER}]`).forEach(t=>{window.getComputedStyle(t).position==="static"&&t.setAttribute(N.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC,"true")})}catch(e){this.loggingService.catch("Error in CommentService addIframeContainerStaticAttribute: ",e)}}removeIframeContainerStaticAttribute(){try{document.querySelectorAll(`[${N.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC}]`).forEach(t=>{t.removeAttribute(N.ATTRIBUTES.VELT_IFRAME_CONTAINER_STATIC)})}catch(e){this.loggingService.catch("Error in CommentService removeIframeContainerStaticAttribute: ",e)}}subscribeHotkeyEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: subscribeHotkeyEvents","color: green;"),this.unsubscribeHotkeyEvents(),this.hotkeySubscriptions.push(this.hotkeyService.getKeyPressEvent("c").subscribe(e=>{e&&!this.addCommentMode$.value&&this.enableAddCommentMode()},e=>{this.loggingService.catch("Error in CommentService hotkeyService.getKeyPressEvent subscription: ",e)}))}catch(e){this.loggingService.catch("Error in CommentService subscribeHotkeyEvents: ",e)}}unsubscribeHotkeyEvents(){try{this.loggingService.log("%c[WB] Calling FUNCTION: unsubscribeHotkeyEvents","color: green;"),this.hotkeySubscriptions.forEach(e=>e?.unsubscribe())}catch(e){this.loggingService.catch("Error in CommentService unsubscribeHotkeyEvents: ",e)}}setCommentAddedEmitter(e){try{this.commentAddedEmitter=e}catch(t){this.loggingService.catch("Error in CommentService setCommentAddedEmitter: ",t)}}setContextProvider(e){try{this.commentContextProvider=e}catch(t){this.loggingService.catch("Error in CommentService setContextProvider: ",t)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$()}getAnonymousAvatarImage(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAnonymousAvatarImage","color: green;"),this.avatarService.generateUserImage()}setAllowedElementIds(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{allowedElementIds:e}}),this.allowedElementIds$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementIds: ",t)}}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}setAllowedElementClassNames(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{allowedElementClassNames:e}}),this.allowedElementClassNames$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementClassNames: ",t)}}getAllowedElementClassNames(){return this.allowedElementClassNames$.asObservable()}setAllowedElementQuerySelectors(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{allowedElementQuerySelectors:e}}),this.allowedElementQuerySelectors$.next(e||[])}catch(t){this.loggingService.catch("Error in CommentService setAllowedElementQuerySelectors: ",t)}}getAllowedElementQuerySelectors(){return this.allowedElementQuerySelectors$.asObservable()}getAllCommentAnnotations({customClientDocumentId:e,params:t,excludeDomChanges:i,detectGhostComments:a,skipPositionCalculation:l,query:c,fromCommentSidebar:d,analytics:m,addFilterCommentsOnDomCheck:u}){this.loggingService.log("%c[WB] Calling FUNCTION: getAllCommentAnnotations","color: green;");let _,I,A;m?.enabled&&this.analyticsService.trackEvent(m?.eventName||Y.Events.Comments.GET_ALL_COMMENT_ANNOTATIONS_TRIGGERED_INTERNAL,m?.properties);try{if(e&&(A=`${er(e)}`),t&&typeof t=="object"){let M=Oi(t);I=M?.id,_=er(JSON.stringify(M))}}catch(M){this.loggingService.catch("Error in CommentService getAllCommentAnnotations: ",M)}return _r(this.afAuth).pipe(Ge(M=>!!M),Se(M=>this.isFeatureAllowed({firebaseUser:M,annotations:[],filteredAnnotations:[]})),Se(M=>M.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(V=>(M.featureAllowed=V,M))):ce(M)),Se(M=>M.featureAllowed?ce(M).pipe(Se(V=>this.docService.getDocumentPaths$().pipe(ue(q=>(this.documentPaths=q,V.documentPaths=q,V)))),Se(V=>c?.documentIds?.length||A?this.getDataFromDocumentIds({documentIds:A?[A]:c?.documentIds?.map(q=>`${er(q)}`),organizationId:this.documentPaths?.organizationId,query:c}).pipe(ue(q=>({res:V,data:q}))):this.docService.getDocumentIds$().pipe(Se(q=>{let ae=q?.length>0?q.map(ye=>ye.documentId):[this.documentPaths?.documentId??""];return this.getDataFromDocumentIds({documentIds:ae.length>0?ae:[A??""],organizationId:this.documentPaths?.organizationId,query:c}).pipe(ue(ye=>({res:V,data:ye})))}))),Se(V=>V?.data?(V.res.annotations=V.data||[],ce(V.res).pipe(Se(q=>this.docService.getLocation$().pipe(ue(ae=>(q.location=ae,q)))),Se(q=>this.docService.getLocations$().pipe(ue(ae=>(q.customLocations=ae,q)))),Se(q=>this.docService.getExcludedLocationIds$().pipe(ue(ae=>(q.excludedLocationIds=ae,q)))),ue(q=>{if(q.filteredAnnotations=[],c)return q.filteredAnnotations=q.annotations?.slice(),q;if(A&&!_||d)return q.filteredAnnotations=q.annotations?.slice(),q?.excludedLocationIds?.length&&(q.filteredAnnotations=q.filteredAnnotations?.filter(ae=>ae?.location?.id?!q.excludedLocationIds.includes(ae.location.id):!0)),q;{let ae=[],ye=[];return _?(ae.push(_),I&&ye.push(I)):(ae.push(q?.location?.locationId),ae.push(...Object.values(q?.customLocations||[]).map(ie=>ie.locationId)),q?.location?.location?.id&&ye.push(q?.location?.location?.id),ye.push(...Object.values(q?.customLocations||{}).map(ie=>ie.location?.id).filter(ie=>!!ie))),q.filteredAnnotations=this.filterAnnotationsByLocationIds(q?.annotations,ae,ye),q?.excludedLocationIds?.length&&(q.filteredAnnotations=q.filteredAnnotations?.filter(ie=>ie?.location?.id?!q.excludedLocationIds.includes(ie.location.id):!0)),q}}),Se(q=>this.isPrivateCommentAllowed$().pipe(ue(ae=>(ae||(q.filteredAnnotations=q.filteredAnnotations?.filter(ye=>!El(ye))),q)))),Se(q=>this.draftCommentAnnotationsByAnnotationId$.pipe(ue(ae=>(q.filteredAnnotations=q.filteredAnnotations?.filter(ye=>!ye.isDraft),ae&&q.filteredAnnotations.push(...Object.values(ae)),q)))),Se(q=>i?ce(q):q?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onWindowResize$().pipe(ue(()=>q)):ce(q)),Se(q=>i?ce(q):this.addCommentMode$.pipe(Se(ae=>ae&&!this.getChangeDetectionInCommentMode()?ce(q):q?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onDomChange$("CommentService getAllCommentAnnotations").pipe(ue(()=>q)):ce(q)))),ue(q=>{if(!l){(!this.getPopoverMode()||this.getPopoverTriangleComponent())&&(q.filteredAnnotations=q.filteredAnnotations?.map(ye=>{let ie=Object.assign({},ye);return this.calculateCommentAnnotationPosition(ie,a),ie}));let ae={};q.filteredAnnotations?.forEach(ye=>{if(ye?.targetTextRange){let ie=this.domService.getElementFromTargetTextRange(ye?.targetTextRange);ae[ye.annotationId]=!!ie}}),q.textAnnotationsElementMap=ae}return q}),Se(q=>q?.annotations?.length?this.viewsService.getCommentFeatureViews$().pipe(ue(ae=>(this.updateUnreadAnnotationsMap(q?.annotations,ae),q))):(ZWe(this.unreadCommentsMap$.value)&&this.unreadCommentsMap$.next({}),ce(q))))):ce(null))):ce(null)),ue(M=>{try{return typeof M=="object"&&M?JSON.parse(JSON.stringify(M)):M}catch{return M}}),_t((M,V)=>Kt(M?.filteredAnnotations,V?.filteredAnnotations)&&Kt(M?.textAnnotationsElementMap,V?.textAnnotationsElementMap)),Se(M=>M?M?.filteredAnnotations?ce(M?.filteredAnnotations||[]):ce([]):ce(null)),Se(M=>u?this.filterCommentsUsingSidebarSettings(M):ce(M)))}getAllMultiThreadCommentAnnotations(e,t,i,a,l,c){this.loggingService.log("%c[WB] Calling FUNCTION: getAllMultiThreadCommentAnnotations","color: green;");let d,m;try{if(e&&(m=er(e)),t&&typeof t=="object"){let u=Oi(t);d=er(JSON.stringify(u))}}catch(u){this.loggingService.catch("Error in CommentService getAllMultiThreadCommentAnnotations: ",u)}return _r(this.afAuth).pipe(Ge(u=>!!u),Se(u=>this.isFeatureAllowed({firebaseUser:u,annotations:[],filteredAnnotations:[]})),Se(u=>u.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(_=>(u.featureAllowed=_,u))):ce(u)),Se(u=>u.featureAllowed?ce(u).pipe(Se(_=>this.docService.getDocumentPaths$().pipe(ue(I=>(this.documentPaths=I,_.documentPaths=I,_)))),Se(_=>m?this.getMultiThreadDataFromDocumentIds([m]).pipe(ue(I=>({res:_,data:I}))):this.docService.getDocumentIds$().pipe(Se(I=>{let A=I?.length>0?I.map(M=>M.documentId):[this.documentPaths?.documentId??""];return this.getMultiThreadDataFromDocumentIds(A.length>0?A:[`${m}`]).pipe(ue(M=>({res:_,data:M})))}))),Se(({res:_,data:I})=>I?(_.annotations=I||[],ce(_).pipe(Se(A=>this.docService.getLocation$().pipe(ue(M=>(A.location=M,A)))),Se(A=>this.docService.getLocations$().pipe(ue(M=>(A.customLocations=M,A)))),Se(A=>this.docService.getExcludedLocationIds$().pipe(ue(M=>(A.excludedLocationIds=M,A)))),ue(A=>{if(A.filteredAnnotations=[],m&&!d)return A.filteredAnnotations=A.annotations?.slice(),A?.excludedLocationIds?.length&&(A.filteredAnnotations=A.filteredAnnotations?.filter(M=>M?.location?.id?!A.excludedLocationIds.includes(M.location.id):!0)),A;{let M=[],V=[];return d?M.push(d):(M.push(A?.location?.locationId),M.push(...Object.values(A?.customLocations||[]).map(q=>q.locationId)),A?.location?.location?.id&&V.push(A?.location?.location?.id),V.push(...Object.values(A?.customLocations||{}).map(q=>q.location?.id).filter(q=>!!q))),A.filteredAnnotations=this.filterAnnotationsByLocationIds(A?.annotations,M,V),A?.excludedLocationIds?.length&&(A.filteredAnnotations=A.filteredAnnotations?.filter(q=>q?.location?.id?!A.excludedLocationIds.includes(q.location.id):!0)),A}}),Se(A=>this.draftMultiThreadCommentAnnotationsByAnnotationId$.pipe(ue(M=>(A.filteredAnnotations=A.filteredAnnotations?.filter(V=>!V.isDraft),M&&A.filteredAnnotations.push(...Object.values(M)),A)))),Se(A=>i?ce(A):A?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onWindowResize$().pipe(ue(()=>A)):ce(A)),Se(A=>i?ce(A):this.addCommentMode$.pipe(Se(M=>M&&!this.getChangeDetectionInCommentMode()?ce(A):A?.annotations?.length&&(!this.getPopoverMode()||this.getPopoverTriangleComponent())?this.domService.onDomChange$("CommentService getAllMultiThreadCommentAnnotations").pipe(ue(()=>A)):ce(A)))),ue(A=>(l||(!this.getPopoverMode()||this.getPopoverTriangleComponent())&&(A.filteredAnnotations=A.filteredAnnotations?.map(M=>{let V=Object.assign({},M);return this.calculateCommentAnnotationPosition(V,a),V})),A)),Se(A=>A?.filteredAnnotations?ce(A?.filteredAnnotations||[]):ce([])))):ce(null))):ce(null)),_t(Kt),Se(u=>c?this.filterCommentsUsingSidebarSettings(u):ce(u)))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})),Se(t=>this.authService.getUser$().pipe(ue(i=>(this.user=i,y(h({},t),{user:i}))))),Se(t=>Ao(t.config,t.user,je.COMMENT)?ce(y(h({},t),{featureAllowed:!0})):(this.loggingService.warn("Comment feature is not allowed."),ce(y(h({},t),{featureAllowed:!1})))),_t((t,i)=>t?.featureAllowed===i?.featureAllowed))}buildVisibilityTokens(e,t,i){try{let a=It(t),l=[N.DEFAULT_VELT_CONTEXT,`${N.VISIBILITY_SELF_PREFIX}${a}`],c=e?.[t];return i&&c?.organization?.[i]?.accessRole&&l.push(`organizationPrivate:${i}`),l}catch(a){return this.loggingService.catch("Error in CommentService buildVisibilityTokens: ",a),[N.DEFAULT_VELT_CONTEXT]}}getDataFromDocuments(e){let{documentIds:t,organizationId:i,query:a}=e;if(!this.configService?.getApiKey())return ce(null);if(t?.some(A=>!A)||!this.documentPaths)return ce(null);let l,c,d=[];if(a)a?.folderId&&(l=Lr(a?.folderId)),a?.locationId&&(d=[...d,a?.locationId]),a?.locationIds?.length&&(d=[...d,...a?.locationIds]),c=a?.statusIds;else{l=this.docService.getDocumentPaths()?.veltFolderId;let A=this.docService.getDocumentPaths()?.locationId;A&&(d=[...d,A])}let m={useCollectionGroup:!0,isCollection:!0,useQuery:!0};this.commonDbService.shouldUseFirestore()||(m.documentId=t?.length?t[0]:void 0,m.organizationId=this.documentPaths?.organizationId);let u=this.authService.getUser()?.userId;if(!u)return ce(null);let _=this.authService.getIsPrivateCommentsEnabled();return(_?this.userPermissionService.getCurrentUserPermissionsWithServerIds$().pipe(Ge(A=>A!==null&&!!A[u])):ce(null)).pipe(Se(A=>{let M=_?this.buildVisibilityTokens(A,u,i??this.documentPaths?.organizationId):[N.DEFAULT_VELT_CONTEXT],V=this.userPermissionService?.getIsContextEnabled()?this.docService.getProcessedDocContext():[],q=[...M,...V],ae=this.userPermissionService?.getIsContextEnabled(),ye;if(ae){let ie=[];for(let ge=0;ge<q.length;ge+=N.LISTENER_CONTEXT_BATCH_SIZE)ie.push(q.slice(ge,ge+N.LISTENER_CONTEXT_BATCH_SIZE));this.loggingService.logContext("[CONTEXT] getDataFromDocuments called with accessFields:",JSON.parse(JSON.stringify(q??"nil"))),ye=gn(ie.map(ge=>this.commonDbService.dbListener({feature:"allComments",properties:y(h({},m),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.organizationId","==",i??this.documentPaths?.organizationId),ft("metadata.documentId","in",t),...c?.length?[ft("status.id","in",c)]:[],...l?[ft("metadata.veltFolderId","==",l)]:[],...d?.length?[ft("location.id","in",d)]:[],...ge?.length?[ft("context.accessFields","array-contains-any",ge)]:[]),uo("lastUpdated","desc"),uo("createdAt","desc")]})}).pipe(la()))).pipe(ue(ge=>Na(JSON.parse(JSON.stringify(ge)))))}else{let ie=[];for(let ge=0;ge<(t?.length??0);ge+=N.LISTENER_BATCH_SIZE)ie.push(t?.slice(ge,ge+N.LISTENER_BATCH_SIZE)??[]);ye=gn(ie.map(ge=>this.commonDbService.dbListener({feature:"allComments",properties:y(h({},m),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.organizationId","==",i??this.documentPaths?.organizationId),ft("metadata.documentId","in",ge),...c?.length?[ft("status.id","in",c)]:[],...l?[ft("metadata.veltFolderId","==",l)]:[],...d?.length?[ft("location.id","in",d)]:[],...q?.length&&_?[ft("context.accessFields","array-contains-any",q)]:[]),uo("lastUpdated","desc"),uo("createdAt","desc")]})}).pipe(la()))).pipe(ue(ge=>Na(JSON.parse(JSON.stringify(ge)))))}return ye.pipe(Se(ie=>ie?.data?ce(ie).pipe(Se(ge=>this.commonDbUtilsService.mergeLocationMetadataWithData$({data:ge,feature:"allComments"}).pipe(ue(Ie=>({data:Object.values(Ie?.data||{}).filter(he=>typeof he=="object"),operation:Ie?.operation})))),ue(({data:ge,operation:Ie})=>{let he=ge.reduce((Te,Oe)=>{let Pe=Oe.metadata?.documentId;return Pe&&(Te[Pe]||(Te[Pe]=[]),Te[Pe].push(Oe)),Te},{});return{data:ge,documentMap:he,operation:Ie}}),ue(({data:ge,documentMap:Ie,operation:he})=>c?{data:ge,documentMap:Ie,operation:he}:(ge?.length&&(ge?.forEach(Te=>{this.sanitizeCommentAnnotation(Te)}),this.setAnnotationIndex(ge),this.updateAnnotationsForSelectAllContentMode(ge),ge.forEach(Te=>{this.customFilterService.convertLegacyAnnotationStatus(Te),this.customFilterService.convertLegacyPriority(Te),this.customFilterService.convertLegacyCategory(Te)})),{data:ge,documentMap:Ie,operation:he})),Xn(ge=>(this.loggingService.catch("Error in CommentService getDataFromDocuments: ",ge),ce([]))),ln(({documentMap:ge})=>{c||Object.entries(ge??{}).forEach(([Ie,he])=>{this.setOriginalCommentAnnotationsByAnnotationId(JSON.parse(JSON.stringify(he)))})}),ue(({data:ge,documentMap:Ie,operation:he})=>({data:this.filterUserDraftComments(ge),documentMap:Ie,operation:he})),ue(({data:ge,documentMap:Ie,operation:he})=>({data:this.removeDraftFlags(ge),documentMap:Ie,operation:he})),Se(({data:ge,documentMap:Ie,operation:he})=>c?ce({data:ge,documentMap:Ie,operation:he}):this.mergeDraftAnnotations(ge).pipe(ue(Te=>({data:Te,documentMap:Ie,operation:he})))),ue(({data:ge,documentMap:Ie,operation:he})=>{if(!c)if(he?.type==="removed"){if(he?.ids?.length){let Te=this.commentAnnotationById$.value??{};he?.ids?.forEach(Oe=>{delete Te?.[Oe]}),this.commentAnnotationById$.next(Te)}}else Object.entries(Ie??{}).length?Object.entries(Ie??{}).forEach(([Oe,Pe])=>{this.setCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:Oe,annotations:Pe})}):this.commentAnnotationById$.value||this.commentAnnotationById$.next({});return ge})):ce(null)))}))}fetchCommentAnnotations(e){return X(this,null,function*(){try{let t=this.authService.getUser();if(!t)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),{data:[],hasMore:!1};let i=this.configService?.getApiKey(),a=e?.organizationId??t?.clientOrganizationId,l=ba(a??""),c=[];e?.allDocuments||(c=e?.documentIds?.map(M=>mi(M??""))??this.docService.getDocumentIds()?.map(M=>M.documentId));let d=[];if(d.push(ft("metadata.organizationId","==",l)),d.push(ft("metadata.apiKey","==",i)),e?.folderId){let M=Lr(e?.folderId);d.push(ft("metadata.veltFolderId","==",M))}if(e?.locationId&&d.push(ft("location.id","==",e?.locationId)),c?.length&&d.push(ft("metadata.documentId","in",c)),e?.resolvedBy){if(e?.order==="asc")throw new Error("Order by resolvedBy is not supported in ascending order.");d.push(ft("resolvedByUserId","==",e?.resolvedBy))}if(e?.mentionedUserIds?.length){if(e?.order==="asc")throw new Error("Order by mentionedUserIds is not supported in ascending order.");d.push(ft("mentionedUserIds","array-contains-any",e?.mentionedUserIds))}if(e?.userIds?.length){if(e?.order==="asc")throw new Error("Order by userIds is not supported in ascending order.");d.push(ft("from.userId","in",e?.userIds))}if(e?.statusIds?.length){if(e?.order==="asc")throw new Error("Order by status id is not supported in ascending order.");d.push(ft("status.id","in",e?.statusIds))}let m=new Date().getTime();if(e?.createdAfter&&d.push(ft("createdAt",">=",e?.createdAfter)),e?.createdBefore&&d.push(ft("createdAt","<=",e?.createdBefore??m)),e?.updatedAfter&&d.push(ft("lastUpdated",">=",e?.updatedAfter??m)),e?.updatedBefore&&d.push(ft("lastUpdated","<=",e?.updatedBefore??m)),d.push(uo("lastUpdated",e?.order??"desc"),uo("createdAt",e?.order??"desc")),e?.pageToken){let M=yield WK(e?.pageToken??"","veltencrypttoken","veltencrypttoken");d.push(sbe(parseInt(M,10),"lastUpdated"))}let u=e?.pageSize??100;d.push(hm(u+1));let _=yield this.commonDbService.queryData({feature:"allComments",properties:{useCollectionGroup:!0,isCollection:!0,useQuery:!0,firestoreQuery:d,apiKey:i??"",organizationId:l}}),I=_.length>u;_=_.slice(0,u);let A=_?.reduce((M,V)=>(M[V?.annotationId]=V,M),{});return A=yield this.commonDbUtilsService.formatResponse({feature:"allComments",data:A,shouldAwait:!0}),A=this.commonDbUtilsService.mergeUsersWithData({feature:"allComments",data:A}),{data:Object.values(A??{}),hasMore:I}}catch(t){throw this.loggingService.catch("Error in CommentService fetchCommentAnnotations:",t),t}})}filterUserDraftComments(e){let t=this.authService.getUser();return e.filter(i=>(i.comments=i?.comments?.filter(a=>a?.from?.userId===t?.userId||!a?.isDraft),!!i?.comments?.length))}removeDraftFlags(e){return e.forEach(t=>delete t.isDraft),e}mergeDraftAnnotations(e){return this.draftCommentAnnotationsByAnnotationId$.pipe(ue(t=>{let i=t||{};return e?.filter(a=>{i?.[a?.annotationId]&&delete i[a?.annotationId]}),i}),ue(t=>{if(t){let i=e.slice();return i.push(...Object.values(t)),i}return e}))}getDataFromDocumentIds({documentIds:e,organizationId:t,query:i}){return this.getDataFromDocuments({documentIds:e,organizationId:t,query:i})}getMultiThreadDataFromDocumentIds(e){return this.getMultiThreadDataFromDocuments({documentIds:e})}getMultiThreadDataFromDocuments(e){if(this.configService?.getApiKey()){let{documentIds:t}=e;if(t?.some(c=>!c)||!this.documentPaths)return ce(null);let i=this.docService.getDocumentPaths()?.veltFolderId,a=ce([]),l={useCollectionGroup:!0,isCollection:!0,useQuery:!0};if(this.commonDbService.shouldUseFirestore()||(l.documentId=t?.length?t[0]:void 0,l.organizationId=this.documentPaths?.organizationId),this.userPermissionService?.getIsContextEnabled()){let c=[N.DEFAULT_VELT_CONTEXT,...this.docService.getProcessedDocContext()],d=[];for(let m=0;m<(c?.length??0);m+=N.LISTENER_CONTEXT_BATCH_SIZE)d.push(c?.slice(m,m+N.LISTENER_CONTEXT_BATCH_SIZE)??[]);a=gn(d.map(m=>this.commonDbService.dbListener({feature:"allMultiThreads",properties:y(h({},l),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.organizationId","==",this.documentPaths?.organizationId),ft("metadata.documentId","in",t),...i?[ft("metadata.veltFolderId","==",i)]:[],...m?.length?[ft("context.accessFields","array-contains-any",m)]:[])]})}).pipe(la()))).pipe(ue(m=>Na(m)))}else{let c=[];for(let d=0;d<(t?.length??0);d+=N.LISTENER_BATCH_SIZE)c.push(t?.slice(d,d+N.LISTENER_BATCH_SIZE)??[]);a=gn(c.map(d=>this.commonDbService.dbListener({feature:"allMultiThreads",properties:y(h({},l),{firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.organizationId","==",this.documentPaths?.organizationId),ft("metadata.documentId","in",d),...i?[ft("metadata.veltFolderId","==",i)]:[])]})}).pipe(la()))).pipe(ue(d=>Na(d)))}return a.pipe(Se(c=>c?.data?ce(c).pipe(ue(d=>({data:d?.data,operation:d?.operation})),ue(({data:d,operation:m})=>{let u=[];return d&&(u=Object.values(d??{}).filter(_=>typeof _=="object")),{data:u,operation:m}}),Xn(d=>(this.loggingService.catch("Error in CommentService getMultiThreadDataFromDocumentId: ",d),ce({data:[],operation:null}))),ue(({data:d,operation:m})=>{d.forEach(_=>{delete _.isDraft});let u=d.reduce((_,I)=>{let A=I.metadata?.documentId;return A&&(_[A]||(_[A]=[]),_[A].push(I)),_},{});return{data:d,documentMap:u,operation:m}}),Se(({data:d,documentMap:m,operation:u})=>{let _=[];return this.commentAnnotationById$.pipe(Se(()=>this.domService.getSelectedAnnotationsMap$().pipe(ue(I=>({selectedAnnotationsMap:I})))),ue(({selectedAnnotationsMap:I})=>{let A={};return Object.keys(m??{}).forEach(M=>{let V=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:M});V&&V?.forEach(q=>{A[q?.annotationId]=q})}),_=d.filter(M=>{let V=!1;if(M?.commentAnnotations){for(let q in M?.commentAnnotations)if(A?.[q]&&A?.[q]?.status?.id!==this.customFilterService.resolvedStatus.id){V=!0;break}}return V}),_.forEach(M=>{Object.keys(M?.commentAnnotations||{}).forEach(V=>{M.commentAnnotationsMap||(M.commentAnnotationsMap={}),M.commentAnnotationsMap[V]=A?.[V]})}),{data:_,operation:u}}))}),Se(({data:d,operation:m})=>this.draftMultiThreadCommentAnnotationsByAnnotationId$.pipe(ue(u=>{let _=u||{};return d?.filter(I=>{_?.[I?.annotationId]&&delete _[I?.annotationId]}),_}),ue(u=>{if(u){let _=d.slice();return _.push(...Object.values(u)),{data:_,operation:m}}return{data:d,operation:m}}))),ue(({data:d,operation:m})=>{let u=d.reduce((_,I)=>{let A=I.metadata?.documentId;return A&&(_[A]||(_[A]=[]),_[A].push(I)),_},{});if(m?.type==="removed"){if(m?.ids?.length){let _=this.multiThreadCommentAnnotationById$.value;m?.ids?.forEach(I=>{delete _?.[I]}),this.multiThreadCommentAnnotationById$.next(_)}}else Object.keys(u??{}).forEach(_=>{this.setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:this.documentPaths?.organizationId,documentId:_,annotations:u[_]})});return d})):ce(null)))}else return ce(null)}updateUnreadAnnotationsMap(e,t){try{let i=new Date(N.UNREAD_COMMENTS_CHECK_FROM_DATE)?.getTime(),a=e.filter(l=>l?.lastUpdated>i);if(t){let l={},c=!1;a.forEach(d=>{let m=0,u=t?.[d?.annotationId];if(u){let _=u?.comments;_&&d?.comments?.forEach(I=>{_?.[I?.commentId]?.views?.[this.user?.userSnippylyId]||m++})}m?m!==l?.[d?.annotationId]&&(l[d?.annotationId]=m,c=!0):l?.[d?.annotationId]&&(delete l[d?.annotationId],c=!0)}),this.unreadCommentsMap$.next(l)}}catch(i){this.loggingService.catch("Error in CommentService updateUnreadAnnotationsMap:",i)}}updateAnnotationsForSelectAllContentMode(e){try{e.forEach(t=>{if(t?.selectAllContent&&t?.targetElementId){let i=nl(t.targetElementId,["id","data-id"]);if(i){let a=i.textContent;a&&(t.targetTextRange={commonAncestorContainer:this.domService.getXPath(i),text:a,occurrence:1,commonAncestorContainerAnchor:this.domService.generateAnchorRecord(i)??void 0},delete t?.targetElement)}}})}catch(t){this.loggingService.catch("Error in CommentService updateAnnotationsForSelectAllContentMode:",t)}}setCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:i,queryHash:a}){try{if(t){e||(e=N.NO_ORGANIZATION_ID),a||(a=N.DEFAULT_QUERY_HASH);let l={};i?.forEach(d=>{d?.annotationId&&(l[d?.annotationId]=d)});let c=h(h({},this.commentAnnotationById$.value??{}),l);this.commentAnnotationById$.next(c)}}catch(l){this.loggingService.catch("Error in CommentService setCommentAnnotationsByOrganizationIdAndDocumentId:",l)}}getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e,documentId:t}){try{return this.commentAnnotationById$.pipe(Se(()=>this.draftCommentAnnotationsByAnnotationId$),ue(()=>this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t})))}catch(i){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByOrganizationIdAndDocumentId$:",i),ce([])}}getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let i=null;this.commentAnnotationById$.value&&(i={},Object.values(this.commentAnnotationById$.value).forEach(l=>{l?.metadata?.documentId==t&&l?.metadata?.organizationId==e&&(i[l?.annotationId]=l)}));let a=this.draftCommentAnnotationsByAnnotationId$.value;return a&&(i===null&&(i={}),Object.values(a).forEach(l=>{l?.metadata?.documentId===t&&l?.metadata?.organizationId===e&&!i[l?.annotationId]&&(i[l?.annotationId]=l)})),i?Object.values(i):null}catch(i){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByOrganizationIdAndDocumentId:",i),[]}}getCommentAnnotationsByDocumentId$({clientDocumentId:e,documentId:t}){try{return e&&!t&&(t=this.docService.generateDocumentId(e)),t?this.docService.getDocumentPaths$().pipe(Se(i=>this.getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:i?.organizationId,documentId:t}))):ce(null)}catch(i){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByDocumentId$:",i),ce(null)}}getCommentAnnotationsOnCurrentOrganizationAndDocument$(){return this.docService.getDocumentPaths$().pipe(Se(e=>e?.documentId?this.getCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e.organizationId,documentId:e.documentId}):ce([])))}getCommentAnnotationsOnCurrentOrganizationAndDocument(){try{let e=this.docService.getDocumentPaths();return e?.documentId?this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e?.organizationId,documentId:e?.documentId}):[]}catch(e){return this.loggingService.catch("Error in CommentService getCommentAnnotationsOnCurrentOrganizationAndDocument:",e),[]}}setOriginalCommentAnnotationsByAnnotationId(e){try{let t={};e?.forEach(i=>{i?.annotationId&&(t[i?.annotationId]=i)}),this.originalCommentAnnotationsByDocumentId$.next(h(h({},this.originalCommentAnnotationsByDocumentId$.value),t))}catch(t){this.loggingService.catch("Error in CommentService setOriginalCommentAnnotationsByAnnotationId:",t)}}setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t,annotations:i,queryHash:a}){try{if(t){e||(e=N.NO_ORGANIZATION_ID),a||(a=N.DEFAULT_QUERY_HASH);let l={};i.forEach(d=>{d?.annotationId&&(l[d?.annotationId]=d)});let c=h(h({},this.multiThreadCommentAnnotationById$.value),l);this.multiThreadCommentAnnotationById$.next(c)}}catch(l){this.loggingService.catch("Error in CommentService setMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId:",l)}}getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e,documentId:t}){return this.multiThreadCommentAnnotationById$.pipe(ue(()=>this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t})))}getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e,documentId:t}){try{let i={};Object.values(this.multiThreadCommentAnnotationById$.value??{}).forEach(l=>{l?.metadata?.documentId==t&&l?.metadata?.organizationId==e&&(i[l?.annotationId]=l)});let a=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value;return a&&Object.values(a??{}).forEach(l=>{l?.metadata?.documentId===t&&l?.metadata?.organizationId===e&&!i[l?.annotationId]&&(i[l?.annotationId]=l)}),Object.values(i)}catch(i){return this.loggingService.catch("Error in CommentService getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId:",i),[]}}getMultiThreadCommentAnnotationsOnCurrentOrganizationAndDocument$(){return this.docService.getDocumentPaths$().pipe(Se(e=>e?.documentId?this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId$({organizationId:e.organizationId,documentId:e.documentId}):ce([])))}getMultiThreadCommentAnnotationsOnCurrentOrganizationAndDocument(){try{let e=this.docService.getDocumentPaths();return this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:e?.organizationId,documentId:e?.documentId})}catch(e){return this.loggingService.catch("Error in CommentService getMultiThreadCommentAnnotationsOnCurrentOrganizationAndDocument:",e),[]}}getLocations$(){return this.docService.getLocation$().pipe(Se(e=>this.docService.getLocations$().pipe(ue(t=>({location:e,locations:t})))),ue(e=>{let t=[];return t.push(e?.location?.locationId),t.push(...Object.values(e.locations||[]).map(i=>i.locationId)),t||[]}))}filterAnnotationsByLocationIds(e,t,i){try{return e.filter(a=>t.includes(a.locationId)||i?.includes(a?.location?.id)||t?.find(l=>l==a?.location?.id)||i?.find(l=>l==a?.locationId+""))}catch(a){return this.loggingService.catch("Error in CommentService filterAnnotationsByLocations:",a),[]}}setAnnotationIndex(e){try{e.forEach((t,i)=>{t?.annotationId&&(t.annotationIndex=i+1)})}catch(t){this.loggingService.catch("Error in CommentService setAnnotationIndex:",t)}}calculateCommentAnnotationPosition(e,t){try{if(e.multiThreadAnnotationId)return;if(e.targetElementId){let i=nl(e.targetElementId,["id","data-id"]);if(i&&this.domService.isElementVisible(i)){let a=i.getAttribute(N.ATTRIBUTES.VELT_COMMENT_TYPE),l=!0;if(a)switch(a){case"popover":l=!0;break;default:l=!1;break}else{let c=document.querySelector(`${N.TAGS.VELT_INLINE_COMMENTS_SECTION}[${N.ATTRIBUTES.TARGET_INLINE_COMMENT_ELEMENT_ID}="${e.targetElementId}"], ${N.TAGS.VELT_INLINE_COMMENTS_SECTION}[${N.ATTRIBUTES.TARGET_COMMENT_ELEMENT_ID}="${e.targetElementId}"], ${N.TAGS.VELT_INLINE_COMMENTS_SECTION}[${N.ATTRIBUTES.TARGET_ELEMENT_ID}="${e.targetElementId}"]`);c&&i?.contains(c)&&(l=!1)}l?e.targetElement={xpath:this.domService.getXPath(i),fXpath:this.domService.getXPath(i,!0),cfXpath:this.domService.getXPath(i,!0,!0),topPercentage:e.targetElement?.topPercentage||50,leftPercentage:e.targetElement?.leftPercentage||90}:e.targetElement=null}else e.targetElement=null}if(e.targetElement){e.position=null,e.ghostComment=null;let i=e.targetElement?.xpath,a=null,l=e?.targetElement?.anchor;if(l){let d=this.domService.resolveAnchorRecord(l);d?.element&&this.domService.isElementVisible(d.element)&&Kr(d.element)&&(a=d.element)}else i&&(a=this.domService.getElementFromXPath(i),this.domService.isXpathWithId(i)||((!a||!this.domService.isElementVisible(a))&&e.targetElement?.cfXpath&&(i=e.targetElement?.cfXpath,a=this.domService.getElementFromXPath(i)),this.getDetectionStrategy()===wN.DYNAMIC_ID&&(!a||!this.domService.isElementVisible(a))&&(i=e.targetElement?.fXpath,i&&(a=this.domService.getElementFromXPath(i)))));(!a||!this.domService.isElementVisible(a))&&t&&(e.ghostComment={},this.setGhostCommentMessage(e),e.ghostComment.targetElement=this.getGhostCommentTargetElement(e),e?.ghostComment?.targetElement?.xpath&&(a=this.domService.getElementFromXPath(e?.ghostComment?.targetElement?.xpath)));let c=!1;if(e?.locationId){let d=this.docService.getLocation();if(!_0({location:d?.location,locationId:d?.locationId},{location:e?.location,locationId:e?.locationId})){let m=this.docService.getAdditionLocationFromElement(a),u=m?this.docService.genarateLocationId(m):void 0;e?.location?.id&&e?.location?.id===m?.id||u&&u===e?.locationId?c=!1:c=!0}}if(c&&(e.ghostComment=null),!c&&a&&Kr(a)&&!a?.closest(".cdk-overlay-container")&&a?.getBoundingClientRect()){let m=this.popoverMode$?.value?0:e.targetElement?.topPercentage,u=this.popoverMode$?.value?100:e.targetElement?.leftPercentage,{height:_,width:I}=np(a);e.position={top:_*(m||0)/100,left:I*(u||0)/100};let A=window.getComputedStyle(a).transform;if(A&&A!=="none")try{let M=new DOMMatrixReadOnly(A),V=Math.sqrt(M.a*M.a+M.b*M.b)||1,q=Math.sqrt(M.c*M.c+M.d*M.d)||1;(Math.abs(V-1)>.01||Math.abs(q-1)>.01)&&(e.position.parentScaleX=V,e.position.parentScaleY=q)}catch{}if(this.transformContext$.value){let{containerSelector:M,transforms:V}=this.transformContext$.value,q=document.querySelector(M);q&&q.contains(a)&&(e.position.transformContext=V)}}!c&&t&&!e?.position&&!e?.ghostComment&&(e.ghostComment={},this.setGhostCommentMessage(e),e.ghostComment.targetElement=e.targetElement)}t&&(e.ghostComment?this.addAnnotationToGhostCommentAnnotationMap(e):this.removeAnnotationFromGhostCommentAnnotationMap(e))}catch(i){this.loggingService.catch("Error in CommentService calculateCommentAnnotationPosition:",i)}}addComment($e,ze,We,gr,nt){return X(this,arguments,function*(e,t,i,a,l,c=[],d,m,u,_,I,A,M,V,q,ae,ye,ie,ge,Ie,he,Te,Oe,Pe){this.loggingService.log("%c[WB] Calling FUNCTION: addComment","color: green;");try{let Et=this.authService.getUser();if(Et)if(Et.isReadOnly||Et.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add comments.");else{yield this.triggerAddCommentAnnotationDraftEvent();let Je=new Nr;ye&&(Je=h(h({},Je),ye)),Je.comments=[],ye?.comments?.length&&(Je.comments=ye.comments.map(Pn=>{let bn=new Xl;return bn=h(h({},bn),Pn),bn.from=Et,bn.lastUpdated=new Date,bn.createdAt=this.timestamp,bn})),Je.from=Et,Je.color=Je?.color||N.DEFAULT_ANNOTATION_COLOR,Je.lastUpdated=this.timestamp,Je.createdAt=this.timestamp,Je.sourceId=q,Je.assignedTo=ye?.assignedTo||ae,Je.customList=ye?.customList||[],Te&&(Je.targetElementId=Te);let{topPositionX:$t,topPositionY:an}=this.domService.getTopLeftPosition();Je.positionX=$t,Je.positionY=an;let Yn=this.domService.getCurrentWindowSizeValue();if(Je.screenWidth=Yn.screenWidth,Je.screenHeight=Yn.screenHeight,Je.screenScrollHeight=Yn.screenScrollHeight,Je.taggedElementPath="",e&&(Je.targetElement=this.domService.getTargetElementForCursorPosition(e,!0,!0,!0,Pn=>{if(this.getSvgAsImg()){let bn=Pn?.closest(`[${N.ATTRIBUTES.VELT_COMMENT_CONTAINER}]`);bn&&bn instanceof HTMLElement&&(Pn=bn)}if(this.getPopoverMode()){let bn=Pn?.closest(`[${N.ATTRIBUTES.VELT_TARGET_COMMENT_ELEMENT_ID}]`);if(bn&&bn instanceof HTMLElement)return bn}return Pn}),this.getCommentToNearestAllowedElement()&&Je.targetElement?.xpath)){let Pn=this.domService.getElementFromXPath(Je.targetElement.xpath);if(Pn&&!this.isElementInsideAllowedElements(Pn)){let bn=this.getNearestAllowedElement(Pn);if(bn)Je.targetElement.xpath=this.domService.getXPath(bn),Je.targetElement.fXpath=this.domService.getXPath(bn,!0),Je.targetElement.cfXpath=this.domService.getXPath(bn,!0,!0),Je.targetElement.anchor=this.domService.generateAnchorRecord(bn);else return}}if(t&&(Je.targetTextRange=t),Je?.targetElement?.xpath){let Pn=this.domService.getXPath(Je.targetElement.xpath);if(Pn){let bn=Pn.iterateNext();bn&&(Kr(bn)||(Je.targetElement=null))}}this.customFilterService.defaultStatus&&!ye?.status&&(Je.status=this.customFilterService.defaultStatus),Je.pageInfo=ro(),Je.pageInfo&&(Je.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth);let xr=this.docService.getClientDocumentId(),Io=this.docService.getLocation()?.location;if(ge&&(Je.context=ge&&Es(ge),Je.contextId=this.generateContextId(Je.context)),this.commentContextProvider!==null){let Pn=this.commentContextProvider(xr,Io),bn=Pn instanceof Promise?yield Pn:Pn;bn&&(Je.context=bn&&Es(bn),Je.contextId=this.generateContextId(Je.context),bn?.commentType==="manual"&&(Je.commentType="manual",delete Je.targetElement))}if(a){Je.sourceId=a?.sourceId;let Pn=a?.targetElement,bn=a?.commentData;if(Pn?.targetText)Je.targetTextRange={commonAncestorContainer:"/html/body",text:Pn.targetText,occurrence:Pn?.occurrence||1,commonAncestorContainerAnchor:this.domService.generateAnchorRecord(document.body)??void 0};else if(Pn?.elementId)if(Je.targetElementId=Pn.elementId,Pn?.selectAllContent)Je.selectAllContent=!!Pn?.selectAllContent;else{let Ro=nl(Pn.elementId,["id","data-id"]);Ro?Je.targetElement={xpath:this.domService.getXPath(Ro),fXpath:this.domService.getXPath(Ro,!0),cfXpath:this.domService.getXPath(Ro,!0,!0),anchor:this.domService.generateAnchorRecord(Ro),topPercentage:50,leftPercentage:90}:Je.targetElement={xpath:"/html/body",fXpath:"/html/body",cfXpath:"/html/body",anchor:this.domService.generateAnchorRecord(document.body),topPercentage:50,leftPercentage:90}}a?.status&&(Je.status=a.status),a?.context&&(Je.context=a.context?Es(a.context):a.context,Je.contextId=this.generateContextId(Je.context)),Je.comments||(Je.comments=[]);let hi=this.authService.getUser();bn?.forEach(Ro=>{let aa=new Xl;aa.commentText=Ro.commentText,aa.commentHtml=Ro.commentHtml,aa.replaceContentHtml=Ro.replaceContentHtml,aa.replaceContentText=Ro.replaceContentText,aa.from=hi,Je.comments.push(aa)})}if(l&&(Je.isPageAnnotation=!0),c?.length&&(Je.comments=c),d&&(Je.commentType="chart",Je.metadata=d),u?.sourceId&&(Je.sourceId=u.sourceId),Je?.targetElement?.xpath&&!u){let Pn=this.domService.getElementFromXPath(Je.targetElement.xpath);Pn&&(u=this.getInlineCommentSectionConfig(Pn))}u?.targetInlineCommentElementId&&(Je.targetInlineCommentElementId=u?.targetInlineCommentElementId,Je.targetElementId=u.targetInlineCommentElementId,u?.config?.id&&(Je.inlineCommentSectionConfig=u?.config));let Kn=!Je?.comments?.length,ao=!!(a?.openComment===!1||Ie);this.getPrivateCommentMode()&&(Je?.iam||(Je.iam=new _3),Je.iam.accessMode=Ca.PRIVATE),_&&(Je.context=_.context?Es(_.context):_.context,Je.commentType="manual",delete Je.targetElement,Je.contextId=this.generateContextId(Je.context)),I&&(Je.targetElementId=I.targetElementId,Je.targetElement=I.targetElement);let Xr=this.getPrivateModeConfig();if(Xr)try{let Pn=h({},Xr);if(Pn.type==="restricted"){let hi=this.authService.getUser();hi?.userId&&(Pn=Ju(Pn,hi.userId))}if(Pn.type==="organizationPrivate"&&!Pn.organizationId){let hi=this.docService.getOrganizationConfig();hi?.clientOrganizationId&&(Pn.organizationId=hi.clientOrganizationId)}let bn=Xu(Pn);Je.context||(Je.context={}),Je.context._setAccessFields=bn,Je.visibilityConfig=h(h({type:Pn.type},Pn.organizationId&&{organizationId:Pn.organizationId}),Pn.userIds&&{userIds:Pn.userIds})}catch(Pn){this.loggingService.catch("Error building accessFields from privateModeConfig: ",Pn)}this.saveCommentToDb(Je,i,Kn,ao,m,A,M,ie,V,he,Oe,Pe)}}catch(Et){this.loggingService.catch("Error in CommentService addComment: ",Et)}})}triggerAddCommentAnnotationDraftEvent(){return X(this,null,function*(){try{this.commentAnnotationContextDraft=null;let e={addContext:i=>{this.commentAnnotationContextDraft=i}},t=yield this.commentActionsService?.getAddCommentAnnotationDraftEventFromCommentAddEventData(e);t&&this.commentActionsService?.triggerAddCommentAnnotationDraftEvent(t)}catch(e){this.loggingService.catch("Error in CommentService triggerAddCommentAnnotationDraftEvent: ",e)}})}triggerAddCommentDraftEventOnAbandon(e,t){return X(this,null,function*(){try{if(!e||!t)return;let i=this.getAnnotationById(e),a=!!i?.comments?.some(l=>l&&!l.isDraft);i&&a&&(yield this.commentActionsService?.triggerAddCommentDraftEventForAnnotation(i,t))}catch(i){this.loggingService.catch("Error in CommentService triggerAddCommentDraftEventOnAbandon: ",i)}})}willDeleteWholeAnnotation(e,t){try{if(!e?.comments?.length)return!1;let i=e.comments.findIndex(a=>a?.commentId===t);return i<0?!1:i===0&&this.deleteThreadWithFirstComment$.value!==!1||e.comments.length===1}catch(i){return this.loggingService.catch("Error in CommentService willDeleteWholeAnnotation: ",i),!1}}confirmDeleteCommentIfRequired(e,t){return X(this,null,function*(){try{if(!e?.comments?.length||!t)return!0;let i=e.comments.findIndex(d=>d?.commentId===t?.commentId);if(i<0||!(i===0&&this.deleteThreadWithFirstComment$.value!==!1||this.deleteReplyConfirmation$.value))return!0;let l;return this.deleteReplyConfirmation$.value&&(i!==0||this.deleteThreadWithFirstComment$.value===!1)?l={title:"Delete comment?",message:"This selected comment will be deleted.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"reply",type:"reply"}:l={title:"Delete thread?",message:"All replies to this thread will be lost.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"comment",type:"comment"},!!(yield this.dialog.open(al,{panelClass:["velt-confirm-dialog-overlay-pane","velt-mat-dialog-container"],data:l}).afterClosed().toPromise())}catch(i){return this.loggingService.catch("Error in CommentService confirmDeleteCommentIfRequired: ",i),!1}})}setLocationToCommentAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location);try{let i;e.targetElement?i=this.domService.getElementFromTargetElement(e.targetElement):e.targetElementId?i=nl(e.targetElementId,["id","data-id"]):e.targetTextRange&&(i=this.domService.getElementFromTargetTextRange(e.targetTextRange));let a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.addLocation({location:a,source:"internal"});l?.[0]&&(e.locationId=l[0].locationId,e.location=l[0].location)}}catch{}}catch(t){this.loggingService.catch("Error in CommentService setLocationToCommentAnnotation:",t)}}getElementForCommentAnnotation(e){try{let t;return e.targetElement?t=this.domService.getElementFromTargetElement(e.targetElement):e.targetElementId?t=nl(e.targetElementId,["id","data-id"]):e.targetTextRange&&(t=this.domService.getElementFromTargetTextRange(e.targetTextRange)),t}catch(t){return this.loggingService.catch("Error in CommentService getElementForCommentAnnotation: ",t),null}}saveCommentToDb(e,t,i=!1,a=!1,l,c,d,m,u,_,I,A){this.loggingService.log("%c[WB] Calling FUNCTION: saveCommentToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(je.COMMENT)&&this.docService.getDocumentPaths$().pipe(Ge(M=>!!M),ut(1),Se(M=>(this.documentPaths=M,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Ge(V=>!!V),ut(1),Se(V=>X(this,null,function*(){if(this.documentPaths?.comment){e.annotationId=this.commonDbService.generateDocumentId();let q=this.docService.getClientDocumentId(),ae=this.docService.getLocation()?.location;if(d)e.multiThreadAnnotationId=d;else if(this.getMultiThread()){let Pe=am();e.targetElementId&&(Pe=am(e.targetElementId),e?.location?.id?Pe=am([e?.location?.id,e.targetElementId]):e?.locationId&&(Pe=am([e?.locationId+"",e.targetElementId]))),e.multiThreadAnnotationId=Pe}let ye={addContext:Pe=>{Pe.access&&(Pe.accessFields=A3(Pe)),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ADD_CONTEXT_TRIGGERED,{annotationId:e.annotationId,commentType:this.getCommentType(e),commentMode:this.getCommentMode(),context:Pe}),e.context=Pe&&Es(Pe),e.contextId=this.generateContextId(e.context),Pe?.commentType==="manual"&&(e.commentType="manual",delete e.targetElement),e?.annotationId&&setTimeout(()=>{this.updateCommentAnnotationContext(e.annotationId,Pe)},200)},documentId:q,location:ae,annotation:this.getCommentAnnotationForClient(e),targetAnnotationId:e?.annotationId,targetCommentId:e?.comments?.length?e?.comments[0]?.commentId:void 0};e?.targetElement?.xpath?ye.elementRef={xpath:e.targetElement.xpath}:ye.elementRef=void 0,this.commentAddedEmitter!==null&&"emit"in this.commentAddedEmitter&&this.commentAddedEmitter.emit(ye),this.commentAdded$.next(ye),u&&u(ye),ye?.annotation?.annotationId&&this.pendingAddCommentAnnotationData.set(ye.annotation.annotationId,ye),this.setLocationToCommentAnnotation(e);let ie=this.getElementForCommentAnnotation(e),ge=this.docService.getBaseMetadata("comment",{element:ie,multiThreadAnnotationId:e.multiThreadAnnotationId});if(!ge?.apiKey)return;if(e?.metadata||(e.metadata={}),e.metadata=h(h({},e.metadata),ge),_&&(e.metadata=h(h({},e.metadata),_)),l&&typeof l=="object"&&(e.locationId=m||this.docService.genarateLocationId(l),e.location=l,A||this.docService.addLocation({location:l})),i)window.localStorage.setItem(N.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT,JSON.stringify(e));else{let Pe=window.localStorage.getItem(N.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);Pe&&JSON.parse(Pe).annotationId===e.annotationId&&e.comments!==void 0&&e.comments.length>0&&window.localStorage.removeItem(N.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT)}e.pageInfo&&(e.pageInfo.commentUrl=this.generateCommentUrl(e));let Ie=e.comments,he=JSON.parse(JSON.stringify(e));if(this.commentAnnotationContextDraft){let Pe=this.commentAnnotationContextDraft;this.commentAnnotationContextDraft=null,Pe.access&&(Pe.accessFields=A3(Pe)),he.context=Pe&&Es(Pe)}if(!this.handleDirectAccessFieldsAssignment(he?.context)&&!he?.context?.access&&(he?.context||(he.context={}),he.context.access={default:"velt"},he.context.accessFields=[...he.context.accessFields||[],N.DEFAULT_VELT_CONTEXT]),he.visibilityConfig||(he.visibilityConfig={type:"public"}),he.position=null,t){he.targetElement=null,he.targetTextRange=null;let Pe={annotationId:e.multiThreadAnnotationId?e.multiThreadAnnotationId:e.annotationId,type:e.multiThreadAnnotationId?je.MULTI_THREAD:je.COMMENT},$e=yield this.areaService.generateAreaAnnotationId();he.areaAnnotationId=$e;let ze=this.areaService.addArea(void 0,t,Pe,$e,{locationId:he.locationId,location:he.location},he.context);ze&&(he.metadata=h(h({},he.metadata),ze?.metadata||{}))}!a&&!he?.targetInlineCommentElementId&&!he?.isPageAnnotation&&this.domService.toggleAnnotationSelection(he,c),e.targetTextRange&&sessionStorage.setItem(N.SESSION_STORAGE.SNIPPYLY_AUTO_SELECT_ANNOTATION_ID,e?.multiThreadAnnotationId?e?.multiThreadAnnotationId:e.annotationId),he?.comments?.length?this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ADDED,{annotationId:e.annotationId,commentThreadId:he?.comments[0]?.commentId,commentThreadIndex:0,commentType:this.getCommentType(he),commentMode:this.getCommentMode(),source:I??"internal",commentAnnotationCreatedAt:e.createdAt,taggedClientUserIds:he?.comments[0]?.taggedUserContacts?.map(Pe=>Pe.contact?.userId).filter(Pe=>!!Pe),taggedSnippylyUserIds:he?.comments[0]?.taggedUserContacts?.filter(Pe=>!!he?.metadata?.apiKey&&!!Pe.contact?.userId).map(Pe=>cd(he.metadata.apiKey,Pe.contact.userId))}):this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_DRAFT_ADDED,{annotationId:e.annotationId,commentType:this.getCommentType(he),commentMode:this.getCommentMode()});let Oe=this.getAnnotationNumber(e);Oe&&(he.annotationNumber=Oe),he?.comments?.length?he.comments=[]:he.isDraft=!0,he?.multiThreadAnnotationId&&this.saveMultiThreadCommentAnnotation(he),he?.context&&(he.contextId=this.generateContextId(he.context),he.context?.commentType==="manual"&&(he.commentType="manual",delete he.targetElement)),Ie?.length&&!he?.isDraft?this.saveComment(he,{type:Ot.NEWLY_ADDED,updatedComment:Ie[0]}):(Ie?.length&&(he.comments=Ie),this.draftCommentAnnotationsByAnnotationId$.next(y(h({},this.draftCommentAnnotationsByAnnotationId$.value),{[e.annotationId]:he})))}})))))).subscribe(()=>{},M=>{this.loggingService.catch("Error in CommentService saveCommentToDb subscription: ",M)})}catch(M){this.loggingService.catch("Error in CommentService saveCommentToDb: ",M)}}saveMultiThreadCommentAnnotation(e){return X(this,null,function*(){try{if(e?.multiThreadAnnotationId){let t=this.docService.getDocumentPaths();if(this.databaseService.getDbValue()&&t?.multiThread){let i={annotationId:e.multiThreadAnnotationId,targetElement:e.targetElement,targetElementId:e.targetElementId,targetInlineCommentElementId:e.targetInlineCommentElementId,inlineCommentSectionConfig:e.inlineCommentSectionConfig,areaAnnotationId:e.areaAnnotationId,targetTextRange:e.targetTextRange,from:e.from,locationId:e.locationId,location:e.location,sourceId:e.sourceId,type:"multiThread",metadata:e.metadata,context:e.context};delete e?.targetElement,delete e?.areaAnnotationId,delete e?.targetTextRange;let a=this.getMultiThreadCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:t?.organizationId,documentId:t?.documentId})?.find(l=>l.annotationId===e.multiThreadAnnotationId);if(a||(a=yield this.commonDbService?.getData({feature:"multiThread",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",id:e.multiThreadAnnotationId}})),a&&(a=JSON.parse(JSON.stringify(a)),delete a.from,i=h(h({},a),i)),i?.commentAnnotations||(i.commentAnnotations={}),i.commentAnnotations[e.annotationId]=!0,e?.isDraft)this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(y(h({},this.draftMultiThreadCommentAnnotationsByAnnotationId$.value),{[i.annotationId]:y(h({},i),{isDraft:!0})}));else{let c=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value[i.annotationId];if(c&&(i=h(h({},i),c)),delete i.isDraft,i.commentAnnotationsMap={},!i?.metadata?.documentId){i?.metadata||(i.metadata={});let u=this.docService.getBaseMetadata("multiThread");i.metadata=h(h({},i?.metadata),u)}let{documentId:d,organizationId:m}=i?.metadata||{};yield this.commonDbService.updateData({feature:"multiThread",properties:{id:i.annotationId,documentId:d,organizationId:m},data:JSON.parse(JSON.stringify(i)),callback:()=>{let u=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value;u[e.annotationId]&&(delete u[e.annotationId],this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(u))}})}return i}}return null}catch(t){return this.loggingService.catch("Error in CommentService saveMultiThreadCommentAnnotation: ",t),null}})}setCommentCategory(e){return X(this,null,function*(){try{if(e?.comments?.length){let t=e.comments[0].commentText?.trim();if(t){let i=yield this.getCommentCategory(t).toPromise();if(i){let a=this.docService.getDocumentPaths();if(a?.comment&&e?.annotationId){let l=this.getCommentAnnotationsOnCurrentOrganizationAndDocument()?.find(c=>c.annotationId===e.annotationId);if(l||(l=yield this.commonDbService?.getData({feature:"comment",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:e.annotationId}})),l?.annotationId){let c=l;c.commentCategories=[i];let{documentId:d,organizationId:m}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(c);yield this.commonDbService.updateData({feature:"comment",properties:{id:e.annotationId,documentId:d,organizationId:m,metadata:{apiKey:this.configService.getApiKey(),organizationId:m,veltFolderId:c?.metadata?.veltFolderId,documentId:d}},data:JSON.parse(JSON.stringify(c))})}}}}}}catch(t){this.loggingService.catch("Error in CommentService setCommentCategory: ",t)}})}getCommentCategory(e){try{let t=Yr(this.functions,Zr({url:On.cloudFunction.chatgptCompletion,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a=[{role:"system",content:`Identify category of this sentence from these categories, ${Object.keys(this.customCategoryMap)?.join(", ")}:`},{role:"user",content:e}];return co(t({messages:a,apiKey:this.configService.getApiKey(),sdkVersion:tl(),sdkType:this.configService.getSdkType(),numResponse:1})).pipe(ue(l=>{if(l?.data){let c=l.data,d=c?.length?c[0]?.content?.trim():void 0;return d&&Object.keys(this.customCategoryMap).includes(d)?this.customCategoryMap[d]:void 0}else return}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentCategory: ",t),ce(void 0)}}handleDirectAccessFieldsAssignment(e){try{if(!e||typeof e!="object")return!1;if("_setAccessFields"in e||"_replaceAccessFields"in e){let t=e._setAccessFields??e._replaceAccessFields;return delete e.access,delete e.accessFields,Array.isArray(t)&&t.length>0?e.accessFields=t:t==null&&delete e.accessFields,delete e._setAccessFields,delete e._replaceAccessFields,!0}return!1}catch(t){return this.loggingService.catch("Error in CommentService handleDirectAccessFieldsAssignment: ",t),!1}}updateCommentAnnotationContext(e,t,i){return X(this,null,function*(){try{this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_UPDATE_CONTEXT_TRIGGERED,{annotationId:e,context:t,merge:i?.merge});let a=this.authService.getUser(),l=this.docService.getDocumentPaths();if(a&&l?.comment&&e){let c=this.getAnnotationById(e);if(typeof c=="object"&&(c=JSON.parse(JSON.stringify(c))),c||(c=yield this.commonDbService?.getData({feature:"comment",properties:{documentId:l?.documentId??"",organizationId:l?.organizationId??"",id:e}})),c?.annotationId){let d=t,m=JSON.parse(JSON.stringify(c.context||{}));i?.merge&&(d=h(h({},m),t));let u=this.handleDirectAccessFieldsAssignment(d);if(d&&"_setVisibilityConfig"in d&&(c.visibilityConfig=d._setVisibilityConfig,delete d._setVisibilityConfig),d&&typeof d=="object"&&!u)if("access"in t)t.access!==null&&t.access!==void 0?d.accessFields=A3(d):(delete d.access,delete d.accessFields);else{if(!i?.merge)for(let A of KWe)!(A in t)&&m?.[A]!==void 0&&(d[A]=m[A]);d.access!==null&&d.access!==void 0&&(d.accessFields=A3(d))}let _={context:JSON.parse(JSON.stringify(d||{}))},I=!1;if(_?.context?.commentType==="manual"&&(_.commentType="manual",_.targetElement=null,c?.targetElement&&(c.targetElement=null,I=!0)),c.context=_.context?Es(_.context):_.context,c.contextId=this.generateContextId(c.context),sr(m,d)&&!I)return Promise.resolve("Comment annotation context is already updated.");if(c?.comments?.length){c.lastUpdated=this.timestamp;let{documentId:A,organizationId:M}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(c);return this.commonDbService.setData({feature:"comment",properties:{id:e,documentId:A,organizationId:M,metadata:{apiKey:this.configService.getApiKey(),organizationId:M,veltFolderId:c?.metadata?.veltFolderId,documentId:A}},data:JSON.parse(JSON.stringify(c)),callback:()=>{this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_UPDATE_CONTEXT_SUCCESS,{annotationId:e,context:_?.context,merge:i?.merge})}})}else return this.draftCommentAnnotationsByAnnotationId$.value?.[e]?(this.draftCommentAnnotationsByAnnotationId$.next(y(h({},this.draftCommentAnnotationsByAnnotationId$.value),{[e]:c})),Promise.resolve("Draft comment annotation context updated.")):(this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_UPDATE_CONTEXT_FAILED,{annotationId:e,context:t,merge:i?.merge,error:"Draft comment annotation not found."}),Promise.resolve("Draft comment annotation not found."))}else return this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_UPDATE_CONTEXT_FAILED,{annotationId:e,context:t,merge:i?.merge,error:"Comment annotation not found in database."}),Promise.resolve("Comment annotation not found in database.")}}catch(a){return this.loggingService.catch("Error in CommentService updateCommentAnnotationContext: ",a),Promise.resolve("Error in CommentService updateCommentAnnotationContext.")}})}updateComment(e,t,i,a,l,c){this.loggingService.log("%c[WB] Calling FUNCTION: updateComment","color: green;");try{if(this.authService.getUser()&&this.authService.isFeatureAllowed(je.COMMENT)){if(t&&this.setLocationToCommentAnnotation(e),e?.targetElement?.xpath){let d=this.domService.getXPath(e.targetElement.xpath);if(d){let m=d.iterateNext();m&&(Kr(m)||(e.targetElement=null))}}if(e?.type==="multiThread"){let d=JSON.parse(JSON.stringify(e));if(d.position=null,d.ghostComment=null,d?.context&&this.handleDirectAccessFieldsAssignment(d.context),!d?.metadata?.documentId){d?.metadata||(d.metadata={});let _=this.docService.getBaseMetadata("multiThread");d.metadata=h(h({},d?.metadata),_)}let{documentId:m,organizationId:u}=d?.metadata||{};i?this.commonDbService.updateData({feature:"multiThread",properties:{id:d.annotationId,documentId:m,organizationId:u},data:JSON.parse(JSON.stringify(d))}):this.commonDbService.setData({feature:"multiThread",properties:{id:d.annotationId,documentId:m,organizationId:u},data:JSON.parse(JSON.stringify(d))})}else{this.setSubscribedUsersDataInCommentAnnotation(e);let d=JSON.parse(JSON.stringify(e));if(d.position=null,d.ghostComment=null,d.lastUpdated=this.timestamp,d.status||(d.status=this.customFilterService.defaultStatus),delete d.resolved,delete d.inProgress,this.setLocationFromDocumentParams(d),d?.context&&this.handleDirectAccessFieldsAssignment(d.context),d?.annotationId?.startsWith("TEMP_COMPOSER_"))return;let m=window.localStorage.getItem(N.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);if(m&&JSON.parse(m).annotationId===d.annotationId&&window.localStorage.removeItem(N.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT),d?.multiThreadAnnotationId&&!l&&this.saveMultiThreadCommentAnnotation(d).then(u=>{}),d?.comments?.length){if(delete d?.isDraft,d?.multiThreadAnnotationId&&this.draftMultiThreadCommentAnnotationsByAnnotationId$.value[d?.multiThreadAnnotationId]&&this.saveMultiThreadCommentAnnotation(d),!d?.metadata?.documentId){d?.metadata||(d.metadata={});let A=this.docService.getBaseMetadata("comment");d.metadata=h(h({},d?.metadata),A)}let{documentId:u,organizationId:_}=d?.metadata||{},I=a?h({annotationData:a?.commentAnnotation,targetAnnotationData:a?.targetComment,actionType:a?.actionType,notificationSource:"comment"},a?.otherFields||{}):null;this.viewsService.updateCommentAnnotationViews(d),this.commonDbService.setData({feature:"comment",properties:{id:d.annotationId,documentId:u,targetCommentId:c?.commentId,organizationId:_,metadata:{apiKey:this.configService.getApiKey(),organizationId:_,veltFolderId:d?.metadata?.veltFolderId,documentId:u}},extraData:I,data:JSON.parse(JSON.stringify(d)),callback:A=>X(this,null,function*(){if(a&&!A?.firestoreAvailable&&this.updateNotificationsDatabase(a.commentAnnotation,a.targetComment,a.actionType,a.otherFields||{}),this.getScreenshotEnabled()&&a?.actionType===Ot.NEWLY_ADDED&&this.captureScreenshot(e),a?.actionType===Ot.NEWLY_ADDED||a?.actionType===Ot.ADDED)try{let M=yield this.metadataService.getGlobalMetadata(),V={annotationId:d.annotationId,commentAnnotation:this.getCommentAnnotationForClient(d),metadata:M};this.commentActionsService?.triggerAction(ar.COMMENT_SAVED,V)}catch(M){this.loggingService.catch("Error triggering commentSaved event: ",M)}})})}else this.draftCommentAnnotationsByAnnotationId$.next(y(h({},this.draftCommentAnnotationsByAnnotationId$.value),{[e.annotationId]:d}))}}}catch(d){this.loggingService.catch("Error in CommentService updateComment: ",d)}}captureScreenshot(e){return X(this,null,function*(){try{if(this.getScreenshotEnabled()){let i=Yr(this.functions,Zr({url:On.cloudFunction.screenshot,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5}),a,l={source:"velt",sourceData:{commentAnnotation:e},eventType:"screenshot"};e?.areaAnnotationId&&(a=this.areaService.getAnnotationById(e?.areaAnnotationId),a&&(l.sourceData||(l.sourceData={}),l.sourceData.areaAnnotation=a));let c=yield ws(l,this.authService.getUser()?.userId??"");yield i({veltData:c})}}catch(t){this.loggingService.catch("Error in CommentService captureScreenshot: ",t)}})}getDocumentIdAndOrganizationIdFromCommentAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIdAndOrganizationIdFromCommentAnnotation: ",t),{}}}getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation(e){try{return{documentId:e?.metadata?.documentId,organizationId:e?.metadata?.organizationId}}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation: ",t),{}}}setLocationFromDocumentParams(e){e?.documentParams&&(e.location=e.documentParams,delete e.documentParams),e?.documentParamsId&&(e.locationId=e.documentParamsId,delete e.documentParamsId)}deleteCommentPinAnnotations(e){return new Promise((t,i)=>X(this,null,function*(){try{let a=this.domService.getSelectedAnnotationsMap(),l=this.authService.getUser(),c=[];Object.keys(a).forEach(d=>{let m=a[d];["tag","recorder","rewriter","arrow","area","multiThread"].includes(m.type)||l&&m.from&&(l?.isAdmin||m.from.userId===l.userId)&&c.push(m)}),c?.length?(this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_DELETE_TRIGGERED,{triggerType:e,annotationId:c.map(d=>d.annotationId).join(),commentMode:this.getCommentMode()}),this.dialog.open(al,{panelClass:["velt-confirm-dialog-overlay-pane","velt-mat-dialog-container"],data:{title:"Delete thread?",message:"All replies to this thread will be lost.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"comment",type:"comment"}}).afterClosed().pipe(ut(1)).subscribe(d=>{try{d?(c.forEach(m=>X(this,null,function*(){yield this.deleteCommentPinAnnotation(m)})),setTimeout(()=>{document.querySelectorAll(`[${N.SNIPPYLY_HIGHLIGHT}]`).forEach(u=>{this.domService.removeHighlightFromElement(u)}),t()},100)):t()}catch(m){i(m)}},d=>{i(d)})):t(),this.domService.resetSelectedAnnotationsMap(!0,"comment")}catch(a){this.loggingService.catch("Error in CommentService deleteCommentPinAnnotations: ",a),i(a)}}))}deleteCommentPinAnnotation(e,t){return X(this,null,function*(){try{if(setTimeout(()=>{if(this.draftCommentAnnotationsByAnnotationId$?.value?.[e.annotationId]){let i=this.draftCommentAnnotationsByAnnotationId$.value;delete i[e.annotationId],this.draftCommentAnnotationsByAnnotationId$.next(i)}},50),e?.annotationId&&this.pendingAddCommentAnnotationData.delete(e.annotationId),this.authService.isFeatureAllowed(je.COMMENT))if((t||e.comments?.length)&&this.updateNotificationsDatabase(e,null,Ot.DELETED),e.comments?.forEach(i=>{i.reactionAnnotationIds&&i.reactionAnnotationIds.forEach(a=>{this.deleteReaction(a)})}),e?.annotationId){this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_DELETED,{annotationId:e.annotationId,commentType:this.getCommentType(e),commentMode:this.getCommentMode()});let i=window.localStorage.getItem(N.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT);i&&JSON.parse(i).annotationId===e.annotationId&&window.localStorage.removeItem(N.LOCAL_STORAGE.SNIPPYLY_QUEUED_COMMENT),this.areaService.onDeleteTargetAnnotation(e?.annotationId,e?.areaAnnotationId);let a={type:"delete",annotation:null,targetAnnotationId:e.annotationId};this.commentUpdated$.next(a),e?.multiThreadAnnotationId&&(yield this.removeCommentAnnotationFromMultiThread(e)),this.commentAnnotationDeleted$.next(e);let{documentId:l,organizationId:c}=this.getDocumentIdAndOrganizationIdFromCommentAnnotation(e);if(e?.isDraft)return Promise.resolve();{let d={annotationData:e,targetAnnotationData:null,actionType:Ot.DELETED,notificationSource:"comment",isAnnotationDelete:!0};return this.commonDbService.deleteData({feature:"comment",properties:{id:e.annotationId,documentId:l,organizationId:c,metadata:{apiKey:this.configService.getApiKey(),organizationId:c,veltFolderId:e?.metadata?.veltFolderId,documentId:l}},extraData:d})}}else return Promise.resolve();return Promise.resolve()}catch(i){return this.loggingService.catch("Error in CommentService deleteCommentPinAnnotation: ",i),Promise.resolve()}})}removeCommentAnnotationFromMultiThread(e){return X(this,null,function*(){try{let t=e?.multiThreadAnnotationId;if(t){let i=this.docService.getDocumentPaths(),a=this.getMultiThreadAnnotationById(t);if(!a){let m=e?.metadata?.documentId||i?.documentId,u=e?.metadata?.organizationId||i?.organizationId;a=yield this.commonDbService?.getData({feature:"multiThread",properties:{documentId:m,organizationId:u,id:t}})}let l=this.draftMultiThreadCommentAnnotationsByAnnotationId$.value?.[t];a&&delete a?.commentAnnotations?.[e.annotationId],l&&(delete l?.commentAnnotations?.[e.annotationId],Object.keys(l?.commentAnnotations||{}).length===0&&(delete this.draftMultiThreadCommentAnnotationsByAnnotationId$.value?.[t],this.draftMultiThreadCommentAnnotationsByAnnotationId$.next(this.draftMultiThreadCommentAnnotationsByAnnotationId$.value))),delete a.commentAnnotationsMap;let{documentId:c,organizationId:d}=this.getDocumentIdAndOrganizationIdFromMultiThreadCommentAnnotation(a);return Object.keys(a?.commentAnnotations||{}).length===0?(this.areaService.onDeleteTargetAnnotation(a?.annotationId,a?.areaAnnotationId),this.multiThreadCommentAnnotationDeleted$.next(a),this.commonDbService.deleteData({feature:"multiThread",properties:{id:a?.annotationId,documentId:c,organizationId:d}})):this.commonDbService.setData({feature:"multiThread",properties:{id:a?.annotationId,documentId:c,organizationId:d},data:JSON.parse(JSON.stringify(a))})}}catch(t){this.loggingService.catch("Error in CommentService removeCommentAnnotationFromMultiThread: ",t)}})}getAnnotationById(e,t){try{let i=this.commentAnnotationById$.value?.[e]||this.draftCommentAnnotationsByAnnotationId$?.value?.[e];if(i){let{documentId:a,organizationId:l}=t||{};if(a&&i.metadata?.documentId!==a||l&&i.metadata?.organizationId!==l)return}return i}catch(i){this.loggingService.catch("Error in CommentService getAnnotationById: ",i);return}}getBaseMetadataFromCommentAnnotationId(e){try{let t=this.commentAnnotationById$.value?.[e];if(t)return t.metadata}catch(t){this.loggingService.catch("Error in CommentService getBaseMetadataFromCommentAnnotationId: ",t)}}getMultiThreadAnnotationById(e,t){try{let i=this.multiThreadCommentAnnotationById$.value?.[e]||this.draftMultiThreadCommentAnnotationsByAnnotationId$?.value?.[e];if(i){let{documentId:a,organizationId:l}=t||{};if(a&&i.metadata?.documentId!==a||l&&i.metadata?.organizationId!==l)return}return i}catch(i){this.loggingService.catch("Error in CommentService getAnnotationById: ",i);return}}getBaseMetadataFromMultiThreadCommentAnnotationId(e){try{let t=this.multiThreadCommentAnnotationById$.value?.[e];if(t)return t.metadata}catch(t){this.loggingService.catch("Error in CommentService getBaseMetadataFromMultiThreadCommentAnnotationId: ",t)}}getElementRefByAnnotationId(e){try{let t=this.getAnnotationById(e);if(t){let i=t?.targetElement?.xpath;if(i)return{xpath:i}}return}catch(t){this.loggingService.catch("Error in CommentService getElementRefByAnnotationId: ",t);return}}scrollToCommentByAnnotationId(e){try{let t=this.getAnnotationById(e),i=document.getElementById(`comment-pin-container-${e}`);i||(i=document.querySelector(`[data-velt-id='${e}']`)),i||(i=document.querySelector(`${N.TAGS.VELT_COMMENT_TEXT}[${N.ATTRIBUTES.ANNOTATION_ID}="${e}"]`)),i&&(i.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"}),t&&(this.domService.getSelectedAnnotationsMap()[e]||this.domService.toggleAnnotationSelection(t)))}catch(t){this.loggingService.catch("Error in CommentService scrollToCommentByAnnotationId: ",t)}}selectCommentByAnnotationId(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: selectCommentByAnnotationId","color: green;");let i=e?this.getAnnotationById(e):void 0;i?this.domService.toggleAnnotationSelection(i,void 0,void 0,!0):this.domService.resetSelectedAnnotationsMap()}catch(i){this.loggingService.catch("Error in CommentService selectCommentByAnnotationId: ",i)}}enableAddCommentMode(){try{this.authService.isFeatureAllowed(je.COMMENT)?!this.authService.isPlanExpired()&&this.iamService.hasRoleAny([Uo.ADMIN,Uo.COMMENTER])?(this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ADD_MODE_ENABLED,{commentMode:this.getCommentMode()}),this.addCommentMode$.next(!0)):this.loggingService.catch("Error in CommentService enableAddCommentMode: ","User is not allowed to add comment."):this.loggingService.catch("Error in CommentService enableAddCommentMode: ","Comment feature is not enabled.")}catch(e){this.loggingService.catch("Error in CommentService enableAddCommentMode: ",e)}}disableAddCommentMode(){this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ADD_MODE_DISABLED,{commentMode:this.getCommentMode()}),this.addCommentMode$.next(!1)}addCommentModeChange(){return this.addCommentMode$.asObservable()}setFreeStyleCommentContext(e){try{this.freeStyleCommentContext=e}catch(t){this.loggingService.catch("Error in CommentService setFreeStyleCommentContext: ",t)}}clearFreeStyleCommentContext(){try{this.freeStyleCommentContext=void 0}catch(e){this.loggingService.catch("Error in CommentService resetFreeStyleCommentContext: ",e)}}enablePersistentCommentMode(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{persistentCommentMode:!0}}),this.persistentCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePersistentCommentMode: ",e)}}enableDeleteReplyConfirmation(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deleteReplyConfirmation:!0}}),this.deleteReplyConfirmation$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeleteReplyConfirmation: ",e)}}enableSeenByUsers(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{seenByUsers:!0}}),this.seenByUsers$.value===!0)return;this.seenByUsers$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSeenByUsers: ",e)}}disableSeenByUsers(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{seenByUsers:!1}}),this.seenByUsers$.value===!1)return;this.seenByUsers$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSeenByUsers: ",e)}}getSeenByUsers$(){return this.seenByUsers$.asObservable()}disableDeleteReplyConfirmation(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deleteReplyConfirmation:!1}}),this.deleteReplyConfirmation$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeleteReplyConfirmation: ",e)}}disablePersistentCommentMode(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{persistentCommentMode:!1}}),this.persistentCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePersistentCommentMode: ",e)}}persistentCommentModeChange(){return this.persistentCommentMode$.asObservable()}enablePersistentModeBanner(){this.persistentModeBanner$.next(!0)}disablePersistentModeBanner(){this.persistentModeBanner$.next(!1)}persistentModeBannerChange(){return this.persistentModeBanner$.asObservable()}setAssignToType(e){try{this.assignToType$.next(e.type)}catch(t){this.loggingService.catch("Error in CommentService setAssignToType: ",t)}}getAssignToType$(){return this.assignToType$.asObservable()}getAssignToType(){return this.assignToType$.value}setPageModeComposerContext(e){try{this.pageModeComposerContext$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setPageModeComposerContext: ",t)}}clearPageModeComposerContext(){try{this.pageModeComposerContext$.next(null)}catch(e){this.loggingService.catch("Error in CommentService clearPageModeComposerContext: ",e)}}getPageModeComposerContext$(){return this.pageModeComposerContext$.asObservable()}getPageModeComposerContext(){return this.pageModeComposerContext$.value}enableContextInPageModeComposer(){try{this.contextInPageModeComposer$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableContextInPageModeComposer: ",e)}}disableContextInPageModeComposer(){try{this.contextInPageModeComposer$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableContextInPageModeComposer: ",e)}}getContextInPageModeComposer$(){return this.contextInPageModeComposer$.asObservable()}getContextInPageModeComposer(){return this.contextInPageModeComposer$.value}focusPageModeComposer(){try{this.focusPageModeComposer$.next()}catch(e){this.loggingService.catch("Error in CommentService focusPageModeComposer: ",e)}}getFocusPageModeComposer$(){return this.focusPageModeComposer$.asObservable()}showCommentIndex(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentIndex:e}}),this.showCommentIndex$.value===e)return;this.showCommentIndex$.next(e)}catch(t){this.loggingService.catch("Error in CommentService showCommentIndex: ",t)}}getShowCommentIndex(){return this.showCommentIndex$.asObservable()}enablePopoverMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{popoverMode:!0}}),this.popoverMode$.value===!0)return;this.popoverMode$.next(!0),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_POPOVER_MODE_ENABLED,{commentMode:this.getCommentMode()})}catch(e){this.loggingService.catch("Error in CommentService enablePopoverMode: ",e)}}disablePopoverMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{popoverMode:!1}}),this.popoverMode$.value===!1)return;this.popoverMode$.next(!1),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_POPOVER_MODE_DISABLED,{commentMode:this.getCommentMode()})}catch(e){this.loggingService.catch("Error in CommentService disablePopoverMode: ",e)}}getPopoverMode(){try{return this.popoverMode$.value}catch(e){return this.loggingService.catch("Error in CommentService getPopoverMode: ",e),!1}}getPopoverMode$(){return this.popoverMode$.asObservable()}enablePopoverTriangleComponent(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{popoverTriangleComponent:!0}}),this.popoverTriangleComponent$.value===!0)return;this.popoverTriangleComponent$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePopoverTriangleComponent: ",e)}}disablePopoverTriangleComponent(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{popoverTriangleComponent:!1}}),this.popoverTriangleComponent$.value===!1)return;this.popoverTriangleComponent$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePopoverTriangleComponent: ",e)}}getPopoverTriangleComponent(){try{return this.popoverTriangleComponent$.value}catch(e){return this.loggingService.catch("Error in CommentService getPopoverTriangleComponent: ",e),!1}}getPopoverTriangleComponent$(){return this.popoverTriangleComponent$.asObservable()}enableDraftMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{draftMode:!0}}),this.draftMode$.value===!0)return;this.draftMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDraftMode: ",e)}}disableDraftMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{draftMode:!1}}),this.draftMode$.value===!1)return;this.draftMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDraftMode: ",e)}}getDraftMode$(){return this.draftMode$.asObservable()}getDraftMode(){return this.draftMode$.value}enableTextComments(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textMode:!0}}),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_TEXT_MODE_ENABLED,{commentMode:this.getCommentMode()}),this.textCommentMode$.value===!0)return;this.textCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextComments: ",e)}}disableTextComments(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textMode:!1}}),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_TEXT_MODE_DISABLED,{commentMode:this.getCommentMode()}),this.textCommentMode$.value===!1)return;this.textCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextComments: ",e)}}getTextCommentMode$(){return this.textCommentMode$.asObservable()}isUserGlobalContact$(){return this.contactService.isUserGlobalContact$()}isSidebarOpenedByCustomTrigger(){try{return this.sidebarOpenedByCustomTrigger$.value}catch(e){return this.loggingService.catch("Error in CommentService isSidebarOpenedByCustomTrigger: ",e),!1}}setSidebarVisibility(e,t=!1,i=!1){try{this.domService.resetSelectedAnnotationsMap(),e?(document.querySelector(N.TAGS.VELT_COMMENTS_SIDEBAR_V2)||document.querySelector(N.TAGS.VELT_COMMENTS_SIDEBAR)||document.querySelector(N.TAGS.SNIPPYLY_COMMENTS_SIDEBAR)?this.sidebarVisible$.next(e):this.loggingService.catch("Error in CommentService setSidebarVisibility: ",`<${N.TAGS.VELT_COMMENTS_SIDEBAR}> or <${N.TAGS.VELT_COMMENTS_SIDEBAR_V2}> tag is not added.`),t&&this.sidebarOpenedByCustomTrigger$.next(!0)):(!this.sidebarOpenedByCustomTrigger$.value||t||i)&&(this.sidebarVisible$.next(e),this.sidebarOpenedByCustomTrigger$.next(!1),this.clearPageModeComposerContext()),e?this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_SIDEBAR_OPENED,{commentMode:this.getCommentMode()}):this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_SIDEBAR_CLOSED,{commentMode:this.getCommentMode()})}catch{this.loggingService.catch("Error in CommentService setSidebarVisibility: ",`<${N.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`)}}toggleSidebarVisibility(e=!1,t=!1){try{this.domService.resetSelectedAnnotationsMap(),this.sidebarVisible$.value?(!this.sidebarOpenedByCustomTrigger$.value||e||t)&&(this.sidebarVisible$.next(!this.sidebarVisible$.value),this.sidebarOpenedByCustomTrigger$.next(!1),this.sidebarVisible$.value||this.clearPageModeComposerContext()):(document.querySelector(N.TAGS.VELT_COMMENTS_SIDEBAR_V2)||document.querySelector(N.TAGS.VELT_COMMENTS_SIDEBAR)||document.querySelector(N.TAGS.SNIPPYLY_COMMENTS_SIDEBAR)?(this.sidebarVisible$.next(!this.sidebarVisible$.value),this.sidebarVisible$.value?this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_SIDEBAR_TOGGLED,{commentMode:this.getCommentMode(),action:"closed"}):this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_SIDEBAR_TOGGLED,{commentMode:this.getCommentMode(),action:"opened"})):this.loggingService.catch("Error in CommentService toggleSidebarVisibility: ",`<${N.TAGS.VELT_COMMENTS_SIDEBAR}> or <${N.TAGS.VELT_COMMENTS_SIDEBAR_V2}> tag is not added.`),e&&this.sidebarOpenedByCustomTrigger$.next(!0))}catch{this.loggingService.catch("Error in CommentService toggleSidebarVisibility: ",`<${N.TAGS.VELT_COMMENTS_SIDEBAR}> tag is not added.`)}}getSidebarVisibility$(){return this.sidebarVisible$.asObservable()}disableFloatingComments(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{floatingCommentDialog:!e}}),this.floatingCommentsEnabled$.value===!e)return;this.floatingCommentsEnabled$.next(!e)}catch(t){this.loggingService.catch("Error in CommentService disableFloatingComments: ",t)}}showFloatingComments$(){return this.floatingCommentsEnabled$.asObservable()}showFloatingComments(){return this.floatingCommentsEnabled$.value}setModeratorMode(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{moderatorMode:e}}),this.moderatorMode$.value===e)return;this.moderatorMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setModeratorMode: ",t)}}getModeratorMode(){return this.moderatorMode$.value}getModeratorMode$(){return this.moderatorMode$.asObservable()}setStreamMode(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{streamMode:e}}),this.streamMode$.value===e)return;this.streamMode$.next(e),e?this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_STREAM_MODE_ENABLED,{commentMode:this.getCommentMode()}):this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_STREAM_MODE_DISABLED,{commentMode:this.getCommentMode()})}catch(t){this.loggingService.catch("Error in CommentService setStreamMode: ",t)}}getStreamMode(){return this.streamMode$.value}getStreamMode$(){return this.streamMode$.asObservable()}getEnableDialogOnHover(){return this.enableDialogOnHover$.value}getEnableDialogOnHover$(){return this.enableDialogOnHover$.asObservable()}setEnableDialogOnHover(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{dialogOnHover:e}}),this.enableDialogOnHover$.value===e)return;this.enableDialogOnHover$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableDialogOnHover: ",t)}}getEnableDialogOnTargetElementClick(){return this.enableDialogOnTargetElementClick$.value}getEnableDialogOnTargetElementClick$(){return this.enableDialogOnTargetElementClick$.asObservable()}setEnableDialogOnTargetElementClick(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{dialogOnTargetElementClick:e}}),this.enableDialogOnTargetElementClick$.value===e)return;this.enableDialogOnTargetElementClick$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableDialogOnTargetElementClick: ",t)}}getEnablePriority(){return this.enablePriority$.value}getEnablePriority$(){return this.enablePriority$.asObservable()}setEnablePriority(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{priority:e}}),this.enablePriority$.value===e)return;this.enablePriority$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnablePriority: ",t)}}getEnableStatus(){return this.enableStatus$.value}getEnableStatus$(){return this.enableStatus$.asObservable()}setEnableStatus(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{status:e}}),this.getEnableStatus()===e)return;this.enableStatus$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableStatus: ",t)}}getEnableVisibilityOptions(){return this.visibilityOptions$.value}getEnableVisibilityOptions$(){return this.visibilityOptions$.asObservable()}setEnableVisibilityOptions(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{visibilityOptions:e}}),this.visibilityOptions$.value===e)return;this.visibilityOptions$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableVisibilityOptions: ",t)}}getEnableResolve(){return this.enableResolve$.value}getEnableResolve$(){return this.enableResolve$.asObservable()}setEnableResolve(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{resolveButton:e}}),this.getEnableResolve()===e)return;this.enableResolve$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableResolve: ",t)}}getEnableGhostComments(){return this.enableGhostComments$.value}getEnableGhostComments$(){return this.enableGhostComments$.asObservable()}enableGhostComments(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{ghostComments:!0}}),this.enableGhostComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableGhostComments: ",e)}}disableGhostComments(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{ghostComments:!1}}),this.enableGhostComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableGhostComments: ",e)}}getEnableGhostCommentsMessage(){return this.enableGhostCommentsMessage$.value}getEnableGhostCommentsMessage$(){return this.enableGhostCommentsMessage$.asObservable()}enableGhostCommentsMessage(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{ghostCommentsIndicator:!0}}),this.enableGhostCommentsMessage$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShowGhostCommentsMessage: ",e)}}disableGhostCommentsMessage(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{ghostCommentsIndicator:!1}}),this.enableGhostCommentsMessage$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShowGhostCommentsMessage: ",e)}}enableInboxMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{inboxMode:!0}}),this.inboxMode$.value===!0)return;this.inboxMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableInboxMode: ",e)}}disableInboxMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{inboxMode:!1}}),this.inboxMode$.value===!1)return;this.inboxMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableInboxMode: ",e)}}getInboxMode(){return this.inboxMode$.value}getInboxMode$(){return this.inboxMode$.asObservable()}setEnableAutoCategorize(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{autoCategorize:e}}),this.enableAutoCategorize$.value===e)return;this.enableAutoCategorize$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEnableAutoCategorize: ",t)}}getEnableAutoCategorize(){return this.enableAutoCategorize$.value}getEnableAutoCategorize$(){return this.enableAutoCategorize$.asObservable()}setCommentContainerDarkMode(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{darkMode:e}}),this.commentContainerDarkMode$.value===e)return;this.commentContainerDarkMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentContainerDarkMode: ",t)}}getCommentContainerDarkMode(){return this.commentContainerDarkMode$.asObservable()}getSuggestionMode(){return this.suggestionMode$.value}getSuggestionMode$(){return this.suggestionMode$.asObservable()}setSuggestionMode(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{suggestionMode:e}}),this.getSuggestionMode()===e)return;this.suggestionMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setSuggestionMode: ",t)}}getMobileMode(){return this.mobileMode$.value}getMobileMode$(){return this.mobileMode$.asObservable()}setMobileMode(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{mobileMode:e}}),this.getMobileMode()===e)return;this.mobileMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setMobileMode: ",t)}}enableInlineCommentMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{inlineCommentMode:!0}}),this.inlineCommentMode$.value===!0)return;this.inlineCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableInlineCommentMode: ",e)}}disableInlineCommentMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{inlineCommentMode:!1}}),this.inlineCommentMode$.value===!1)return;this.inlineCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableInlineCommentMode: ",e)}}getInlineCommentMode(){return this.inlineCommentMode$.value}getInlineCommentMode$(){return this.inlineCommentMode$.asObservable()}enableMinimap(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{minimap:!0}}),this.minimap$.value===!0)return;this.minimap$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableMinimap: ",e)}}disableMinimap(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{minimap:!1}}),this.minimap$.value===!1)return;this.minimap$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableMinimap: ",e)}}getMinimap(){return this.minimap$.value}getMinimap$(){return this.minimap$.asObservable()}showCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentsOnDom:!0}}),this.commentsOnDom$.value===!0)return;this.commentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService showCommentsOnDom: ",e)}}hideCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentsOnDom:!1}}),this.commentsOnDom$.value===!1)return;this.commentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService hideCommentsOnDom: ",e)}}getCommentsOnDom(){return this.commentsOnDom$.value}getCommentsOnDom$(){return this.commentsOnDom$.asObservable()}enableCommentTool(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentTool:!0}}),this.commentToolEnabled$.value===!0)return;this.commentToolEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCommentTool: ",e)}}disableCommentTool(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentTool:!1}}),this.commentToolEnabled$.value===!1)return;this.commentToolEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCommentTool: ",e)}}getCommentTool(){return this.commentToolEnabled$.value}getCommentTool$(){return this.commentToolEnabled$.asObservable()}setTotalMediaLength(e){try{if(this.totalMediaLength$.value===e)return;this.totalMediaLength$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setTotalMediaLength: ",t)}}getTotalMediaLength(){return this.totalMediaLength$.value}getTotalMediaLength$(){return this.totalMediaLength$.asObservable()}enableSidebarUrlNavigation(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{sidebarUrlNavigation:!0}}),this.sidebarUrlNavigationEnabled$.value===!0)return;this.sidebarUrlNavigationEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarUrlNavigation: ",e)}}disableSidebarUrlNavigation(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{sidebarUrlNavigation:!1}}),this.sidebarUrlNavigationEnabled$.value===!1)return;this.sidebarUrlNavigationEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarUrlNavigation: ",e)}}getSidebarUrlNavigation(){return this.sidebarUrlNavigationEnabled$.value}getSidebarUrlNavigation$(){return this.sidebarUrlNavigationEnabled$.asObservable()}setDetectionStrategy(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{detectionStrategy:e}}),this.detectionStrategy$.value===e)return;this.detectionStrategy$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setDetectionStrategy: ",t)}}getDetectionStrategy(){return this.detectionStrategy$.value}getDetectionStrategy$(){return this.detectionStrategy$.asObservable()}enableSidebarButtonOnCommentDialog(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{sidebarButtonOnCommentDialog:!0}}),this.sidebarButtonOnCommentDialogVisible$.value===!0)return;this.sidebarButtonOnCommentDialogVisible$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarButtonOnCommentDialog: ",e)}}disableSidebarButtonOnCommentDialog(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{sidebarButtonOnCommentDialog:!1}}),this.sidebarButtonOnCommentDialogVisible$.value===!1)return;this.sidebarButtonOnCommentDialogVisible$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarButtonOnCommentDialog: ",e)}}getSidebarButtonOnCommentDialogVisibility(){return this.sidebarButtonOnCommentDialogVisible$.value}getSidebarButtonOnCommentDialogVisibility$(){return this.sidebarButtonOnCommentDialogVisible$.asObservable()}onSidebarButtonOnCommentDialogClick(){this.sidebarButtonOnCommentDialogClick$.next()}getSidebarButtonOnCommentDialogClick$(){return this.sidebarButtonOnCommentDialogClick$.asObservable()}enableDeviceIndicatorOnCommentPins(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deviceIndicatorOnCommentPins:!0}}),this.deviceIndicatorOnCommentPins$.value===!0)return;this.deviceIndicatorOnCommentPins$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeviceIndicatorOnCommentPins: ",e)}}disableDeviceIndicatorOnCommentPins(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deviceIndicatorOnCommentPins:!1}}),this.deviceIndicatorOnCommentPins$.value===!1)return;this.deviceIndicatorOnCommentPins$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeviceIndicatorOnCommentPins: ",e)}}getDeviceIndicatorOnCommentPins(){return this.deviceIndicatorOnCommentPins$.value}getDeviceIndicatorOnCommentPins$(){return this.deviceIndicatorOnCommentPins$.asObservable()}onSidebarCommentClick(e){this.sidebarCommentClick$.next(e)}getSidebarCommentClick$(){return this.sidebarCommentClick$.asObservable()}onCommentNavigationButtonClick(e){this.commentNavigationButtonClick$.next(e)}getCommentNavigationButtonClick$(){return this.commentNavigationButtonClick$.asObservable()}addBubbleCommentAnnotationIds(e){try{let i=[...this.bubbleCommentAnnotationIds$.value||[],...e],a=[...new Set(i)];this.bubbleCommentAnnotationIds$.next(a)}catch(t){this.loggingService.catch("Error in CommentService addBubbleCommentAnnotationIds: ",t)}}getBubbleCommentAnnotationIds(){return this.bubbleCommentAnnotationIds$.value}getBubbleCommentAnnotationIds$(){return this.bubbleCommentAnnotationIds$.asObservable()}removeBubbleCommentAnnotationIds(e){try{let i=(this.bubbleCommentAnnotationIds$.value||[]).filter(a=>!e.includes(a));this.bubbleCommentAnnotationIds$.next(i)}catch(t){this.loggingService.catch("Error in CommentService removeBubbleCommentAnnotationIds: ",t)}}enableSignInButton(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{signInButton:e}}),this.enableSignInButton$.next(e)}catch(t){this.loggingService.catch("Error in CommentService enableSignInButton: ",t)}}getSignInButton(){return this.enableSignInButton$.value}getSignInButton$(){return this.enableSignInButton$.asObservable()}onSignInClick(){this.onSignInClick$.next()}getSignInButtonClick$(){return this.onSignInClick$.asObservable()}enableUpgradeButton(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{upgradeButton:e}}),this.enableUpgradeButton$.next(e)}catch(t){this.loggingService.catch("Error in CommentService enableUpgradeButton: ",t)}}getUpgradeButton(){return this.enableUpgradeButton$.value}getUpgradeButton$(){return this.enableUpgradeButton$.asObservable()}onUpgradeClick(){this.onUpgradeClick$.next()}getUpgradeButtonClick$(){return this.onUpgradeClick$.asObservable()}openSidebar(){this.openSidebar$.next()}getOpenSidebar$(){return this.openSidebar$.asObservable()}enableAttachment(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{attachments:e}}),this.enableAttachment$.value===e)return;this.enableAttachment$.next(e)}catch(t){this.loggingService.catch("Error in CommentService enableAttachment: ",t)}}getEnableAttachment$(){return this.enableAttachment$.asObservable()}enableAttachmentDownload(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{attachmentDownload:!0}}),this.enableAttachmentDownload$.value===!0)return;this.enableAttachmentDownload$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAttachmentDownload: ",e)}}disableAttachmentDownload(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{attachmentDownload:!1}}),this.enableAttachmentDownload$.value===!1)return;this.enableAttachmentDownload$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAttachmentDownload: ",e)}}getEnableAttachmentDownload$(){return this.enableAttachmentDownload$.asObservable()}getEnableAttachmentDownload(){return this.enableAttachmentDownload$.value}enableFormatOptions(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{formatOptions:!0}}),this.enableFormatOptions$.value===!0)return;this.enableFormatOptions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFormatOptions: ",e)}}disableFormatOptions(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{formatOptions:!1}}),this.enableFormatOptions$.value===!1)return;this.enableFormatOptions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFormatOptions: ",e)}}getEnableFormatOptions$(){return this.enableFormatOptions$.asObservable()}setFormatConfig(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{formatConfig:e}}),this.formatConfig$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setFormatConfig: ",t)}}getFormatConfig$(){return this.formatConfig$.asObservable()}setAllowedRecordings(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{recordings:e}}),e?.includes("all")?this.allowedRecordings$.next(["audio","video","screen"]):e?.includes("none")?this.allowedRecordings$.next([]):this.allowedRecordings$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setAllowedRecordings: ",t)}}getAllowedRecordings(){return this.allowedRecordings$.value}getAllowedRecordings$(){return this.allowedRecordings$.asObservable()}enableReactions(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{reactions:!0}}),this.enableReactions$.value===!0)return;this.enableReactions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReactions: ",e)}}disableReactions(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{reactions:!1}}),this.enableReactions$.value===!1)return;this.enableReactions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReactions: ",e)}}getEnableReactions(){return this.enableReactions$.value}getEnableReactions$(){return this.enableReactions$.asObservable()}enableAnonymousEmail(){try{if(this.enableAnonymousEmail$.value===!0)return;this.enableAnonymousEmail$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAnonymousEmail: ",e)}}disableAnonymousEmail(){try{if(this.enableAnonymousEmail$.value===!1)return;this.enableAnonymousEmail$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAnonymousEmail: ",e)}}getEnableAnonymousEmail(){return this.enableAnonymousEmail$.value}getEnableAnonymousEmail$(){return this.enableAnonymousEmail$.asObservable()}addCommentOnElement(e){this.addComment(void 0,void 0,void 0,e)}enablePrivateCommentMode(){return X(this,null,function*(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{privateCommentMode:!0}}),this.privateCommentMode$.value===!0)return;this.isPrivateCommentAllowed$().pipe(ut(1)).subscribe(e=>{e?(this.privateCommentMode$.next(!0),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_PRIVATE_COMMENT_MODE_ENABLED)):this.loggingService.logsEnabled&&console.warn("You are not allowed to enable private comment mode.")})}catch(e){this.loggingService.catch("Error in CommentService enablePrivateCommentMode: ",e)}})}disablePrivateCommentMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{privateCommentMode:!1}}),this.privateCommentMode$.value===!1)return;this.privateCommentMode$.next(!1),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_PRIVATE_COMMENT_MODE_DISABLED)}catch(e){this.loggingService.catch("Error in CommentService disablePrivateCommentMode: ",e)}}getPrivateCommentMode(){return this.privateCommentMode$.value}getPrivateCommentMode$(){return this.privateCommentMode$.asObservable()}isPrivateCommentAllowed(){return this.privateCommentAllowed$.value}isPrivateCommentAllowed$(){return this.privateCommentAllowed$.asObservable()}enablePrivateMode(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{privateModeConfig:e}}),!e?.type){this.loggingService.catch("enablePrivateMode: type is required in config");return}let t=h({},e);if(t.type==="restricted"){let i=this.authService.getUser();if(!i?.userId){this.loggingService.catch("enablePrivateMode: Current user not found. Cannot set restricted visibility without userIds.");return}t=Ju(t,i.userId)}this.privateModeConfig$.next(t)}catch(t){this.loggingService.catch("Error in CommentService enablePrivateMode: ",t)}}disablePrivateMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{privateModeConfig:null}}),this.privateModeConfig$.value===null)return;this.privateModeConfig$.next(null)}catch(e){this.loggingService.catch("Error in CommentService disablePrivateMode: ",e)}}getPrivateModeConfig(){return this.privateModeConfig$.value}getPrivateModeConfig$(){return this.privateModeConfig$.asObservable()}enableScrollToComment(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{scrollToComment:!0}}),this.scrollToComment$.value===!0)return;this.scrollToComment$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableScrollToComment: ",e)}}disableScrollToComment(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{scrollToComment:!1}}),this.scrollToComment$.value===!1)return;this.scrollToComment$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableScrollToComment: ",e)}}getScrollToComment(){return this.scrollToComment$.value}getScrollToComment$(){return this.scrollToComment$.asObservable()}showScreenSizeInfo(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deviceInfo:e}}),this.showScreenSizeInfo$.value===e)return;this.showScreenSizeInfo$.next(e)}catch(t){this.loggingService.catch("Error in CommentService showScreenSizeInfo: ",t)}}getShowScreenSizeInfo$(){return this.showScreenSizeInfo$.asObservable()}enableUserMentions(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableUserMentions","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{userMentions:!0}}),this.userMentions$.value===!0)return;this.userMentions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableUserMentions: ",e)}}disableUserMentions(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableUserMentions","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{userMentions:!1}}),this.userMentions$.value===!1)return;this.userMentions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableUserMentions: ",e)}}getUserMentions(){return this.userMentions$.value}getUserMentions$(){return this.userMentions$.asObservable()}enablePaginatedContactList(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enablePaginatedContactList","color: green;"),this.paginatedContactList$.value===!0)return;this.paginatedContactList$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePaginatedContactList: ",e)}}disablePaginatedContactList(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disablePaginatedContactList","color: green;"),this.paginatedContactList$.value===!1)return;this.paginatedContactList$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePaginatedContactList: ",e)}}getPaginatedContactList(){return this.paginatedContactList$.value}getPaginatedContactList$(){return this.paginatedContactList$.asObservable()}enableDeleteOnBackspace(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDeleteOnBackspace","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deleteOnBackspace:!0}}),this.deleteOnBackspace$.value===!0)return;this.deleteOnBackspace$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeleteOnBackspace: ",e)}}disableDeleteOnBackspace(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDeleteOnBackspace","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deleteOnBackspace:!1}}),this.deleteOnBackspace$.value===!1)return;this.deleteOnBackspace$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeleteOnBackspace: ",e)}}getDeleteOnBackspace(){return this.deleteOnBackspace$.value}getDeleteOnBackspace$(){return this.deleteOnBackspace$.asObservable()}enableHotkey(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableHotkey","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{hotkey:!0}}),this.hotkeyEnabled$.value===!0)return;this.hotkeyEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableHotkey: ",e)}}disableHotkey(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableHotkey","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{hotkey:!1}}),this.hotkeyEnabled$.value===!1)return;this.hotkeyEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableHotkey: ",e)}}enableRecordingSummary(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableRecordingSummary","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{recordingSummary:!0}}),this.recordingSummaryEnabled$.value===!0)return;this.recordingSummaryEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableRecordingSummary: ",e)}}disableRecordingSummary(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableRecordingSummary","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{recordingSummary:!1}}),this.recordingSummaryEnabled$.value===!1)return;this.recordingSummaryEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableRecordingSummary: ",e)}}getRecordingSummaryEnabled(){return this.recordingSummaryEnabled$.value}getRecordingSummaryEnabled$(){return this.recordingSummaryEnabled$.asObservable()}setUnreadIndicatorMode(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setUnreadIndicatorMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{unreadIndicatorMode:e}}),this.unreadIndicatorMode$.value===e)return;this.unreadIndicatorMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setUnreadIndicatorMode: ",t)}}getUnreadIndicatorMode(){return this.unreadIndicatorMode$.value}getUnreadIndicatorMode$(){return this.unreadIndicatorMode$.asObservable()}setComposerMode(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: setComposerMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{composerMode:e}}),this.composerMode$.value===e)return;this.composerMode$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setComposerMode: ",t)}}getComposerMode(){return this.composerMode$.value}getComposerMode$(){return this.composerMode$.asObservable()}enableEnterKeyToSubmit(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableEnterKeyToSubmit","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{enterKeyToSubmit:!0}}),this.enterKeyToSubmit$.value===!0)return;this.enterKeyToSubmit$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableEnterKeyToSubmit: ",e)}}disableEnterKeyToSubmit(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableEnterKeyToSubmit","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{enterKeyToSubmit:!1}}),this.enterKeyToSubmit$.value===!1)return;this.enterKeyToSubmit$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableEnterKeyToSubmit: ",e)}}getEnterKeyToSubmit(){return this.enterKeyToSubmit$.value}getEnterKeyToSubmit$(){return this.enterKeyToSubmit$.asObservable()}enablePinShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enablePinShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{pinShadowDom:!0}}),this.pinShadowDOM$.value===!0)return;this.pinShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePinShadowDOM: ",e)}}disablePinShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disablePinShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{pinShadowDom:!1}}),this.pinShadowDOM$.value===!1)return;this.pinShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePinShadowDOM: ",e)}}getPinShadowDOM(){return this.pinShadowDOM$.value}getPinDarkMode(){return this.pinDarkMode$.value}getPinDarkMode$(){return this.pinDarkMode$.asObservable()}getTextCommentToolDarkMode(){return this.textCommentToolDarkMode$.value}getTextCommentToolDarkMode$(){return this.textCommentToolDarkMode$.asObservable()}getTextCommentToolbarDarkMode(){return this.textCommentToolbarDarkMode$.value}getTextCommentToolbarDarkMode$(){return this.textCommentToolbarDarkMode$.asObservable()}getPinShadowDOM$(){return this.pinShadowDOM$.asObservable()}getTextCommentToolShadowDOM$(){return this.textCommentToolShadowDOM$.asObservable()}getTextCommentToolbarShadowDOM$(){return this.textCommentToolbarShadowDOM$.asObservable()}enableDialogShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableDialogShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{dialogShadowDom:!0}}),this.dialogShadowDOM$.value===!0)return;this.dialogShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDialogShadowDOM: ",e)}}enableTextCommentToolbarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolbarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolbarShadowDom:!0}}),this.textCommentToolbarShadowDOM$.value===!0)return;this.textCommentToolbarShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolbarShadowDOM: ",e)}}disableTextCommentToolbarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolbarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolbarShadowDom:!1}}),this.textCommentToolbarShadowDOM$.value===!1)return;this.textCommentToolbarShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolbarShadowDOM: ",e)}}enableTextCommentToolShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolShadowDom:!0}}),this.textCommentToolShadowDOM$.value===!0)return;this.textCommentToolShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolShadowDOM: ",e)}}disableTextCommentToolShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolShadowDom:!1}}),this.textCommentToolShadowDOM$.value===!1)return;this.textCommentToolShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolShadowDOM: ",e)}}enableTextCommentToolDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolDarkMode:!0}}),this.textCommentToolDarkMode$.value===!0)return;this.textCommentToolDarkMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolDarkMode: ",e)}}disableTextCommentToolDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolDarkMode:!1}}),this.textCommentToolDarkMode$.value===!1)return;this.textCommentToolDarkMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolDarkMode: ",e)}}enableTextCommentToolbarDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableTextCommentToolbarDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolbarDarkMode:!0}}),this.textCommentToolbarDarkMode$.value===!0)return;this.textCommentToolbarDarkMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableTextCommentToolbarDarkMode: ",e)}}disableTextCommentToolbarDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableTextCommentToolbarDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{textCommentToolbarDarkMode:!1}}),this.textCommentToolbarDarkMode$.value===!1)return;this.textCommentToolbarDarkMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableTextCommentToolbarDarkMode: ",e)}}enablePinDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enablePinDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{pinDarkMode:!0}}),this.pinDarkMode$.value===!0)return;this.pinDarkMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePinDarkMode: ",e)}}disablePinDarkMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disablePinDarkMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{pinDarkMode:!1}}),this.pinDarkMode$.value===!1)return;this.pinDarkMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePinDarkMode: ",e)}}disableDialogShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableDialogShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{dialogShadowDom:!1}}),this.dialogShadowDOM$.value===!1)return;this.dialogShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDialogShadowDOM: ",e)}}getDialogShadowDOM(){return this.dialogShadowDOM$.value}getDialogShadowDOM$(){return this.dialogShadowDOM$.asObservable()}setDialogShadowDOMExplicit(e){this.dialogShadowDOMExplicit$.next(e)}getDialogShadowDOMExplicit$(){return this.dialogShadowDOMExplicit$.asObservable()}enableSidebarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableSidebarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{sidebarShadowDOM:!0}}),this.sidebarShadowDOM$.value===!0)return;this.sidebarShadowDOM$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarShadowDOM: ",e)}}disableSidebarShadowDOM(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableSidebarShadowDOM","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{sidebarShadowDOM:!1}}),this.sidebarShadowDOM$.value===!1)return;this.sidebarShadowDOM$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarShadowDOM: ",e)}}getSidebarShadowDOM(){return this.sidebarShadowDOM$.value}getSidebarShadowDOM$(){return this.sidebarShadowDOM$.asObservable()}enableChangeDetectionInCommentMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableChangeDetectionInCommentMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{changeDetectionInCommentMode:!0}}),this.changeDetectionInCommentMode$.value===!0)return;this.changeDetectionInCommentMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableChangeDetectionInCommentMode: ",e)}}disableChangeDetectionInCommentMode(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableChangeDetectionInCommentMode","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{changeDetectionInCommentMode:!1}}),this.changeDetectionInCommentMode$.value===!1)return;this.changeDetectionInCommentMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableChangeDetectionInCommentMode: ",e)}}getChangeDetectionInCommentMode(){return this.changeDetectionInCommentMode$.value}getChangeDetectionInCommentMode$(){return this.changeDetectionInCommentMode$.asObservable()}showResolvedCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{resolvedCommentsOnDom:!0}}),this.resolvedCommentsOnDom$.value===!0)return;this.resolvedCommentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService showResolvedCommentsOnDom: ",e)}}hideResolvedCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{resolvedCommentsOnDom:!1}}),this.resolvedCommentsOnDom$.value===!1)return;this.resolvedCommentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService hideResolvedCommentsOnDom: ",e)}}getResolvedCommentsOnDom(){return this.resolvedCommentsOnDom$.value}getResolvedCommentsOnDom$(){return this.resolvedCommentsOnDom$.asObservable()}enableBubbleOnPin(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{bubbleOnPin:!0}}),this.bubbleOnPinEnabled$.value===!0)return;this.bubbleOnPinEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableBubbleOnPin: ",e)}}disableBubbleOnPin(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{bubbleOnPin:!1}}),this.bubbleOnPinEnabled$.value===!1)return;this.bubbleOnPinEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableBubbleOnPin: ",e)}}getBubbleOnPin(){return this.bubbleOnPinEnabled$.value}getBubbleOnPin$(){return this.bubbleOnPinEnabled$.asObservable()}enableBubbleOnPinHover(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{bubbleOnPinHover:!0}}),this.bubbleOnPinHoverEnabled$.value===!0)return;this.bubbleOnPinHoverEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableBubbleOnPinHover: ",e)}}disableBubbleOnPinHover(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{bubbleOnPinHover:!1}}),this.bubbleOnPinHoverEnabled$.value===!1)return;this.bubbleOnPinHoverEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableBubbleOnPinHover: ",e)}}getBubbleOnPinHover(){return this.bubbleOnPinHoverEnabled$.value}getBubbleOnPinHover$(){return this.bubbleOnPinHoverEnabled$.asObservable()}enablePinDrag(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{pinDrag:!0}}),this.pinDragEnabled$.value===!0)return;this.pinDragEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enablePinDrag: ",e)}}disablePinDrag(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{pinDrag:!1}}),this.pinDragEnabled$.value===!1)return;this.pinDragEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disablePinDrag: ",e)}}getPinDrag(){return this.pinDragEnabled$.value}getPinDrag$(){return this.pinDragEnabled$.asObservable()}setExcludeLocationIdsFromSidebar(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{excludeLocationIdsFromSidebar:e}}),this.excludeLocationIdsFromSidebar$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setExcludeLocationIdsFromSidebar: ",t)}}getExcludeLocationIdsFromSidebar(){return this.excludeLocationIdsFromSidebar$.value}getExcludeLocationIdsFromSidebar$(){return this.excludeLocationIdsFromSidebar$.asObservable()}enableMultiThread(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{multiThread:!0}}),this.multiThread$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableMultiThread: ",e)}}disableMultiThread(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{multiThread:!1}}),this.multiThread$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableMultiThread: ",e)}}getMultiThread(){return this.multiThread$.value}getMultiThread$(){return this.multiThread$.asObservable()}enableGroupMatchedComments(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{groupMatchedComments:!0}}),this.groupMatchedComments$.value===!0)return;this.groupMatchedComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableGroupMatchedComments: ",e)}}disableGroupMatchedComments(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{groupMatchedComments:!1}}),this.groupMatchedComments$.value===!1)return;this.groupMatchedComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableGroupMatchedComments: ",e)}}getGroupMatchedComments(){return this.groupMatchedComments$.value}getGroupMatchedComments$(){return this.groupMatchedComments$.asObservable()}enableShortUserName(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableShortUserName","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{shortUserName:!0}}),this.shortUserName$.value===!0)return;this.shortUserName$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShortUserName: ",e)}}disableShortUserName(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableShortUserName","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{shortUserName:!1}}),this.shortUserName$.value===!1)return;this.shortUserName$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShortUserName: ",e)}}getShortUserName(){return this.shortUserName$.value}getShortUserName$(){return this.shortUserName$.asObservable()}enableRecordingCountdown(){try{this.loggingService.log("%c[WB] Calling FUNCTION: enableRecordingCountdown","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{recordingCountdown:!0}}),this.recorderService.enableRecordingCountdown()}catch(e){this.loggingService.catch("Error in CommentService enableRecordingCountdown: ",e)}}disableRecordingCountdown(){try{this.loggingService.log("%c[WB] Calling FUNCTION: disableRecordingCountdown","color: green;"),this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{recordingCountdown:!1}}),this.recorderService.disableRecordingCountdown()}catch(e){this.loggingService.catch("Error in CommentService disableRecordingCountdown: ",e)}}setCommentSidebarFilters(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setCommentSidebarFilters","color: green;"),this.commentSidebarFilters$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentSidebarFilters: ",t)}}getCommentSidebarFilters(){return this.commentSidebarFilters$.value??{}}getCommentSidebarFilters$(){return this.commentSidebarFilters$.asObservable()}setEffectiveSidebarFilters(e){try{this.effectiveSidebarFilters$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEffectiveSidebarFilters: ",t)}}getEffectiveSidebarFilters$(){return this.effectiveSidebarFilters$.asObservable()}setCommentSidebarSystemFiltersOperator(e){try{this.commentSidebarSystemFiltersOperator$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentSidebarSystemFiltersOperator: ",t)}}getCommentSidebarSystemFiltersOperator(){return this.commentSidebarSystemFiltersOperator$.value}getCommentSidebarSystemFiltersOperator$(){return this.commentSidebarSystemFiltersOperator$.asObservable()}enableCommentPinHighlighter(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentPinHighlighter:!0}}),this.domService.enableCommentPinHighlighter()}catch(e){this.loggingService.catch("Error in CommentService enableCommentPinHighlighter: ",e)}}disableCommentPinHighlighter(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentPinHighlighter:!1}}),this.domService.disableCommentPinHighlighter()}catch(e){this.loggingService.catch("Error in CommentService disableCommentPinHighlighter: ",e)}}setCustomReactions(e){try{this.reactionService.setCustomReactions(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomReactions: ",t)}}onCommentSelectionChange$(){return this.commentSelectionChange$.asObservable()}onVisibilityOptionClicked$(){return this.visibilityOptionClicked$.asObservable()}emitVisibilityOptionClicked(e){this.visibilityOptionClicked$.next(e)}onCommentAdd$(){return this.commentAdded$.asObservable()}onCommentUpdate$(){return this.commentUpdated$.asObservable()}onCommentAnnotationDelete$(){return this.commentAnnotationDeleted$.asObservable()}onMultiThreadCommentAnnotationDelete$(){return this.multiThreadCommentAnnotationDeleted$.asObservable()}getCommentMode(){try{let e="freestyle";return this.getStreamMode()?e="stream":this.getPopoverMode()&&(e="popover"),e}catch(e){return this.loggingService.catch("Error in CommentService getCommentMode: ",e),"freestyle"}}getCommentType(e){try{return e.targetElement?"element":e.targetTextRange?"text":e.areaAnnotationId?"area":""}catch(t){return this.loggingService.catch("Error in CommentService getCommentType: ",t),""}}getCommentAnnotationAvailableOnXPath(e,t,i){try{return this.commentAnnotationById$.pipe(Se(()=>this.draftCommentAnnotationsByAnnotationId$),Se(a=>(!i&&t&&(i=nl(t,["id","data-id"])),ce(y(h({},a),{element:i})))),Se(a=>this.getLocations$().pipe(ue(l=>y(h({},a),{locationIds:l})))),ue(({locationIds:a,element:l})=>{let c=[],d=this.docService.getDocumentPaths();if(d?.documentId){let m=this.docService.getAdditionalDocumentIdFromElement(l),u=m?this.docService.generateDocumentId(m):d?.documentId,_=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:d?.organizationId,documentId:u||""});if(_)for(let I of _)(t&&I?.targetElementId===t||I?.targetElement?.xpath===e)&&a?.includes(I?.locationId)&&c.push(I)}return c.length?c:null}))}catch(a){return this.loggingService.catch("Error in CommentService isCommentAnnotationAvailableOnXPath: ",a),ce(null)}}getCommentAnnotationsByContext({context:e,contextOptions:t,element:i,clientDocumentId:a}){try{return this.commentAnnotationById$.pipe(Se(()=>this.draftCommentAnnotationsByAnnotationId$),Se(()=>this.docService.getDocumentPaths$()),ue(()=>{let l=null,c=this.docService.getDocumentPaths(),d=Es(e),m=this.generateContextId(d);if(c?.documentId){let u=a||this.docService.getAdditionalDocumentIdFromElement(i??null),_=u?this.docService.generateDocumentId(u):c?.documentId,I=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:c?.organizationId,documentId:_||""});if(I){l=[];for(let A of I)t?.partialMatch?WN(A?.context,d)&&l.push(A):m&&A?.contextId===m&&l.push(A)}}return l}))}catch(l){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByContext: ",l),ce(null)}}getCommentAnnotationByAnnotationId(e){try{return this.commentAnnotationById$.pipe(ue(()=>this.getAnnotationById(e)),Se(t=>t?t?.iam?.accessMode===Ca.PRIVATE?this.isPrivateCommentAllowed$().pipe(ue(i=>{if(i)return t})):ce(t):ce(t)),Se(t=>t?this.filterCommentsUsingSidebarSettings(t).pipe(ue(i=>{if(i)return i})):ce(t)))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationByAnnotationId: ",t),ce(void 0)}}getMultiThreadCommentAnnotationByAnnotationId(e){return this.multiThreadCommentAnnotationById$.pipe(ue(()=>this.getMultiThreadAnnotationById(e)))}getCommentBubbleElement(e){try{let t=document.querySelector(`${N.TAGS.VELT_COMMENT_BUBBLE}[${N.ATTRIBUTES.VELT_ANNOTATION_IDS}*="${e?.annotationId}"]`);return t||(t=document.querySelector(`${N.TAGS.SNIPPYLY_COMMENT_BUBBLE}[${N.ATTRIBUTES.VELT_ANNOTATION_IDS}*="${e?.annotationId}"]`)),t}catch(t){return this.loggingService.catch("Error in CommentService getCommentBubbleElement: ",t),null}}getCommentAnnotationsBySectionId(e){try{return this.commentAnnotationById$.pipe(Se(()=>this.docService.getDocumentPaths$().pipe(ue(t=>({documentPaths:t,sectionId:e})))),Se(t=>{let i=nl(e,["id","data-id"]);if(i){let a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.genarateLocationId(a);return this.docService.getLocations$().pipe(ue(c=>{let m=Object.values(c||{}).find(u=>u.locationId===l||a?.id&&u.location.id===a.id);return y(h({},t),{additionalLocation:m,locationOnElement:!!a})}))}}return ce(y(h({},t),{additionalLocation:null,element:i}))}),Se(t=>t?.locationOnElement?ce(t):this.docService.getLocation$().pipe(ue(i=>y(h({},t),{location:i})))),ue(({documentPaths:t,location:i,additionalLocation:a,locationOnElement:l,element:c})=>{let d=null;if(this.authService.getUser()&&t?.documentId){let u=this.docService.getAdditionalDocumentIdFromElement(c),_=u?this.docService.generateDocumentId(u):t?.documentId,I=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:t?.organizationId,documentId:_||""});if(I){d=[];let A=am(e);l?a?.location?.id?A=am([a?.location?.id,e]):a?.locationId&&(A=am([a?.locationId+"",e])):i&&(i?.location?.id?A=am([i?.location?.id,e]):i?.locationId&&(A=am([i?.locationId+"",e])));for(let M of I)M?.multiThreadAnnotationId===A?d.push(M):(M?.targetInlineCommentElementId===e||M?.targetElementId===e)&&(l?a&&_0({location:a?.location,locationId:a?.locationId},{location:M.location,locationId:M.locationId})&&d.push(M):i?_0({location:i?.location,locationId:i?.locationId},{location:M.location,locationId:M.locationId})&&d.push(M):M?.locationId||d.push(M))}}return d}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsBySectionId: ",t),ce(null)}}getCommentAnnotationsByMultiThreadAnnotationId(e){try{return this.commentAnnotationById$.pipe(Se(()=>this.multiThreadCommentAnnotationById$),Se(()=>this.docService.getDocumentPaths$().pipe(ue(t=>({documentPaths:t,multiThreadAnnotationId:e})))),ue(({documentPaths:t,location:i,additionalLocation:a,locationOnElement:l})=>{let c=null;if(t?.documentId){let d=this.getMultiThreadAnnotationById(e),{documentId:m,organizationId:u}=d?.metadata||{documentId:t?.documentId,organizationId:t?.organizationId},_=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:u,documentId:m||""});if(_){c=[];for(let I of _)I?.multiThreadAnnotationId===e&&d?.commentAnnotations?.[I?.annotationId]&&c.push(I)}}return c}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsBySectionId: ",t),ce(null)}}getCommentAnnotationsByAnnotationIds(e){try{return this.commentAnnotationById$.pipe(Se(()=>this.draftCommentAnnotationsByAnnotationId$),Se(()=>this.docService.getDocumentPaths$().pipe(ue(t=>({documentPaths:t,annotationIds:e})))),ue(({documentPaths:t})=>{let i=null;if(t?.documentId){let a=this.commentAnnotationById$.value?Object.values(this.commentAnnotationById$.value):[],l=this.draftCommentAnnotationsByAnnotationId$.value?Object.values(this.draftCommentAnnotationsByAnnotationId$.value):[];if(a=[...a,...l],a){i=[];for(let c of a)e.includes(c?.annotationId)&&i.push(c)}}return i}))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByAnnotationIds: ",t),ce(null)}}getCommentAnnotationsByFolderId({folderId:e,veltFolderId:t}){try{return this.commentAnnotationById$.pipe(Se(()=>this.draftCommentAnnotationsByAnnotationId$),Se(()=>this.docService.getDocumentPaths$()),ue(()=>{e&&!t&&(t=Lr(e));let i=this.authService.getUser(),a=this.docService.getDocumentPaths(),l=null;if(i&&a?.documentId){this.commentAnnotationById$.value&&(l={},Object.values(this.commentAnnotationById$.value).forEach(d=>{d?.metadata?.folderId==e&&d?.metadata?.veltFolderId==t&&(l[d?.annotationId]=d)}));let c=this.draftCommentAnnotationsByAnnotationId$.value;c&&(l===null&&(l={}),Object.values(c).forEach(d=>{d?.metadata?.folderId==e&&d?.metadata?.veltFolderId==t&&!l[d?.annotationId]&&(l[d?.annotationId]=d)}))}return l?Object.values(l):null}))}catch(i){return this.loggingService.catch("Error in CommentService getCommentAnnotationsByFolderId: ",i),ce(null)}}getCommentAnnotationsForCommentComponent(e){try{let{annotationId:t,folderId:i,veltFolderId:a,targetElementId:l,clientDocumentId:c,documentId:d,context:m,contextOptions:u,element:_,type:I,sectionId:A,locationId:M}=e||{};if(c&&!d&&(d=this.docService.generateDocumentId(c)),i&&!a&&(a=Lr(i)),t)return this.getCommentAnnotationByAnnotationId(t).pipe(ue(q=>q?[q]:null));let V=[];if(l&&(I==="pin"||I==="tool"||I==="bubble")){let q=nl(l,["id","data-id"]);if(q){let ae=q,ye=this.domService.getXPath(q);V.push(this.getCommentAnnotationAvailableOnXPath(ye,l,ae))}}return A&&V.push(this.getCommentAnnotationsBySectionId(A)),m&&V.push(this.getCommentAnnotationsByContext({context:m,contextOptions:u,element:_,clientDocumentId:c})),d&&V.push(this.getCommentAnnotationsByDocumentId$({documentId:d})),i&&V.push(this.getCommentAnnotationsByFolderId({folderId:i,veltFolderId:a})),V.length===0?ce(null):gn(V).pipe(ue(q=>{let ae=q.filter(ie=>ie!==null&&Array.isArray(ie));if(ae.length===0)return null;if(ae.length===1){let ie=ae[0];return M&&ie?.length?ie.filter(Ie=>Ie?.location?.id===M):ie}let ye=ae[0];for(let ie=1;ie<ae.length;ie++){let ge=ae[ie];ye=ye.filter(Ie=>ge.some(Te=>Te.annotationId===Ie.annotationId))}return M&&ye?.length&&(ye=ye.filter(ie=>ie?.location?.id===M)),ye}),_t(Kt))}catch(t){return this.loggingService.catch("Error in CommentService getCommentAnnotationsForCommentComponent: ",t),ce(null)}}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.allowedElementIds$.value?.length||this.allowedElementClassNames$.value?.length||this.allowedElementQuerySelectors$.value?.length?!!(this.allowedElementIds$.value?.length&&this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)||this.allowedElementClassNames$.value?.length&&this.domService.isElementInsideListedElementClassNames(e,this.allowedElementClassNames$.value)||this.allowedElementQuerySelectors$.value?.length&&this.domService.isElementInsideListedElementQuerySelectors(e,this.allowedElementQuerySelectors$.value)):!0}catch(t){return this.loggingService.catch("Error in CommentService isElementInsideAllowedElements: ",t),!1}}getNearestAllowedElement(e){try{let t=this.domService.getListedElements({elementIds:this.allowedElementIds$.value,elementClassNames:this.allowedElementClassNames$.value,elementQuerySelectors:this.allowedElementQuerySelectors$.value});if(t?.length){for(let i=0;i<t.length;i++){let a=t[i];if(e.contains(a))return a}return null}return null}catch(t){return this.loggingService.catch("Error in CommentService getNearestAllowedElement: ",t),null}}isElementInsideManualCommentContainer(e){try{return this.domService.isElementInsideParentWithAttribute(e,N.ATTRIBUTES.VELT_MANUAL_COMMENT_CONTAINER,"true")}catch(t){return this.loggingService.catch("Error in CommentService isElementInsideManualCommentContainer: ",t),!1}}saveComment(e,t){return X(this,null,function*(){try{t?.annotation&&(e=t.annotation),e&&(e=JSON.parse(JSON.stringify(e)));let i=this.originalCommentAnnotationsByDocumentId$.value[e.annotationId];if(i?.comments?.length){let u=JSON.parse(JSON.stringify(e.comments||[]));e.comments=[],i.comments?.forEach(_=>{let I=u.find(A=>A.commentId===_.commentId);I?e.comments.push(I):e.comments.push(_)})}e.comments||(e.comments=[]);let a=!1,l=!1,c;switch(t.type){case Ot.NEWLY_ADDED:case Ot.ADDED:if(!t.updatedComment)break;e?.comments?.length||(l=!0),e.comments.push(t.updatedComment);let u=t?.assigned||void 0;c={commentAnnotation:e,targetComment:t.updatedComment,actionType:t.type,otherFields:{assigned:u}};break;case Ot.PUBLISHED:e.isDraft=!1;break;case Ot.APPROVED:e.approved=!0,c={commentAnnotation:e,targetComment:null,actionType:Ot.APPROVED};break;case Ot.ASSIGNED:{let ae=i?.assignedTo;e.assignedTo=t.assignedTo,c={commentAnnotation:e,targetComment:null,actionType:Ot.ASSIGNED,otherFields:{oldAssignedTo:ae,newAssignedTo:t.assignedTo}};break}case Ot.UPDATED:if(!t.updatedComment)break;let _=e.comments.findIndex(ae=>ae.commentId===t.updatedComment.commentId);if(_>=0){let ae=e.comments[_]?.commentText;e.comments[_]=t.updatedComment,e.comments[_].status=Ot.UPDATED;let ye=t?.assigned||void 0;c={commentAnnotation:e,targetComment:t.updatedComment,actionType:Ot.UPDATED,otherFields:{assigned:ye,oldCommentText:ae}}}break;case Ot.REACTION_ADDED:if(!t.updatedComment)break;let I=e.comments.findIndex(ae=>ae.commentId===t.updatedComment.commentId);I>=0&&(e.comments[I]=t.updatedComment,e.comments[I].status=Ot.UPDATED,c={commentAnnotation:e,targetComment:t.updatedComment,actionType:Ot.REACTION_ADDED});break;case Ot.REACTION_DELETED:if(!t.updatedComment)break;let A=e.comments.findIndex(ae=>ae.commentId===t.updatedComment.commentId);A>=0&&(e.comments[A]=t.updatedComment,e.comments[A].status=Ot.UPDATED,c={commentAnnotation:e,targetComment:t.updatedComment,actionType:Ot.REACTION_DELETED});break;case Ot.STATUS_CHANGED:if(e.status.type==="terminal"){this.domService.resetSelectedAnnotationsMap(!1,"comment");let ae=this.authService.getUser();e.resolvedByUserId=ae?.userId,e.resolvedByUser=ae}c={commentAnnotation:e,targetComment:null,actionType:Ot.STATUS_CHANGED,otherFields:{oldStatus:t.oldStatus,newStatus:t.newStatus}};break;case Ot.PRIORITY_CHANGED:c={commentAnnotation:e,targetComment:null,actionType:Ot.PRIORITY_CHANGED,otherFields:{oldPriority:t.oldPriority,newPriority:t.newPriority}};break;case Ot.ACCESS_MODE_CHANGED:c={commentAnnotation:e,targetComment:null,actionType:Ot.ACCESS_MODE_CHANGED,otherFields:{oldAccessMode:t.oldAccessMode,newAccessMode:t.newAccessMode}};break;case Ot.CUSTOM_LIST_CHANGED:c={commentAnnotation:e,targetComment:null,actionType:Ot.CUSTOM_LIST_CHANGED,otherFields:{oldCustomList:t.oldCustomList,newCustomList:t.newCustomList}};break;case Ot.SUBSCRIBED:c={commentAnnotation:e,targetComment:null,actionType:Ot.SUBSCRIBED};break;case Ot.UNSUBSCRIBED:c={commentAnnotation:e,targetComment:null,actionType:Ot.UNSUBSCRIBED};break;case Ot.DELETED:if(!t.updatedComment)break;let M=e.comments.findIndex(ae=>ae.commentId===t.updatedComment.commentId);if(M>=0){if((M===0&&this.deleteThreadWithFirstComment$.value!==!1||this.deleteReplyConfirmation$.value)&&!t.skipDeleteThreadConfirmation){let ie={};if(this.deleteReplyConfirmation$.value&&(M!==0||this.deleteThreadWithFirstComment$.value===!1)?ie={title:"Delete comment?",message:"This selected comment will be deleted.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"reply",type:"reply"}:ie={title:"Delete thread?",message:"All replies to this thread will be lost.",yesButton:"Delete",noButton:"Cancel",darkMode:this.commentContainerDarkMode$.value,variant:"comment",type:"comment"},!(yield this.dialog.open(al,{panelClass:["velt-confirm-dialog-overlay-pane","velt-mat-dialog-container"],data:ie}).afterClosed().toPromise()))return}let ae=e.comments.splice(M,1),ye=e.metadata;ae?.length&&ae.forEach(ie=>{ie?.attachments&&ie.attachments.forEach(ge=>{let Ie={attachmentId:ge.attachmentId,organizationId:ye?.clientOrganizationId??ye?.organizationId??null,documentId:ye?.clientDocumentId??ye?.documentId??null,folderId:ye?.folderId??null,commentAnnotationId:e.annotationId,apiKey:ye?.apiKey??null};this.deleteAttachment({attachment:ge,metadata:Ie})}),ie?.reactionAnnotationIds&&ie.reactionAnnotationIds.forEach(ge=>{this.deleteReaction(ge)})})}e?.status?.type==="terminal"&&(e.status=this.customFilterService.defaultStatus),M===0&&this.deleteThreadWithFirstComment$.value!==!1||e.comments?.length===0?a=!0:(this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_THREAD_DELETED,{annotationId:e.annotationId,commentThreadId:t.updatedComment.commentId,commentMode:this.getCommentMode()}),c={commentAnnotation:e,targetComment:t.updatedComment,actionType:Ot.DELETED});break;case Ot.ACCEPTED:let V={annotationId:e.annotationId,actionUser:this.authService.getUser(),actionType:Ot.ACCEPTED,replaceContentHtml:e?.comments?.length?e?.comments[0]?.replaceContentHtml:void 0,replaceContentText:e?.comments?.length?e?.comments[0]?.replaceContentText:void 0,annotation:this.getCommentAnnotationForClient(e)};this.commentAccepted$.next(V),c={commentAnnotation:e,targetComment:null,actionType:Ot.ACCEPTED};break;case Ot.REJECTED:let q={annotationId:e.annotationId,actionUser:this.authService.getUser(),actionType:Ot.REJECTED,replaceContentHtml:e?.comments?.length?e?.comments[0]?.replaceContentHtml:void 0,replaceContentText:e?.comments?.length?e?.comments[0]?.replaceContentText:void 0,annotation:this.getCommentAnnotationForClient(e)};this.commentRejected$.next(q),this.domService.resetSelectedAnnotationsMap(),c={commentAnnotation:e,targetComment:null,actionType:Ot.REJECTED};break;default:break}if(e.resolvedByUserId&&e.status.type!=="terminal"&&(e.resolvedByUserId=null,e.resolvedByUser=null),t.visibility)try{let u=h({},t.visibility);if(u.type==="organizationPrivate"&&!u.organizationId){let I=this.docService.getOrganizationConfig();I?.clientOrganizationId&&(u.organizationId=I.clientOrganizationId)}let _=Xu(u);_.length>0&&(e.context||(e.context={}),e.context._setAccessFields=_)}catch(u){this.loggingService.catch("Error building accessFields from visibility in saveComment:",u)}if(t?.updatedComment?.isDraft&&(c=void 0),a)this.deleteCommentPinAnnotation(e,!0),this.domService.resetSelectedAnnotationsMap(!1,"comment");else{if(l&&e.comments?.length&&this.enableAutoCategorize$?.value&&this.setCommentCategory(e),e.context?.access&&e.context?.accessFields&&t.updatedComment?.from?.userId&&!this.userPermissionService?.hasUserContextAccess({userId:t.updatedComment?.from?.userId,accessFields:e.context.accessFields})){this.loggingService.catch("User does not have context access to update comment annotation.",void 0,void 0,!0);return}this.updateComment(e,!1,!1,c,!0,t.updatedComment),e?.multiThreadAnnotationId&&(t.type===Ot.ADDED||t.type===Ot.NEWLY_ADDED)&&e.comments?.length===1?setTimeout(()=>{this.domService.resetSelectedAnnotationsMap(!1,"comment")},100):this.domService.updateSelectedAnnotationInMap([e])}let d=this.getCustomPinById(e.annotationId),m={type:t.type,annotation:this.getCommentAnnotationForClient(e),targetAnnotationId:e.annotationId,targetCommentId:t.updatedComment?.commentId,updateContext:(u,_)=>{this.updateCommentAnnotationContext(e.annotationId,u,_)}};if(d!==void 0&&(m.element=d),delete m?.annotation?.pageInfo,delete m?.annotation?.targetElement,delete m?.annotation?.targetTextRange,m?.type===Ot.DELETED&&(e.comments?.length||(m.annotation=null)),a||this.commentUpdated$.next(m),t.type===Ot.NEWLY_ADDED&&!a&&e?.annotationId){let u=this.pendingAddCommentAnnotationData.get(e.annotationId);if(u){this.pendingAddCommentAnnotationData.delete(e.annotationId);let _=y(h({},u),{annotation:this.getCommentAnnotationForClient(e),targetCommentId:t.updatedComment?.commentId}),I=yield this.commentActionsService?.getAddCommentAnnotationEventFromCommentAddEventData(_);I&&this.commentActionsService?.triggerAddCommentAnnotationEvent(I),t.updatedComment&&(yield this.commentActionsService?.triggerAddCommentEvent({annotation:e,newComment:t.updatedComment}))}}t.type===Ot.ADDED&&t._dispatchAddCommentEvent&&!a&&e?.annotationId&&t.updatedComment&&(yield this.commentActionsService?.triggerAddCommentEvent({annotation:e,newComment:t.updatedComment}))}catch(i){this.loggingService.catch("Error in CommentService saveComment: ",i)}})}attachComment(e,t=[],i,a,l,c,d,m){try{this.loggingService.log("%c[WB] Calling FUNCTION: attachComment","color: green;");let u;if(e){let _=nl(e,t);_&&(u={targetElement:{xpath:this.domService.getXPath(_),topPercentage:50,leftPercentage:90},targetElementId:e})}(u||i||l)&&this.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,c,void 0,void 0,u,m,void 0,void 0,a,void 0,void 0,void 0,i,void 0,l,void 0,void 0,d)}catch(u){this.loggingService.catch("Error in CommentService attachComment: ",u)}}generateComponentIdFromObject(e){try{let t=Es(e||{});return It(JSON.stringify(t))}catch(t){this.loggingService.catch("Error in CommentService generateComponentIdFromObject: ",t);return}}updateNotificationsDatabase(e,t,i,a={}){try{let l=h({annotationData:e,targetAnnotationData:t,actionType:i,notificationSource:"comment"},a);this.notificationService.updateNotificationDatabase(l)}catch(l){this.loggingService.catch("Error in CommentService updateNotificationsDatabase: ",l)}}getUserContacts$(){return this.contactService.getUserContacts$()}addUserContact(e){this.contactService.addUserContact(e)}getCustomUserContacts(){try{return this.contactService.getCustomUserContacts()}catch(e){return this.loggingService.catch("Error in CommentService getCustomUserContacts:",e),null}}getCustomUserContactsConfig(){try{return this.contactService.getCustomUserContactsConfig()}catch(e){this.loggingService.catch("Error in CommentService getCustomUserContactsConfig:",e);return}}getElementFromComment(e){try{let t=null;if(e?.ghostComment)!t&&e.ghostComment?.targetElement?.fXpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.fXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e.ghostComment?.targetElement?.cfXpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.cfXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e.ghostComment?.targetElement?.xpath&&(t=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.xpath),t&&!this.domService.isElementVisible(t)&&(t=null));else{let i=!1,a=e?.targetElement?.anchor;if(!t&&a){let l=this.domService.resolveAnchorRecord(a);l?.element&&this.domService.isElementVisible(l.element)&&Kr(l.element)&&(t=l.element)}!t&&e?.targetElement?.xpath&&(i=this.domService.isXpathWithId(e?.targetElement?.xpath),t=this.domService.getElementFromXPath(e?.targetElement?.xpath),t&&!this.domService.isElementVisible(t)&&(t=null)),i||(!t&&e?.targetElement?.cfXpath&&(t=this.domService.getElementFromXPath(e?.targetElement?.cfXpath),t&&!this.domService.isElementVisible(t)&&(t=null)),!t&&e?.targetElement?.fXpath&&(t=this.domService.getElementFromXPath(e?.targetElement?.fXpath),t&&!this.domService.isElementVisible(t)&&(t=null)))}return t&&!Kr(t)&&(t=null),t}catch(t){return this.loggingService.catch("Error in CommentService getElementFromComment: ",t),null}}getElementFromComments(e){try{let t=[],i=null;if(e?.ghostComment)!i&&e.ghostComment?.targetElement?.fXpath&&(i=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.fXpath),i&&!this.domService.isElementVisible(i)&&(i=null)),!i&&e.ghostComment?.targetElement?.cfXpath&&(i=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.cfXpath),i&&!this.domService.isElementVisible(i)&&(i=null)),!i&&e.ghostComment?.targetElement?.xpath&&(i=this.domService.getElementFromXPath(e.ghostComment?.targetElement?.xpath),i&&!this.domService.isElementVisible(i)&&(i=null));else{let a=!1,l=e?.targetElement?.anchor;if(!i&&l){let c=this.domService.resolveAnchorRecord(l);c?.element&&this.domService.isElementVisible(c.element)&&Kr(c.element)&&(i=c.element)}!i&&e?.targetElement?.xpath&&(a=this.domService.isXpathWithId(e?.targetElement?.xpath),i=this.domService.getElementFromXPath(e?.targetElement?.xpath),i&&!this.domService.isElementVisible(i)&&(i=null)),a||(!i&&e?.targetElement?.cfXpath&&(i=this.domService.getElementFromXPath(e?.targetElement?.cfXpath),i&&!this.domService.isElementVisible(i)&&(i=null)),!i&&e?.targetElement?.fXpath&&(i=this.domService.getElementFromXPath(e?.targetElement?.fXpath),i&&!this.domService.isElementVisible(i)&&(i=null)))}return i&&!Kr(i)&&(i=null),e?.targetElementId&&(t=Array.from(ahe(e.targetElementId,["id","data-id"]))),i&&!t.includes(i)&&t.push(i),t}catch(t){return this.loggingService.catch("Error in CommentService getElementFromComment: ",t),[]}}getGhostCommentTargetElement(e){try{let t=e.targetElement?.fXpath||e.targetElement?.xpath,i=null;if(t)for(;!i&&t;)i=this.domService.getElementFromXPath(t),i&&(!this.domService.isElementVisible(i)||!Kr(i))&&(i=null),i||(t=t.substring(0,t.lastIndexOf("/")));return t==="/"&&(t=""),t?{xpath:t,topPercentage:e?.targetElement?.topPercentage||0,leftPercentage:e?.targetElement?.leftPercentage||0}:null}catch(t){return this.loggingService.catch("Error in CommentService getGhostCommentTargetElement: ",t),null}}setGhostCommentMessage(e){try{if(e?.ghostComment){e.ghostComment.message="Original content not found.",e.ghostComment.type=ys.ELEMENT_DELETED;let t=e?.pageInfo?.deviceInfo?.deviceType,i=new hr().getDeviceType();t&&t!==i&&(e.ghostComment.type=ys.DIFFERENT_DEVICE,e.ghostComment.message=`Original comment was added on ${t}.`,[$i.MOBILE,$i.TABLET].includes(t)&&[$i.MOBILE,$i.TABLET].includes(i)||[$i.DESKTOP,$i.MONITOR].includes(t)&&[$i.DESKTOP,$i.MONITOR].includes(i)?e.ghostComment.isSameGroup=!0:e.ghostComment.isSameGroup=!1)}}catch(t){this.loggingService.catch("Error in CommentService setGhostCommentMessage: ",t)}}addAnnotationToGhostCommentAnnotationMap(e){try{let t=this.ghostCommentAnnotationMap$.value||{},i=t[e?.annotationId]||{};sr(e.ghostComment,i)||(t[e?.annotationId]=e.ghostComment,this.ghostCommentAnnotationMap$.next(t))}catch(t){this.loggingService.catch("Error in CommentService addAnnotationToGhostCommentAnnotationMap: ",t)}}removeAnnotationFromGhostCommentAnnotationMap(e){try{let t=this.ghostCommentAnnotationMap$.value||{};t[e?.annotationId]&&(delete t[e?.annotationId],this.ghostCommentAnnotationMap$.next(t))}catch(t){this.loggingService.catch("Error in CommentService removeAnnotationFromGhostCommentAnnotationMap: ",t)}}getGhostCommentAnnotationMap$(){return this.ghostCommentAnnotationMap$.asObservable()}getGhostCommentAnnotationMap(){return this.ghostCommentAnnotationMap$.value||{}}getUnreadCommentsMap$(){return this.unreadCommentsMap$.asObservable().pipe(_t(Kt))}getUnreadCommentsMap(){return this.unreadCommentsMap$.value}getUnreadCommentCountByAnnotationId$(e){return this.getUnreadCommentsMap$().pipe(ue(t=>t?{count:t[e]||0}:null))}getUnreadCommentAnnotationCountOnCurrentDocument$(){return this.getUnreadCommentsMap$().pipe(ue(e=>e?{count:Object.keys(e??{}).length||0}:null))}getUnreadCommentCountOnCurrentDocument$(){return this.getUnreadCommentsMap$().pipe(ue(e=>e?{count:Object.values(e).reduce((i,a)=>i+a,0)}:null))}getUnreadCommentCountByLocationId$(e){return this.getUnreadCommentsMap$().pipe(ue(t=>{if(t){let i=this.docService.getDocumentPaths(),a=[],l=0;return i?.documentId&&(a=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:i?.organizationId,documentId:i?.documentId}),a&&Object.keys(t).forEach(c=>{a?.find(m=>m.annotationId===c)?.location?.id===e&&(l+=t[c])})),{count:l}}else return null}))}getUnreadCommentAnnotationCountByLocationId$(e){return this.getUnreadCommentsMap$().pipe(ue(t=>{if(t){let i=this.docService.getDocumentPaths(),a=[],l=0;return i?.documentId&&(a=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:i?.organizationId,documentId:i?.documentId}),Object.keys(t).forEach(c=>{t[c]&&a?.find(m=>m.annotationId===c)?.location?.id===e&&(l+=1)})),{count:l}}else return null}))}setCommentAnnotationsAsRead(e){try{for(let t of e)this.viewsService.setCommentAnnotationAsRead(t)}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsAsRead: ",t)}}setCommentAnnotationsAsResolved(e){try{let t=this.customFilterService.resolvedStatus;if(t){for(let i of e)if(t?.id!==i?.status?.id){let a=JSON.parse(JSON.stringify(i||{}));i.status=this.customFilterService.resolvedStatus;let l={annotation:i,type:Ot.STATUS_CHANGED,oldStatus:a.status,newStatus:this.customFilterService.resolvedStatus};this.saveComment(i,l)}}}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsAsResolved: ",t)}}isCommentAnnotationUnread(e){try{let t=this.authService.getUser();return!(t?.userSnippylyId&&e?.viewedByUserIds?.length&&e?.viewedByUserIds?.includes(t?.userSnippylyId))}catch(t){return this.loggingService.catch("Error in CommentService isCommentAnnotationUnread: ",t),!1}}updateCommentDialogPosition(){try{this.updateCommentDialogPositionTriggerSubject$.next()}catch(e){this.loggingService.catch("Error in CommentService updateCommentDialogPosition: ",e)}}updateCommentDialogPositionTrigger$(){return this.updateCommentDialogPositionTriggerSubject$.asObservable()}enableAreaComment(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{areaComment:!0}}),this.areaCommentEnabled$.value===!0)return;this.areaCommentEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAreaComment: ",e)}}disableAreaComment(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{areaComment:!1}}),this.areaCommentEnabled$.value===!1)return;this.areaCommentEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAreaComment: ",e)}}getAreaCommentEnabled$(){return this.areaCommentEnabled$.asObservable()}getAreaCommentEnabled(){return this.areaCommentEnabled$.value}setPinCursorImage(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: setPinCursorImage","color: green;"),e&&(e=`url(${e}) 0 31, auto`),this.commentPinCursorImage$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setPinCursorImage: ",t)}}getPinCursorImage$(){return this.commentPinCursorImage$.asObservable()}getPinCursorImage(){return this.commentPinCursorImage$.value}setCommentAnnotationsFromCommentsContainer(e){try{this.commentAnnotationsFromCommentsContainer$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentAnnotationsFromCommentsContainer: ",t)}}getCommentAnnotationsFromCommentsContainer$(){return this.commentAnnotationsFromCommentsContainer$.asObservable()}getCommentAnnotationsFromCommentsContainer(){return this.commentAnnotationsFromCommentsContainer$.value}addManualComment(e){return X(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: addManualComment","color: green;"),new Promise((t,i)=>{let a=this.domService.getLastDocumentClick()?.target,l=e?.location||this.docService.getAdditionLocationFromElement(a);if(l?.id){let c=this.docService.getLocationByClientLocationId(l.id);c&&(l=c)}this.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,l,void 0,e,void 0,void 0,void 0,c=>{t(c)}),this.addCommentMode$?.value&&!this.persistentCommentMode$?.value&&this.disableAddCommentMode()})}catch(t){return this.loggingService.catch("Error in CommentService addManualComment: ",t),null}})}getCommentUrl(e){try{return e?.pageInfo?.commentUrl?e.pageInfo.commentUrl:(e?.pageInfo||(e.pageInfo=ro(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.commentUrl=this.generateCommentUrl(e),this.updateComment(e),e.pageInfo?.commentUrl)}catch(t){this.loggingService.catch("Error in CommentService getCommentUrl: ",t);return}}uploadFile(e,t){let i=`${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentPaths?.documentId}/${N.FIREBASE_PARTIAL_PATH_COMMENT}/${t.annotationId}`;this.documentPaths?.organizationId&&(i=`${N.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}/${N.FIREBASE_PARTIAL_PATH_DOCS}/${this.documentPaths?.documentId}/${N.FIREBASE_PARTIAL_PATH_COMMENT}/${t.annotationId}`);let a={organizationId:t.metadata?.clientOrganizationId??this.documentPaths?.clientOrganizationId??null,documentId:t.metadata?.clientDocumentId??this.documentPaths?.clientDocumentId??null,commentAnnotationId:t.annotationId,apiKey:t.metadata?.apiKey??this.configService?.getApiKey()??null,folderId:t.metadata?.folderId??this.documentPaths?.folderId??null,attachmentId:null};return this.storageService.uploadFile({path:i,file:e,metadata:a,useAttachmentResolver:this.attachmentResolverService.attachmentDataProviderAvailable()})}downloadAttachment(e){this.storageService.downloadAttachment(e)}deleteAttachment({attachment:e,metadata:t}){return this.storageService.deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:this.attachmentResolverService.attachmentDataProviderAvailable()})}deleteReaction(e){try{this.reactionService.deleteReactionPinAnnotation(e)}catch(t){this.loggingService.catch("Error in CommentService deleteReaction: ",t)}}generateCommentUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(N.URL_PARAMS.COMMENT_ID),t.searchParams.append(N.URL_PARAMS.COMMENT_ID,e.annotationId),t.href}getCustomPinById(e){if(this.customPinsById.has(e))return this.customPinsById.get(e)}setCustomStatuses(e){try{if(e===void 0)return;this.customStatusesShown$.next(!0),this.customFilterService.setCustomStatusFilters(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomStatuses: ",t)}}getCustomStatusesShown$(){return this.customStatusesShown$.asObservable()}getCustomStatusesShown(){return this.customStatusesShown$.value}setCustomPriorities(e){try{if(e===void 0)return;this.customFilterService.setCustomPriorityFilters(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomPriorities: ",t)}}setCustomCategories(e){try{if(e===void 0)return;this.customFilterService.setCustomCategories(e)}catch(t){this.loggingService.catch("Error in CommentService setCustomCategories: ",t)}}addCommentOnSelectedText(){try{let e=this.authService.getUser();if(this.textCommentMode$.value&&e&&!(e?.isReadOnly||e?.isAnonymous)&&this.authService.isFeatureAllowed(je.COMMENT)){let t=this.domService.getRange();if(window.getSelection()?.toString()&&!O3()&&t?.commonAncestorContainer&&this.isElementInsideAllowedElements(t.commonAncestorContainer)&&!xg(t.commonAncestorContainer)){let i=t?this.domService.getTargetTextRangeFromSelectionRange(t):void 0;this.domService.clearTextSelection(),setTimeout(()=>{this.addComment(void 0,i)},100)}}}catch(e){this.loggingService.catch("Error in CommentService addCommentOnSelectedText: ",e)}}getInlineCommentSectionConfig(e){try{let t;if(e){let i=e?.closest(`[${N.ATTRIBUTES.VELT_TARGET_INLINE_COMMENT_ELEMENT_ID}]`);if(i){let a=i.getAttribute(N.ATTRIBUTES.VELT_TARGET_INLINE_COMMENT_ELEMENT_ID);a&&(t={},t.targetInlineCommentElementId=a,i.getAttribute(N.ATTRIBUTES.VELT_INLINE_COMMENT_SECTION_CONFIG)&&(t.config=JSON.parse(i.getAttribute(N.ATTRIBUTES.VELT_INLINE_COMMENT_SECTION_CONFIG)||"{}")))}}return t}catch(t){this.loggingService.catch("Error in CommentService getInlineCommentSectionConfig: ",t)}}createCustomListDataOnAnnotation(e){try{if(e===void 0)return;this.customChipDropdownData$.next(e)}catch(t){this.loggingService.catch("Error in CommentService createCustomListDataOnAnnotation: ",t)}}getCustomChipDropdownData$(){return this.customChipDropdownData$.asObservable()}getCustomChipDropdownData(){return this.customChipDropdownData$.value}setSubscribedUsersDataInCommentAnnotation(e){try{let t={},i=e?.unsubscribedUsers||{},a={};if(e?.subscribedUsers&&Object.keys(e.subscribedUsers||{}).forEach(l=>{let c=e.subscribedUsers?.[l];c?.type==="manual"&&(t[l]=c)}),e?.assignedTo?.userId){let l=It(e?.assignedTo?.userId);i[l]||t[l]?.type!=="manual"&&(t[l]={user:e?.assignedTo,type:"auto"})}e?.comments?.filter(l=>!l?.isDraft)?.forEach(l=>{if(l?.from?.userId){let c=It(l?.from?.userId);i[c]||t[c]?.type!=="manual"&&(t[c]={user:l?.from,type:"auto"})}l?.to?.forEach(c=>{if(c?.userId){let d=It(c.userId);i[d]||t[d]?.type!=="manual"&&(t[d]={user:c,type:"auto"})}}),l?.toOrganizationUserGroup?.forEach(c=>{if(c?.groupId)a[c?.groupId]={type:"auto"};else if(c?.clientGroupId){let d=It(c.clientGroupId);a[d]={type:"auto"}}})}),e.subscribedUsers=t,e.unsubscribedUsers=i,e.subscribedGroups=a}catch(t){this.loggingService.catch("Error in CommentService setSubscribeUsersDataInCommentAnnotation: ",t)}}getCopyLink$(){return this.copyLink$.asObservable()}setCopyLink(e){try{this.copyLink$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCopyLink: ",t)}}getCommentAnnotationById(e){return this.commentAnnotationById$.pipe(Se(()=>{let{annotationId:t,documentId:i}=e;if(i){let a=er(i).toString();return this.getDataCommentAnnotationsFromDocumentId(a).pipe(ue(l=>l.find(d=>d.annotationId===t)||null))}else{let a=this.docService.getDocumentPaths();if(a?.documentId){let l=this.getCommentAnnotationsByOrganizationIdAndDocumentId({organizationId:a?.organizationId,documentId:a?.documentId});if(l){let c=l.find(d=>d.annotationId===t);return ce(c||null)}}}return ce(null)}),Xn(t=>(this.loggingService.catch("Error in CommentService getCommentAnnotationById: ",t),ce(null))))}getDataCommentAnnotationsFromDocumentId(e){return this.configService?.getApiKey()?this.commonDbService.dbListener({feature:"allComments",properties:{documentId:e||this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,isCollection:!0}}).pipe(ue(t=>t?.data),ue(t=>{let i=[];return t&&(i=Object.values(t??{}).filter(a=>typeof a=="object")),i})):ce([])}enableCollapsedComments(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{collapsedComments:!0}}),this.collapsedComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCollapsedComments: ",e)}}disableCollapsedComments(){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{collapsedComments:!1}}),this.collapsedComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCollapsedComments: ",e)}}getCollapsedComments$(){return this.collapsedComments$.asObservable()}enableFullExpanded(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{fullExpanded:!0}}),this.fullExpanded$.value===!0)return;this.fullExpanded$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFullExpanded: ",e)}}disableFullExpanded(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{fullExpanded:!1}}),this.fullExpanded$.value===!1)return;this.fullExpanded$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFullExpanded: ",e)}}getFullExpanded$(){return this.fullExpanded$.asObservable()}getFullExpanded(){return this.fullExpanded$.value}setSidebarCustomActionEventData(e,t,i,a,l){try{this.sidebarCustomActionEventData$.next({actions:e,data:t,unreadDataMap:i,systemFilteredData:a,customFilters:l})}catch(c){this.loggingService.catch("Error in CommentService emitOnSidebarCustomAction: ",c)}}getSidebarCustomActionEventData(){return this.sidebarCustomActionEventData$.asObservable()}setCommentSidebarData(e,t){try{let i=new Set;(e||[]).forEach(l=>{(l?.annotations||[]).forEach(c=>{c?.annotationId&&i.add(c.annotationId)})});let a=this.customSidebarDataAnnotationIds$.value;this.areAnnotationIdSetsEqual(a,i)||this.customSidebarDataAnnotationIds$.next(i),this.sidebarData$.next({data:e,options:t})}catch(i){this.loggingService.catch("Error in CommentService setCommentSidebarData: ",i)}}areAnnotationIdSetsEqual(e,t){if(e===t)return!0;if(e===null||t===null||e.size!==t.size)return!1;for(let i of e)if(!t.has(i))return!1;return!0}getSidebarCustomData(){return this.sidebarData$.asObservable()}getCustomSidebarDataAnnotationIds$(){return this.customSidebarDataAnnotationIds$.asObservable()}getCustomSidebarDataAnnotationIds(){return this.customSidebarDataAnnotationIds$.value}setSidebarCustomActionEventDataAllChanges(e,t,i,a,l){return X(this,null,function*(){try{this.sidebarCustomActionEventDataAllChanges$.next({actions:e,data:t,unreadDataMap:i,systemFilteredData:a,customFilters:l});let c=yield this.metadataService.getGlobalMetadata(),d={buttonContext:{selections:this.buttonService.buttonToggleMapValue()},unreadCommentAnnotationsMap:i,commentAnnotations:t,systemFilteredAnnotations:a,metadata:c,customFilters:l};this.commentActionsService?.triggerAction(ar.COMMENT_SIDEBAR_DATA_UPDATE,d)}catch(c){this.loggingService.catch("Error in CommentService setSidebarCustomActionEventDataAllChanges: ",c)}})}setSidebarCustomActionEventDataOnInit(e,t,i,a,l){return X(this,null,function*(){try{this.sidebarCustomActionEventDataOnInit$.next({actions:e,data:t,unreadDataMap:i,systemFilteredData:a,customFilters:l});let d={metadata:yield this.metadataService.getGlobalMetadata(),unreadCommentAnnotationsMap:i,commentAnnotations:t,systemFilteredAnnotations:a,buttonContext:{selections:this.buttonService.buttonToggleMapValue()},customFilters:l};this.commentActionsService?.triggerAction(ar.COMMENT_SIDEBAR_DATA_INIT,d)}catch(c){this.loggingService.catch("Error in CommentService setSidebarCustomActionEventDataOnInit: ",c)}})}getSidebarCustomActionEventDataAllChanges(){return this.sidebarCustomActionEventDataAllChanges$.asObservable()}getSidebarCustomActionEventDataOnInit(){return this.sidebarCustomActionEventDataOnInit$.asObservable()}getSidebarCustomActionEventDataOnInitValue(){return this.sidebarCustomActionEventDataOnInit$.getValue()}setTransformContext(e){try{e?sr(this.transformContext$.value,e)||this.transformContext$.next(e):this.transformContext$.next(null)}catch(t){this.loggingService.catch("Error in CommentService setTransformContext: ",t)}}getTransformContext$(){return this.transformContext$.asObservable()}getTransformContext(){return this.transformContext$.value}enableSidebarCustomActions(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{customActions:!0}}),this.customActions$.value===!0)return;this.customActions$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSidebarCustomActions: ",e)}}disableSidebarCustomActions(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{customActions:!1}}),this.customActions$.value===!1)return;this.customActions$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSidebarCustomActions: ",e)}}getSidebarCustomActionsValue(){return this.customActions$.getValue()}enableQueryParamsComments(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{queryParamsComments:!0}}),this.queryParamsComments$.value===!0)return;this.queryParamsComments$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableQueryParamsComments: ",e)}}disableQueryParamsComments(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{queryParamsComments:!1}}),this.queryParamsComments$.value===!1)return;this.queryParamsComments$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableQueryParamsComments: ",e)}}getQueryParamsComments$(){return this.queryParamsComments$.asObservable()}getQueryParamsComments(){return this.queryParamsComments$.value}enableResolveStatusAccessAdminOnly(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{resolveStatusAccessAdminOnly:!0}}),this.resolveStatusAccessAdminOnly$.value===!0)return;this.resolveStatusAccessAdminOnly$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableResolveStatusAccessAdminOnly: ",e)}}disableResolveStatusAccessAdminOnly(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{resolveStatusAccessAdminOnly:!1}}),this.resolveStatusAccessAdminOnly$.value===!1)return;this.resolveStatusAccessAdminOnly$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableResolveStatusAccessAdminOnly: ",e)}}enableLinkCallback(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{linkCallback:!0}}),this.linkCallback$.value===!0)return;this.linkCallback$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableLinkCallback: ",e)}}disableLinkCallback(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{linkCallback:!1}}),this.linkCallback$.value===!1)return;this.linkCallback$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableLinkCallback: ",e)}}getResolveStatusAccessAdminOnly$(){return this.resolveStatusAccessAdminOnly$.asObservable()}getLinkCallback$(){return this.linkCallback$.asObservable()}getResolveStatusAccessAdminOnly(){return this.resolveStatusAccessAdminOnly$.value}getLinkCallback(){return this.linkCallback$.value}enableSvgAsImg(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{svgAsImg:!0}}),this.svgAsImg$.value===!0)return;this.svgAsImg$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableSvgAsImg: ",e)}}disableSvgAsImg(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{svgAsImg:!1}}),this.svgAsImg$.value===!1)return;this.svgAsImg$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableSvgAsImg: ",e)}}getSvgAsImg$(){return this.svgAsImg$.asObservable()}getSvgAsImg(){return this.svgAsImg$.value}enableCommentToNearestAllowedElement(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentToNearestAllowedElement:!0}}),this.commentToNearestAllowedElement$.value===!0)return;this.commentToNearestAllowedElement$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCommentToNearestAllowedElement: ",e)}}disableCommentToNearestAllowedElement(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentToNearestAllowedElement:!1}}),this.commentToNearestAllowedElement$.value===!1)return;this.commentToNearestAllowedElement$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCommentToNearestAllowedElement: ",e)}}getCommentToNearestAllowedElement$(){return this.commentToNearestAllowedElement$.asObservable()}getCommentToNearestAllowedElement(){return this.commentToNearestAllowedElement$.value}enableFilterCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{filterCommentsOnDom:!0}}),this.filterCommentsOnDom$.value===!0)return;this.filterCommentsOnDom$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFilterCommentsOnDom: ",e)}}disableFilterCommentsOnDom(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{filterCommentsOnDom:!1}}),this.filterCommentsOnDom$.value===!1)return;this.filterCommentsOnDom$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFilterCommentsOnDom: ",e)}}getFilterCommentsOnDom$(){return this.filterCommentsOnDom$.asObservable()}getFilterCommentsOnDom(){return this.filterCommentsOnDom$.value}setCommentsFromSidebarMap(e){try{let{comments:t,sidebarVisible:i}=e||{},a=null;t&&(a={},t.forEach(c=>{c?.annotationId&&a&&(a[c.annotationId]=c)}));let l={};t===void 0?l.data=this.commentsFromSidebarMap$.value?.data:l.data=a,i===void 0?l.sidebarVisible=this.commentsFromSidebarMap$.value?.sidebarVisible:l.sidebarVisible=i,sr(this.commentsFromSidebarMap$.value,l)||this.commentsFromSidebarMap$.next(l)}catch(t){this.loggingService.catch("Error in CommentService setCommentsFromSidebarMap: ",t)}}getCommentsFromSidebarMap$(){return this.commentsFromSidebarMap$.asObservable()}getCommentsFromSidebarMap(){return this.commentsFromSidebarMap$.value}hasActiveFilters(e){try{return e?!!(e.people?.length||e.assigned?.length||e.tagged?.length||e.involved?.length||e.priority?.length||e.status?.length||e.category?.length||e.location?.length||e.document?.length||e.version?.length||e.accessModes?.length||this.hasCustomContextFilters(e)):!1}catch(t){return this.loggingService.catch("Error in CommentService hasActiveFilters: ",t),!1}}hasCustomContextFilters(e){try{if(!e)return!1;let t=new Set(["people","assigned","tagged","involved","priority","status","category","version","document","location","accessModes"]);return Object.keys(e).some(i=>!t.has(i)&&Array.isArray(e[i])&&e[i]?.length>0)}catch(t){return this.loggingService.catch("Error in CommentService hasCustomContextFilters: ",t),!1}}applyDirectFilters(e,t){try{let i=this.commentSidebarSystemFiltersOperator$.value,a,l=!1,c=new Set;i===qc.AND?a=e.slice():a=[];let d=m=>{i===qc.AND?a=a.filter(u=>m.some(_=>_.annotationId===u.annotationId)):m.forEach(u=>c.add(u.annotationId)),l=!0};if(t.people?.length){let m=[];t.people.forEach(u=>{let _=u.userId||u.email;_&&(m=[...m,...this.filterAnnotationsByPeople({id:_,name:u.name},e)])}),d(m)}if(t.assigned?.length){let m=[];t.assigned.forEach(u=>{let _=u.userId||u.email;_&&(m=[...m,...this.filterAnnotationsByAssigned({id:_,name:u.name},e)])}),d(m)}if(t.tagged?.length){let m=[];t.tagged.forEach(u=>{let _=u.userId||u.email;_&&(m=[...m,...this.filterAnnotationsByTagged({id:_,name:u.name},e)])}),d(m)}if(t.involved?.length){let m=[];t.involved.forEach(u=>{let _=u.userId||u.email;_&&(m=[...m,...this.filterAnnotationsByInvolved({id:_,name:u.name},e)])}),d(m)}if(t.priority?.length){let m=[];t.priority.forEach(u=>m=[...m,...this.filterAnnotationsByPriority({id:u},e)]),d(m)}if(t.status?.length){let m=[];t.status.forEach(u=>m=[...m,...this.filterAnnotationsByStatus({id:u},e)]),d(m)}if(t.category?.length){let m=[];t.category.forEach(u=>m=[...m,...this.filterAnnotationsByCommentCategory({id:u},e)]),d(m)}if(t.version?.length){let m=[];t.version.forEach(u=>m=[...m,...this.filterAnnotationsByVersion(u,e)]),d(m)}if(t.document?.length){let m=[];t.document.forEach(u=>m=[...m,...this.filterAnnotationsByDocument(u,e)]),d(m)}if(t.location?.length){let m=[];t.location.forEach(u=>{u.id&&(m=[...m,...e.filter(_=>_.location?.id===u.id||_.documentParams?.id===u.id)])}),d(m)}if(t.accessModes?.length){let m=[];t.accessModes.forEach(u=>{u===Ca.PRIVATE?m=[...m,...e.filter(_=>El(_))]:u===Ca.PUBLIC&&(m=[...m,...e.filter(_=>!El(_))])}),d(m)}return this.getCustomContextFilterEntries(t).forEach(({key:m,values:u})=>{let _=this.matchAnnotationsByContext(e,m,u);d(_)}),i!==qc.AND&&(l?a=e.filter(m=>c.has(m.annotationId)):a=e),a}catch(i){return this.loggingService.catch("Error in CommentService applyDirectFilters: ",i),e}}getCustomContextFilterEntries(e){try{if(!e)return[];let t=new Set(["people","assigned","tagged","involved","priority","status","category","version","document","location","accessModes"]),i=[];return Object.keys(e).forEach(a=>{if(t.has(a))return;let l=e[a];!Array.isArray(l)||!l.length||i.push({key:a,values:l})}),i}catch(t){return this.loggingService.catch("Error in CommentService getCustomContextFilterEntries: ",t),[]}}matchAnnotationsByContext(e,t,i){try{return e.filter(a=>{let l=a.context?.[t];return l==null?!1:i.some(c=>{let d=typeof c=="string"?c:c?.id;return l===d||l?.toString()===d})})}catch(a){return this.loggingService.catch("Error in CommentService matchAnnotationsByContext: ",a),[]}}filterAnnotationsByPeople(e,t){try{return e.id?t.filter(i=>i?.from?.userId===e.id||i?.from?.email===e.id):t}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByPeople: ",i),[]}}filterAnnotationsByTagged(e,t){try{return t.filter(i=>i?.comments?.some(a=>a.taggedUserContacts?.some(l=>l?.contact?.userId===e.id)))}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByTagged: ",i),[]}}filterAnnotationsByAssigned(e,t){try{return t.filter(i=>i?.assignedTo?.userId===e.id)}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByAssigned: ",i),[]}}filterAnnotationsByInvolved(e,t){try{return t.filter(i=>{let a=i?.from?.userId===e.id||i?.from?.email===e.id,l=i?.assignedTo?.userId===e.id,c=i?.comments?.some(d=>d.taggedUserContacts?.some(m=>m?.contact?.userId===e.id));return a||l||c})}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByInvolved: ",i),[]}}filterAnnotationsByPriority(e,t){try{return e.id==="unset"?t.filter(i=>!i?.priority):t.filter(i=>i?.priority?.id===e.id)}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByPriority: ",i),[]}}filterAnnotationsByStatus(e,t){try{return t.filter(i=>i?.status?.id===e.id)}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByStatus: ",i),[]}}filterAnnotationsByCommentCategory(e,t){try{return e.id==="other"?t.filter(i=>!i?.commentCategories?.length||i?.commentCategories?.some(a=>a.id===e.id)):t.filter(i=>(i?.commentCategories||[]).some(a=>a.id===e.id))}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByCommentCategory: ",i),[]}}filterAnnotationsByVersion(e,t){try{return e.id==="unset"?t.filter(i=>!i?.location?.version):t.filter(i=>i?.location?.version?.id===e.id)}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByVersion: ",i),[]}}filterAnnotationsByDocument(e,t){try{return e?.id&&e.id!=="other"?t.filter(i=>i?.metadata?.clientDocumentId?.toString()===e.id):t.filter(i=>!i?.metadata?.clientDocumentId)}catch(i){return this.loggingService.catch("Error in CommentService filterAnnotationsByDocument: ",i),[]}}setSidebarButtonCountType(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{sidebarButtonCountType:e}}),this.sidebarButtonCountType$.value===e)return;this.sidebarButtonCountType$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setSidebarButtonCountType: ",t)}}getSidebarButtonCountType$(){return this.sidebarButtonCountType$.asObservable()}getSidebarButtonCountType(){return this.sidebarButtonCountType$.value}enableFilterGhostCommentsInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{filterGhostCommentsInSidebar:!0}}),this.filterGhostCommentsInSidebar$.value===!0)return;this.filterGhostCommentsInSidebar$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFilterGhostCommentsInSidebar: ",e)}}disableFilterGhostCommentsInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{filterGhostCommentsInSidebar:!1}}),this.filterGhostCommentsInSidebar$.value===!1)return;this.filterGhostCommentsInSidebar$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFilterGhostCommentsInSidebar: ",e)}}getFilterGhostCommentsInSidebar$(){return this.filterGhostCommentsInSidebar$.asObservable()}getFilterGhostCommentsInSidebar(){return this.filterGhostCommentsInSidebar$.value}filterCommentsUsingSidebarSettings(e){try{let t=Array.isArray(e),i;return t?i=e||[]:e?i=[e]:i=[],this.getFilterCommentsOnDom$().pipe(Se(a=>a?i.length===0?ce(e):gn([this.effectiveSidebarFilters$,this.customSidebarDataAnnotationIds$]).pipe(ue(([l,c])=>{let d=i,m=!1;if(this.hasActiveFilters(l)){let u=this.applyDirectFilters(i,l),_=new Set(u.map(I=>I.annotationId));d=d.filter(I=>I?.isDraft||_.has(I.annotationId)),m=!0}return c&&(d=d.filter(u=>u?.isDraft||u?.annotationId&&c.has(u.annotationId)),m=!0),m?t?d:d.length>0?d[0]:null:e})):ce(e)))}catch{return ce(e)}}enableFocusedThreadMode(){try{if(this.focusedThreadMode$.value===!0)return;this.focusedThreadMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFocusedThreadMode: ",e)}}disableFocusedThreadMode(){try{if(this.focusedThreadMode$.value===!1)return;this.focusedThreadMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFocusedThreadMode: ",e)}}getFocusedThreadMode$(){return this.focusedThreadMode$.asObservable()}enableOpenAnnotationInFocusMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{openAnnotationInFocusMode:!0}}),this.openAnnotationInFocusMode$.value===!0)return;this.openAnnotationInFocusMode$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableOpenAnnotationInFocusMode: ",e)}}disableOpenAnnotationInFocusMode(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{openAnnotationInFocusMode:!1}}),this.openAnnotationInFocusMode$.value===!1)return;this.openAnnotationInFocusMode$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableOpenAnnotationInFocusMode: ",e)}}getOpenAnnotationInFocusMode$(){return this.openAnnotationInFocusMode$.asObservable()}getOpenAnnotationInFocusMode(){return this.openAnnotationInFocusMode$.value}enableReadOnly(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{readOnly:!0}}),this.readOnly$.value===!0)return;this.readOnly$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReadOnly: ",e)}}disableReadOnly(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{readOnly:!1}}),this.readOnly$.value===!1)return;this.readOnly$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReadOnly: ",e)}}getReadOnly$(){return this.readOnly$.asObservable()}getReadOnly(){return this.readOnly$.value}shouldEnableReadOnly(){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentService FUNCTION: shouldEnableReadOnly","color: green;");let e=this.authService.getUser(),t=this.docService.getDocumentPaths()?.folderId,i=this.docService.getDocumentIds().map(a=>a.clientDocumentId);if(e){let a=this.userPermissionService.getCurrentUserPermissions();a?.[e.userId]?t&&a[e.userId]?.folders?.[t]?.accessRole==="viewer"?this.enableReadOnly():i.forEach(l=>{a[e.userId]?.documents?.[l]?.accessRole==="viewer"&&this.enableReadOnly()}):this.getReadOnly()||this.disableReadOnly()}}catch(e){this.loggingService.catch("Error in CommentService shouldEnableReadOnly:",e)}})}sanitizeCommentAnnotation(e){try{return e?.comments?.length&&e.comments.forEach(t=>{t?.commentHtml&&(t.commentHtml=this.domService.sanitizeHtml(t.commentHtml))}),e}catch(t){return this.loggingService.catch("Error in CommentService sanitizeCommentAnnotation: ",t),e}}enableCustomAutocompleteSearch(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{customAutocompleteSearch:!0}}),this.customAutocompleteSearch$.value===!0)return;this.customAutocompleteSearch$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableCustomAutocompleteSearch: ",e)}}disableCustomAutocompleteSearch(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{customAutocompleteSearch:!1}}),this.customAutocompleteSearch$.value===!1)return;this.customAutocompleteSearch$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableCustomAutocompleteSearch: ",e)}}getCustomAutocompleteSearch$(){return this.customAutocompleteSearch$.asObservable()}getCustomAutocompleteSearch(){return this.customAutocompleteSearch$.value}enableDeleteThreadWithFirstComment(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deleteThreadWithFirstComment:!0}}),this.deleteThreadWithFirstComment$.value===!0)return;this.deleteThreadWithFirstComment$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableDeleteThreadWithFirstComment: ",e)}}disableDeleteThreadWithFirstComment(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{deleteThreadWithFirstComment:!1}}),this.deleteThreadWithFirstComment$.value===!1)return;this.deleteThreadWithFirstComment$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableDeleteThreadWithFirstComment: ",e)}}getDeleteThreadWithFirstComment$(){return this.deleteThreadWithFirstComment$.asObservable()}enableExpandMentionGroups(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{expandMentionGroups:!0}}),this.expandMentionGroups$.value===!0)return;this.expandMentionGroups$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableExpandMentionGroups: ",e)}}disableExpandMentionGroups(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{expandMentionGroups:!1}}),this.expandMentionGroups$.value===!1)return;this.expandMentionGroups$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableExpandMentionGroups: ",e)}}getExpandMentionGroups$(){return this.expandMentionGroups$.asObservable()}getExpandMentionGroups(){return this.expandMentionGroups$.value}enableShowMentionGroupsFirst(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{showMentionGroupsFirst:!0}}),this.showMentionGroupsFirst$.value===!0)return;this.showMentionGroupsFirst$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShowMentionGroupsFirst: ",e)}}disableShowMentionGroupsFirst(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{showMentionGroupsFirst:!1}}),this.showMentionGroupsFirst$.value===!1)return;this.showMentionGroupsFirst$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShowMentionGroupsFirst: ",e)}}getShowMentionGroupsFirst$(){return this.showMentionGroupsFirst$.asObservable()}getShowMentionGroupsFirst(){return this.showMentionGroupsFirst$.value}enableShowMentionGroupsOnly(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{showMentionGroupsOnly:!0}}),this.showMentionGroupsOnly$.value===!0)return;this.showMentionGroupsOnly$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableShowMentionGroupsOnly: ",e)}}disableShowMentionGroupsOnly(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{showMentionGroupsOnly:!1}}),this.showMentionGroupsOnly$.value===!1)return;this.showMentionGroupsOnly$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableShowMentionGroupsOnly: ",e)}}getShowMentionGroupsOnly$(){return this.showMentionGroupsOnly$.asObservable()}getShowMentionGroupsOnly(){return this.showMentionGroupsOnly$.value}setAnalyticsFeatureConfig({config:e,feature:t}){try{this.analyticsService.setFeatureConfig({feature:t||je.COMMENT,config:e})}catch(i){this.loggingService.catch("Error in CommentService setAnalyticsFeatureConfig: ",i)}}generateContextId(e){try{let t;if(e&&typeof e=="object"){let i=JSON.parse(JSON.stringify(e));if(delete i.accessFields,delete i.access,Object.keys(i).length){let a=Es(i),l=JSON.stringify(a);t=It(l)}}return t}catch{return}}setMaxReplyAvatars(e){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{maxReplyAvatars:e}}),this.maxReplyAvatars$.value===e)return;this.maxReplyAvatars$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setMaxReplyAvatars: ",t)}}getMaxReplyAvatars$(){return this.maxReplyAvatars$.asObservable()}getMaxReplyAvatars(){return this.maxReplyAvatars$.value}enableReplyAvatars(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{replyAvatars:!0}}),this.replyAvatars$.value===!0)return;this.replyAvatars$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableReplyAvatars: ",e)}}disableReplyAvatars(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{replyAvatars:!1}}),this.replyAvatars$.value===!1)return;this.replyAvatars$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableReplyAvatars: ",e)}}getReplyAvatars$(){return this.replyAvatars$.asObservable()}getReplyAvatars(){return this.replyAvatars$.value}setCommentplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{commentplaceholder:e}}),this.commentplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setCommentplaceholder: ",t)}}getCommentplaceholder$(){return this.commentplaceholder$.asObservable()}getCommentplaceholder(){return this.commentplaceholder$.value}setReplyplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{replyplaceholder:e}}),this.replyplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setReplyplaceholder: ",t)}}getReplyplaceholder$(){return this.replyplaceholder$.asObservable()}getReplyplaceholder(){return this.replyplaceholder$.value}setEditplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{editplaceholder:e}}),this.editplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEditplaceholder: ",t)}}getEditplaceholder$(){return this.editplaceholder$.asObservable()}getEditplaceholder(){return this.editplaceholder$.value}setEditcommentplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{editcommentplaceholder:e}}),this.editcommentplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEditcommentplaceholder: ",t)}}getEditcommentplaceholder$(){return this.editcommentplaceholder$.asObservable()}getEditcommentplaceholder(){return this.editcommentplaceholder$.value}setEditreplyplaceholder(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{editreplyplaceholder:e}}),this.editreplyplaceholder$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setEditreplyplaceholder: ",t)}}getEditreplyplaceholder$(){return this.editreplyplaceholder$.asObservable()}getEditreplyplaceholder(){return this.editreplyplaceholder$.value}enableScreenshot(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{screenshotEnabled:!0}}),this.screenshotEnabled$.value===!0)return;this.screenshotEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableScreenshot: ",e)}}disableScreenshot(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{screenshotEnabled:!1}}),this.screenshotEnabled$.value===!1)return;this.screenshotEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableScreenshot: ",e)}}getScreenshotEnabled$(){return this.screenshotEnabled$.asObservable()}getScreenshotEnabled(){return this.screenshotEnabled$.value}getAnnotationNumber(e){try{let t=this.commentAnnotationById$.value||{},i=-1,a=Object.values(t).filter(l=>{let c=l.metadata?.documentId===e.metadata?.documentId;return c&&l.annotationNumber&&(i=Math.max(i,l.annotationNumber)),c});return i===-1?a.length+1:i+1}catch(t){return this.loggingService.catch("Error in CommentService getAnnotationNumber: ",t),null}}enableFullScreenInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{fullScreen:!0}}),this.fullScreenInSidebar$.value===!0)return;this.fullScreenInSidebar$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableFullScreenInSidebar: ",e)}}disableFullScreenInSidebar(){try{if(this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{fullScreen:!1}}),this.fullScreenInSidebar$.value===!1)return;this.fullScreenInSidebar$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableFullScreenInSidebar: ",e)}}getFullScreenInSidebar$(){return this.fullScreenInSidebar$.asObservable()}getFullScreenInSidebar(){return this.fullScreenInSidebar$.value}setComposerFileAttachments(e){try{this.composerFileAttachments$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setComposerFileAttachments: ",t)}}getComposerFileAttachments$(){return this.composerFileAttachments$.asObservable()}getComposerFileAttachments(){return this.composerFileAttachments$.value}clearComposerFileAttachments(){try{this.composerFileAttachments$.next(null)}catch(e){this.loggingService.catch("Error in CommentService clearComposerFileAttachments: ",e)}}enableAttachmentNameInMessage(){try{if(this.attachmentNameInMessage$.value===!0)return;this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{attachmentNameInMessage:!0}}),this.attachmentNameInMessage$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableAttachmentNameInMessage: ",e)}}disableAttachmentNameInMessage(){try{if(this.attachmentNameInMessage$.value===!1)return;this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{attachmentNameInMessage:!1}}),this.attachmentNameInMessage$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableAttachmentNameInMessage: ",e)}}getAttachmentNameInMessage$(){return this.attachmentNameInMessage$.asObservable()}getAttachmentNameInMessage(){return this.attachmentNameInMessage$.value}setAllowedFileTypes(e){try{this.allowedFileTypes$.next(e)}catch(t){this.loggingService.catch("Error in CommentService setAllowedFileTypes: ",t)}}getAllowedFileTypes$(){return this.allowedFileTypes$.asObservable()}getAllowedFileTypes(){return this.allowedFileTypes$.value}enableForceCloseAllOnEsc(){try{if(this.forceCloseAllOnEsc$.value===!0)return;this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{forceCloseAllOnEsc:!0}}),this.forceCloseAllOnEsc$.next(!0)}catch(e){this.loggingService.catch("Error in CommentService enableForceCloseAllOnEsc: ",e)}}disableForceCloseAllOnEsc(){try{if(this.forceCloseAllOnEsc$.value===!1)return;this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{forceCloseAllOnEsc:!1}}),this.forceCloseAllOnEsc$.next(!1)}catch(e){this.loggingService.catch("Error in CommentService disableForceCloseAllOnEsc: ",e)}}getForceCloseAllOnEsc$(){return this.forceCloseAllOnEsc$.asObservable()}getForceCloseAllOnEsc(){return this.forceCloseAllOnEsc$.value}markAsRead(e){return X(this,null,function*(){try{let t;e&&(t=this.getAnnotationById(e)),t&&(yield this.viewsService.setCommentAnnotationAsRead(t))}catch(t){this.loggingService.catch("Error in ViewsService markAsRead:",t)}})}markAsUnread(e){return X(this,null,function*(){try{let t;e&&(t=this.getAnnotationById(e)),t&&(yield this.viewsService.setCommentAnnotationAsUnread(t))}catch(t){this.loggingService.catch("Error in ViewsService markAsUnread:",t)}})}setAutoCompleteScrollConfig(e){try{this.analyticsService.setFeatureConfig({feature:je.COMMENT,config:{autoCompleteScrollConfig:e}});let t=this.autoCompleteScrollConfig$.value,i={itemSize:e.itemSize??t.itemSize,minBufferPx:e.minBufferPx??t.minBufferPx,maxBufferPx:e.maxBufferPx??t.maxBufferPx,templateCacheSize:e.templateCacheSize??t.templateCacheSize};this.autoCompleteScrollConfig$.next(i)}catch(t){this.loggingService.catch("Error in CommentService setAutoCompleteScrollConfig: ",t)}}getAutoCompleteScrollConfig(){return this.autoCompleteScrollConfig$.value}getAutoCompleteScrollConfig$(){return this.autoCompleteScrollConfig$.asObservable()}submitComment(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: submitComment","color: green;"),this.submitComment$.next(e.targetComposerElementId)}catch(t){this.loggingService.catch("Error in CommentService submitComment: ",t)}}onSubmitComment$(){return this.submitComment$.asObservable()}clearComposer(e){try{this.clearComposer$.next(e.targetComposerElementId),this.composerDataMap.delete(e.targetComposerElementId)}catch(t){this.loggingService.catch("Error in CommentService clearComposer: ",t)}}onClearComposer$(){return this.clearComposer$.asObservable()}emitComposerTextChange(e,t,i){try{this.commentActionsService?.onComposerTextChange({text:e,annotation:t,targetComposerElementId:i})}catch(a){this.loggingService.catch("Error in CommentService emitComposerTextChange: ",a)}}setComposerData(e,t){try{this.composerDataMap.set(e,t)}catch(i){this.loggingService.catch("Error in CommentService setComposerData: ",i)}}clearComposerData(e){try{this.composerDataMap.delete(e)}catch(t){this.loggingService.catch("Error in CommentService clearComposerData: ",t)}}getComposerData(e){try{return this.composerDataMap.get(e.targetComposerElementId)||null}catch(t){return this.loggingService.catch("Error in CommentService getComposerData: ",t),null}}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(uv),K(yn),K(Ft),K(st),K($n),K(qe),K(Ve),K(eo),K(fm),K(vn),K(Pp),K(Do),K(Lo),K(Vn),K(k),K(mn),K(po),K(zi),K(jbe),K(Un),K(Ol),K(CS),K(ts),K(vd),K(es),K(Ia),K(ho))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Hbe=(()=>{let o=class o{constructor(e,t,i){this.commentService=e,this.reactionService=t,this.loggingService=i}getActivityForClient(e){try{let t=JSON.parse(JSON.stringify(e));return t.metadata&&(t.metadata=oi(t.metadata)),t.actionUser&&(t.actionUser=Vo(t.actionUser)),t.entityData&&(t.entityData=this.transformEntityData(t.featureType,t.entityData),t.entityData?.metadata&&(t.entityData.metadata=oi(t.entityData.metadata))),t.entityTargetData&&(t.entityTargetData=this.transformEntityTargetData(t.featureType,t.entityTargetData)),t.changes&&(t.changes=this.transformChanges(t.changes)),t.displayMessageTemplateData&&(t.displayMessageTemplateData=this.transformTemplateData(t.displayMessageTemplateData)),t}catch(t){return this.loggingService.catch("Error in ActivityActionsService getActivityForClient:",t),e}}transformEntityData(e,t){try{switch(e){case"comment":return this.commentService.getCommentAnnotationForClient(t);case"reaction":return this.reactionService.getReactionAnnotationForClient(t);case"recorder":return bhe(t);default:return t}}catch(i){return this.loggingService.catch("Error in ActivityActionsService transformEntityData:",i),t}}transformEntityTargetData(e,t){try{return t}catch(i){return this.loggingService.catch("Error in ActivityActionsService transformEntityTargetData:",i),t}}transformChanges(e){try{let t={};for(let i of Object.keys(e)){let a=e[i];if(!a){t[i]=a;continue}t[i]=h({},a),this.isUserObject(a.from)&&(t[i].from=Vo(a.from)),this.isUserObject(a.to)&&(t[i].to=Vo(a.to))}return t}catch(t){return this.loggingService.catch("Error in ActivityActionsService transformChanges:",t),e}}transformTemplateData(e){try{let t={};for(let i of Object.keys(e)){let a=e[i];this.isUserObject(a)?t[i]=Vo(a):t[i]=a}return t}catch(t){return this.loggingService.catch("Error in ActivityActionsService transformTemplateData:",t),e}}isUserObject(e){return!!e&&typeof e=="object"&&"userId"in e}};o.\u0275fac=function(t){return new(t||o)(K(Re),K(zi),K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Lg=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A,M,V){this.activityResolverService=e,this.activityUtilsService=t,this.authService=i,this.commentAnnotationsResolverService=a,this.reactionAnnotationsResolverService=l,this.recorderAnnotationsResolverService=c,this.commonDbService=d,this.commonDbUtilsService=m,this.configService=u,this.docService=_,this.functions=I,this.loggingService=A,this.usersService=M,this.userPermissionService=V,this.isActivityFeatureEnabled$=new _e(!1),this.isActivityFeatureImmutable$=new _e(!1),this.allActivities$=new _e(null),this.subscriptions=new Map,this.fetchedEntityIds=new Set;try{this.commonDbService.setActivityService(this),this.authService.setActivityService(this),this.initializeService()}catch(q){this.loggingService.catch("Error in ActivityService constructor:",q)}}setActivityFeatureConfig(e){try{this.isActivityFeatureEnabled$.next(e?.isEnabled??!1),this.isActivityFeatureImmutable$.next(e?.immutable??!1)}catch(t){this.loggingService.catch("Error in setActivityFeatureConfig: ",t)}}getIsActivityFeatureEnabled(){return this.isActivityFeatureEnabled$.value}getIsActivityFeatureImmutable(){return this.isActivityFeatureImmutable$.value}getIsActivityFeatureEnabled$(){return this.isActivityFeatureEnabled$.asObservable().pipe(_t(Kt))}initializeService(){try{this.authSubscription=this.getIsActivityFeatureEnabled$().pipe(_t(),Ge(e=>e===!0)).subscribe(()=>{this.subscriptions.size>0&&!this.triggerListenerSubscription&&this.rebuildTriggerListener()},e=>{this.loggingService.catch("Error in ActivityService feature flag subscription:",e)})}catch(e){this.loggingService.catch("Error in ActivityService initializeService:",e)}}subscribe(e){let t=lt(),i=new _e(null);try{let a={id:t,config:e??{},activities$:i};this.subscriptions.set(t,a),this.getIsActivityFeatureEnabled()&&this.rebuildTriggerListener(),this.allActivities$.getValue()!==null&&this.distributeActivitiesToSubscription(a)}catch(a){this.loggingService.catch("Error in ActivityService subscribe:",a)}return{getActivities$:()=>i.asObservable(),unsubscribe:()=>{try{this.subscriptions.delete(t),i.complete(),this.getIsActivityFeatureEnabled()&&this.rebuildTriggerListener()}catch(a){this.loggingService.catch("Error in ActivityService unsubscribe:",a)}}}}getActivities$(){return this.allActivities$.asObservable().pipe(_t(Kt))}getActivitiesForDocument$(e){return this.allActivities$.pipe(ue(t=>t===null?null:t.filter(i=>i.metadata?.documentId===e)),_t(Kt))}getActivitiesForEntity$(e){return this.allActivities$.pipe(ue(t=>t===null?null:t.filter(i=>i.targetEntityId===e)),_t(Kt))}fetchActivitiesForEntity(e){return X(this,null,function*(){try{if(!this.getIsActivityFeatureEnabled())return;let{targetEntityId:t,documentId:i,organizationId:a}=e;if(!t||!i||this.fetchedEntityIds.has(t))return;this.fetchedEntityIds.add(t);let l=this.authService.getUser();if(!l?.userId){this.fetchedEntityIds.delete(t);return}let c=a||this.docService.getOrganizationConfig()?.clientOrganizationId;if(!c){this.fetchedEntityIds.delete(t);return}let d=Yr(this.functions,Zr({url:On.cloudFunction.sdkProxy,apiProxyDomain:this.configService.getApiProxyDomain()})),m=yield wl({methodName:"getActivitiesForEntity",data:{type:"getActivitiesForEntity",organizationId:c,documentId:i,targetEntityId:String(t),isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable()},getSdkProxy:d,userId:l.userId});if(m?.activities?.length){let u=m.activities;this.appendActivities(u),this.rehydrateActivities(u)}}catch(t){this.fetchedEntityIds.delete(e.targetEntityId),this.loggingService.catch("Error in ActivityService fetchActivitiesForEntity:",t)}})}createActivity(e){return X(this,null,function*(){try{if(!this.getIsActivityFeatureEnabled())return;let t=this.authService.getUser();if(!t?.userId){this.loggingService.warn("ActivityService createActivity: No user available");return}let i=this.docService.getBaseMetadata("activity");if(!i?.apiKey||!i?.organizationId){this.loggingService.warn("ActivityService createActivity: Missing metadata or organizationId");return}let a=this.getIsActivityFeatureImmutable(),l=lt(),c={id:l,featureType:e.featureType,actionType:e.actionType,eventType:e.eventType,actionUser:t,timestamp:this.commonDbService.getServerTimestamp(),metadata:i,targetEntityId:e.targetEntityId!=null?String(e.targetEntityId):void 0,targetSubEntityId:e.targetSubEntityId!=null?String(e.targetSubEntityId):void 0,changes:e.changes,entityData:e.entityData,entityTargetData:e.entityTargetData,actionIcon:e.actionIcon,displayMessageTemplate:e.displayMessageTemplate,displayMessageTemplateData:e.displayMessageTemplateData,immutable:a};this.appendActivities([c]);let{strippedActivity:d,activityResolverData:m}=yield this.activityUtilsService.stripActivityPII(c);m&&this.activityResolverService.activityDataProviderAvailable()&&this.activityResolverService.saveActivity({activity:{[m.id]:m},event:ko.ACTIVITY_SAVE});try{yield this.sendActivityToBackend(d)}catch{let u=this.allActivities$.getValue()??[];this.allActivities$.next(u.filter(_=>_.id!==l)),this.subscriptions.forEach(_=>this.distributeActivitiesToSubscription(_))}}catch(t){this.loggingService.catch("Error in ActivityService createActivity:",t)}})}rebuildTriggerListener(){try{if(this.triggerListenerSubscription&&(this.triggerListenerSubscription.unsubscribe(),this.triggerListenerSubscription=void 0),this.subscriptions.size===0)return;let e=this.getCombinedSubscriptionScope();this.triggerListenerSubscription=this.getLastActivityTimestamps$(e).pipe(_o(null),Fr(),ue(([t,i])=>{if(!i)return;if(i.length===0){this.allActivities$.getValue()===null&&!this.emptyStateTimeoutId&&(this.emptyStateTimeoutId=setTimeout(()=>{this.emptyStateTimeoutId=void 0,this.allActivities$.getValue()===null&&(this.allActivities$.next([]),this.subscriptions.forEach(d=>this.distributeActivitiesToSubscription(d)))},5e3));return}this.emptyStateTimeoutId&&(clearTimeout(this.emptyStateTimeoutId),this.emptyStateTimeoutId=void 0);let a=new Map;t?.forEach(d=>a.set(d.documentId,d.timestamp));let l=[],c=[];if(i.forEach(d=>{let m=a.get(d.documentId);m===void 0?l.push(d.documentId):m!==d.timestamp&&c.push({documentId:d.documentId,previousTimestamp:m})}),l.length>0){let d=this.getStartAtTimestamp(e.maxDays);this.fetchActivitiesForDocuments(l,e.organizationId,void 0,d)}c.length>0&&this.fetchActivitiesForDocuments(c.map(d=>d.documentId),e.organizationId,c)})).subscribe(()=>{},t=>this.loggingService.catch("Error in ActivityService trigger listener:",t))}catch(e){this.loggingService.catch("Error in ActivityService rebuildTriggerListener:",e)}}getLastActivityTimestamps$(e){try{return this.authService.getUser$().pipe(Ge(t=>!!t),Se(t=>this.docService.getOrganizationConfig$().pipe(Ge(i=>!!i),ue(i=>{let l=(e.organizationId?ba(e.organizationId):void 0)||i?.organizationId||t?.organizationId;return{user:t,organizationId:l}}))),Se(({user:t,organizationId:i})=>{if(!t||!i)return ce(null);if(e.type===Fg.CURRENT_DOCUMENT)return this.docService.getDocumentPaths$().pipe(Se(l=>{let c=l?.clientDocumentId;if(!c&&!e.documentIds?.length)return this.resetCurrentDocumentSubscriptions(),ce(null);let d=new Set(e.documentIds??[]);c&&d.add(c);let m=Array.from(d).slice(0,30).map(u=>mi(u));return m.length===1?this.buildTriggerQuery(i,[ft("metadata.documentId","==",m[0])],e.maxDays):this.buildTriggerQuery(i,[ft("metadata.documentId","in",m)],e.maxDays)}));let a=[];if(e.type===Fg.DOCUMENTS&&e.documentIds?.length){e.documentIds.length>30&&this.loggingService.catch("Error in ActivityService getLastActivityTimestamps$: Subscription includes more than 30 document IDs. Only the first 30 will be monitored.",new Error("Subscription includes more than 30 document IDs. Only the first 30 will be monitored."),void 0,!0);let l=e.documentIds.slice(0,30).map(c=>mi(c));a.push(ft("metadata.documentId","in",l))}return this.buildTriggerQuery(i,a,e.maxDays)}))}catch(t){return this.loggingService.catch("Error in ActivityService getLastActivityTimestamps$:",t),ce(null)}}buildTriggerQuery(e,t,i=XL){try{let a=this.getStartAtTimestamp(i);t.push(ft("timestamp",">=",a));let c=[t.length>1?yr(...t):t[0],uo("timestamp","desc")];return this.commonDbService.dbListener({feature:"allLastActivityTimestamp",properties:{organizationId:e,isCollection:!0,useQuery:!0,firestoreQuery:c}}).pipe(ue(d=>d?.data),ue(d=>{if(!d)return[];let m=[];return Object.keys(d).forEach(u=>{let _=this.commonDbService.shouldUseFirestore()?d[u]?.timestamp??0:d[u];m.push({documentId:u,timestamp:_})}),m}))}catch(a){return this.loggingService.catch("Error in ActivityService buildTriggerQuery:",a),ce([])}}fetchActivitiesForDocuments(e,t,i,a){return X(this,null,function*(){try{if(!e.length)return;let l=this.authService.getUser();if(!l?.userId)return;let c=t||this.docService.getOrganizationConfig()?.clientOrganizationId;if(!c)return;let d=Yr(this.functions,Zr({url:On.cloudFunction.sdkProxy,apiProxyDomain:this.configService.getApiProxyDomain()})),m={type:"getActivitiesForDocuments",organizationId:c,documentIds:e,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable()};a&&(m.startAtTimestamp=a),i?.length&&(m.documentTimestamps=i.map(_=>({documentId:_.documentId,timestamp:_.previousTimestamp})));let u=yield wl({methodName:"getActivitiesForDocuments",data:m,getSdkProxy:d,userId:l.userId});if(u?.activities?.length){let _=u.activities;this.appendActivities(_),this.rehydrateActivities(_)}else this.allActivities$.getValue()===null&&(this.allActivities$.next([]),this.subscriptions.forEach(_=>this.distributeActivitiesToSubscription(_)))}catch(l){this.loggingService.catch("Error in ActivityService fetchActivitiesForDocuments:",l)}})}sendActivityToBackend(e){return X(this,null,function*(){try{let t=this.authService.getUser();if(!t?.userId)return;let i=Yr(this.functions,Zr({url:On.cloudFunction.sdkProxy,apiProxyDomain:this.configService.getApiProxyDomain()}));yield wl({methodName:"createActivity",data:{type:"createActivity",activityData:e},getSdkProxy:i,userId:t.userId})}catch(t){throw this.loggingService.catch("Error in ActivityService sendActivityToBackend:",t),t}})}rehydrateActivities(e){try{let t=this.usersService.userDataProviderAvailable(),i=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),a=this.reactionAnnotationsResolverService.reactionAnnotationDataProviderAvailable(),l=this.recorderAnnotationsResolverService.recorderAnnotationDataProviderAvailable(),c=this.activityResolverService.activityDataProviderAvailable(),d=Promise.resolve();t&&(d=d.then(()=>this.commonDbUtilsService.formatResponse({feature:"allActivities",data:e,shouldAwait:!0,forceResolve:!0})).then(()=>{this.resolveAndUpdateActivities(e,"user")})),i&&(d=d.then(()=>this.commonDbUtilsService.formatResponse({feature:"allActivities",data:e,shouldCommentAnnotationsResolverAwait:!0})).then(()=>{this.resolveAndUpdateActivities(e,"comment")})),a&&(d=d.then(()=>this.commonDbUtilsService.formatResponse({feature:"allActivities",data:e,shouldReactionResolverAwait:!0})).then(()=>{this.resolveAndUpdateActivities(e,"reaction")})),l&&(d=d.then(()=>this.commonDbUtilsService.formatResponse({feature:"allActivities",data:e,shouldRecorderResolverAwait:!0})).then(()=>{this.resolveAndUpdateActivities(e,"recorder")})),c&&(d=d.then(()=>this.commonDbUtilsService.formatResponse({feature:"allActivities",data:e,shouldActivityResolverAwait:!0})).then(()=>{this.resolveAndUpdateActivities(e,"activity")}))}catch(t){this.loggingService.catch("Error in ActivityService rehydrateActivities:",t)}}resolveAndUpdateActivities(e,t){try{let i=this.allActivities$.getValue()??[],a=new Map(i.map(m=>[m.id,m])),l=e.map(m=>a.get(m.id)??m),c=JSON.parse(JSON.stringify(l)),d;switch(t){case"user":d=this.commonDbUtilsService.mergeUsersWithData({feature:"allActivities",data:c});break;case"comment":d=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allActivities",data:c});break;case"reaction":d=this.commonDbUtilsService.mergeReactionAnnotationsWithData({feature:"allActivities",data:c});break;case"recorder":d=this.commonDbUtilsService.mergeRecorderAnnotationsWithData({feature:"allActivities",data:c});break;case"activity":d=this.commonDbUtilsService.mergeActivityResolverWithData({feature:"allActivities",data:c});break}d?.length&&this.appendActivities(d)}catch(i){this.loggingService.catch("Error in ActivityService resolveAndUpdateActivities:",i)}}appendActivities(e){try{let t=this.allActivities$.getValue()??[],i=new Map;e.forEach(m=>{m.id&&i.set(m.id,m)});let a=t.map(m=>i.get(m.id)??m),l=new Set(t.map(m=>m.id)),d=[...e.filter(m=>!l.has(m.id)),...a].sort((m,u)=>(u.timestamp??0)-(m.timestamp??0));if(d.forEach(m=>{m.displayMessage=this.activityUtilsService.getActivityDisplayMessage(m)}),this.activitiesEqual(t,d))return;this.allActivities$.next(d),this.subscriptions.forEach(m=>{this.distributeActivitiesToSubscription(m)})}catch(t){this.loggingService.catch("Error in ActivityService appendActivities:",t)}}distributeActivitiesToSubscription(e){try{let t=this.allActivities$.getValue();if(t===null)return;let i=e.config,a;if(i.currentDocumentOnly){let c=this.docService.getDocumentPaths()?.documentId;a=c?t.filter(d=>d.metadata?.documentId===c):[]}else if(i.documentIds?.length){let c=new Set(i.documentIds.map(d=>mi(d)));a=t.filter(d=>d.metadata?.documentId&&c.has(d.metadata.documentId))}else a=t;if(i.featureTypes?.length){let c=new Set(i.featureTypes);a=a.filter(d=>c.has(d.featureType))}else if(i.excludeFeatureTypes?.length){let c=new Set(i.excludeFeatureTypes);a=a.filter(d=>!c.has(d.featureType))}if(i.actionTypes?.length){let c=new Set(i.actionTypes);a=a.filter(d=>c.has(d.actionType))}else if(i.excludeActionTypes?.length){let c=new Set(i.excludeActionTypes);a=a.filter(d=>!c.has(d.actionType))}if(i.userIds?.length){let c=new Set(i.userIds);a=a.filter(d=>d.actionUser?.userId&&c.has(d.actionUser.userId))}else if(i.excludeUserIds?.length){let c=new Set(i.excludeUserIds);a=a.filter(d=>!d.actionUser?.userId||!c.has(d.actionUser.userId))}let l=e.activities$.getValue();if(l!==null&&this.activitiesEqual(l,a))return;e.activities$.next(a)}catch(t){this.loggingService.catch("Error in ActivityService distributeActivitiesToSubscription:",t)}}resetCurrentDocumentSubscriptions(){try{this.subscriptions.forEach(e=>{e.config.currentDocumentOnly&&e.activities$.getValue()!==null&&e.activities$.next(null)})}catch(e){this.loggingService.catch("Error in ActivityService resetCurrentDocumentSubscriptions:",e)}}activitiesEqual(e,t){try{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i].id!==t[i].id)return!1;return JSON.stringify(e)===JSON.stringify(t)}catch(i){return this.loggingService.catch("Error in ActivityService activitiesEqual:",i),!1}}getCombinedSubscriptionScope(){try{let e=!1,t=!1,i,a=new Set,l=XL;this.subscriptions.forEach(d=>{let m=d.config;m.organizationId&&(i=m.organizationId),m.currentDocumentOnly?t=!0:m.documentIds?.length?m.documentIds.forEach(u=>a.add(u)):e=!0,m.maxDays&&m.maxDays>l&&(l=m.maxDays)});let c={organizationId:i,maxDays:l};return e?h({type:Fg.ORG_WIDE},c):t&&a.size>0?h({type:Fg.CURRENT_DOCUMENT,documentIds:Array.from(a)},c):t?h({type:Fg.CURRENT_DOCUMENT},c):a.size>0?h({type:Fg.DOCUMENTS,documentIds:Array.from(a)},c):h({type:Fg.ORG_WIDE},c)}catch(e){return this.loggingService.catch("Error in ActivityService getCombinedSubscriptionScope:",e),{type:Fg.ORG_WIDE,organizationId:void 0,maxDays:XL}}}getStartAtTimestamp(e){try{let t=new Date,i=e>0?e:XL;return t.setDate(t.getDate()-i),t.getTime()}catch(t){return this.loggingService.catch("Error in ActivityService getStartAtTimestamp:",t),0}}cleanup(){try{this.triggerListenerSubscription?.unsubscribe(),this.triggerListenerSubscription=void 0,this.emptyStateTimeoutId&&(clearTimeout(this.emptyStateTimeoutId),this.emptyStateTimeoutId=void 0),this.subscriptions.forEach(e=>e.activities$.complete()),this.subscriptions.clear(),this.allActivities$.next(null),this.fetchedEntityIds.clear()}catch(e){this.loggingService.catch("Error in ActivityService cleanup:",e)}}destroy(){try{this.cleanup(),this.authSubscription?.unsubscribe()}catch(e){this.loggingService.catch("Error in ActivityService destroy:",e)}}};o.\u0275fac=function(t){return new(t||o)(K(Op),K(uS),K(qe),K(ol),K(Qc),K(il),K(yn),K(vd),K(Ft),K(st),K(Do),K(k),K(An),K(Ia))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})(),Fg=(function(n){return n.ORG_WIDE="orgWide",n.DOCUMENTS="documents",n.CURRENT_DOCUMENT="currentDocument",n})(Fg||{}),XL=30;var Cr=class{constructor(o){this.injector=o,this.hideAnalytics=!1}ha(o){try{this.hideAnalytics=o}catch{}}getService(o){return this.injector.get(o)}trackEvent(o,r={},e=!0){try{this.hideAnalytics||(r||(r={}),r=y(h({},r),{source:"external"}),this.getService(ct).trackAuthenticatedEvent(o,r,e))}catch(t){this.getService(k).catch("Error in _trackEvent: ",t);return}}};var QL=class extends Cr{constructor(o){super(o),this.getService(k).log("%c[WB] Creating CLASS: ActivityElement","color: blue;"),this.getAllActivities=this._getAllActivities,this.createActivity=this._createActivity}_getAllActivities(o){this.getService(k).log("%c[WB] Calling FUNCTION: getAllActivities","color: green;");try{let r=this.getService(Hbe),e=this.getService(Lg).subscribe(o);return new Vt(t=>{let i=e.getActivities$().pipe(ue(a=>a?.map(l=>r.getActivityForClient(l))??null)).subscribe(t);return()=>{i.unsubscribe(),e.unsubscribe()}})}catch(r){return this.getService(k).catch("Error in _getAllActivities: ",r),ce(null)}}_createActivity(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: createActivity","color: green;");try{yield this.getService(Lg).createActivity(o)}catch(r){this.getService(k).catch("Error in _createActivity: ",r)}})}};var eU=class extends Cr{constructor(o){super(o),this.getService(k).log("%c[WB] Creating CLASS: AreaElement","color: blue;"),this.enableArea=this._enableAreaComment,this.disableArea=this._disableAreaComment,this.enableAreaComment=this._enableAreaComment,this.disableAreaComment=this._disableAreaComment}_enableAreaComment(){this.getService(k).log("%c[WB] Calling FUNCTION: enableAreaComment","color: green;");try{this.trackEvent(Y.Events.Area.ENABLE_AREA_COMMENT_TRIGGERED),this.getService(uv).enableArea()}catch(o){this.getService(k).catch("Error in _enableAreaComment: ",o)}}_disableAreaComment(){this.getService(k).log("%c[WB] Calling FUNCTION: disableAreaComment","color: green;");try{this.trackEvent(Y.Events.Area.DISABLE_AREA_COMMENT_TRIGGERED),this.getService(uv).disableArea()}catch(o){this.getService(k).catch("Error in _disableAreaComment: ",o)}}};var km=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A){this.analyticsService=e,this.configService=t,this.docService=i,this.databaseService=a,this.authService=l,this.domService=c,this.afAuth=d,this.iamService=m,this.dialog=u,this.loggingService=_,this.notificationService=I,this.commonDbService=A,this.arrowAnnotations$=new _e({}),this.arrowAnnotationsByDocumentId$=new _e({}),this.documentPaths=null,this.allowedElementIds$=new _e([]),this.addArrowMode$=new _e(!1),this.loggingService.log("%c[WB] Creating CLASS: ArrowService","color: blue;"),this.databaseService.getDb().pipe(Ge(M=>!!M),ut(1)).subscribe(M=>{M&&this.getDocumentPaths()},M=>{this.loggingService.catch("Error in ArrowService getDb subscription: ",M)}),this.domService.onWindowPointerMove$().subscribe(M=>{if(this.addArrowMode$.value){let V=!0,q=this.domService.getBackgroundElement(M.clientX,M.clientY);q&&(this.isElementInsideAllowedElements(q)?QN(M.target)?this.domService.removeClassFromElement(document.body,"show-pin-cursor"):(this.domService.addClassToElement(document.body,"show-pin-cursor"),this.highlightElement&&this.highlightElement!==q&&this.domService.removeHighlightFromElement(this.highlightElement),this.highlightElement=q,this.domService.highlightElement(this.highlightElement,N.CURSOR.ARROW_PIN),V=!1):this.domService.removeClassFromElement(document.body,"show-pin-cursor")),this.highlightElement&&V&&(this.domService.removeHighlightFromElement(this.highlightElement),this.highlightElement=null)}},M=>{this.loggingService.catch("Error in ArrowService onWindowPointerMove$ subscription: ",M)}),this.domService.onWindowKeyupEsc$().subscribe(M=>{this.addArrowMode$.value&&this.disableAddArrowMode()},M=>{this.loggingService.catch("Error in ArrowService onWindowKeyupEsc$ subscription: ",M)}),this.domService.onDocumentClick$().subscribe(M=>{if(M&&this.addArrowMode$.value){if(!QN(M.target)){let V=this.domService.getBackgroundElement(M.clientX,M.clientY);V&&this.isElementInsideAllowedElements(V)&&(M.preventDefault(),M.stopPropagation(),this.addArrow(M))}this.disableAddArrowMode()}},M=>{this.loggingService.catch("Error in ArrowService onDocumentClick$ subscription: ",M)}),this.addArrowMode$.subscribe(M=>{this.highlightElement&&this.domService.removeHighlightFromElement(this.highlightElement),M?this.domService.addClassToElement(document.body,"snippyly-add-arrow-mode"):(this.domService.removeClassFromElement(document.body,"snippyly-add-arrow-mode"),this.domService.removeClassFromElement(document.body,"show-pin-cursor"))},M=>{this.loggingService.catch("Error in ArrowService addArrowMode$ subscription: ",M)}),this.domService.onWindowKeyupBackspace$().subscribe(M=>{this.deleteArrowPinAnnotations("keyupBackspace")},M=>{this.loggingService.catch("Error in ArrowService onWindowKeyupBackspace$ subscription: ",M)}),this.domService.onWindowKeyupDelete$().subscribe(M=>{this.deleteArrowPinAnnotations("keyupDelete")},M=>{this.loggingService.catch("Error in ArrowService onWindowKeyupDelete$ subscription: ",M)})}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$()}setAllowedElementIds(e){this.allowedElementIds$.next(e||[])}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}getAllArrowAnnotations(e,t,i){this.loggingService.log("%c[WB] Calling FUNCTION: getAllArrowAnnotations","color: green;");let a,l;try{if(e&&(l=er(e)),t&&typeof t=="object"){let c=Oi(t);a=er(JSON.stringify(c))}}catch(c){this.loggingService.catch("Error in ArrowService getAllArrowAnnotations: ",c)}return _r(this.afAuth).pipe(Ge(c=>!!c),Se(c=>this.isFeatureAllowed({firebaseUser:c,annotations:[],filteredAnnotations:[]})),Se(c=>c.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(d=>(c.featureAllowed=d,c))):ce(c)),Se(c=>c.featureAllowed?this.authService.isPlanExpired$().pipe(ue(d=>(c.featureAllowed=!d,c))):ce(c)),Se(c=>c.featureAllowed?ce(c).pipe(Se(d=>this.docService.getDocumentPaths$().pipe(ue(m=>(this.documentPaths=m,d.documentPaths=m,d)))),Se(d=>this.getDataFromDocumentId(l).pipe(ue(m=>(d.annotations=m||[],h({},d))))),Se(d=>this.docService.getLocation$().pipe(ue(m=>(d.location=m,d)))),Se(d=>this.docService.getLocations$().pipe(ue(m=>(d.customLocations=m,d)))),ue(d=>{if(d.filteredAnnotations=[],l&&!a)return d.filteredAnnotations=d.annotations?.slice(),d;{let m=[];return a?m.push(a):(m.push(d?.location?.locationId),m.push(...Object.values(d?.customLocations||[]).map(u=>u.locationId))),d.filteredAnnotations=this.filterAnnotationsByLocationIds(d?.annotations,m),d}}),Se(d=>i?ce(d):d?.annotations?.length?this.domService.onWindowResize$().pipe(ue(()=>d)):ce(d)),Se(d=>i?ce(d):d?.annotations?.length?this.domService.onDomChange$("ArrowService getAllArrowAnnotations").pipe(ue(()=>d)):ce(d)),ue(d=>(d?.filteredAnnotations?.forEach(m=>{this.calculateArrowAnnotationPosition(m)}),d)),Se(d=>d?.filteredAnnotations?ce(d?.filteredAnnotations||[]):ce([]))):ce([])),_t(Kt))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})),Se(t=>this.authService.getUser$().pipe(ue(i=>y(h({},t),{user:i})))),Se(t=>Ao(t.config,t.user,je.ARROW)?ce(y(h({},t),{featureAllowed:!0})):(this.loggingService.warn("Arrow feature is not allowed."),ce(y(h({},t),{featureAllowed:!1})))),_t((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ge(t=>!!t),Se(t=>this.configService.getApiKey()&&this.documentPaths?.arrow&&this.documentPaths?this.commonDbService.dbListener({feature:"allArrows",properties:{documentId:e??this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ue(i=>({data:i?.data,operation:i?.operation})),ue(({data:i,operation:a})=>{let l=[];return i&&(l=Object.values(i).filter(c=>typeof c=="object")),{data:l,operation:a}}),Xn(i=>(this.loggingService.catch("Error in ArrowService getDataFromDocumentId: ",i),ce({data:[],operation:null}))),ue(({data:i,operation:a})=>{if(a?.type==="removed"){if(a?.ids?.length){let l=this.arrowAnnotationsByDocumentId$.value;a?.ids?.forEach(c=>{delete l?.[c]}),this.arrowAnnotationsByDocumentId$.next(l)}}else this.setArrowAnnotationsByDocumentId(e||this.documentPaths?.documentId,i);return i})):ce([])))}setArrowAnnotationsByDocumentId(e,t){try{if(e){let i=y(h({},this.arrowAnnotationsByDocumentId$.value),{[e]:t});this.arrowAnnotationsByDocumentId$.next(i)}}catch(i){this.loggingService.catch("Error in ArrowService setArrowAnnotationsByDocumentId:",i)}}filterAnnotationsByLocationIds(e,t){try{return e.filter(i=>t.includes(i.locationId))}catch(i){return this.loggingService.catch("Error in ArrowService filterAnnotationsByLocations:",i),[]}}calculateArrowAnnotationPosition(e){try{if(e.targetElement){let t=this.domService.getXPath(e.targetElement?.xpath);if(t){let i=t.iterateNext();if(i&&Kr(i)){let a=i.getBoundingClientRect();if(a&&a.width&&a.height){let{height:l,width:c}=np(i);e.position={top:l*e.targetElement.topPercentage/100,left:c*e.targetElement.leftPercentage/100}}else e.position=null}else e.position=null}else e.position=null}}catch(t){this.loggingService.catch("Error in ArrowService calculateArrowAnnotationPosition:",t)}}addArrow(e){this.loggingService.log("%c[WB] Calling FUNCTION: addArrow","color: green;");try{let t=this.authService.getUser();if(t)if(t.isReadOnly||t.isAnonymous)this.loggingService.catch("Anonymous/Readonly users cannot add arrows.");else{let i=new DN;i.from=t,i.color=t?.color||N.DEFAULT_ANNOTATION_COLOR,i.lastUpdated=this.timestamp,i.props=new ad;let a=this.domService.getCurrentWindowSizeValue();if(i.props.screenWidth=a.screenWidth,i.props.screenHeight=a.screenHeight,i.props.screenScrollHeight=a.screenScrollHeight,i.props.viewportWidth=window.innerWidth,i.props.viewportHeight=window.innerHeight,i.props.arrowLength=N.VELT_MIN_ARROW_LENGTH,(e?.clientX||0)>N.VELT_MIN_ARROW_LENGTH?i.props.arrowAngle=135:i.props.arrowAngle=45,e&&(i.targetElement=this.domService.getTargetElementForCursorPosition(e)),i?.targetElement?.xpath){let l=this.domService.getXPath(i.targetElement.xpath);if(l){let c=l.iterateNext();c&&(Kr(c)||(i.targetElement=null))}}this.setLocationToArrowAnnotation(i),i.pageInfo=ro(),i.pageInfo&&(i.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth),this.saveArrowToDb(i)}}catch(t){this.loggingService.catch("Error in ArrowService addArrow: ",t)}}setLocationToArrowAnnotation(e){try{let t=this.docService.getLocation();t?(e.locationId=t.locationId,e.location=t.location):(delete e.locationId,delete e.location);try{if(e.targetElement?.xpath){let i=this.domService.getElementFromXPath(e.targetElement.xpath),a=this.docService.getAdditionLocationFromElement(i);if(a){let l=this.docService.addLocation({location:a,source:"internal"});l?.[0]&&(e.locationId=l[0].locationId,e.location=l[0].location)}}}catch{}}catch(t){this.loggingService.catch("Error in ArrowService setLocationToArrowAnnotation:",t)}}saveArrowToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: saveArrowToDb","color: green;");try{this.authService.getUser()&&this.authService.isFeatureAllowed(je.ARROW)&&this.docService.getDocumentPaths$().pipe(Ge(t=>!!t),ut(1),Se(t=>(this.documentPaths=t,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Ge(i=>!!i),ut(1),Se(i=>{if(this.documentPaths?.arrow){e.annotationId=this.commonDbService.generateDocumentId(),e.pageInfo&&(e.pageInfo.arrowUrl=this.generateArrowUrl(e));let a=JSON.parse(JSON.stringify(e));return a.position=null,this.domService.toggleAnnotationSelection(a),this.analyticsService.trackEvent(Y.Events.Arrow.ARROW_DRAFT_ADDED,{annotationId:e.annotationId}),this.commonDbService.setData({feature:"arrow",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.annotationId,skipFirestore:!0},data:JSON.parse(JSON.stringify(a))})}else return ce(null)}))))).subscribe(()=>{},t=>{this.loggingService.catch("Error in ArrowService saveArrowToDb subscription: ",t)})}catch(t){this.loggingService.catch("Error in ArrowService saveArrowToDb: ",t)}}updateArrow(e,t=!1,i){try{i&&this.setLocationToArrowAnnotation(e),t&&this.updateNotificationsDatabase(e,IN.UPDATED),this.updateArrowToDb(e)}catch(a){this.loggingService.catch("Error in ArrowService updateArrow: ",a)}}updateArrowToDb(e){this.loggingService.log("%c[WB] Calling FUNCTION: updateArrowToDb","color: green;");try{if(e?.targetElement?.xpath){let t=this.domService.getXPath(e.targetElement.xpath);if(t){let i=t.iterateNext();i&&(Kr(i)||(e.targetElement=null))}}this.domService.updateSelectedAnnotationInMap([e]),this.authService.getUser()&&this.authService.isFeatureAllowed(je.ARROW)&&this.docService.getDocumentPaths$().pipe(Ge(t=>!!t),ut(1),Se(t=>(this.documentPaths=t,this.loggingService.log(this.documentPaths),this.databaseService.getDb().pipe(Ge(i=>!!i),ut(1),Se(i=>{if(this.documentPaths?.arrow&&e?.annotationId){let a=JSON.parse(JSON.stringify(e));return a.position=null,this.commonDbService.setData({feature:"arrow",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.annotationId,skipFirestore:!0},data:JSON.parse(JSON.stringify(a))})}else return ce(null)}))))).subscribe(()=>{},t=>{this.loggingService.catch("Error in ArrowService updateArrowToDb subscription: ",t)})}catch(t){this.loggingService.catch("Error in ArrowService updateArrowToDb: ",t)}}deleteArrowPinAnnotations(e){try{let t=this.domService.getSelectedAnnotationsMap(),i=this.authService.getUser(),a=[];Object.keys(t).forEach(l=>X(this,null,function*(){let c=t[l];if(c.type==="arrow"){let d=i&&!i?.isAnonymous&&!i?.isGuest;i&&c.from&&(d||c.from.userId===i.userId)&&a.push(c)}})),a?.length&&(this.analyticsService.trackEvent(Y.Events.Arrow.ARROW_DELETE_TRIGGERED,{triggerType:e,annotationId:a.map(l=>l.annotationId).join()}),this.dialog.open(al,{panelClass:"velt-mat-dialog-container",data:{title:"Delete arrow?",message:"This selected arrow will be deleted.",yesButton:"Delete",noButton:"Cancel",variant:"arrow"}}).afterClosed().pipe(ut(1)).subscribe(l=>{l&&(a.forEach(c=>X(this,null,function*(){yield this.deleteArrowPinAnnotation(c)})),setTimeout(()=>{document.querySelectorAll(`[${N.SNIPPYLY_HIGHLIGHT}]`).forEach(d=>{this.domService.removeHighlightFromElement(d)})},100))})),this.domService.resetSelectedAnnotationsMap(!0,"arrow")}catch(t){this.loggingService.catch("Error in ArrowService deleteArrowPinAnnotations: ",t)}}deleteArrowPinAnnotation(e){return this.authService.isFeatureAllowed(je.ARROW)&&this.documentPaths?.arrow&&e?.annotationId?(this.updateNotificationsDatabase(e,IN.DELETED),this.analyticsService.trackEvent(Y.Events.Arrow.ARROW_DELETED,{annotationId:e.annotationId}),this.commonDbService.deleteData({feature:"arrow",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.annotationId,skipFirestore:!0}})):Promise.resolve()}enableAddArrowMode(){this.authService.isFeatureAllowed(je.ARROW)?(this.analyticsService.trackEvent(Y.Events.Arrow.ARROW_ADD_MODE_ENABLED),this.addArrowMode$.next(!0)):this.loggingService.catch("Error in ArrowService enableAddArrowMode: ","Arrow feature is not enabled.")}disableAddArrowMode(){this.analyticsService.trackEvent(Y.Events.Arrow.ARROW_ADD_MODE_DISABLED),this.addArrowMode$.next(!1)}addArrowModeChange(){return this.addArrowMode$.asObservable()}get timestamp(){return this.commonDbService.getServerTimestamp()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(t){return this.loggingService.catch("Error in ArrowService isElementInsideAllowedElements: ",t),!1}}updateNotificationsDatabase(e,t){try{let i={annotationData:e,actionType:t,notificationSource:"arrow"};this.notificationService.updateNotificationDatabase(i)}catch(i){this.loggingService.catch("Error in ArrowService updateNotificationsDatabase: ",i)}}getArrowUrl(e){try{return e?.pageInfo?.arrowUrl?e.pageInfo.arrowUrl:(e?.pageInfo||(e.pageInfo=ro(),e.pageInfo&&(e.pageInfo.screenWidth=this.domService.getCurrentWindowSizeValue()?.screenWidth)),e.pageInfo.arrowUrl=this.generateArrowUrl(e),this.updateArrow(e),e.pageInfo?.arrowUrl)}catch(t){this.loggingService.catch("Error in ArrowService getArrowUrl: ",t);return}}generateArrowUrl(e){let t=new URL(window.location.href);return t.searchParams.delete(N.URL_PARAMS.TAG_ID),t.searchParams.append(N.URL_PARAMS.TAG_ID,e.annotationId),t.href}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(Ft),K(st),K($n),K(qe),K(Ve),K(eo),K(Vn),K(Lo),K(k),K(mn),K(yn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var nU=class extends Cr{constructor(o){super(o),this.getService(k).log("%c[WB] Creating CLASS: ArrowElement","color: blue;"),this.allowedElementIds=this._allowedElementIds}_allowedElementIds(o){this.getService(k).log("%c[WB] Calling FUNCTION: allowedElementIds","color: green;");try{this.trackEvent(Y.Events.Arrow.ALLOWED_ELEMENT_IDS_TRIGGERED,{payload:{elementIds:o}}),this.getService(km).setAllowedElementIds(o)}catch(r){this.getService(k).catch("Error in allowedElementIds: ",r)}}};var Ec=(()=>{let o=class o{constructor(e){this.loggingService=e,this.autocompleteDataMap$=new _e({}),this.onAutocompleteChipClick$=new at;try{this.loggingService.log("%c[WB] Creating CLASS: AutocompleteService","color: blue;"),this.create({hotkey:"@",type:"contact",data:[]})}catch(t){this.loggingService.catch("Error in AutocompleteService constructor: ",t)}}create(e){try{if(this.loggingService.log("%c[WB] Calling AutocompleteService FUNCTION: create","color: green;"),e?.hotkey){let t=this.autocompleteDataMap$.value;t[e.hotkey]=e,this.autocompleteDataMap$.next(t)}}catch(t){this.loggingService.catch("Error in AutocompleteService create: ",t)}}remove(e){try{this.loggingService.log("%c[WB] Calling AutocompleteService FUNCTION: remove","color: green;");let t=this.autocompleteDataMap$.value;delete t[e],this.autocompleteDataMap$.next(t)}catch(t){this.loggingService.catch("Error in AutocompleteService remove: ",t)}}getAutocompleteDataMap$(){return this.autocompleteDataMap$.asObservable()}getAutocompleteDataMap(){return this.autocompleteDataMap$.value}setOnAutocompleteChipClick(e){this.onAutocompleteChipClick$.next(e)}getOnAutocompleteChipClick$(){return this.onAutocompleteChipClick$.asObservable()}};o.\u0275fac=function(t){return new(t||o)(K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var rU=class extends Cr{constructor(o){super(o),this.getService(k).log("%c[WB] Creating CLASS: AutocompleteElement","color: blue;"),this.create=this._create,this.onAutocompleteChipClick=this._onAutocompleteChipClick}_create(o){this.getService(k).log("%c[WB] Calling FUNCTION: create","color: green;");try{return this.trackEvent(Y.Events.Autocomplete.CREATE_TRIGGERED,{payload:{data:o}}),this.getService(Ec).create(o)}catch(r){this.getService(k).catch("Error in _create: ",r)}}_onAutocompleteChipClick(){this.getService(k).log("%c[WB] Calling FUNCTION: onAutocompleteChipClick","color: green;");try{return this.trackEvent(Y.Events.Autocomplete.ON_AUTOCOMPLETE_CHIP_CLICK_TRIGGERED),this.getService(Ec).getOnAutocompleteChipClick$()}catch(o){return this.getService(k).catch("Error in _onAutocompleteChipClick: ",o),ce(null)}}};var zbe=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m){this.authService=e,this.iamService=t,this.docService=i,this.configService=a,this.commonDbService=l,this.loggingService=c,this.commentService=d,this.userPermissionService=m,this.documentPaths=null,this.LISTENER_BATCH_SIZE=5}getAnnotationsCount(e){try{return this.authService.getUser$().pipe(Ge(t=>!!t),Se(t=>this.docService.getOrganizationConfig$().pipe(Ge(i=>!!i),ue(()=>t))),Se(t=>this.commentService.isFeatureAllowed({firebaseUser:t,annotations:[],filteredAnnotations:[]})),Se(t=>t.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(i=>(t.featureAllowed=i,t))):ce(t)),Se(t=>t.featureAllowed?this.processRequest(t,e):ce(null)),ue(t=>t??{data:null}),_t(Kt))}catch(t){return this.loggingService.catch("Error in CommentService getAnnotationsCount: ",t),ce({data:null})}}processRequest(e,t){try{return ce(e).pipe(Se(()=>this.initializeDocumentPaths(t,e)),Se(()=>this.getDocumentIds$(t)),Se(i=>{let a=this.authService.getUser()?.userSnippylyId,l=this.buildRequestContext(t,i);if(!this.validateRequestContext(l,t))return ce({data:null,mode:l.mode,serverDocumentIds:l.serverDocumentIds});if(!l.organizationId)return ce({data:null,mode:l.mode,serverDocumentIds:l.serverDocumentIds});let c=this.setupTriggers$(l.mode,l.organizationId,l.clientOrganizationId,l.veltFolderId,l.serverDocumentIds);if(this.shouldUseAggregateMode(l.mode))return this.handleAggregateCounts$({triggers$:c,serverDocumentIds:l.serverDocumentIds,request:t,userId:a,organizationId:l.organizationId,clientOrganizationId:l.clientOrganizationId,veltFolderId:l.veltFolderId,folderId:l.folderId,mode:l.mode}).pipe(ue(d=>({data:d,mode:l.mode,serverDocumentIds:l.serverDocumentIds})));if(l.mode.isBatchedGroupedMode){let d=t?.debounceMs??5e3;return this.handleBatchedGroupedCounts$({triggers$:c,documentIds:i,request:t,userId:a,organizationId:l.organizationId,veltFolderId:l.veltFolderId,debounceMs:d}).pipe(ue(m=>({data:m,mode:l.mode,serverDocumentIds:l.serverDocumentIds})))}else return this.handleGroupedCounts$(c,i,t,a,l.organizationId,l.veltFolderId).pipe(ue(d=>({data:d,mode:l.mode,serverDocumentIds:l.serverDocumentIds})))}),Se(i=>{if(!i?.data)return ce(null);let{data:a,mode:l,serverDocumentIds:c}=i;return t?.filterGhostComments?this.filterGhostComments$(a,l,c):ce(a)}),Xn(i=>(this.loggingService.catch("Error processing request: ",i),ce(null))))}catch(i){return this.loggingService.catch("Error in CommentService getAnnotationsCount: ",i),ce(null)}}initializeDocumentPaths(e,t){try{return e?ce(t):this.docService.getDocumentPaths$().pipe(Ge(i=>!!i),ln(i=>{this.documentPaths=i,t.documentPaths=i}),ue(()=>{}))}catch(i){return this.loggingService.catch("Error in CommentService initializeDocumentPaths: ",i),ce(t)}}buildRequestContext(e,t){try{let i=this.docService.getOrganizationConfig(),a=this.documentPaths?.organizationId??i?.organizationId,l=this.documentPaths?.clientOrganizationId??i?.clientOrganizationId,c,d,m;if(e?.allDocuments||e?.documentIds||e?.folderId||e?.organizationId||e?.locationIds){if(e.organizationId&&(a=ba(e.organizationId),l=e.organizationId),!a)throw new Error("organizationId is required for this request type");e.folderId&&(c=Lr(e.folderId),d=e.folderId),e.allDocuments&&(m=!0)}else c=this.documentPaths?.veltFolderId,d=this.documentPaths?.folderId,m=this.documentPaths?.allDocuments;let u=this.determineMode(e,c,m,t),_=u.isOrgMode?[]:t.length>0?t.map(I=>I.documentId):[this.documentPaths?.documentId??""];return{organizationId:a,clientOrganizationId:l,veltFolderId:c,folderId:d,allDocuments:m,mode:u,serverDocumentIds:_}}catch(i){return this.loggingService.catch("Error in CommentService buildRequestContext: ",i),{organizationId:void 0,clientOrganizationId:void 0,veltFolderId:void 0,folderId:void 0,allDocuments:void 0,mode:{isOrgMode:!1,isFolderMode:!1,isBatchMode:!1,isBatchedGroupedMode:!1},serverDocumentIds:[]}}}validateRequestContext(e,t){try{if(t?.aggregateDocuments&&!e.serverDocumentIds.length)throw this.loggingService.catch("Error in CommentService getAnnotationsCount: documentIds is required when aggregateDocuments is true"),new Error("documentIds is required when aggregateDocuments is true");return!(!e.organizationId||!(e.mode.isOrgMode||e.mode.isFolderMode)&&e.serverDocumentIds.some(i=>!i))}catch(i){return this.loggingService.catch("Error in CommentService validateRequestContext: ",i),!1}}shouldUseAggregateMode(e){try{return e.isFolderMode||e.isOrgMode||e.isBatchMode}catch(t){return this.loggingService.catch("Error in CommentService shouldUseAggregateMode: ",t),!1}}getDocumentIds$(e){try{return e?.documentIds?.length?ce(e.documentIds.map(t=>({clientDocumentId:t,documentId:mi(t)}))):this.docService.getDocumentIds$().pipe(ue(t=>t.length>0?t:[{documentId:this.documentPaths?.documentId??"",clientDocumentId:this.documentPaths?.clientDocumentId||""}]))}catch(t){return this.loggingService.catch("Error in CommentService getDocumentIds: ",t),ce([])}}determineMode(e,t,i,a){try{let l=!!e?.organizationId&&!e?.documentIds?.length&&!t&&!i,c=!!t&&!!i,d=!!e?.aggregateDocuments&&!i&&!!a?.length,m=(!!e?.batchedPerDocument||a.length>1)&&!!a?.length&&!e?.aggregateDocuments&&!i;return{isOrgMode:l,isFolderMode:c,isBatchMode:d,isBatchedGroupedMode:m}}catch(l){return this.loggingService.catch("Error in CommentService determineMode: ",l),{isOrgMode:!1,isFolderMode:!1,isBatchMode:!1,isBatchedGroupedMode:!1}}}setupTriggers$(e,t,i,a,l){try{if(e.isOrgMode){let c=this.authService.getUser()?.userId??"";return[co(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:i})??Promise.resolve({})).pipe(Se(m=>c&&m?.[c]?.organization?.[i]?.errorCode===mr.PERMISSION_DENIED?(this.loggingService.log(`%c[WB] commentViews org listener skipped \u2014 user does not have access to organization: ${i}`,"color: orange;"),Pc):this.commonDbService.dbListener({feature:"organizationMetadata",properties:{useCollectionGroup:!1,isCollection:!1,organizationId:t}}))).pipe(ue(m=>m?.data?.commentViewsUpdatedAt??null),Ge(m=>!!m),_t(Kt))]}else{if(e.isFolderMode)return[this.commonDbService.dbListener({feature:"folder",properties:{useCollectionGroup:!1,isCollection:!1,folderId:a,organizationId:t}}).pipe(ue(d=>d?.data?.commentViewsUpdatedAt??null),Ge(d=>!!d),_t(Kt))];if(e.isBatchMode||e.isBatchedGroupedMode){let c=[];for(let d=0;d<l.length;d+=this.LISTENER_BATCH_SIZE)c.push(l.slice(d,d+this.LISTENER_BATCH_SIZE));return c.map(d=>this.commonDbService.dbListener({feature:"allDocuments",properties:{useCollectionGroup:!0,isCollection:!0,useQuery:!0,firestoreQuery:[yr(ft("metadata.apiKey","==",this.configService?.getApiKey()),ft("metadata.organizationId","==",t),ft("metadata.documentId","in",d))]}}).pipe(ue(u=>Object.values(u?.data||{}).map(I=>I?.commentViewsUpdatedAt??null).sort().join(",")),_t(Kt)))}else return l.map(c=>this.commonDbService.dbListener({feature:"documentMetadata",properties:{useCollectionGroup:!1,isCollection:!1,documentId:c,organizationId:t}}).pipe(ue(m=>m?.data?.commentViewsUpdatedAt??null),Ge(m=>!!m),_t(Kt)))}}catch(c){return this.loggingService.catch("Error in CommentService setupTriggers: ",c),[]}}handleGroupedCounts$(e,t,i,a,l,c){try{let d=t.map((m,u)=>e[u].pipe(_o(void 0),Se(()=>co(this.getCountsForDocument$(m.documentId,m.clientDocumentId,i,a,l,c)))));return gn(d).pipe(ue(m=>{let u={};return m.forEach(_=>{_&&(u[_.clientDocumentId]={total:_.total,unread:_.unread})}),{data:u}}),Xn(m=>(this.loggingService.catch("Error in grouped counts: ",m),ce(null))))}catch(d){return this.loggingService.catch("Error in CommentService handleGroupedCounts: ",d),ce(null)}}handleBatchedGroupedCounts$(e){try{let{triggers$:t,documentIds:i,request:a,userId:l,organizationId:c,veltFolderId:d,debounceMs:m}=e,u=this.LISTENER_BATCH_SIZE,_=new Td(1),I=t.map((q,ae)=>q.pipe(KB(_),ue(()=>ae))),A=No(...I).pipe(Qr(m)),M=ce(-1).pipe(Se(()=>co(this.fetchAllDocumentCounts$(i,a,l,c,d))),ue(q=>({batchIndex:-1,data:q?.data||{}})),ln(()=>{_.next()})),V=A.pipe(Se(q=>{let ae=q*u,ye=Math.min(ae+u,i.length),ie=i.slice(ae,ye);return co(this.fetchAllDocumentCounts$(ie,a,l,c,d)).pipe(ue(ge=>({batchIndex:q,data:ge?.data||{}})))}));return No(M,V).pipe(ub((q,ae)=>({data:h(h({},q.data),ae.data)}),{data:{}}),Xn(q=>(this.loggingService.catch("Error in batched grouped counts: ",q),ce(null))))}catch(t){return this.loggingService.catch("Error in CommentService handleBatchedGroupedCounts: ",t),ce(null)}}fetchAllDocumentCounts$(e,t,i,a,l){return X(this,null,function*(){try{let c=e.map(u=>this.getCountsForDocument$(u.documentId,u.clientDocumentId,t,i,a,l)),d=yield Promise.allSettled(c),m={};return d.forEach(u=>{if(u.status==="fulfilled"&&u.value){let{clientDocumentId:_,total:I,unread:A}=u.value;m[_]={total:I,unread:A}}}),{data:m}}catch(c){return this.loggingService.catch("Error in CommentService fetchAllDocumentCounts: ",c),null}})}handleAggregateCounts$(e){try{let{triggers$:t,serverDocumentIds:i,request:a,userId:l,organizationId:c,clientOrganizationId:d,veltFolderId:m,folderId:u,mode:_}=e;return gn(t).pipe(ue(()=>{})).pipe(_o(void 0),Se(()=>co(this.getAggregateCounts({serverDocumentIds:i,request:a,userId:l,organizationId:c,clientOrganizationId:d,veltFolderId:m,folderId:u,mode:_}))),Xn(A=>(this.loggingService.catch("Error in aggregate counts: ",A),ce(null))))}catch(t){return this.loggingService.catch("Error in CommentService handleAggregateCounts: ",t),ce(null)}}getCountsForDocument$(e,t,i,a,l,c){return X(this,null,function*(){try{let d=this.configService?.getApiKey(),m={useCollectionGroup:!0,isCollection:!0,useQuery:!0,getCount:!0},u=[ft("metadata.apiKey","==",d),ft("metadata.organizationId","==",l),ft("metadata.documentId","in",[e]),...c?[ft("metadata.veltFolderId","==",c)]:[],...i?.statusIds?.length?[ft("status.id","in",i.statusIds)]:[],...i?.locationIds?.length?[ft("location.id","in",i.locationIds)]:[],...i?.agentFields?.length?[ft("agent.agentFields","array-contains-any",i.agentFields)]:[]],_=[yr(...u),uo("lastUpdated","desc"),uo("createdAt","desc")],I=yield this.commonDbService.queryData({feature:"allComments",properties:y(h({},m),{firestoreQuery:_})}),A=0;if(!i?.agentFields?.length){let M=[...u,ft("viewedByUserIds","array-contains",a)],V=[yr(...M),uo("lastUpdated","desc"),uo("createdAt","desc")];A=yield this.commonDbService.queryData({feature:"allComments",properties:y(h({},m),{firestoreQuery:V})})}return{clientDocumentId:t,total:I,unread:I-A}}catch(d){return this.loggingService.catch("Error in CommentService getCountsForDocument: ",d),null}})}getAggregateCounts(e){return X(this,null,function*(){try{let t="",{serverDocumentIds:i,request:a,userId:l,organizationId:c,clientOrganizationId:d,veltFolderId:m,folderId:u,mode:_}=e,I=this.configService?.getApiKey(),A={useCollectionGroup:!0,isCollection:!0,useQuery:!0,getCount:!0},M=[ft("metadata.apiKey","==",I),ft("metadata.organizationId","==",c),...a?.statusIds?.length?[ft("status.id","in",a.statusIds)]:[],...a?.locationIds?.length?[ft("location.id","in",a.locationIds)]:[],...a?.agentFields?.length?[ft("agent.agentFields","array-contains-any",a.agentFields)]:[]],V,q=0;if(_.isFolderMode){t=u??"",M.push(ft("metadata.veltFolderId","==",m));let ae=[yr(...M),uo("lastUpdated","desc"),uo("createdAt","desc")];if(V=yield this.commonDbService.queryData({feature:"allComments",properties:y(h({},A),{firestoreQuery:ae})}),!a?.agentFields?.length){let ye=[...M,ft("viewedByUserIds","array-contains",l)],ie=[yr(...ye),uo("lastUpdated","desc"),uo("createdAt","desc")];q=yield this.commonDbService.queryData({feature:"allComments",properties:y(h({},A),{firestoreQuery:ie})})}}else if(_.isOrgMode){t=d??"";let ae=[yr(...M),uo("lastUpdated","desc"),uo("createdAt","desc")];if(V=yield this.commonDbService.queryData({feature:"allComments",properties:y(h({},A),{firestoreQuery:ae})}),!a?.agentFields?.length){let ye=[...M,ft("viewedByUserIds","array-contains",l)],ie=[yr(...ye),uo("lastUpdated","desc"),uo("createdAt","desc")];q=yield this.commonDbService.queryData({feature:"allComments",properties:y(h({},A),{firestoreQuery:ie})})}}else{t="result";let ae=[];for(let ge=0;ge<i.length;ge+=this.LISTENER_BATCH_SIZE)ae.push(i.slice(ge,ge+this.LISTENER_BATCH_SIZE));let ye=ae.map(ge=>X(this,null,function*(){let Ie=[...M,ft("metadata.documentId","in",ge),...m?[ft("metadata.veltFolderId","==",m)]:[]],he=[yr(...Ie),uo("lastUpdated","desc"),uo("createdAt","desc")];return this.commonDbService.queryData({feature:"allComments",properties:y(h({},A),{firestoreQuery:he})})}));if(V=(yield Promise.allSettled(ye)).reduce((ge,Ie)=>ge+(Ie.status==="fulfilled"&&Ie.value||0),0),!a?.agentFields?.length){let ge=ae.map(he=>X(this,null,function*(){let Te=[...M,ft("metadata.documentId","in",he),...m?[ft("metadata.veltFolderId","==",m)]:[],ft("viewedByUserIds","array-contains",l)],Oe=[yr(...Te),uo("lastUpdated","desc"),uo("createdAt","desc")];return this.commonDbService.queryData({feature:"allComments",properties:y(h({},A),{firestoreQuery:Oe})})}));q=(yield Promise.allSettled(ge)).reduce((he,Te)=>he+(Te.status==="fulfilled"&&Te.value||0),0)}}return{data:{[t]:{total:V,unread:V-q}}}}catch(t){return this.loggingService.catch("Error in CommentService getAggregateCounts: ",t),null}})}filterGhostComments$(e,t,i){try{return e?this.commentService.getGhostCommentAnnotationMap$().pipe(ue(a=>{if(!a)return e;let l=this.buildGhostCommentAnnotationMap(a),c=this.groupGhostCommentsByModeId(l,t,i);return this.adjustCountsForGhostComments(e,c),e})):ce(null)}catch(a){return this.loggingService.catch("Error in CommentService filterGhostComments: ",a),ce(null)}}buildGhostCommentAnnotationMap(e){let t={};return Object.keys(e).forEach(i=>{let a=this.commentService.getAnnotationById(i);a&&(t[i]=a)}),t}groupGhostCommentsByModeId(e,t,i){try{let a={};return Object.values(e).forEach(l=>{let c=this.getModeIdForAnnotation(l,t,i);c&&(a[c]||(a[c]=[]),a[c].push(l))}),a}catch(a){return this.loggingService.catch("Error in CommentService groupGhostCommentsByModeId: ",a),{}}}getModeIdForAnnotation(e,t,i){try{return t.isOrgMode?e?.metadata?.clientOrganizationId||null:t.isFolderMode?e?.metadata?.folderId||null:t.isBatchMode?i.includes(e?.metadata?.documentId??"")?"result":null:e?.metadata?.clientDocumentId||null}catch(a){return this.loggingService.catch("Error in CommentService getModeIdForAnnotation: ",a),null}}adjustCountsForGhostComments(e,t){try{if(typeof e?.data!="object")return;let a=this.authService.getUser()?.userSnippylyId;Object.keys(e.data||{}).forEach(l=>{let c=t[l];if(!(!c||!e?.data?.[l]?.total)&&(e.data[l].total=Math.max(0,e.data[l].total-c.length),a)){let d=c.filter(m=>m?.viewedByUserIds&&!m?.viewedByUserIds?.includes(a));d.length>0&&(e.data[l].unread=Math.max(0,e.data[l].unread-d.length))}})}catch(i){this.loggingService.catch("Error in CommentService adjustCountsForGhostComments: ",i)}}};o.\u0275fac=function(t){return new(t||o)(K(qe),K(Vn),K(st),K(Ft),K(yn),K(k),K(Re),K(Ia))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Mn=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A){this.analyticsService=e,this.authService=t,this.commentService=i,this.commentViewsService=a,this.contactService=l,this.customFilterService=c,this.docService=d,this.iamService=m,this.loggingService=u,this.metadataService=_,this.reactionService=I,this.commonDbService=A,this.actionSubjects=new Map,this.defaultSource="internal",this.isUserAdmin=!1,this.subscriptions=[],this.loggingService.log("%c[WB] Creating CLASS: CommentActionsService","color: blue;");try{this.commentService.setCommentActionsService(this),this.iamService.isUserAdmin$().subscribe(M=>{this.isUserAdmin=M})}catch(M){this.loggingService.catch("Error in CommentActionsService constructor: ",M)}}addCommentAnnotation(l,c){return X(this,arguments,function*({annotation:e,options:t,visibility:i},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addCommentAnnotation","color: green;"),i){if(i.type==="restricted"){let m=this.authService.getUser();m?.userId&&(i=Ju(i,m.userId))}if(i.type==="organizationPrivate"&&!i.organizationId){let m=this.docService.getOrganizationConfig();m?.clientOrganizationId&&(i=y(h({},i),{organizationId:m.clientOrganizationId}))}let d=Xu(i);d.length>0&&(e.context||(e.context={}),e.context._setAccessFields=d,e.visibilityConfig=h(h({type:i.type},i.organizationId&&{organizationId:i.organizationId}),i.userIds&&{userIds:i.userIds}))}return new Promise(d=>{this.commentService.addComment(void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,m=>X(this,null,function*(){let u=yield this.getAddCommentAnnotationEventFromCommentAddEventData(m);d(u)}),void 0,void 0,e,void 0,void 0,void 0,void 0,void 0,a)})}catch(d){return this.loggingService.catch("Error in CommentActionsService addCommentAnnotation: ",d),null}})}publishCommentAnnotation(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: publishCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t);if(c){let d=JSON.parse(JSON.stringify(c));d.isDraft=!1,this.commentService.saveComment(d,{type:Ot.PUBLISHED}),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_PUBLISHED,{annotationId:e,commentType:this.commentService.getCommentType(d),commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource});let m=yield this.metadataService.getGlobalMetadata(),u={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(d),metadata:m};return this.triggerAction(ar.PUBLISH_COMMENT_ANNOTATION,u),u}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService publishCommentAnnotation: ",c),null}})}getAddCommentAnnotationEventFromCommentAddEventData(e){return X(this,null,function*(){try{let t=yield this.metadataService.getGlobalMetadata();return{commentAnnotation:this.commentService.getCommentAnnotationForClient(e?.annotation),annotationId:e?.annotation?.annotationId,metadata:t,addContext:e?.addContext,elementRef:e?.elementRef}}catch(t){return this.loggingService.catch("Error in CommentActionsService getAddCommentAnnotationEventFromData: ",t),null}})}triggerAddCommentAnnotationEvent(e){try{this.triggerAction(ar.ADD_COMMENT_ANNOTATION,e)}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAddCommentAnnotationEvent: ",t)}}getAddCommentAnnotationDraftEventFromCommentAddEventData(e){return X(this,null,function*(){try{return{metadata:yield this.metadataService.getGlobalMetadata(),addContext:e?.addContext}}catch(t){return this.loggingService.catch("Error in CommentActionsService getAddCommentAnnotationEventFromData: ",t),null}})}triggerAddCommentAnnotationDraftEvent(e){try{this.triggerAction(ar.ADD_COMMENT_ANNOTATION_DRAFT,e)}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAddCommentAnnotationDraftEvent: ",t)}}triggerAddCommentDraftEventForAnnotation(e,t){return X(this,null,function*(){try{if(!e?.annotationId||!t)return;let i=yield this.metadataService.getGlobalMetadata(),a={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),comment:t,metadata:i};this.triggerAction(ar.ADD_COMMENT_DRAFT,a)}catch(i){this.loggingService.catch("Error in CommentActionsService triggerAddCommentDraftEventForAnnotation: ",i)}})}triggerAnnotationNotFoundError(e){try{this.loggingService.catch("Annotation not found:","The annotation with the given id was not found.")}catch(t){this.loggingService.catch("Error in CommentActionsService triggerAnnotationNotFoundError: ",t)}}deleteCommentAnnotation(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteCommentAnnotation","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let d=this.commentService.getAnnotationById(e,t);if(d){let m=this.authService.getUser();if(this.isUserAdmin||m?.userId===d?.from?.userId){this.commentService.deleteCommentPinAnnotation(d);let u=yield this.metadataService.getGlobalMetadata(),_={annotationId:d.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(d),metadata:u};return this.triggerAction(ar.DELETE_COMMENT_ANNOTATION,_),_}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete it.")}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService deleteCommentAnnotation: ",c),null}})}updatePriority(l,c){return X(this,arguments,function*({annotationId:e,priority:t,options:i},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updatePriority","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let m=this.commentService.getAnnotationById(e,i);if(m){m=JSON.parse(JSON.stringify(m));let u=m.priority?JSON.parse(JSON.stringify(m.priority)):null;u&&t&&u?.id===t?.id?m.priority=void 0:m.priority=t,this.commentService.saveComment(m,{type:Ot.PRIORITY_CHANGED,newPriority:t,oldPriority:u});let _=yield this.metadataService.getGlobalMetadata(),I={newPriority:t,oldPriority:u,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:_};return this.triggerAction(ar.UPDATE_PRIORITY,I),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_PRIORITY_CHANGED,{annotationId:e,commentType:this.commentService.getCommentType(m),oldPriority:m.priority,newPriority:t,commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource}),I}else this.triggerAnnotationNotFoundError(e);return null}catch(d){return this.loggingService.catch("Error in CommentActionsService updatePriority: ",d),null}})}updateStatus(l,c){return X(this,arguments,function*({annotationId:e,status:t,options:i},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateStatus","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let m=this.commentService.getAnnotationById(e,i);if(m){m=JSON.parse(JSON.stringify(m));let u=m.status?JSON.parse(JSON.stringify(m.status)):null;m.status=t,this.commentService.saveComment(m,{type:Ot.STATUS_CHANGED,newStatus:t,oldStatus:u});let _=yield this.metadataService.getGlobalMetadata(),I={newStatus:t,oldStatus:u,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:_};return this.triggerAction(ar.UPDATE_STATUS,I),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_STATUS_CHANGED,{annotationId:e,commentType:this.commentService.getCommentType(m),oldStatus:u,newStatus:t,commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource,commentAnnotationCreatedAt:m.createdAt}),I}else this.triggerAnnotationNotFoundError(e);return null}catch(d){return this.loggingService.catch("Error in CommentActionsService updateStatus: ",d),null}})}updateAccess(l,c){return X(this,arguments,function*({annotationId:e,accessMode:t,options:i},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateAccess","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let m=this.commentService.getAnnotationById(e,i);if(m)if(this.commentService.isPrivateCommentAllowed()){m=JSON.parse(JSON.stringify(m));let u=m.iam?.accessMode;m.iam.accessMode=t,this.commentService.saveComment(m,{type:Ot.ACCESS_MODE_CHANGED,newAccessMode:t,oldAccessMode:u});let _=yield this.metadataService.getGlobalMetadata(),I={newAccessMode:t,oldAccessMode:u,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:_};switch(this.triggerAction(ar.UPDATE_ACCESS,I),t){case Ca.PRIVATE:this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ACCESS_MODE_CHANGED,{type:Ca.PRIVATE,source:a??this.defaultSource});break;case Ca.PUBLIC:this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ACCESS_MODE_CHANGED,{type:Ca.PUBLIC,source:a??this.defaultSource});break;default:break}return I}else this.loggingService.catch("Access Denied","You must be an admin to update the access mode of the comment.");else this.triggerAnnotationNotFoundError(e);return null}catch(d){return this.loggingService.catch("Error in CommentActionsService updateAccess: ",d),null}})}resolveCommentAnnotation(i){return X(this,arguments,function*({annotationId:e,options:t}){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: resolveCommentAnnotation","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let l=this.commentService.getAnnotationById(e,t);if(l){l=JSON.parse(JSON.stringify(l));let c=this.customFilterService.resolvedStatus,d=l.status?JSON.parse(JSON.stringify(l.status)):null;c&&(l.status=c,this.commentService.saveComment(l,{type:Ot.STATUS_CHANGED,newStatus:c,oldStatus:d}));let m=yield this.metadataService.getGlobalMetadata(),u={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(l),metadata:m};return this.triggerAction(ar.RESOLVE_COMMENT,u),u}else this.triggerAnnotationNotFoundError(e);return null}catch(a){return this.loggingService.catch("Error in CommentActionsService resolveCommentAnnotation: ",a),null}})}getLink(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getLink","color: green;");let c=this.commentService.getAnnotationById(e,t);if(c){let d=this.commentService.getCommentUrl(c)??null,m=yield this.metadataService.getGlobalMetadata();return{link:d,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(c),metadata:m}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService getLink: ",c),null}})}copyLink(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: copyLink","color: green;");let c=yield this.getLink({annotationId:e,options:t},i);if(c?.link){Kc(c.link),this.commentService.setCopyLink(c.link),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_LINK_COPIED,{annotationId:e,commentType:this.commentService.getCommentType(c.commentAnnotation),commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource,link:c.link});let d=yield this.metadataService.getGlobalMetadata(),m={link:c.link,annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(c.commentAnnotation),metadata:d};return this.triggerAction(ar.COPY_LINK,m),m}return null}catch(c){return this.loggingService.catch("Error in CommentActionsService copyLink: ",c),null}})}addComment(m,u){return X(this,arguments,function*({annotationId:e,comment:t,assignedTo:i,assigned:a,options:l,visibility:c},d){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addComment","color: green;");let _=this.authService.getUser();if(!_)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;if(_){let I=this.commentService.getAnnotationById(e,l),A=I?.comments?.length?Ot.ADDED:Ot.NEWLY_ADDED;if(I){I.status.type==="terminal"&&(I.status=this.customFilterService.defaultStatus);let M=new Xl;M=h(h({},M),t),M.lastUpdated=new Date,M.attachments||(M.attachments=[]),M.attachments=M.attachments.filter(ie=>ie?.attachmentId),M.createdAt=this.timestamp,M.from=_,i&&(I.assignedTo=i),this.commentService.saveComment(I,{type:A,updatedComment:M,assigned:a,visibility:c,_dispatchAddCommentEvent:!0});let V=y(h({},I),{comments:[...I.comments||[],M]}),q=yield this.buildAddCommentEvent({annotation:V,newComment:M});if(!q)return null;let ae=t?.commentId,ye=this.calculateCommentThreadIndex(t,I);return this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ADDED,{annotationId:e,commentThreadId:ae,commentThreadIndex:ye,commentType:this.commentService.getCommentType(I),commentMode:this.commentService.getCommentMode(),source:d??this.defaultSource,commentAnnotationCreatedAt:I.createdAt,taggedClientUserIds:M.taggedUserContacts?.map(ie=>ie.contact?.userId).filter(ie=>!!ie),taggedSnippylyUserIds:M.taggedUserContacts?.filter(ie=>!!I?.metadata?.apiKey&&!!ie.contact?.userId).map(ie=>cd(I.metadata.apiKey,ie.contact.userId))}),q}else this.triggerAnnotationNotFoundError(e)}return null}catch(_){return this.loggingService.catch("Error in CommentActionsService addComment: ",_),null}})}buildAddCommentEvent(i){return X(this,arguments,function*({annotation:e,newComment:t}){try{let a=yield this.metadataService.getGlobalMetadata();return{annotationId:e.annotationId,commentId:t?.commentId,comment:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:a}}catch(a){return this.loggingService.catch("Error in CommentActionsService buildAddCommentEvent: ",a),null}})}triggerAddCommentEvent(i){return X(this,arguments,function*({annotation:e,newComment:t}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: triggerAddCommentEvent","color: green;");let a=yield this.buildAddCommentEvent({annotation:e,newComment:t});return a&&this.triggerAction(ar.ADD_COMMENT,a),a}catch(a){return this.loggingService.catch("Error in CommentActionsService triggerAddCommentEvent: ",a),null}})}approveCommentAnnotation(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: approveCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t);if(c){c.approved=!0,this.commentService.saveComment(c,{type:Ot.APPROVED}),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_APPROVED,{annotationId:e,commentType:this.commentService.getCommentType(c),commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource});let d=yield this.metadataService.getGlobalMetadata(),m={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(c),metadata:d};return this.triggerAction(ar.APPROVE_COMMENT_ANNOTATION,m),m}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService approveComment: ",c),null}})}acceptCommentAnnotation(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: acceptCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t),d=this.authService.getUser();if(c&&d){let m=c.status?JSON.parse(JSON.stringify(c.status)):null;c.status=N.CommentAcceptStatus,this.commentService.saveComment(c,{type:Ot.ACCEPTED,oldStatus:m,newStatus:N.CommentAcceptStatus});let u=yield this.metadataService.getGlobalMetadata(),_={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(c),metadata:u,actionUser:d,replaceContentHtml:c?.comments?.length?c?.comments[0]?.replaceContentHtml:void 0,replaceContentText:c?.comments?.length?c?.comments[0]?.replaceContentText:void 0};return this.triggerAction(ar.ACCEPT_COMMENT_ANNOTATION,_),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ACCEPTED,{annotationId:e,commentType:this.commentService.getCommentType(c),commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource}),_}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService acceptCommentAnnotation: ",c),null}})}rejectCommentAnnotation(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: rejectCommentAnnotation","color: green;");let c=this.commentService.getAnnotationById(e,t),d=this.authService.getUser();if(c&&d){let m=c.status?JSON.parse(JSON.stringify(c.status)):null;c.status=N.CommentRejectStatus,this.commentService.saveComment(c,{type:Ot.REJECTED,oldStatus:m,newStatus:N.CommentRejectStatus});let u=yield this.metadataService.getGlobalMetadata(),_={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(c),metadata:u,actionUser:d,replaceContentHtml:c?.comments?.length?c?.comments[0]?.replaceContentHtml:void 0,replaceContentText:c?.comments?.length?c?.comments[0]?.replaceContentText:void 0};return this.triggerAction(ar.REJECT_COMMENT_ANNOTATION,_),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_REJECTED,{annotationId:e,commentType:this.commentService.getCommentType(c),commentMode:this.commentService.getCommentMode(),source:i??this.defaultSource}),_}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService rejectCommentAnnotation: ",c),null}})}toggleNotificationSubscription(a,l){return X(this,arguments,function*({annotationId:e,options:t},i){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: toggleNotificationSubscription","color: green;");let c=this.commentService.getAnnotationById(e,t),d=this.authService.getUser();if(c&&d){let m=It(d.userId);if(m){c.subscribedUsers||(c.subscribedUsers={}),c.unsubscribedUsers||(c.unsubscribedUsers={});let u,_=!1;if(c?.unsubscribedUsers?.[m])_=!1;else if(c?.subscribedUsers?.[m])_=!0;else{let M=this.contactService.getCurrentOrganizationUserIAM();if(M){let V=M.groups||{};Object.keys(V).forEach(q=>{c?.subscribedGroups?.[q]&&(_=!0)})}}if(i==="subscribe"||!i&&!_)delete c.unsubscribedUsers[m],c.subscribedUsers[m]={user:d,type:"manual"},u=Ot.SUBSCRIBED;else if(i==="unsubscribe"||!i&&_)delete c.subscribedUsers[m],c.unsubscribedUsers[m]={user:d,type:"manual"},u=Ot.UNSUBSCRIBED;else return null;this.commentService.saveComment(c,{type:u});let I=yield this.metadataService.getGlobalMetadata(),A={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(c),metadata:I};return u===Ot.SUBSCRIBED?this.triggerAction(ar.SUBSCRIBE_COMMENT_ANNOTATION,A):this.triggerAction(ar.UNSUBSCRIBE_COMMENT_ANNOTATION,A),A}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService toggleNotificationSubscription: ",c),null}})}assignUser(l,c){return X(this,arguments,function*({annotationId:e,assignedTo:t,options:i},a){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: assignUser","color: green;"),!this.authService.getUser())return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;let m=this.commentService.getAnnotationById(e,i);if(m){m.assignedTo=t,this.commentService.saveComment(m,{type:Ot.ASSIGNED,assignedTo:t});let u=yield this.metadataService.getGlobalMetadata(),_={annotationId:e,assignedTo:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:u};return this.triggerAction(ar.ASSIGN_USER,_),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_ASSIGNED,{annotationId:e,commentType:this.commentService.getCommentType(m),commentMode:this.commentService.getCommentMode(),source:a??this.defaultSource,assignedToUserId:t?.userId}),_}else this.triggerAnnotationNotFoundError(e);return null}catch(d){return this.loggingService.catch("Error in CommentActionsService assignUser: ",d),null}})}getComment(i){return X(this,arguments,function*({annotationId:e,options:t}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getComment","color: green;");let a=this.commentService.getAnnotationById(e,t);return a?a.comments||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(a){return this.loggingService.catch("Error in CommentActionsService getComment: ",a),[]}})}updateOrDeleteComment(e,t,i,a,l){return X(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateOrDeleteComment","color: green;"),t?.commentText?.trim()||t?.attachments?.length||t?.recorders?.length){let c=this.authService.getUser();if(this.isUserAdmin||c?.userId===t?.from?.userId){t.lastUpdated=new Date,t.status=Ot.UPDATED,t.isEdited||(t.isEdited=!0,t.editedAt=new Date),this.commentService.saveComment(e,{type:Ot.UPDATED,updatedComment:t});let d=yield this.metadataService.getGlobalMetadata(),m={annotationId:e?.annotationId,commentId:t?.commentId,comment:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:d};return this.triggerAction(ar.UPDATE_COMMENT,m),this.analyticsService.trackEvent(Y.Events.Comments.COMMENT_EDITED,{annotationId:e?.annotationId,commentThreadId:t?.commentId,commentType:this.commentService.getCommentType(e),commentMode:this.commentService.getCommentMode(),source:l??this.defaultSource}),m}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to update it.")}else yield this.deleteComment({annotationId:e?.annotationId,commentId:t.commentId,skipDeleteThreadConfirmation:i,options:a});return null}catch(c){return this.loggingService.catch("Error in CommentActionsService updateOrDeleteComment: ",c),null}})}updateComment(d,m){return X(this,arguments,function*({annotationId:e,comment:t,skipDeleteThreadConfirmation:i,merge:a,options:l},c){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateComment","color: green;");let u=this.commentService.getAnnotationById(e,l),_=this.authService.getUser();if(!_)return this.loggingService.catch("User not found. Ensure Identify method is called.",void 0,void 0,!0),null;if(u&&_){let I=t,A=u.comments?.find(M=>M.commentId===t.commentId);if(A){if(this.isUserAdmin||_?.userId===A?.from?.userId)return u?.status.type==="terminal"&&(u.status=this.customFilterService.defaultStatus),a&&(I=h(h({},A),t)),I.from=A.from,I.createdAt=A.createdAt,I.lastUpdated=new Date,yield this.updateOrDeleteComment(u,I,i,l,c);this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to update it.")}}else this.triggerAnnotationNotFoundError(e);return null}catch(u){return this.loggingService.catch("Error in CommentActionsService updateComment: ",u),null}})}deleteComment(c,d){return X(this,arguments,function*({annotationId:e,commentId:t,skipDeleteThreadConfirmation:i,options:a},l){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteComment","color: green;");let m=this.commentService.getAnnotationById(e,a),u=this.authService.getUser();if(!m)return this.triggerAnnotationNotFoundError(e),null;let _=m.comments?.find(q=>q?.commentId===t);if(!_)return null;if(!(this.isUserAdmin||u?.userId===_?.from?.userId))return this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete it."),null;let I=this.commentService.willDeleteWholeAnnotation(m,t),A=this.commentService.getCommentAnnotationForClient(m);if(!i&&!(yield this.commentService.confirmDeleteCommentIfRequired(m,_)))return null;this.commentService.saveComment(m,{type:Ot.DELETED,updatedComment:_,skipDeleteThreadConfirmation:!0});let M=yield this.metadataService.getGlobalMetadata(),V={annotationId:e,commentId:t,commentAnnotation:A,comment:_,metadata:M};if(I){let q={annotationId:e,commentAnnotation:A,metadata:M};this.triggerAction(ar.DELETE_COMMENT_ANNOTATION,q)}else this.triggerAction(ar.DELETE_COMMENT,V);return V}catch(m){return this.loggingService.catch("Error in CommentActionsService deleteComment: ",m),null}})}addAttachment(l,c){return X(this,arguments,function*({annotationId:e,files:t,options:i},a){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: addAttachment","color: green;");let d=[],m=this.commentService.getAnnotationById(e,i);if(m||a==="internal"){let I=[];t.forEach(A=>{let{valid:M,file:V,maxAllowedSize:q,error:ae}=this.validateFile(A);M&&V?I.push(this.uploadFile(V,m||{}).then(ye=>({valid:M,file:V,maxAllowedSize:q,error:ae,attachment:ye||void 0}))):I.push(Promise.resolve({valid:M,file:V,maxAllowedSize:q,error:ae,attachment:void 0}))}),d=yield Promise.all(I)}else this.triggerAnnotationNotFoundError(e);let u=yield this.metadataService.getGlobalMetadata(),_={annotationId:e,commentAnnotation:m?this.commentService.getCommentAnnotationForClient(m):void 0,attachments:d,metadata:u};return this.triggerAction(ar.ADD_ATTACHMENT,_),d}catch(d){return this.loggingService.catch("Error in CommentActionsService addAttachment: ",d),[]}})}validateFile(e){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: validateFile","color: green;");let t=100*1024*1024;(e?.type?.includes("image")||e?.type?.includes("pdf"))&&(t=15*1024*1024);let i=e.size<=t;return{valid:i,file:e,maxAllowedSize:t,maxAllowedSizeInMB:t/1024/1024,error:i?void 0:`File size should be less than ${t/1024/1024} MB`}}catch(t){return this.loggingService.catch("Error in CommentActionsService validateFile: ",t),{valid:!1,maxAllowedSize:0,maxAllowedSizeInMB:0,error:"Error in validating file"}}}deleteAttachment(l){return X(this,arguments,function*({annotationId:e,commentId:t,attachmentId:i,options:a}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteAttachment","color: green;");let c=this.commentService.getAnnotationById(e,a);if(c){let d=c.comments?.find(u=>u?.commentId===t),m=c.metadata;if(d){let u=this.authService.getUser();if(this.isUserAdmin||u?.userId===d?.from?.userId){let _=d.attachments?.find(I=>I?.attachmentId===i);if(_){d.attachments=d.attachments?.filter(V=>V?.attachmentId!==i);let I={attachmentId:_.attachmentId,organizationId:m?.clientOrganizationId??m?.organizationId??null,documentId:m?.clientDocumentId??m?.documentId??null,folderId:m?.folderId??null,commentAnnotationId:c.annotationId,apiKey:m?.apiKey??null};yield this.commentService.deleteAttachment({attachment:_,metadata:I});let A=yield this.metadataService.getGlobalMetadata(),M={attachment:_,annotationId:e,commentId:t,commentAnnotation:this.commentService.getCommentAnnotationForClient(c),metadata:A};return this.triggerAction(ar.DELETE_ATTACHMENT,M),this.updateComment({annotationId:e,comment:d,options:a}),M}}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete the attachment.")}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService deleteAttachment: ",c),null}})}getAttachment(a){return X(this,arguments,function*({annotationId:e,commentId:t,options:i}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getAttachment","color: green;");let l=this.commentService.getAnnotationById(e,i);return l?l.comments?.find(d=>d?.commentId===t)?.attachments||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(l){return this.loggingService.catch("Error in CommentActionsService getAttachment: ",l),[]}})}uploadFile(e,t){return X(this,null,function*(){try{return this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: uploadFile","color: green;"),this.commentService.uploadFile(e,t)}catch(i){return this.loggingService.catch("Error in CommentActionsService uploadFile: ",i),null}})}getRecording(a){return X(this,arguments,function*({annotationId:e,commentId:t,options:i}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: getRecording","color: green;");let l=this.commentService.getAnnotationById(e,i);return l?l.comments?.find(d=>d?.commentId===t)?.recorders||[]:(this.triggerAnnotationNotFoundError(e),[])}catch(l){return this.loggingService.catch("Error in CommentActionsService getRecording: ",l),[]}})}deleteRecording(l){return X(this,arguments,function*({annotationId:e,commentId:t,recorderId:i,options:a}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: deleteRecording","color: green;");let c=this.commentService.getAnnotationById(e,a);if(c){let d=c.comments?.find(m=>m?.commentId===t);if(d){let m=this.authService.getUser();if(this.isUserAdmin||m?.userId===d?.from?.userId){let u=d.recorders?.find(_=>_?.id===i);if(u){d.recorders=d.recorders?.filter(A=>A?.id!==i);let _=yield this.metadataService.getGlobalMetadata(),I={annotationId:e,commentId:t,recording:u,commentAnnotation:this.commentService.getCommentAnnotationForClient(c),metadata:_};return this.triggerAction(ar.DELETE_RECORDING,I),this.updateComment({annotationId:e,comment:d,skipDeleteThreadConfirmation:!0,options:a}),I}}else this.loggingService.catch("Access Denied","You must be the author of the comment or an admin to delete the recording.")}}else this.triggerAnnotationNotFoundError(e);return null}catch(c){return this.loggingService.catch("Error in CommentActionsService deleteRecording: ",c),null}})}fetchCommentAnnotations(e){return X(this,null,function*(){try{let t=yield this.commentService.fetchCommentAnnotations(e),i;if(t?.hasMore){let l=t?.data[t?.data?.length-1];i=yield zK(l?.lastUpdated?.toString()??"","veltencrypttoken","veltencrypttoken")}let a=t?.data?.reduce((l,c)=>(l[c.metadata.clientDocumentId??c.metadata.documentId]=l[c.metadata.clientDocumentId??c.metadata.documentId]||[],l[c.metadata.clientDocumentId??c.metadata.documentId].push(this.commentService.getCommentAnnotationForClient(c)),l),{});return h({data:a},t?.hasMore?{nextPageToken:i}:{})}catch(t){return this.loggingService.catch("Error in CommentActionsService fetchCommentAnnotations: ",t),{data:null}}})}toggleReaction(c,d){return X(this,arguments,function*({annotationId:e,commentId:t,reaction:i,options:a},l){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: toggleReaction","color: green;");let m=this.commentService.getAnnotationById(e,a),u=this.authService.getUser();if(m&&u){let _=m.comments?.find(I=>I?.commentId===t);if(_){let I=yield this.reactionService.addOrUpdateReaction(i.reactionId,_?.reactionAnnotationIds||[],void 0,void 0,m?.annotationId,i.customReaction,l),A=Ot.REACTION_ADDED;if(I){I?.reactions?.find(q=>q.from?.userId===u?.userId)||(A=Ot.REACTION_DELETED),_.reactionAnnotationIds||(_.reactionAnnotationIds=[]),_.reactionAnnotationIds.includes(I.annotationId)||_.reactionAnnotationIds.push(I.annotationId),I?.reactions?.length||(_.reactionAnnotationIds=_.reactionAnnotationIds.filter(q=>q!==I.annotationId)),this.commentService.saveComment(m,{type:A,updatedComment:_});let M=yield this.metadataService.getGlobalMetadata(),V={annotationId:e,commentId:t,reaction:I,commentAnnotation:this.commentService.getCommentAnnotationForClient(m),metadata:M};return l==="add"?this.triggerAction(ar.ADD_REACTION,V):l==="delete"?this.triggerAction(ar.DELETE_REACTION,V):this.triggerAction(ar.TOGGLE_REACTION,V),A===Ot.REACTION_ADDED?this.analyticsService.trackEvent(Y.Events.Comments.REACTION_ADDED,{annotationId:e,commentId:t,reactionId:i.reactionId,commentMode:this.commentService.getCommentMode()}):A===Ot.REACTION_DELETED&&this.analyticsService.trackEvent(Y.Events.Comments.REACTION_DELETED,{annotationId:e,commentId:t,reactionId:i.reactionId,commentMode:this.commentService.getCommentMode()}),V}}}else this.triggerAnnotationNotFoundError(e);return null}catch(m){return this.loggingService.catch("Error in CommentActionsService toggleReaction: ",m),null}})}onComposerClick(t){return X(this,arguments,function*({commentAnnotation:e}){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onComposerClick","color: green;");let i=yield this.metadataService.getGlobalMetadata(),a={commentAnnotation:e?.annotationId?this.commentService.getCommentAnnotationForClient(e):void 0,metadata:i};this.triggerAction(ar.COMPOSER_CLICKED,a)}catch(i){this.loggingService.catch("Error in CommentActionsService onComposerClick: ",i)}})}onComposerTextChange(e){return X(this,null,function*(){try{let t=yield this.metadataService.getGlobalMetadata(),i={text:e.text,annotation:e.annotation,targetComposerElementId:e.targetComposerElementId,metadata:t};this.commentService.setComposerData(e.targetComposerElementId,i),this.triggerAction(ar.COMPOSER_TEXT_CHANGE,i)}catch(t){this.loggingService.catch("Error in CommentActionsService onComposerTextChange: ",t)}})}autocompleteSearch(e){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: autocompleteSearch","color: green;");let t=yield this.metadataService.getGlobalMetadata();e.metadata=t,this.triggerAction(ar.AUTOCOMPLETE_SEARCH,e)}catch(t){this.loggingService.catch("Error in CommentActionsService autocompleteSearch: ",t)}})}onCommentPinClick(e){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentPinClick","color: green;");let t=yield this.metadataService.getGlobalMetadata(),i={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:t};return this.triggerAction(ar.COMMENT_PIN_CLICKED,i),i}catch(t){return this.loggingService.catch("Error in CommentActionsService onCommentPinClick: ",t),null}})}onCommentBubbleClick(e){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentBubbleClick","color: green;");let t=yield this.metadataService.getGlobalMetadata(),i={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),metadata:t};return this.triggerAction(ar.COMMENT_BUBBLE_CLICKED,i),i}catch(t){return this.loggingService.catch("Error in CommentActionsService onCommentBubbleClick: ",t),null}})}onCommentToolClick(e,t){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentToolClick","color: green;");let i=yield this.metadataService.getGlobalMetadata(),a={context:e,targetElementId:t,metadata:i},l={context:e,targetElementId:t,metadata:i};return this.triggerAction(ar.COMMENT_TOOL_CLICK,a),this.triggerAction(ar.COMMENT_TOOL_CLICKED,l),a}catch(i){return this.loggingService.catch("Error in CommentActionsService onCommentToolClick: ",i),null}})}onSidebarButtonClick(){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onSidebarButtonClick","color: green;");let e=yield this.metadataService.getGlobalMetadata(),t={metadata:e},i={metadata:e};return this.triggerAction(ar.SIDEBAR_BUTTON_CLICK,t),this.triggerAction(ar.SIDEBAR_BUTTON_CLICKED,i),t}catch(e){return this.loggingService.catch("Error in CommentActionsService onSidebarButtonClick: ",e),null}})}onAttachmentDownloadClick(e,t){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onAttachmentDownloadClick","color: green;");let i=yield this.metadataService.getGlobalMetadata(),a={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),attachment:t,metadata:i};return this.triggerAction(ar.ATTACHMENT_DOWNLOAD_CLICKED,a),a}catch(i){return this.loggingService.catch("Error in CommentActionsService onAttachmentDownloadClick: ",i),null}})}onCommentSaveTriggered(e,t){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onCommentSaveTriggered","color: green;");let i=yield this.metadataService.getGlobalMetadata(),a={annotationId:e,commentAnnotation:this.commentService.getCommentAnnotationForClient(t),metadata:i};return this.triggerAction(ar.COMMENT_SAVE_TRIGGERED,a),a}catch(i){return this.loggingService.catch("Error in CommentActionsService onCommentSaveTriggered: ",i),null}})}onVisibilityOptionClick(e,t,i){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: onVisibilityOptionClick","color: green;");let a=yield this.metadataService.getGlobalMetadata(),l={annotationId:e.annotationId,commentAnnotation:this.commentService.getCommentAnnotationForClient(e),visibility:t,users:i?.map(c=>Vo(c)).filter(Boolean),metadata:a};return this.triggerAction(ar.VISIBILITY_OPTION_CLICKED,l),l}catch(a){return this.loggingService.catch("Error in CommentActionsService onVisibilityOptionClick: ",a),null}})}convert(e){try{if(e?.options){let{documentId:t,organizationId:i}=this.docService.getServerId(e?.options);e.options=y(h({},e?.options),{documentId:t,organizationId:i})}return this}catch(t){return this.loggingService.catch("Error in CommentActionsService convert: ",t),this}}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new at),this.actionSubjects.get(e)?.next(t)}catch(i){this.loggingService.catch("Error in CommentActionsService triggerAction: ",i)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new at),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in CommentActionsService onAction: ",t),ce(null)}}get timestamp(){return this.commonDbService.getServerTimestamp()}getCommentAnnotations(e){try{if(e){if(e?.allDocuments&&!e?.folderId)return this.loggingService.catch("folderId is required when allDocuments is true."),ce({data:null});if(!e?.allDocuments&&!e?.documentIds?.length)return this.loggingService.catch("documentIds is required."),ce({data:null})}return this.commentService.getAllCommentAnnotations({excludeDomChanges:!0,skipPositionCalculation:!0,query:e,addFilterCommentsOnDomCheck:!0}).pipe(ue(t=>t?t.reduce((i,a)=>{let l=a.metadata?.clientDocumentId;return!l||e?.documentIds&&!e?.documentIds?.includes(l)||(i[l]||(i[l]=[]),i[l].push(a)),i},{}):null),ue(t=>({data:t})))}catch(t){return this.loggingService.catch("Error in CommentActionsService getCommentAnnotation: ",t),ce({data:null})}}getCommentAnnotationsCount$(e){try{return this.commentViewsService.getAnnotationsCount(e).pipe(ue(t=>t||{data:null}))}catch(t){return this.loggingService.catch("Error in CommentActionsService getCommentAnnotation: ",t),ce({data:null})}}updateVisibility(e){this.loggingService.log("%c[WB] Calling CommentActionsService FUNCTION: updateVisibility","color: green;");try{let t=e.annotationId;if(!t)throw new Error("annotationId is required in visibility config");if(e.type==="restricted"){let l=this.authService.getUser();if(!l?.userId)throw new Error("Current user not found. Cannot set restricted visibility without userIds.");e=Ju(e,l.userId)}if(e.type==="organizationPrivate"&&!e.organizationId){let l=this.docService.getOrganizationConfig();if(!l?.clientOrganizationId)throw new Error("No organizationId found. Cannot set organizationPrivate visibility without organizationId.");e=y(h({},e),{organizationId:l.clientOrganizationId})}this.analyticsService.trackEvent(Y.Events.Comments.UPDATE_VISIBILITY_TRIGGERED,{payload:{annotationId:t,visibility:e}});let i=Xu(e),a=h(h({type:e.type},e.organizationId&&{organizationId:e.organizationId}),e.userIds&&{userIds:e.userIds});return this.commentService.updateCommentAnnotationContext(t,{_setAccessFields:i,_setVisibilityConfig:a},{merge:!0})}catch(t){return this.loggingService.catch("Error in updateVisibility: ",t),Promise.resolve()}}calculateCommentThreadIndex(e,t){try{let i=e?.commentId,a;return i&&(a=t?.comments?.findIndex(l=>l.commentId===i)),a===-1&&(a=t?.comments?.length),a}catch(i){this.loggingService.catch("Error in calculateCommentThreadIndex: ",i);return}}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(qe),K(Re),K(zbe),K(vn),K(po),K(st),K(Vn),K(k),K(ts),K(zi),K(yn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var oU=class extends Cr{constructor(o){super(o),this._submitComment=r=>{this.getService(k).log("%c[WB] Calling FUNCTION: submitComment","color: green;");try{this.trackEvent(Y.Events.Comments.SUBMIT_COMMENT_TRIGGERED,{payload:{referenceId:r.targetComposerElementId}}),this.getService(Re).submitComment(r)}catch(e){this.getService(k).catch("Error in _submitComment: ",e)}},this._clearComposer=r=>{this.getService(k).log("%c[WB] Calling FUNCTION: clearComposer","color: green;");try{this.trackEvent(Y.Events.Comments.CLEAR_COMPOSER_TRIGGERED),this.getService(Re).clearComposer(r)}catch(e){this.getService(k).catch("Error in _clearComposer: ",e)}},this._enableFormatOptions=()=>{this.getService(k).log("%c[WB] Calling FUNCTION: enableFormatOptions","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_FORMAT_OPTIONS_TRIGGERED),this.getService(Re).enableFormatOptions()}catch(r){this.getService(k).catch("Error in _enableFormatOptions: ",r)}},this._disableFormatOptions=()=>{this.getService(k).log("%c[WB] Calling FUNCTION: disableFormatOptions","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_FORMAT_OPTIONS_TRIGGERED),this.getService(Re).disableFormatOptions()}catch(r){this.getService(k).catch("Error in _disableFormatOptions: ",r)}},this._setFormatConfig=r=>{this.getService(k).log("%c[WB] Calling FUNCTION: setFormatConfig","color: green;");try{this.trackEvent(Y.Events.Comments.SET_FORMAT_CONFIG_TRIGGERED,{payload:{config:r}}),this.getService(Re).setFormatConfig(r)}catch(e){this.getService(k).catch("Error in _setFormatConfig: ",e)}},this._getComposerData=r=>{this.getService(k).log("%c[WB] Calling FUNCTION: getComposerData","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_COMPOSER_DATA_TRIGGERED),this.getService(Re).getComposerData(r)}catch(e){return this.getService(k).catch("Error in _getComposerData: ",e),null}},this.getService(k).log("%c[WB] Creating CLASS: CommentElement","color: blue;"),this.getAllCommentAnnotations=this._getAllCommentAnnotations,this.deleteSelectedComment=this._deleteSelectedComment,this.enableTextComments=this._enableTextComments,this.disableTextComments=this._disableTextComments,this.allowedElementIds=this._allowedElementIds,this.allowedElementClassNames=this._allowedElementClassNames,this.allowedElementQuerySelectors=this._allowedElementQuerySelectors,this.disableFloatingCommentDialog=this._disableFloatingComments,this.enableFloatingCommentDialog=this._enableFloatingComments,this.attachComment=this._attachComment,this.openCommentSidebar=this._openCommentSidebar,this.closeCommentSidebar=this._closeCommentSidebar,this.toggleCommentSidebar=this._toggleCommentSidebar,this.enableModeratorMode=this._enableModeratorMode,this.disableModeratorMode=this._disableModeratorMode,this.enableStreamMode=this._enableStreamMode,this.disableStreamMode=this._disableStreamMode,this.enableSignInButton=this._enableSignInButton,this.disableSignInButton=this._disableSignInButton,this.enableUpgradeButton=this._enableUpgradeButton,this.disableUpgradeButton=this._disableUpgradeButton,this.onCommentModeChange=this._onCommentModeChange,this.enableAttachments=this._enableAttachment,this.disableAttachments=this._disableAttachment,this.enableAttachmentDownload=this._enableAttachmentDownload,this.disableAttachmentDownload=this._disableAttachmentDownload,this.isUserGlobalContact=this._isUserGlobalContact,this.enableDeviceInfo=this._enableDeviceInfo,this.disableDeviceInfo=this._disableDeviceInfo,this.enableCommentMode=this._enableCommentMode,this.disableCommentMode=this._disableCommentMode,this.enablePersistentCommentMode=this._enablePersistentCommentMode,this.disablePersistentCommentMode=this._disablePersistentCommentMode,this.enableCommentIndex=this._enableCommentIndex,this.disableCommentIndex=this._disableCommentIndex,this.enablePopoverMode=this._enablePopoverMode,this.disablePopoverMode=this._disablePopoverMode,this.enableDialogOnHover=this._enableDialogOnHover,this.enablePopoverTriangleComponent=this._enablePopoverTriangleComponent,this.disablePopoverTriangleComponent=this._disablePopoverTriangleComponent,this.disableDialogOnHover=this._disableDialogOnHover,this.enableDialogOnTargetElementClick=this._enableDialogOnTargetElementClick,this.disableDialogOnTargetElementClick=this._disableDialogOnTargetElementClick,this.enablePriority=this._enablePriority,this.disablePriority=this._disablePriority,this.enableStatus=this._enableStatus,this.disableStatus=this._disableStatus,this.enableVisibilityOptions=this._enableVisibilityOptions,this.disableVisibilityOptions=this._disableVisibilityOptions,this.enableResolveButton=this._enableResolveButton,this.disableResolveButton=this._disableResolveButton,this.enableGhostComments=this._enableGhostComments,this.disableGhostComments=this._disableGhostComments,this.enableGhostCommentsIndicator=this._enableGhostCommentsIndicator,this.disableGhostCommentsIndicator=this._disableGhostCommentsIndicator,this.setCustomStatus=this._setCustomStatus,this.setCustomPriority=this._setCustomPriority,this.setCustomCategory=this._setCustomCategory,this.enableInboxMode=this._enableInboxMode,this.disableInboxMode=this._disableInboxMode,this.enableAutoCategorize=this._enableAutoCategorize,this.disableAutoCategorize=this._disableAutoCategorize,this.enableDarkMode=this._enableDarkMode,this.disableDarkMode=this._disableDarkMode,this.setContextProvider=this._setContextProvider,this.enableSuggestionMode=this._enableSuggestionMode,this.disableSuggestionMode=this._disableSuggestionMode,this.enableMobileMode=this._enableMobileMode,this.disableMobileMode=this._disableMobileMode,this.enableInlineCommentMode=this._enableInlineCommentMode,this.disableInlineCommentMode=this._disableInlineCommentMode,this.enableMinimap=this._enableMinimap,this.disableMinimap=this._disableMinimap,this.showCommentsOnDom=this._showCommentsOnDom,this.hideCommentsOnDom=this._hideCommentsOnDom,this.enableCommentTool=this._enableCommentTool,this.disableCommentTool=this._disableCommentTool,this.setTotalMediaLength=this._setTotalMediaLength,this.onCommentAdd=this._onCommentAdd,this.onCommentUpdate=this._onCommentUpdate,this.addCommentOnSelectedText=this._addCommentOnSelectedText,this.enableSidebarUrlNavigation=this._enableSidebarUrlNavigation,this.disableSidebarUrlNavigation=this._disableSidebarUrlNavigation,this.setDStrategy=this._setDStrategy,this.enableSidebarButtonOnCommentDialog=this._enableSidebarButtonOnCommentDialog,this.disableSidebarButtonOnCommentDialog=this._disableSidebarButtonOnCommentDialog,this.onSidebarButtonOnCommentDialogClick=this._onSidebarButtonOnCommentDialogClick,this.enableReactions=this._enableReactions,this.disableReactions=this._disableReactions,this.enableAnonymousEmail=this._enableAnonymousEmail,this.disableAnonymousEmail=this._disableAnonymousEmail,this.setRecordings=this._setRecordings,this.addCommentOnElement=this._addCommentOnElement,this.enablePrivateCommentMode=this._enablePrivateCommentMode,this.disablePrivateCommentMode=this._disablePrivateCommentMode,this.enablePrivateMode=this._enablePrivateMode,this.disablePrivateMode=this._disablePrivateMode,this.enableScrollToComment=this._enableScrollToComment,this.disableScrollToComment=this._disableScrollToComment,this.enableUserMentions=this._enableUserMentions,this.disableUserMentions=this._disableUserMentions,this.setCommentSidebarFilters=this._setCommentSidebarFilters,this.setSystemFiltersOperator=this._setSystemFiltersOperator,this.enableCommentPinHighlighter=this._enableCommentPinHighlighter,this.disableCommentPinHighlighter=this._disableCommentPinHighlighter,this.enableDeleteOnBackspace=this._enableDeleteOnBackspace,this.disableDeleteOnBackspace=this._disableDeleteOnBackspace,this.enableHotkey=this._enableHotkey,this.disableHotkey=this._disableHotkey,this.enableDeviceIndicatorOnCommentPins=this._enableDeviceIndicatorOnCommentPins,this.disableDeviceIndicatorOnCommentPins=this._disableDeviceIndicatorOnCommentPins,this.getElementRefByAnnotationId=this._getElementRefByAnnotationId,this.scrollToCommentByAnnotationId=this._scrollToCommentByAnnotationId,this.selectCommentByAnnotationId=this._selectCommentByAnnotationId,this.enableRecordingSummary=this._enableRecordingSummary,this.disableRecordingSummary=this._disableRecordingSummary,this.enableRecordingTranscription=this._enableRecordingTranscription,this.disableRecordingTranscription=this._disableRecordingTranscription,this.enableRecordingCountdown=this._enableRecordingCountdown,this.disableRecordingCountdown=this._disableRecordingCountdown,this.setUnreadIndicatorMode=this._setUnreadIndicatorMode,this.enableEnterKeyToSubmit=this._enableEnterKeyToSubmit,this.disableEnterKeyToSubmit=this._disableEnterKeyToSubmit,this.enablePinShadowDOM=this._enablePinShadowDOM,this.disablePinShadowDOM=this._disablePinShadowDOM,this.enableDialogShadowDOM=this._enableDialogShadowDOM,this.disableDialogShadowDOM=this._disableDialogShadowDOM,this.enableSidebarShadowDOM=this._enableSidebarShadowDOM,this.disableSidebarShadowDOM=this._disableSidebarShadowDOM,this.enableChangeDetectionInCommentMode=this._enableChangeDetectionInCommentMode,this.disableChangeDetectionInCommentMode=this._disableChangeDetectionInCommentMode,this.showResolvedCommentsOnDom=this._showResolvedCommentsOnDom,this.hideResolvedCommentsOnDom=this._hideResolvedCommentsOnDom,this.setCustomReactions=this._setCustomReactions,this.onCommentSelectionChange=this._onCommentSelectionChange,this.getUnreadCommentCountByAnnotationId=this._getUnreadCommentCountByAnnotationId,this.getUnreadCommentAnnotationCountOnCurrentDocument=this._getUnreadCommentAnnotationCountOnCurrentDocument,this.getUnreadCommentCountOnCurrentDocument=this._getUnreadCommentCountOnCurrentDocument,this.getUnreadCommentAnnotationCountByLocationId=this._getUnreadCommentAnnotationCountByLocationId,this.getUnreadCommentCountByLocationId=this._getUnreadCommentCountByLocationId,this.updateCommentDialogPosition=this._updateCommentDialogPosition,this.enableAreaComment=this._enableAreaComment,this.disableAreaComment=this._disableAreaComment,this.setPinCursorImage=this._setPinCursorImage,this.addManualComment=this._addManualComment,this.createCustomListDataOnAnnotation=this._createCustomListDataOnAnnotation,this.createCustomListDataOnComment=this._createCustomListDataOnComment,this.excludeLocationIdsFromSidebar=this._excludeLocationIdsFromSidebar,this.enableBubbleOnPin=this._enableBubbleOnPin,this.disableBubbleOnPin=this._disableBubbleOnPin,this.enableBubbleOnPinHover=this._enableBubbleOnPinHover,this.disableBubbleOnPinHover=this._disableBubbleOnPinHover,this.enablePinDrag=this._enablePinDrag,this.disablePinDrag=this._disablePinDrag,this.enableMultiThreadMode=this._enableMultiThread,this.disableMultiThreadMode=this._disableMultiThread,this.enableMultiThread=this._enableMultiThread,this.disableMultiThread=this._disableMultiThread,this.enableGroupMultipleMatch=this._enableGroupMatchedComments,this.disableGroupMultipleMatch=this._disableGroupMatchedComments,this.enableGroupMatchedComments=this._enableGroupMatchedComments,this.disableGroupMatchedComments=this._disableGroupMatchedComments,this.updateContext=this._updateContext,this.updateVisibility=this._updateVisibility,this.getSelectedComments=this._getSelectedComments,this.enableDeleteReplyConfirmation=this._enableDeleteReplyConfirmation,this.disableDeleteReplyConfirmation=this._disableDeleteReplyConfirmation,this.onCopyLink=this._onCopyLink,this.getCommentAnnotationById=this._getCommentAnnotationById,this.enableCollapsedComments=this._enableCollapsedComments,this.disableCollapsedComments=this._disableCollapsedComments,this.onCommentSidebarActionButtonClick=this._onCommentSidebarActionButtonClick,this.setCommentSidebarData=this._setCommentSidebarData,this.onCommentSidebarInit=this._onCommentSidebarInit,this.onCommentSidebarData=this._onCommentSidebarData,this.setCommentSidebarDefaultCustomActions=this._setCommentSidebarDefaultCustomActions,this.enableSidebarCustomActions=this._enableSidebarCustomActions,this.disableSidebarCustomActions=this._disableSidebarCustomActions,this.enableQueryParamsComments=this._enableQueryParamsComments,this.disableQueryParamsComments=this._disableQueryParamsComments,this.enableResolveStatusAccessAdminOnly=this._enableResolveStatusAccessAdminOnly,this.disableResolveStatusAccessAdminOnly=this._disableResolveStatusAccessAdminOnly,this.enableLinkCallback=this._enableLinkCallback,this.disableLinkCallback=this._disableLinkCallback,this.enableSeenByUsers=this._enableSeenByUsers,this.disableSeenByUsers=this._disableSeenByUsers,this.enableShortUserName=this._enableShortUserName,this.disableShortUserName=this._disableShortUserName,this.addCommentAnnotation=this._addCommentAnnotation,this.publishCommentAnnotation=this._publishCommentAnnotation,this.approveCommentAnnotation=this._approveCommentAnnotation,this.acceptCommentAnnotation=this._acceptCommentAnnotation,this.rejectCommentAnnotation=this._rejectCommentAnnotation,this.subscribeCommentAnnotation=this._subscribeCommentAnnotation,this.unsubscribeCommentAnnotation=this._unsubscribeCommentAnnotation,this.deleteCommentAnnotation=this._deleteCommentAnnotation,this.getCommentAnnotations=this._getCommentAnnotations,this.getCommentAnnotationsCount=this._getCommentAnnotationsCount,this.assignUser=this._assignUser,this.updatePriority=this._updatePriority,this.updateStatus=this._updateStatus,this.updateAccess=this._updateAccess,this.resolveCommentAnnotation=this._resolveCommentAnnotation,this.getLink=this._getLink,this.copyLink=this._copyLink,this.addComment=this._addComment,this.updateComment=this._updateComment,this.deleteComment=this._deleteComment,this.getComment=this._getComment,this.addAttachment=this._addAttachment,this.deleteAttachment=this._deleteAttachment,this.getAttachment=this._getAttachment,this.deleteRecording=this._deleteRecording,this.getRecording=this._getRecording,this.addReaction=this._addReaction,this.deleteReaction=this._deleteReaction,this.toggleReaction=this._toggleReaction,this.enableReadOnly=this._enableReadOnly,this.disableReadOnly=this._disableReadOnly,this.setAssignToType=this._setAssignToType,this.enableContextInPageModeComposer=this._enableContextInPageModeComposer,this.disableContextInPageModeComposer=this._disableContextInPageModeComposer,this.clearPageModeComposerContext=this._clearPageModeComposerContext,this.setContextInPageModeComposer=this._setContextInPageModeComposer,this.focusPageModeComposer=this._focusPageModeComposer,this.enableCustomAutocompleteSearch=this._enableCustomAutocompleteSearch,this.disableCustomAutocompleteSearch=this._disableCustomAutocompleteSearch,this.fetchCommentAnnotations=this._fetchCommentAnnotations,this.setTransformContext=this._setTransformContext,this.enableSvgAsImg=this._enableSvgAsImg,this.disableSvgAsImg=this._disableSvgAsImg,this.enableFullExpanded=this._enableFullExpanded,this.disableFullExpanded=this._disableFullExpanded,this.enableCommentToNearestAllowedElement=this._enableCommentToNearestAllowedElement,this.disableCommentToNearestAllowedElement=this._disableCommentToNearestAllowedElement,this.enableDraftMode=this._enableDraftMode,this.disableDraftMode=this._disableDraftMode,this.enableFilterCommentsOnDom=this._enableFilterCommentsOnDom,this.disableFilterCommentsOnDom=this._disableFilterCommentsOnDom,this.enableReplyAvatars=this._enableReplyAvatars,this.disableReplyAvatars=this._disableReplyAvatars,this.setMaxReplyAvatars=this._setMaxReplyAvatars,this.setSidebarButtonCountType=this._setSidebarButtonCountType,this.enableFilterGhostCommentsInSidebar=this._enableFilterGhostCommentsInSidebar,this.disableFilterGhostCommentsInSidebar=this._disableFilterGhostCommentsInSidebar,this.enableFullScreenInSidebar=this._enableFullScreenInSidebar,this.disableFullScreenInSidebar=this._disableFullScreenInSidebar,this.setComposerFileAttachments=this._setComposerFileAttachments,this.setAllowedFileTypes=this._setAllowedFileTypes,this.enableForceCloseAllOnEsc=this._enableForceCloseAllOnEsc,this.disableForceCloseAllOnEsc=this._disableForceCloseAllOnEsc,this.markAsRead=this._markAsRead,this.markAsUnread=this._markAsUnread,this.enableScreenshot=this._enableScreenshot,this.disableScreenshot=this._disableScreenshot,this.enablePaginatedContactList=this._enablePaginatedContactList,this.disablePaginatedContactList=this._disablePaginatedContactList,this.enableFormatOptions=this._enableFormatOptions,this.disableFormatOptions=this._disableFormatOptions,this.setFormatConfig=this._setFormatConfig,this.submitComment=this._submitComment,this.clearComposer=this._clearComposer,this.on=this._on,this.getComposerData=this._getComposerData}_getAllCommentAnnotations(o,r){this.getService(k).log("%c[WB] Calling FUNCTION: getOnlineUsers","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_ALL_COMMENT_ANNOTATIONS_TRIGGERED,{payload:{documentId:o,location:r}}),this.getService(Re).getAllCommentAnnotations({customClientDocumentId:o,params:r,excludeDomChanges:!0,skipPositionCalculation:!0,addFilterCommentsOnDomCheck:!0}).pipe(ue(e=>e?.length?e?.map(t=>this.getService(Re).getCommentAnnotationForClient(t)):e))}catch(e){return this.getService(k).catch("Error in _getLiveCommentsOnCurrentDocument: ",e),ce(null)}}_deleteSelectedComment(){this.getService(k).log("%c[WB] Calling FUNCTION: deleteSelectedComment","color: green;");try{return this.trackEvent(Y.Events.Comments.DELETE_SELECTED_COMMENT_TRIGGERED),this.getService(Re).deleteCommentPinAnnotations("commentElement")}catch(o){return this.getService(k).catch("Error in _deleteSelectedComment: ",o),Promise.resolve(null)}}_enableTextComments(){this.getService(k).log("%c[WB] Calling FUNCTION: enableTextComments","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_TEXT_COMMENTS_TRIGGERED),this.getService(Re).enableTextComments()}catch(o){this.getService(k).catch("Error in _enableTextComments: ",o)}}_disableTextComments(){this.getService(k).log("%c[WB] Calling FUNCTION: disableTextComments","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_TEXT_COMMENTS_TRIGGERED),this.getService(Re).disableTextComments()}catch(o){this.getService(k).catch("Error in _disableTextComments: ",o)}}_allowedElementIds(o){this.getService(k).log("%c[WB] Calling FUNCTION: allowedElementIds","color: green;");try{this.trackEvent(Y.Events.Comments.ALLOWED_ELEMENT_IDS_TRIGGERED,{payload:{elementIds:o}}),this.getService(Re).setAllowedElementIds(o)}catch(r){this.getService(k).catch("Error in allowedElementIds: ",r)}}_allowedElementClassNames(o){this.getService(k).log("%c[WB] Calling FUNCTION: allowedElementClassNames","color: green;");try{this.trackEvent(Y.Events.Comments.ALLOWED_ELEMENT_CLASS_NAMES_TRIGGERED,{payload:{classNames:o}}),this.getService(Re).setAllowedElementClassNames(o)}catch(r){this.getService(k).catch("Error in allowedElementClassNames: ",r)}}_allowedElementQuerySelectors(o){this.getService(k).log("%c[WB] Calling FUNCTION: allowedElementQuerySelectors","color: green;");try{this.trackEvent(Y.Events.Comments.ALLOWED_ELEMENT_QUERY_SELECTORS_TRIGGERED,{payload:{querySelectors:o}}),this.getService(Re).setAllowedElementQuerySelectors(o)}catch(r){this.getService(k).catch("Error in allowedElementQuerySelectors: ",r)}}_disableFloatingComments(){this.getService(k).log("%c[WB] Calling FUNCTION: disableFloatingComments","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_FLOATING_COMMENT_DIALOG_TRIGGERED),this.getService(Re).disableFloatingComments(!0)}catch(o){this.getService(k).catch("Error in _disableFloatingComments: ",o)}}_enableFloatingComments(){this.getService(k).log("%c[WB] Calling FUNCTION: enableFloatingComments","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_FLOATING_COMMENT_DIALOG_TRIGGERED),this.getService(Re).disableFloatingComments(!1)}catch(o){this.getService(k).catch("Error in _enableFloatingComments: ",o)}}_attachComment(o){this.getService(k).log("%c[WB] Calling FUNCTION: attachComment","color: green;");try{this.trackEvent(Y.Events.Comments.ATTACH_COMMENT_TRIGGERED,{payload:{elementId:o}}),this.getService(Re).attachComment(o,["id","data-id"])}catch(r){this.getService(k).catch("Error in _attachComment: ",r)}}_openCommentSidebar(){this.getService(k).log("%c[WB] Calling FUNCTION: openCommentSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.OPEN_COMMENT_SIDEBAR_TRIGGERED),this.getService(Re).setSidebarVisibility(!0,!0)}catch(o){this.getService(k).catch("Error in _openCommentSidebar: ",o)}}_closeCommentSidebar(){this.getService(k).log("%c[WB] Calling FUNCTION: closeCommentSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.CLOSE_COMMENT_SIDEBAR_TRIGGERED),this.getService(Re).setSidebarVisibility(!1,!0)}catch(o){this.getService(k).catch("Error in _closeCommentSidebar: ",o)}}_toggleCommentSidebar(){this.getService(k).log("%c[WB] Calling FUNCTION: toggleCommentSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.TOGGLE_COMMENT_SIDEBAR_TRIGGERED),this.getService(Re).toggleSidebarVisibility(!0)}catch(o){this.getService(k).catch("Error in _toggleCommentSidebar: ",o)}}_enableModeratorMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableModeratorMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_MODERATOR_MODE_TRIGGERED),this.getService(Re).setModeratorMode(!0)}catch(o){this.getService(k).catch("Error in _enableModeratorMode: ",o)}}_disableModeratorMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableModeratorMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_MODERATOR_MODE_TRIGGERED),this.getService(Re).setModeratorMode(!1)}catch(o){this.getService(k).catch("Error in _disableModeratorMode: ",o)}}_enableStreamMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableStreamMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_STREAM_MODE_TRIGGERED),this.getService(Re).setStreamMode(!0)}catch(o){this.getService(k).catch("Error in _enableStreamMode: ",o)}}_disableStreamMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableStreamMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_STREAM_MODE_TRIGGERED),this.getService(Re).setStreamMode(!1)}catch(o){this.getService(k).catch("Error in _disableStreamMode: ",o)}}_enableSignInButton(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSignInButton","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SIGN_IN_BUTTON_TRIGGERED),this.getService(Re).enableSignInButton(!0)}catch(o){this.getService(k).catch("Error in _enableSignInButton: ",o)}}_disableSignInButton(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSignInButton","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SIGN_IN_BUTTON_TRIGGERED),this.getService(Re).enableSignInButton(!1)}catch(o){this.getService(k).catch("Error in _disableSignInButton: ",o)}}_enableUpgradeButton(){this.getService(k).log("%c[WB] Calling FUNCTION: enableUpgradeButton","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_UPGRADE_BUTTON_TRIGGERED),this.getService(Re).enableUpgradeButton(!0)}catch(o){this.getService(k).catch("Error in _enableUpgradeButton: ",o)}}_disableUpgradeButton(){this.getService(k).log("%c[WB] Calling FUNCTION: disableUpgradeButton","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_UPGRADE_BUTTON_TRIGGERED),this.getService(Re).enableUpgradeButton(!1)}catch(o){this.getService(k).catch("Error in _disableUpgradeButton: ",o)}}_onCommentModeChange(){this.getService(k).log("%c[WB] Calling FUNCTION: onCommentModeChange","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_COMMENT_MODE_CHANGE_TRIGGERED),this.getService(Re).addCommentModeChange()}catch(o){return this.getService(k).catch("Error in _onCommentModeChange: ",o),ce(!1)}}_enableAttachment(){this.getService(k).log("%c[WB] Calling FUNCTION: enableAttachment","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_ATTACHMENTS_TRIGGERED),this.getService(Re).enableAttachment(!0)}catch(o){this.getService(k).catch("Error in _enableAttachment: ",o)}}_disableAttachment(){this.getService(k).log("%c[WB] Calling FUNCTION: disableAttachment","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_ATTACHMENTS_TRIGGERED),this.getService(Re).enableAttachment(!1)}catch(o){this.getService(k).catch("Error in _disableAttachment: ",o)}}_enableAttachmentDownload(){this.getService(k).log("%c[WB] Calling FUNCTION: enableAttachmentDownload","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_ATTACHMENT_DOWNLOAD_TRIGGERED),this.getService(Re).enableAttachmentDownload()}catch(o){this.getService(k).catch("Error in _enableAttachmentDownload: ",o)}}_disableAttachmentDownload(){this.getService(k).log("%c[WB] Calling FUNCTION: disableAttachmentDownload","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_ATTACHMENT_DOWNLOAD_TRIGGERED),this.getService(Re).disableAttachmentDownload()}catch(o){this.getService(k).catch("Error in _disableAttachmentDownload: ",o)}}_isUserGlobalContact(){this.getService(k).log("%c[WB] Calling FUNCTION: isUserGlobalContact","color: green;");try{return this.trackEvent(Y.Events.Comments.IS_USER_GLOBAL_CONTACT_TRIGGERED),this.getService(Re).isUserGlobalContact$()}catch(o){return this.getService(k).catch("Error in _isUserGlobalContact: ",o),ce(!1)}}_enableDeviceInfo(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDeviceInfo","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DEVICE_INFO_TRIGGERED),this.getService(Re).showScreenSizeInfo(!0)}catch(o){this.getService(k).catch("Error in _enableDeviceInfo: ",o)}}_disableDeviceInfo(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDeviceInfo","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DEVICE_INFO_TRIGGERED),this.getService(Re).showScreenSizeInfo(!1)}catch(o){this.getService(k).catch("Error in _disableDeviceInfo: ",o)}}_enableCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_COMMENT_MODE_TRIGGERED),this.getService(Re).enableAddCommentMode()}catch(o){this.getService(k).catch("Error in _enableCommentMode: ",o)}}_disableCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_COMMENT_MODE_TRIGGERED),this.getService(Re).disableAddCommentMode()}catch(o){this.getService(k).catch("Error in _disableCommentMode: ",o)}}_enablePersistentCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePersistentCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_PERSISTENT_COMMENT_MODE_TRIGGERED),this.getService(Re).enablePersistentCommentMode()}catch(o){this.getService(k).catch("Error in _enablePersistentCommentMode: ",o)}}_disablePersistentCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePersistentCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_PERSISTENT_COMMENT_MODE_TRIGGERED),this.getService(Re).disablePersistentCommentMode()}catch(o){this.getService(k).catch("Error in _disablePersistentCommentMode: ",o)}}_showCommentIndex(o){this.getService(k).log("%c[WB] Calling FUNCTION: showCommentIndex","color: green;");try{this.trackEvent(Y.Events.Comments.SHOW_COMMENT_INDEX_TRIGGERED,{payload:{show:o}}),this.getService(Re).showCommentIndex(o)}catch(r){this.getService(k).catch("Error in _showCommentIndex: ",r)}}_enableCommentIndex(){this.getService(k).log("%c[WB] Calling FUNCTION: enableCommentIndex","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_COMMENT_INDEX_TRIGGERED),this.getService(Re).showCommentIndex(!0)}catch(o){this.getService(k).catch("Error in _enableCommentIndex: ",o)}}_disableCommentIndex(){this.getService(k).log("%c[WB] Calling FUNCTION: disableCommentIndex","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_COMMENT_INDEX_TRIGGERED),this.getService(Re).showCommentIndex(!1)}catch(o){this.getService(k).catch("Error in _disableCommentIndex: ",o)}}_enablePopoverMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePopoverMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_POPOVER_MODE_TRIGGERED),this.getService(Re).enablePopoverMode()}catch(o){this.getService(k).catch("Error in _enablePopoverMode: ",o)}}_disablePopoverMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePopoverMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_POPOVER_MODE_TRIGGERED),this.getService(Re).disablePopoverMode()}catch(o){this.getService(k).catch("Error in _disablePopoverMode: ",o)}}_enableDialogOnHover(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDialogOnHover","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DIALOG_ON_HOVER_TRIGGERED),this.getService(Re).setEnableDialogOnHover(!0)}catch(o){this.getService(k).catch("Error in _enableDialogOnHover: ",o)}}_disableDialogOnHover(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDialogOnHover","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DIALOG_ON_HOVER_TRIGGERED),this.getService(Re).setEnableDialogOnHover(!1)}catch(o){this.getService(k).catch("Error in _disableDialogOnHover: ",o)}}_enablePopoverTriangleComponent(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePopoverTriangleComponent","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_POPOVER_TRIANGLE_COMPONENT_TRIGGERED),this.getService(Re).enablePopoverTriangleComponent()}catch(o){this.getService(k).catch("Error in _enablePopoverTriangleComponent: ",o)}}_disablePopoverTriangleComponent(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePopoverTriangleComponent","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_POPOVER_TRIANGLE_COMPONENT_TRIGGERED),this.getService(Re).disablePopoverTriangleComponent()}catch(o){this.getService(k).catch("Error in _disablePopoverTriangleComponent: ",o)}}_enableDialogOnTargetElementClick(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDialogOnTargetElementClick","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DIALOG_ON_TARGET_ELEMENT_CLICK_TRIGGERED),this.getService(Re).setEnableDialogOnTargetElementClick(!0)}catch(o){this.getService(k).catch("Error in _enableDialogOnTargetElementClick: ",o)}}_disableDialogOnTargetElementClick(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDialogOnTargetElementClick","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DIALOG_ON_TARGET_ELEMENT_CLICK_TRIGGERED),this.getService(Re).setEnableDialogOnTargetElementClick(!1)}catch(o){this.getService(k).catch("Error in _disableDialogOnTargetElementClick: ",o)}}_enablePriority(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePriority","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_PRIORITY_TRIGGERED),this.getService(Re).setEnablePriority(!0)}catch(o){this.getService(k).catch("Error in _enablePriority: ",o)}}_disablePriority(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePriority","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_PRIORITY_TRIGGERED),this.getService(Re).setEnablePriority(!1)}catch(o){this.getService(k).catch("Error in _disablePriority: ",o)}}_enableStatus(){this.getService(k).log("%c[WB] Calling FUNCTION: enableStatus","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_STATUS_TRIGGERED),this.getService(Re).setEnableStatus(!0)}catch(o){this.getService(k).catch("Error in _enableStatus: ",o)}}_disableStatus(){this.getService(k).log("%c[WB] Calling FUNCTION: disableStatus","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_STATUS_TRIGGERED),this.getService(Re).setEnableStatus(!1)}catch(o){this.getService(k).catch("Error in _disableStatus: ",o)}}_enableVisibilityOptions(){this.getService(k).log("%c[WB] Calling FUNCTION: enableVisibilityOptions","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_VISIBILITY_OPTIONS_TRIGGERED),this.getService(Re).setEnableVisibilityOptions(!0)}catch(o){this.getService(k).catch("Error in _enableVisibilityOptions: ",o)}}_disableVisibilityOptions(){this.getService(k).log("%c[WB] Calling FUNCTION: disableVisibilityOptions","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_VISIBILITY_OPTIONS_TRIGGERED),this.getService(Re).setEnableVisibilityOptions(!1)}catch(o){this.getService(k).catch("Error in _disableVisibilityOptions: ",o)}}_enableResolveButton(){this.getService(k).log("%c[WB] Calling FUNCTION: enableResolveButton","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_RESOLVE_BUTTON_TRIGGERED),this.getService(Re).setEnableResolve(!0)}catch(o){this.getService(k).catch("Error in _enableResolveButton: ",o)}}_disableResolveButton(){this.getService(k).log("%c[WB] Calling FUNCTION: disableResolveButton","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_RESOLVE_BUTTON_TRIGGERED),this.getService(Re).setEnableResolve(!1)}catch(o){this.getService(k).catch("Error in _disableResolveButton: ",o)}}_enableGhostComments(){this.getService(k).log("%c[WB] Calling FUNCTION: enableGhostComments","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_GHOST_COMMENTS_TRIGGERED),this.getService(Re).enableGhostComments()}catch(o){this.getService(k).catch("Error in _enableGhostCommentsInDOM: ",o)}}_disableGhostComments(){this.getService(k).log("%c[WB] Calling FUNCTION: disableGhostComments","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_GHOST_COMMENTS_TRIGGERED),this.getService(Re).disableGhostComments()}catch(o){this.getService(k).catch("Error in _disableGhostComments: ",o)}}_enableGhostCommentsIndicator(){this.getService(k).log("%c[WB] Calling FUNCTION: enableGhostCommentsIndicator","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_GHOST_COMMENTS_INDICATOR_TRIGGERED),this.getService(Re).enableGhostCommentsMessage()}catch(o){this.getService(k).catch("Error in _enableGhostCommentsIndicator: ",o)}}_disableGhostCommentsIndicator(){this.getService(k).log("%c[WB] Calling FUNCTION: disableGhostCommentsIndicator","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_GHOST_COMMENTS_INDICATOR_TRIGGERED),this.getService(Re).disableGhostCommentsMessage()}catch(o){this.getService(k).catch("Error in _disableGhostCommentsIndicator: ",o)}}_setCustomStatus(o){this.getService(k).log("%c[WB] Calling FUNCTION: setCustomStatus","color: green;");try{this.trackEvent(Y.Events.Comments.SET_CUSTOM_STATUS_TRIGGERED,{payload:{customStatuses:o}}),this.getService(Re).setCustomStatuses(o)}catch(r){this.getService(k).catch("Error in _setCustomStatus: ",r)}}_enableInboxMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableInboxMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_INBOX_MODE_TRIGGERED),this.getService(Re).enableInboxMode()}catch(o){this.getService(k).catch("Error in _enableInboxMode: ",o)}}_setCustomPriority(o){this.getService(k).log("%c[WB] Calling FUNCTION: setCustomPriority","color: green;");try{this.trackEvent(Y.Events.Comments.SET_CUSTOM_PRIORITY_TRIGGERED,{payload:{customPriorities:o}}),this.getService(Re).setCustomPriorities(o)}catch(r){this.getService(k).catch("Error in _setCustomPriority: ",r)}}_setCustomCategory(o){this.getService(k).log("%c[WB] Calling FUNCTION: setCustomCategory","color: green;");try{this.trackEvent(Y.Events.Comments.SET_CUSTOM_CATEGORY_TRIGGERED,{payload:{customCategories:o}}),this.getService(Re).setCustomCategories(o)}catch(r){this.getService(k).catch("Error in _setCustomCategory: ",r)}}_disableInboxMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableInboxMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_INBOX_MODE_TRIGGERED),this.getService(Re).disableInboxMode()}catch(o){this.getService(k).catch("Error in _disableInboxMode: ",o)}}_enableAutoCategorize(){this.getService(k).log("%c[WB] Calling FUNCTION: enableAutoCategorize","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_AUTO_CATEGORIZE_TRIGGERED),this.getService(Re).setEnableAutoCategorize(!0)}catch(o){this.getService(k).catch("Error in _enableAutoCategorize: ",o)}}_disableAutoCategorize(){this.getService(k).log("%c[WB] Calling FUNCTION: disableAutoCategorize","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_AUTO_CATEGORIZE_TRIGGERED),this.getService(Re).setEnableAutoCategorize(!1)}catch(o){this.getService(k).catch("Error in _disableAutoCategorize: ",o)}}_enableDarkMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDarkMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DARK_MODE_TRIGGERED),this.getService(Re).setCommentContainerDarkMode(!0)}catch(o){this.getService(k).catch("Error in _enableDarkMode: ",o)}}_disableDarkMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDarkMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DARK_MODE_TRIGGERED),this.getService(Re).setCommentContainerDarkMode(!1)}catch(o){this.getService(k).catch("Error in _disableDarkMode: ",o)}}_setContextProvider(o){try{this.trackEvent(Y.Events.Comments.SET_CONTEXT_PROVIDER_TRIGGERED,{payload:{}}),this.getService(Re).setContextProvider(o)}catch(r){this.getService(k).catch("Error in _setContextProvider: ",r)}}_enableSuggestionMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSuggestionMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SUGGESTION_MODE_TRIGGERED),this.getService(Re).setSuggestionMode(!0)}catch(o){this.getService(k).catch("Error in _enableSuggestionMode: ",o)}}_disableSuggestionMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSuggestionMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SUGGESTION_MODE_TRIGGERED),this.getService(Re).setSuggestionMode(!1)}catch(o){this.getService(k).catch("Error in _disableSuggestionMode: ",o)}}_enableMobileMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableMobileMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_MOBILE_MODE_TRIGGERED),this.getService(Re).setMobileMode(!0)}catch(o){this.getService(k).catch("Error in _enableMobileMode: ",o)}}_disableMobileMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableMobileMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_MOBILE_MODE_TRIGGERED),this.getService(Re).setMobileMode(!1)}catch(o){this.getService(k).catch("Error in _disableMobileMode: ",o)}}_enableInlineCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableInlineCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_INLINE_COMMENT_MODE_TRIGGERED),this.getService(Re).enableInlineCommentMode()}catch(o){this.getService(k).catch("Error in _enableInlineCommentMode: ",o)}}_disableInlineCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableInlineCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_INLINE_COMMENT_MODE_TRIGGERED),this.getService(Re).disableInlineCommentMode()}catch(o){this.getService(k).catch("Error in _disableInlineCommentMode: ",o)}}_enableMinimap(){this.getService(k).log("%c[WB] Calling FUNCTION: enableMinimap","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_MINIMAP_TRIGGERED),this.getService(Re).enableMinimap()}catch(o){this.getService(k).catch("Error in _enableMinimap: ",o)}}_disableMinimap(){this.getService(k).log("%c[WB] Calling FUNCTION: disableMinimap","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_MINIMAP_TRIGGERED),this.getService(Re).disableMinimap()}catch(o){this.getService(k).catch("Error in _disableMinimap: ",o)}}_showCommentsOnDom(){this.getService(k).log("%c[WB] Calling FUNCTION: showCommentsOnDom","color: green;");try{this.trackEvent(Y.Events.Comments.SHOW_COMMENTS_ON_DOM_TRIGGERED),this.getService(Re).showCommentsOnDom()}catch(o){this.getService(k).catch("Error in _showCommentsOnDom: ",o)}}_hideCommentsOnDom(){this.getService(k).log("%c[WB] Calling FUNCTION: hideCommentsOnDom","color: green;");try{this.trackEvent(Y.Events.Comments.HIDE_COMMENTS_ON_DOM_TRIGGERED),this.getService(Re).hideCommentsOnDom()}catch(o){this.getService(k).catch("Error in _hideCommentsOnDom: ",o)}}_enableCommentTool(){this.getService(k).log("%c[WB] Calling FUNCTION: enableCommentTool","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_COMMENT_TOOL_TRIGGERED),this.getService(Re).enableCommentTool()}catch(o){this.getService(k).catch("Error in _enableCommentTool: ",o)}}_disableCommentTool(){this.getService(k).log("%c[WB] Calling FUNCTION: disableCommentTool","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_COMMENT_TOOL_TRIGGERED),this.getService(Re).disableCommentTool()}catch(o){this.getService(k).catch("Error in _disableCommentTool: ",o)}}_setTotalMediaLength(o){this.getService(k).log("%c[WB] Calling FUNCTION: setTotalMediaLength","color: green;");try{this.trackEvent(Y.Events.Comments.SET_TOTAL_MEDIA_LENGTH_TRIGGERED,{payload:{length:o}}),this.getService(Re).setTotalMediaLength(o)}catch(r){this.getService(k).catch("Error in _setTotalMediaLength: ",r)}}_onCommentAdd(){this.getService(k).log("%c[WB] Calling FUNCTION: onCommentAdd","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_COMMENT_ADD_TRIGGERED),this.getService(Re).onCommentAdd$()}catch(o){return this.getService(k).catch("Error in _onCommentAdd: ",o),ce()}}_onCommentUpdate(){this.getService(k).log("%c[WB] Calling FUNCTION: onCommentUpdate","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_COMMENT_UPDATE_TRIGGERED),this.getService(Re).onCommentUpdate$()}catch(o){return this.getService(k).catch("Error in _onCommentUpdate: ",o),ce()}}_addCommentOnSelectedText(){this.getService(k).log("%c[WB] Calling FUNCTION: addCommentOnSelectedText","color: green;");try{this.trackEvent(Y.Events.Comments.ADD_COMMENT_ON_SELECTED_TEXT_TRIGGERED),this.getService(Re).addCommentOnSelectedText()}catch(o){this.getService(k).catch("Error in _addCommentOnSelectedText: ",o)}}_enableSidebarUrlNavigation(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSidebarUrlNavigation","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SIDEBAR_URL_NAVIGATION_TRIGGERED),this.getService(Re).enableSidebarUrlNavigation()}catch(o){this.getService(k).catch("Error in _enableSidebarUrlNavigation: ",o)}}_disableSidebarUrlNavigation(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSidebarUrlNavigation","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SIDEBAR_URL_NAVIGATION_TRIGGERED),this.getService(Re).disableSidebarUrlNavigation()}catch(o){this.getService(k).catch("Error in _disableSidebarUrlNavigation: ",o)}}_setDStrategy(o){this.getService(k).log("%c[WB] Calling FUNCTION: setDStrategy","color: green;");try{this.trackEvent(Y.Events.Comments.SET_D_STRATEGY_TRIGGERED,{payload:{strategy:o}}),this.getService(Re).setDetectionStrategy(o)}catch(r){this.getService(k).catch("Error in _setDStrategy: ",r)}}_enableSidebarButtonOnCommentDialog(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSidebarButtonOnCommentDialog","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SIDEBAR_BUTTON_ON_COMMENT_DIALOG_TRIGGERED),this.getService(Re).enableSidebarButtonOnCommentDialog()}catch(o){this.getService(k).catch("Error in _enableSidebarButtonOnCommentDialog: ",o)}}_disableSidebarButtonOnCommentDialog(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSidebarButtonOnCommentDialog","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SIDEBAR_BUTTON_ON_COMMENT_DIALOG_TRIGGERED),this.getService(Re).disableSidebarButtonOnCommentDialog()}catch(o){this.getService(k).catch("Error in _disableSidebarButtonOnCommentDialog: ",o)}}_onSidebarButtonOnCommentDialogClick(){this.getService(k).log("%c[WB] Calling FUNCTION: onSidebarButtonOnCommentDialogClick","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_SIDEBAR_BUTTON_ON_COMMENT_DIALOG_CLICK_TRIGGERED),this.getService(Re).getSidebarButtonOnCommentDialogClick$()}catch(o){return this.getService(k).catch("Error in _onSidebarButtonOnCommentDialogClick: ",o),ce(null)}}_enableReactions(){this.getService(k).log("%c[WB] Calling FUNCTION: enableReactions","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_REACTIONS_TRIGGERED),this.getService(Re).enableReactions()}catch(o){this.getService(k).catch("Error in _enableReactions: ",o)}}_disableReactions(){this.getService(k).log("%c[WB] Calling FUNCTION: disableReactions","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_REACTIONS_TRIGGERED),this.getService(Re).disableReactions()}catch(o){this.getService(k).catch("Error in _disableReactions: ",o)}}_enableAnonymousEmail(){this.getService(k).log("%c[WB] Calling FUNCTION: enableAnonymousEmail","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_ANONYMOUS_EMAIL_TRIGGERED),this.getService(Re).enableAnonymousEmail()}catch(o){this.getService(k).catch("Error in _enableAnonymousEmail: ",o)}}_disableAnonymousEmail(){this.getService(k).log("%c[WB] Calling FUNCTION: disableAnonymousEmail","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_ANONYMOUS_EMAIL_TRIGGERED),this.getService(Re).disableAnonymousEmail()}catch(o){this.getService(k).catch("Error in _disableAnonymousEmail: ",o)}}_setRecordings(o){this.getService(k).log("%c[WB] Calling FUNCTION: setRecordings","color: green;");try{this.trackEvent(Y.Events.Comments.SET_RECORDINGS_TRIGGERED,{payload:{allowedRecordings:o}}),typeof o=="string"&&(o=o?.split(",")?.map(r=>r.trim())),this.getService(Re).setAllowedRecordings(o)}catch(r){this.getService(k).catch("Error in _setRecordings: ",r)}}_addCommentOnElement(o){this.getService(k).log("%c[WB] Calling FUNCTION: addCommentOnElement","color: green;");try{this.trackEvent(Y.Events.Comments.ADD_COMMENT_ON_ELEMENT_TRIGGERED,{payload:{data:o}}),this.getService(Re).addCommentOnElement(o)}catch(r){this.getService(k).catch("Error in _addCommentOnElement: ",r)}}_enablePrivateCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePrivateCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_PRIVATE_COMMENT_MODE_TRIGGERED),this.getService(Re).enablePrivateCommentMode()}catch(o){this.getService(k).catch("Error in _enablePrivateCommentMode: ",o)}}_disablePrivateCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePrivateCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_PRIVATE_COMMENT_MODE_TRIGGERED),this.getService(Re).disablePrivateCommentMode()}catch(o){this.getService(k).catch("Error in _disablePrivateCommentMode: ",o)}}_enablePrivateMode(o){this.getService(k).log("%c[WB] Calling FUNCTION: enablePrivateMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_PRIVATE_MODE_TRIGGERED,{payload:{config:o}}),this.getService(Re).enablePrivateMode(o)}catch(r){this.getService(k).catch("Error in _enablePrivateMode: ",r)}}_disablePrivateMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePrivateMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_PRIVATE_MODE_TRIGGERED),this.getService(Re).disablePrivateMode()}catch(o){this.getService(k).catch("Error in _disablePrivateMode: ",o)}}_enableScrollToComment(){this.getService(k).log("%c[WB] Calling FUNCTION: enableScrollToComment","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SCROLL_TO_COMMENT_TRIGGERED),this.getService(Re).enableScrollToComment()}catch(o){this.getService(k).catch("Error in _enableScrollToComment: ",o)}}_disableScrollToComment(){this.getService(k).log("%c[WB] Calling FUNCTION: disableScrollToComment","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SCROLL_TO_COMMENT_TRIGGERED),this.getService(Re).disableScrollToComment()}catch(o){this.getService(k).catch("Error in _disableScrollToComment: ",o)}}_enableUserMentions(){this.getService(k).log("%c[WB] Calling FUNCTION: enableUserMentions","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_USER_MENTIONS_TRIGGERED),this.getService(Re).enableUserMentions()}catch(o){this.getService(k).catch("Error in _enableUserMentions: ",o)}}_disableUserMentions(){this.getService(k).log("%c[WB] Calling FUNCTION: disableUserMentions","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_USER_MENTIONS_TRIGGERED),this.getService(Re).disableUserMentions()}catch(o){this.getService(k).catch("Error in _disableUserMentions: ",o)}}_setCommentSidebarFilters(o){this.getService(k).log("%c[WB] Calling FUNCTION: setCommentSidebarFilters","color: green;");try{this.trackEvent(Y.Events.Comments.SET_COMMENT_SIDEBAR_FILTERS_TRIGGERED,{payload:{filters:o}}),this.getService(Re).setCommentSidebarFilters(o)}catch(r){this.getService(k).catch("Error in _setCommentSidebarFilters: ",r)}}_setSystemFiltersOperator(o){this.getService(k).log("%c[WB] Calling FUNCTION: setSystemFiltersOperator","color: green;");try{this.trackEvent(Y.Events.Comments.SET_SYSTEM_FILTERS_OPERATOR_TRIGGERED,{payload:{operator:o}}),this.getService(Re).setCommentSidebarSystemFiltersOperator(o)}catch(r){this.getService(k).catch("Error in _setSystemFiltersOperator: ",r)}}_enableCommentPinHighlighter(){this.getService(k).log("%c[WB] Calling FUNCTION: enableCommentPinHighlighter","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_COMMENT_PIN_HIGHLIGHTER_TRIGGERED),this.getService(Re).enableCommentPinHighlighter()}catch(o){this.getService(k).catch("Error in _enableCommentPinHighlighter: ",o)}}_disableCommentPinHighlighter(){this.getService(k).log("%c[WB] Calling FUNCTION: disableCommentPinHighlighter","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_COMMENT_PIN_HIGHLIGHTER_TRIGGERED),this.getService(Re).disableCommentPinHighlighter()}catch(o){this.getService(k).catch("Error in _disableCommentPinHighlighter: ",o)}}_enableDeleteOnBackspace(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDeleteOnBackspace","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DELETE_ON_BACKSPACE_TRIGGERED),this.getService(Re).enableDeleteOnBackspace()}catch(o){this.getService(k).catch("Error in _enableDeleteOnBackspace: ",o)}}_disableDeleteOnBackspace(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDeleteOnBackspace","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DELETE_ON_BACKSPACE_TRIGGERED),this.getService(Re).disableDeleteOnBackspace()}catch(o){this.getService(k).catch("Error in _disableDeleteOnBackspace: ",o)}}_enableHotkey(){this.getService(k).log("%c[WB] Calling FUNCTION: enableHotkey","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_HOTKEY_TRIGGERED),this.getService(Re).enableHotkey()}catch(o){this.getService(k).catch("Error in _enableHotkey: ",o)}}_disableHotkey(){this.getService(k).log("%c[WB] Calling FUNCTION: disableHotkey","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_HOTKEY_TRIGGERED),this.getService(Re).disableHotkey()}catch(o){this.getService(k).catch("Error in _disableHotkey: ",o)}}_enableDeviceIndicatorOnCommentPins(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDeviceIndicatorOnCommentPins","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DEVICE_INDICATOR_ON_COMMENT_PINS_TRIGGERED),this.getService(Re).enableDeviceIndicatorOnCommentPins()}catch(o){this.getService(k).catch("Error in _enableDeviceIndicatorOnCommentPins: ",o)}}_disableDeviceIndicatorOnCommentPins(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDeviceIndicatorOnCommentPins","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DEVICE_INDICATOR_ON_COMMENT_PINS_TRIGGERED),this.getService(Re).disableDeviceIndicatorOnCommentPins()}catch(o){this.getService(k).catch("Error in _disableDeviceIndicatorOnCommentPins: ",o)}}_getElementRefByAnnotationId(o){this.getService(k).log("%c[WB] Calling FUNCTION: getElementRefByAnnotationId","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_ELEMENT_REF_BY_ANNOTATION_ID_TRIGGERED,{payload:{annotationId:o}}),this.getService(Re).getElementRefByAnnotationId(o)}catch(r){this.getService(k).catch("Error in _getElementRefByAnnotationId: ",r);return}}_scrollToCommentByAnnotationId(o){this.getService(k).log("%c[WB] Calling FUNCTION: scrollToCommentByAnnotationId","color: green;");try{this.trackEvent(Y.Events.Comments.SCROLL_TO_COMMENT_BY_ANNOTATION_ID_TRIGGERED,{payload:{annotationId:o}}),this.getService(Re).scrollToCommentByAnnotationId(o)}catch(r){this.getService(k).catch("Error in _scrollToCommentByAnnotationId: ",r)}}_selectCommentByAnnotationId(o){this.getService(k).log("%c[WB] Calling FUNCTION: selectCommentByAnnotationId","color: green;");try{this.trackEvent(Y.Events.Comments.SELECT_COMMENT_BY_ANNOTATION_ID_TRIGGERED,{payload:{annotationId:o}}),this.getService(Re).selectCommentByAnnotationId(o)}catch(r){this.getService(k).catch("Error in _selectCommentByAnnotationId: ",r)}}_enableRecordingSummary(){this.getService(k).log("%c[WB] Calling FUNCTION: enableRecordingSummary","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_RECORDING_SUMMARY_TRIGGERED),this.getService(Re).enableRecordingSummary()}catch(o){this.getService(k).catch("Error in _enableRecordingSummary: ",o)}}_disableRecordingSummary(){this.getService(k).log("%c[WB] Calling FUNCTION: disableRecordingSummary","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_RECORDING_SUMMARY_TRIGGERED),this.getService(Re).disableRecordingSummary()}catch(o){this.getService(k).catch("Error in _disableRecordingSummary: ",o)}}_enableRecordingTranscription(){this.getService(k).log("%c[WB] Calling FUNCTION: enableRecordingTranscription","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_RECORDING_TRANSCRIPTION_TRIGGERED),this.getService(ho).enableRecordingTranscription()}catch(o){this.getService(k).catch("Error in _enableRecordingTranscription: ",o)}}_disableRecordingTranscription(){this.getService(k).log("%c[WB] Calling FUNCTION: disableRecordingTranscription","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_RECORDING_TRANSCRIPTION_TRIGGERED),this.getService(ho).disableRecordingTranscription()}catch(o){this.getService(k).catch("Error in _disableRecordingTranscription: ",o)}}_enableRecordingCountdown(){this.getService(k).log("%c[WB] Calling FUNCTION: enableRecordingCountdown","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_RECORDING_COUNTDOWN_TRIGGERED),this.getService(Re).enableRecordingCountdown()}catch(o){this.getService(k).catch("Error in _enableRecordingCountdown: ",o)}}_disableRecordingCountdown(){this.getService(k).log("%c[WB] Calling FUNCTION: disableRecordingCountdown","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_RECORDING_COUNTDOWN_TRIGGERED),this.getService(Re).disableRecordingCountdown()}catch(o){this.getService(k).catch("Error in _disableRecordingCountdown: ",o)}}_setUnreadIndicatorMode(o){this.getService(k).log("%c[WB] Calling FUNCTION: setUnreadIndicatorMode","color: green;");try{this.trackEvent(Y.Events.Comments.SET_UNREAD_INDICATOR_MODE_TRIGGERED,{payload:{mode:o}}),this.getService(Re).setUnreadIndicatorMode(o)}catch(r){this.getService(k).catch("Error in _setUnreadIndicatorMode: ",r)}}_enableEnterKeyToSubmit(){this.getService(k).log("%c[WB] Calling FUNCTION: enableEnterKeyToSubmit","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_ENTER_KEY_TO_SUBMIT_TRIGGERED),this.getService(Re).enableEnterKeyToSubmit()}catch(o){this.getService(k).catch("Error in _enableEnterKeyToSubmit: ",o)}}_disableEnterKeyToSubmit(){this.getService(k).log("%c[WB] Calling FUNCTION: disableEnterKeyToSubmit","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_ENTER_KEY_TO_SUBMIT_TRIGGERED),this.getService(Re).disableEnterKeyToSubmit()}catch(o){this.getService(k).catch("Error in _disableEnterKeyToSubmit: ",o)}}_enablePinShadowDOM(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePinShadowDOM","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_PIN_SHADOW_DOM_TRIGGERED),this.getService(Re).enablePinShadowDOM()}catch(o){this.getService(k).catch("Error in _enablePinShadowDOM: ",o)}}_disablePinShadowDOM(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePinShadowDOM","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_PIN_SHADOW_DOM_TRIGGERED),this.getService(Re).disablePinShadowDOM()}catch(o){this.getService(k).catch("Error in _disablePinShadowDOM: ",o)}}_enableDialogShadowDOM(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDialogShadowDOM","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DIALOG_SHADOW_DOM_TRIGGERED),this.getService(Re).enableDialogShadowDOM()}catch(o){this.getService(k).catch("Error in _enableDialogShadowDOM: ",o)}}_disableDialogShadowDOM(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDialogShadowDOM","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DIALOG_SHADOW_DOM_TRIGGERED),this.getService(Re).disableDialogShadowDOM()}catch(o){this.getService(k).catch("Error in _disableDialogShadowDOM: ",o)}}_enableSidebarShadowDOM(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSidebarShadowDOM","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SIDEBAR_SHADOW_DOM_TRIGGERED),this.getService(Re).enableSidebarShadowDOM()}catch(o){this.getService(k).catch("Error in _enableSidebarShadowDOM: ",o)}}_disableSidebarShadowDOM(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSidebarShadowDOM","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SIDEBAR_SHADOW_DOM_TRIGGERED),this.getService(Re).disableSidebarShadowDOM()}catch(o){this.getService(k).catch("Error in _disableSidebarShadowDOM: ",o)}}_enableChangeDetectionInCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableChangeDetectionInCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_CHANGE_DETECTION_IN_COMMENT_MODE_TRIGGERED),this.getService(Re).enableChangeDetectionInCommentMode()}catch(o){this.getService(k).catch("Error in _enableChangeDetectionInCommentMode: ",o)}}_disableChangeDetectionInCommentMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableChangeDetectionInCommentMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_CHANGE_DETECTION_IN_COMMENT_MODE_TRIGGERED),this.getService(Re).disableChangeDetectionInCommentMode()}catch(o){this.getService(k).catch("Error in _disableChangeDetectionInCommentMode: ",o)}}_showResolvedCommentsOnDom(){this.getService(k).log("%c[WB] Calling FUNCTION: showResolvedCommentsOnDom","color: green;");try{this.trackEvent(Y.Events.Comments.SHOW_RESOLVED_COMMENTS_ON_DOM_TRIGGERED),this.getService(Re).showResolvedCommentsOnDom()}catch(o){this.getService(k).catch("Error in _showResolvedCommentsOnDom: ",o)}}_hideResolvedCommentsOnDom(){this.getService(k).log("%c[WB] Calling FUNCTION: hideResolvedCommentsOnDom","color: green;");try{this.trackEvent(Y.Events.Comments.HIDE_RESOLVED_COMMENTS_ON_DOM_TRIGGERED),this.getService(Re).hideResolvedCommentsOnDom()}catch(o){this.getService(k).catch("Error in _hideResolvedCommentsOnDom: ",o)}}_setCustomReactions(o){this.getService(k).log("%c[WB] Calling FUNCTION: setCustomReactions","color: green;");try{this.trackEvent(Y.Events.Comments.SET_CUSTOM_REACTIONS_TRIGGERED,{payload:{reactions:o}}),this.getService(Re).setCustomReactions(o)}catch(r){this.getService(k).catch("Error in _setCustomReactions: ",r)}}_onCommentSelectionChange(){this.getService(k).log("%c[WB] Calling FUNCTION: onCommentSelectionChange","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_COMMENT_SELECTION_CHANGE_TRIGGERED),this.getService(Re).onCommentSelectionChange$()}catch(o){return this.getService(k).catch("Error in _onCommentSelectionChange: ",o),ce(null)}}_getUnreadCommentCountByAnnotationId(o){this.getService(k).log("%c[WB] Calling FUNCTION: getUnreadCommentCountByAnnotationId","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_UNREAD_COMMENT_COUNT_BY_ANNOTATION_ID_TRIGGERED,{payload:{commentAnnotationId:o}}),this.getService(Re).getUnreadCommentCountByAnnotationId$(o)}catch(r){return this.getService(k).catch("Error in _getUnreadCommentCountByAnnotationId: ",r),ce(null)}}_getUnreadCommentAnnotationCountOnCurrentDocument(){this.getService(k).log("%c[WB] Calling FUNCTION: getUnreadCommentAnnotationCountOnCurrentDocument","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_UNREAD_COMMENT_ANNOTATION_COUNT_ON_CURRENT_DOCUMENT_TRIGGERED),this.getService(Re).getUnreadCommentAnnotationCountOnCurrentDocument$()}catch(o){return this.getService(k).catch("Error in _getUnreadCommentAnnotationCountOnCurrentDocument: ",o),ce(null)}}_getUnreadCommentCountOnCurrentDocument(){this.getService(k).log("%c[WB] Calling FUNCTION: getUnreadCommentCountOnCurrentDocument","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_UNREAD_COMMENT_COUNT_ON_CURRENT_DOCUMENT_TRIGGERED),this.getService(Re).getUnreadCommentCountOnCurrentDocument$()}catch(o){return this.getService(k).catch("Error in _getUnreadCommentCountOnCurrentDocument: ",o),ce(null)}}_getUnreadCommentAnnotationCountByLocationId(o){this.getService(k).log("%c[WB] Calling FUNCTION: getUnreadCommentAnnotationCountByLocationId","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_UNREAD_COMMENT_ANNOTATION_COUNT_BY_LOCATION_ID_TRIGGERED,{payload:{locationId:o}}),this.getService(Re).getUnreadCommentAnnotationCountByLocationId$(o)}catch(r){return this.getService(k).catch("Error in _getUnreadCommentAnnotationCountByLocationId: ",r),ce(null)}}_getUnreadCommentCountByLocationId(o){this.getService(k).log("%c[WB] Calling FUNCTION: getUnreadCommentCountByLocationId","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_UNREAD_COMMENT_COUNT_BY_LOCATION_ID_TRIGGERED,{payload:{locationId:o}}),this.getService(Re).getUnreadCommentCountByLocationId$(o)}catch(r){return this.getService(k).catch("Error in _getUnreadCommentCountByLocationId: ",r),ce(null)}}_updateCommentDialogPosition(){this.getService(k).log("%c[WB] Calling FUNCTION: updateCommentDialogPosition","color: green;");try{this.trackEvent(Y.Events.Comments.UPDATE_COMMENT_DIALOG_POSITION_TRIGGERED),this.getService(Re).updateCommentDialogPosition()}catch(o){this.getService(k).catch("Error in _updateCommentDialogPosition: ",o)}}_enableAreaComment(){this.getService(k).log("%c[WB] Calling FUNCTION: enableAreaComment","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_AREA_COMMENT_TRIGGERED),this.getService(Re).enableAreaComment()}catch(o){this.getService(k).catch("Error in _enableAreaComment: ",o)}}_disableAreaComment(){this.getService(k).log("%c[WB] Calling FUNCTION: disableAreaComment","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_AREA_COMMENT_TRIGGERED),this.getService(Re).disableAreaComment()}catch(o){this.getService(k).catch("Error in _disableAreaComment: ",o)}}_setPinCursorImage(o){this.getService(k).log("%c[WB] Calling FUNCTION: setPinCursorImage","color: green;");try{this.trackEvent(Y.Events.Comments.SET_PIN_CURSOR_IMAGE_TRIGGERED,{payload:{image:o}}),this.getService(Re).setPinCursorImage(o)}catch(r){this.getService(k).catch("Error in _setPinCursorImage: ",r)}}_addManualComment(o){this.getService(k).log("%c[WB] Calling FUNCTION: addManualComment","color: green;");try{return this.trackEvent(Y.Events.Comments.ADD_MANUAL_COMMENT_TRIGGERED,{payload:{config:o}}),this.getService(Re).addManualComment(o)}catch(r){return this.getService(k).catch("Error in _addManualComment: ",r),Promise.resolve()}}_createCustomListDataOnAnnotation(o){this.getService(k).log("%c[WB] Calling FUNCTION: createCustomListDataOnAnnotation","color: green;");try{this.trackEvent(Y.Events.Comments.CREATE_CUSTOM_LIST_DATA_ON_ANNOTATION_TRIGGERED,{payload:{data:o}}),this.getService(Re).createCustomListDataOnAnnotation(o)}catch(r){this.getService(k).catch("Error in _createCustomListDataOnAnnotation: ",r)}}_createCustomListDataOnComment(o){this.getService(k).log("%c[WB] Calling FUNCTION: createCustomListDataOnComment","color: green;");try{return this.trackEvent(Y.Events.Comments.CREATE_CUSTOM_LIST_DATA_ON_COMMENT_TRIGGERED,{payload:{data:o}}),this.getService(Ec).create(o)}catch(r){this.getService(k).catch("Error in _createCustomListDataOnComment: ",r)}}_excludeLocationIdsFromSidebar(o){this.getService(k).log("%c[WB] Calling FUNCTION: excludeLocationIdsFromSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.EXCLUDE_LOCATION_IDS_FROM_SIDEBAR_TRIGGERED,{payload:{locationIds:o}}),this.getService(Re).setExcludeLocationIdsFromSidebar(o)}catch(r){this.getService(k).catch("Error in _excludeLocationIdsFromSidebar: ",r)}}_enableBubbleOnPin(){this.getService(k).log("%c[WB] Calling FUNCTION: enableBubbleOnPin","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_BUBBLE_ON_PIN_TRIGGERED),this.getService(Re).enableBubbleOnPin()}catch(o){this.getService(k).catch("Error in _enableBubbleOnPin: ",o)}}_disableBubbleOnPin(){this.getService(k).log("%c[WB] Calling FUNCTION: disableBubbleOnPin","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_BUBBLE_ON_PIN_TRIGGERED),this.getService(Re).disableBubbleOnPin()}catch(o){this.getService(k).catch("Error in _disableBubbleOnPin: ",o)}}_enableBubbleOnPinHover(){this.getService(k).log("%c[WB] Calling FUNCTION: enableBubbleOnPinHover","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_BUBBLE_ON_PIN_HOVER_TRIGGERED),this.getService(Re).enableBubbleOnPinHover()}catch(o){this.getService(k).catch("Error in _enableBubbleOnPinHover: ",o)}}_disableBubbleOnPinHover(){this.getService(k).log("%c[WB] Calling FUNCTION: disableBubbleOnPinHover","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_BUBBLE_ON_PIN_HOVER_TRIGGERED),this.getService(Re).disableBubbleOnPinHover()}catch(o){this.getService(k).catch("Error in _disableBubbleOnPinHover: ",o)}}_enablePinDrag(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePinDrag","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_PIN_DRAG_TRIGGERED),this.getService(Re).enablePinDrag()}catch(o){this.getService(k).catch("Error in _enablePinDrag: ",o)}}_disablePinDrag(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePinDrag","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_PIN_DRAG_TRIGGERED),this.getService(Re).disablePinDrag()}catch(o){this.getService(k).catch("Error in _disablePinDrag: ",o)}}_enableMultiThread(){this.getService(k).log("%c[WB] Calling FUNCTION: enableMultiThread","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_MULTI_THREAD_TRIGGERED),this.getService(Re).enableMultiThread()}catch(o){this.getService(k).catch("Error in _enableMultiThread: ",o)}}_disableMultiThread(){this.getService(k).log("%c[WB] Calling FUNCTION: disableMultiThread","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_MULTI_THREAD_TRIGGERED),this.getService(Re).disableMultiThread()}catch(o){this.getService(k).catch("Error in _disableMultiThread: ",o)}}_enableGroupMatchedComments(){this.getService(k).log("%c[WB] Calling FUNCTION: enableGroupMatchedComments","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_GROUP_MATCHED_COMMENTS_TRIGGERED),this.getService(Re).enableGroupMatchedComments()}catch(o){this.getService(k).catch("Error in _enableGroupMatchedComments: ",o)}}_disableGroupMatchedComments(){this.getService(k).log("%c[WB] Calling FUNCTION: disableGroupMatchedComments","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_GROUP_MATCHED_COMMENTS_TRIGGERED),this.getService(Re).disableGroupMatchedComments()}catch(o){this.getService(k).catch("Error in _disableGroupMatchedComments: ",o)}}_updateContext(o,r,e){this.getService(k).log("%c[WB] Calling FUNCTION: updateContext","color: green;");try{return this.trackEvent(Y.Events.Comments.UPDATE_CONTEXT_TRIGGERED,{payload:{annotationId:o,context:r,config:e}}),this.getService(Re).updateCommentAnnotationContext(o,r,e)}catch(t){return this.getService(k).catch("Error in _updateContext: ",t),Promise.resolve()}}_updateVisibility(o){this.getService(k).log("%c[WB] Calling FUNCTION: updateVisibility","color: green;");try{return this.trackEvent(Y.Events.Comments.UPDATE_VISIBILITY_TRIGGERED,{payload:{visibility:o}}),this.getService(Mn).updateVisibility(o)}catch(r){return this.getService(k).catch("Error in _updateVisibility: ",r),Promise.resolve()}}_getSelectedComments(){this.getService(k).log("%c[WB] Calling FUNCTION: getSelectedComments","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_SELECTED_COMMENTS_TRIGGERED),this.getService(Ve).getSelectedComments$()}catch(o){return this.getService(k).catch("Error in _getSelectedComments: ",o),ce([])}}_enableDeleteReplyConfirmation(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDeleteReplyConfirmation","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DELETE_REPLY_CONFIRMATION_TRIGGERED),this.getService(Re).enableDeleteReplyConfirmation()}catch(o){this.getService(k).catch("Error in _enableDeleteReplyConfirmation: ",o)}}_disableDeleteReplyConfirmation(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDeleteReplyConfirmation","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DELETE_REPLY_CONFIRMATION_TRIGGERED),this.getService(Re).disableDeleteReplyConfirmation()}catch(o){this.getService(k).catch("Error in _disableDeleteReplyConfirmation: ",o)}}_onCopyLink(){this.getService(k).log("%c[WB] Calling FUNCTION: onCopyLink","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_COPY_LINK_TRIGGERED),this.getService(Re).getCopyLink$()}catch(o){return this.getService(k).catch("Error in _onCopyLink: ",o),ce("")}}_getCommentAnnotationById(o){this.getService(k).log("%c[WB] Calling FUNCTION: getCommentAnnotationById","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_COMMENT_ANNOTATION_BY_ID_TRIGGERED,{payload:{config:o}}),this.getService(Re).getCommentAnnotationById(o)}catch(r){return this.getService(k).catch("Error in _getCommentAnnotationById: ",r),ce(null)}}_enableCollapsedComments(){this.getService(k).log("%c[WB] Calling FUNCTION: enableCollapsedComments","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_COLLAPSED_COMMENTS_TRIGGERED),this.getService(Re).enableCollapsedComments()}catch(o){this.getService(k).catch("Error in _enableCollapsedComments: ",o)}}_disableCollapsedComments(){this.getService(k).log("%c[WB] Calling FUNCTION: disableCollapsedComments","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_COLLAPSED_COMMENTS_TRIGGERED),this.getService(Re).disableCollapsedComments()}catch(o){this.getService(k).catch("Error in _disableCollapsedComments: ",o)}}_onCommentSidebarActionButtonClick(){this.getService(k).log("%c[WB] Calling FUNCTION: onCommentSidebarActionButtonClick","color: green;");try{return this.getService(Re).getSidebarCustomActionEventData()}catch(o){return this.getService(k).catch("Error in _onCommentSidebarActionButtonClick: ",o),ce(null)}}_setCommentSidebarData(o,r){this.getService(k).log("%c[WB] Calling FUNCTION: setCommentSidebarData","color: green;");try{this.trackEvent(Y.Events.Comments.SET_COMMENT_SIDEBAR_DATA_TRIGGERED,{payload:{data:o,options:r}}),this.getService(Re).setCommentSidebarData(o,r)}catch(e){this.getService(k).catch("Error in _setCommentSidebarData: ",e)}}_onCommentSidebarInit(){this.getService(k).log("%c[WB] Calling FUNCTION: onCommentSidebarInit","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_COMMENT_SIDEBAR_INIT_TRIGGERED),this.getService(Re).getSidebarCustomActionEventDataOnInit()}catch(o){return this.getService(k).catch("Error in _onCommentSidebarInit: ",o),ce(null)}}_onCommentSidebarData(){this.getService(k).log("%c[WB] Calling FUNCTION: onCommentSidebarData","color: green;");try{return this.trackEvent(Y.Events.Comments.ON_COMMENT_SIDEBAR_DATA_TRIGGERED),this.getService(Re).getSidebarCustomActionEventDataAllChanges()}catch(o){return this.getService(k).catch("Error in _onCommentSidebarData: ",o),ce(null)}}_setCommentSidebarDefaultCustomActions(o){this.getService(k).log("%c[WB] Calling FUNCTION: setCommentSidebarDefaultCustomActions","color: green;");try{this.trackEvent(Y.Events.Comments.SET_COMMENT_SIDEBAR_DEFAULT_CUSTOM_ACTIONS_TRIGGERED,{payload:{actions:o}}),this.getService(Re).setSidebarCustomActionEventData(o,[],{},[],{})}catch(r){this.getService(k).catch("Error in _setCommentSidebarDefaultCustomActions: ",r)}}_enableSidebarCustomActions(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSidebarCustomActions","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SIDEBAR_CUSTOM_ACTIONS_TRIGGERED),this.getService(Re).enableSidebarCustomActions()}catch(o){this.getService(k).catch("Error in _enableSidebarCustomActions: ",o)}}_disableSidebarCustomActions(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSidebarCustomActions","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SIDEBAR_CUSTOM_ACTIONS_TRIGGERED),this.getService(Re).disableSidebarCustomActions()}catch(o){this.getService(k).catch("Error in _disableSidebarCustomActions: ",o)}}_enableQueryParamsComments(){this.getService(k).log("%c[WB] Calling FUNCTION: enableQueryParamsComments","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_QUERY_PARAMS_COMMENTS_TRIGGERED),this.getService(Re).enableQueryParamsComments()}catch(o){this.getService(k).catch("Error in _enableQueryParamsComments: ",o)}}_disableQueryParamsComments(){this.getService(k).log("%c[WB] Calling FUNCTION: disableQueryParamsComments","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_QUERY_PARAMS_COMMENTS_TRIGGERED),this.getService(Re).disableQueryParamsComments()}catch(o){this.getService(k).catch("Error in _disableQueryParamsComments: ",o)}}_enableResolveStatusAccessAdminOnly(){this.getService(k).log("%c[WB] Calling FUNCTION: enableResolveStatusAccessAdminOnly","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_RESOLVE_STATUS_ACCESS_ADMIN_ONLY_TRIGGERED),this.getService(Re).enableResolveStatusAccessAdminOnly()}catch(o){this.getService(k).catch("Error in _enableResolveStatusAccessAdminOnly: ",o)}}_disableResolveStatusAccessAdminOnly(){this.getService(k).log("%c[WB] Calling FUNCTION: disableResolveStatusAccessAdminOnly","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_RESOLVE_STATUS_ACCESS_ADMIN_ONLY_TRIGGERED),this.getService(Re).disableResolveStatusAccessAdminOnly()}catch(o){this.getService(k).catch("Error in _disableResolveStatusAccessAdminOnly: ",o)}}_enableLinkCallback(){this.getService(k).log("%c[WB] Calling FUNCTION: enableLinkCallback","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_LINK_CALLBACK_TRIGGERED),this.getService(Re).enableLinkCallback()}catch(o){this.getService(k).catch("Error in _enableLinkCallback: ",o)}}_disableLinkCallback(){this.getService(k).log("%c[WB] Calling FUNCTION: disableLinkCallback","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_LINK_CALLBACK_TRIGGERED),this.getService(Re).disableLinkCallback()}catch(o){this.getService(k).catch("Error in _disableLinkCallback: ",o)}}_enableSeenByUsers(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSeenByUsers","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SEEN_BY_USERS_TRIGGERED),this.getService(Re).enableSeenByUsers()}catch(o){this.getService(k).catch("Error in _enableSeenByUsers: ",o)}}_disableSeenByUsers(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSeenByUsers","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SEEN_BY_USERS_TRIGGERED),this.getService(Re).disableSeenByUsers()}catch(o){this.getService(k).catch("Error in _disableSeenByUsers: ",o)}}_enableShortUserName(){this.getService(k).log("%c[WB] Calling FUNCTION: enableShortUserName","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SHORT_USER_NAME_TRIGGERED),this.getService(Re).enableShortUserName()}catch(o){this.getService(k).catch("Error in _enableShortUserName: ",o)}}_disableShortUserName(){this.getService(k).log("%c[WB] Calling FUNCTION: disableShortUserName","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SHORT_USER_NAME_TRIGGERED),this.getService(Re).disableShortUserName()}catch(o){this.getService(k).catch("Error in _disableShortUserName: ",o)}}_addCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: addCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.ADD_COMMENT_ANNOTATION_TRIGGERED,{payload:{addCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).addCommentAnnotation(o,"external")}catch(r){return this.getService(k).catch("Error in _addCommentAnnotation: ",r),null}})}_publishCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: publishCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.PUBLISH_COMMENT_ANNOTATION_TRIGGERED,{payload:{publishCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).publishCommentAnnotation(o,"external")}catch(r){return this.getService(k).catch("Error in _publishCommentAnnotation: ",r),null}})}_approveCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: approveCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.APPROVE_COMMENT_ANNOTATION_TRIGGERED,{payload:{approveCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).approveCommentAnnotation(o,"external")}catch(r){return this.getService(k).catch("Error in _approveCommentAnnotation: ",r),null}})}_acceptCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: acceptCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.ACCEPT_COMMENT_ANNOTATION_TRIGGERED,{payload:{acceptCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).acceptCommentAnnotation(o,"external")}catch(r){return this.getService(k).catch("Error in _acceptCommentAnnotation: ",r),null}})}_rejectCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: rejectCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.REJECT_COMMENT_ANNOTATION_TRIGGERED,{payload:{rejectCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).rejectCommentAnnotation(o,"external")}catch(r){return this.getService(k).catch("Error in _rejectCommentAnnotation: ",r),null}})}_subscribeCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: subscribeCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.SUBSCRIBE_COMMENT_ANNOTATION_TRIGGERED,{payload:{subscribeCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).toggleNotificationSubscription(o,"subscribe")}catch(r){return this.getService(k).catch("Error in _subscribeCommentAnnotation: ",r),null}})}_unsubscribeCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: unsubscribeCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.UNSUBSCRIBE_COMMENT_ANNOTATION_TRIGGERED,{payload:{unsubscribeCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).toggleNotificationSubscription(o,"unsubscribe")}catch(r){return this.getService(k).catch("Error in _unsubscribeCommentAnnotation: ",r),null}})}_deleteCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: deleteCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.DELETE_COMMENT_ANNOTATION_TRIGGERED,{payload:{deleteCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).deleteCommentAnnotation(o,"external")}catch(r){return this.getService(k).catch("Error in _deleteCommentAnnotation: ",r),null}})}_getCommentAnnotations(o){this.getService(k).log("%c[WB] Calling FUNCTION: getCommentAnnotations","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_COMMENT_ANNOTATIONS_TRIGGERED,{payload:{query:o}}),this.getService(Mn).getCommentAnnotations(o).pipe(ue(r=>(r.data&&Object.keys(r.data).forEach(e=>{if(r.data?.[e]?.length){let t=r.data[e];r.data[e]=t?.map(i=>this.getService(Re).getCommentAnnotationForClient(i))}}),r)))}catch(r){return this.getService(k).catch("Error in _getCommentAnnotations: ",r),ce({data:null})}}_getCommentAnnotationsCount(o){this.getService(k).log("%c[WB] Calling FUNCTION: getCommentAnnotationsCount","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_COMMENT_ANNOTATIONS_COUNT_TRIGGERED,{payload:{query:o}}),this.getService(Mn).getCommentAnnotationsCount$(o)}catch(r){return this.getService(k).catch("Error in _getCommentAnnotationsCount: ",r),ce({data:null})}}_assignUser(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: assignUser","color: green;");try{return this.trackEvent(Y.Events.Comments.ASSIGN_USER_TRIGGERED,{payload:{assignUserRequest:o}}),this.getService(Mn).convert(o).assignUser(o,"external")}catch(r){return this.getService(k).catch("Error in _assignUser: ",r),null}})}_updatePriority(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: updatePriority","color: green;");try{return this.trackEvent(Y.Events.Comments.UPDATE_PRIORITY_TRIGGERED,{payload:{updatePriorityRequest:o}}),this.getService(Mn).convert(o).updatePriority(o,"external")}catch(r){return this.getService(k).catch("Error in _updatePriority: ",r),null}})}_updateStatus(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: updateStatus","color: green;");try{return this.trackEvent(Y.Events.Comments.UPDATE_STATUS_TRIGGERED,{payload:{updateStatusRequest:o}}),this.getService(Mn).convert(o).updateStatus(o,"external")}catch(r){return this.getService(k).catch("Error in _updateStatus: ",r),null}})}_updateAccess(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: updateAccess","color: green;");try{return this.trackEvent(Y.Events.Comments.UPDATE_ACCESS_TRIGGERED,{payload:{updateAccessRequest:o}}),this.getService(Mn).convert(o).updateAccess(o,"external")}catch(r){return this.getService(k).catch("Error in _updateAccess: ",r),null}})}_resolveCommentAnnotation(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: resolveCommentAnnotation","color: green;");try{return this.trackEvent(Y.Events.Comments.RESOLVE_COMMENT_ANNOTATION_TRIGGERED,{payload:{resolveCommentAnnotationRequest:o}}),this.getService(Mn).convert(o).resolveCommentAnnotation(o)}catch(r){return this.getService(k).catch("Error in _resolveCommentAnnotation: ",r),null}})}_getLink(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: getLink","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_LINK_TRIGGERED,{payload:{getLinkRequest:o}}),this.getService(Mn).convert(o).getLink(o,"external")}catch(r){return this.getService(k).catch("Error in _getLink: ",r),null}})}_copyLink(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: copyLink","color: green;");try{return this.trackEvent(Y.Events.Comments.COPY_LINK_TRIGGERED,{payload:{copyLinkRequest:o}}),this.getService(Mn).convert(o).copyLink(o,"external")}catch(r){return this.getService(k).catch("Error in _copyLink: ",r),null}})}_addComment(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: addComment","color: green;");try{return this.trackEvent(Y.Events.Comments.ADD_COMMENT_TRIGGERED,{payload:{addCommentRequest:o}}),this.getService(Mn).convert(o).addComment(o,"external")}catch(r){return this.getService(k).catch("Error in _addComment: ",r),null}})}_updateComment(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: updateComment","color: green;");try{return this.trackEvent(Y.Events.Comments.UPDATE_COMMENT_TRIGGERED,{payload:{updateCommentRequest:o}}),this.getService(Mn).convert(o).updateComment(o,"external")}catch(r){return this.getService(k).catch("Error in _updateComment: ",r),null}})}_deleteComment(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: deleteComment","color: green;");try{return this.trackEvent(Y.Events.Comments.DELETE_COMMENT_TRIGGERED,{payload:{deleteCommentRequest:o}}),this.getService(Mn).convert(o).deleteComment(o,"external")}catch(r){return this.getService(k).catch("Error in _deleteComment: ",r),null}})}_getComment(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: getComment","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_COMMENT_TRIGGERED,{payload:{getCommentRequest:o}}),this.getService(Mn).convert(o).getComment(o)}catch(r){return this.getService(k).catch("Error in _getComment: ",r),[]}})}_addAttachment(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: addAttachment","color: green;");try{return this.trackEvent(Y.Events.Comments.ADD_ATTACHMENT_TRIGGERED,{payload:{addAttachmentRequest:o}}),this.getService(Mn).convert(o).addAttachment(o)}catch(r){return this.getService(k).catch("Error in _addAttachment: ",r),Promise.resolve([])}})}_deleteAttachment(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: deleteAttachment","color: green;");try{return this.trackEvent(Y.Events.Comments.DELETE_ATTACHMENT_TRIGGERED,{payload:{deleteAttachmentRequest:o}}),this.getService(Mn).convert(o).deleteAttachment(o)}catch(r){return this.getService(k).catch("Error in _deleteAttachment: ",r),null}})}_getAttachment(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: getAttachment","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_ATTACHMENT_TRIGGERED,{payload:{getAttachmentRequest:o}}),this.getService(Mn).convert(o).getAttachment(o)}catch(r){return this.getService(k).catch("Error in _getAttachment: ",r),[]}})}_getRecording(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: getRecording","color: green;");try{return this.trackEvent(Y.Events.Comments.GET_RECORDING_TRIGGERED,{payload:{getRecordingRequest:o}}),this.getService(Mn).convert(o).getRecording(o)}catch(r){return this.getService(k).catch("Error in _getRecording: ",r),[]}})}_deleteRecording(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: deleteRecording","color: green;");try{return this.trackEvent(Y.Events.Comments.DELETE_RECORDING_TRIGGERED,{payload:{deleteRecordingRequest:o}}),this.getService(Mn).convert(o).deleteRecording(o)}catch(r){return this.getService(k).catch("Error in _deleteRecording: ",r),null}})}_fetchCommentAnnotations(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: fetchCommentAnnotations","color: green;");try{return this.trackEvent(Y.Events.Comments.FETCH_COMMENT_ANNOTATIONS_TRIGGERED,{payload:{fetchCommentAnnotationsRequest:o}}),this.getService(Mn).fetchCommentAnnotations(o)}catch(r){return this.getService(k).catch("Error in _fetchCommentAnnotations: ",r),{data:null}}})}_addReaction(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: addReaction","color: green;");try{return this.trackEvent(Y.Events.Comments.ADD_REACTION_TRIGGERED,{payload:{addReactionRequest:o}}),this.getService(Mn).convert(o).toggleReaction(o,"add")}catch(r){return this.getService(k).catch("Error in _addReaction: ",r),null}})}_deleteReaction(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: deleteReaction","color: green;");try{return this.trackEvent(Y.Events.Comments.DELETE_REACTION_TRIGGERED,{payload:{deleteReactionRequest:o}}),this.getService(Mn).convert(o).toggleReaction(o,"delete")}catch(r){return this.getService(k).catch("Error in _deleteReaction: ",r),null}})}_toggleReaction(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: toggleReaction","color: green;");try{return this.trackEvent(Y.Events.Comments.TOGGLE_REACTION_TRIGGERED,{payload:{toggleReactionRequest:o}}),this.getService(Mn).convert(o).toggleReaction(o)}catch(r){return this.getService(k).catch("Error in _toggleReaction: ",r),null}})}_on(o){this.getService(k).log("%c[WB] Calling FUNCTION: on","color: green;");try{return this.getService(Mn).onAction(o)}catch(r){return this.getService(k).catch("Error in _on: ",r),ce(null)}}_enableReadOnly(){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: enableReadOnly","color: green;");try{return this.trackEvent(Y.Events.Comments.ENABLE_READ_ONLY_TRIGGERED),this.getService(Re).enableReadOnly()}catch(o){this.getService(k).catch("Error in _toggleReaction: ",o);return}})}_disableReadOnly(){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: disableReadOnly","color: green;");try{return this.trackEvent(Y.Events.Comments.DISABLE_READ_ONLY_TRIGGERED),this.getService(Re).disableReadOnly()}catch(o){this.getService(k).catch("Error in _disableReadOnly: ",o);return}})}_setAssignToType(o){this.getService(k).log("%c[WB] Calling FUNCTION: setAssignToType","color: green;");try{this.trackEvent(Y.Events.Comments.SET_ASSIGN_TO_TYPE_TRIGGERED,{payload:{type:o.type}}),this.getService(Re).setAssignToType(o)}catch(r){this.getService(k).catch("Error in _setAssignToType: ",r)}}_enableContextInPageModeComposer(){this.getService(k).log("%c[WB] Calling FUNCTION: enableContextInPageModeComposer","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_CONTEXT_IN_PAGE_MODE_COMPOSER_TRIGGERED),this.getService(Re).enableContextInPageModeComposer()}catch(o){this.getService(k).catch("Error in _enableContextInPageModeComposer: ",o)}}_disableContextInPageModeComposer(){this.getService(k).log("%c[WB] Calling FUNCTION: disableContextInPageModeComposer","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_CONTEXT_IN_PAGE_MODE_COMPOSER_TRIGGERED),this.getService(Re).disableContextInPageModeComposer()}catch(o){this.getService(k).catch("Error in _disableContextInPageModeComposer: ",o)}}_clearPageModeComposerContext(){this.getService(k).log("%c[WB] Calling FUNCTION: clearPageModeComposerContext","color: green;");try{this.trackEvent(Y.Events.Comments.CLEAR_PAGE_MODE_COMPOSER_CONTEXT_TRIGGERED),this.getService(Re).clearPageModeComposerContext()}catch(o){this.getService(k).catch("Error in _clearPageModeComposerContext: ",o)}}_setContextInPageModeComposer(o){this.getService(k).log("%c[WB] Calling FUNCTION: setContextInPageModeComposer","color: green;");try{this.trackEvent(Y.Events.Comments.SET_CONTEXT_IN_PAGE_MODE_COMPOSER_TRIGGERED),this.getService(Re).setPageModeComposerContext(o)}catch(r){this.getService(k).catch("Error in _setContextInPageModeComposer: ",r)}}_focusPageModeComposer(){this.getService(k).log("%c[WB] Calling FUNCTION: focusPageModeComposer","color: green;");try{this.trackEvent(Y.Events.Comments.FOCUS_PAGE_MODE_COMPOSER_TRIGGERED),this.getService(Re).focusPageModeComposer()}catch(o){this.getService(k).catch("Error in _focusPageModeComposer: ",o)}}_enableCustomAutocompleteSearch(){this.getService(k).log("%c[WB] Calling FUNCTION: enableCustomAutocompleteSearch","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_CUSTOM_AUTOCOMPLETE_SEARCH_TRIGGERED),this.getService(Re).enableCustomAutocompleteSearch()}catch(o){this.getService(k).catch("Error in _enableCustomAutocompleteSearch: ",o);return}}_disableCustomAutocompleteSearch(){this.getService(k).log("%c[WB] Calling FUNCTION: disableCustomAutocompleteSearch","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_CUSTOM_AUTOCOMPLETE_SEARCH_TRIGGERED),this.getService(Re).disableCustomAutocompleteSearch()}catch(o){this.getService(k).catch("Error in _disableCustomAutocompleteSearch: ",o);return}}_setTransformContext(o){this.getService(k).log("%c[WB] Calling FUNCTION: setTransformContext","color: green;");try{this.trackEvent(Y.Events.Comments.SET_TRANSFORM_CONTEXT_TRIGGERED,{payload:{transformContext:o}}),this.getService(Re).setTransformContext(o)}catch(r){this.getService(k).catch("Error in _setTransformContext: ",r);return}}_enableSvgAsImg(){this.getService(k).log("%c[WB] Calling FUNCTION: enableSvgAsImg","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SVG_AS_IMG_TRIGGERED),this.getService(Re).enableSvgAsImg()}catch(o){this.getService(k).catch("Error in _enableSvgAsImg: ",o);return}}_disableSvgAsImg(){this.getService(k).log("%c[WB] Calling FUNCTION: disableSvgAsImg","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SVG_AS_IMG_TRIGGERED),this.getService(Re).disableSvgAsImg()}catch(o){this.getService(k).catch("Error in _disableSvgAsImg: ",o);return}}_enableFullExpanded(){this.getService(k).log("%c[WB] Calling FUNCTION: enableFullExpanded","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_FULL_EXPANDED_TRIGGERED),this.getService(Re).enableFullExpanded()}catch(o){this.getService(k).catch("Error in _enableFullExpanded: ",o);return}}_disableFullExpanded(){this.getService(k).log("%c[WB] Calling FUNCTION: disableFullExpanded","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_FULL_EXPANDED_TRIGGERED),this.getService(Re).disableFullExpanded()}catch(o){this.getService(k).catch("Error in _disableFullExpanded: ",o);return}}_enableCommentToNearestAllowedElement(){this.getService(k).log("%c[WB] Calling FUNCTION: enableCommentToNearestAllowedElement","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_COMMENT_TO_NEAREST_ALLOWED_ELEMENT_TRIGGERED),this.getService(Re).enableCommentToNearestAllowedElement()}catch(o){this.getService(k).catch("Error in _enableCommentToNearestAllowedElement: ",o);return}}_disableCommentToNearestAllowedElement(){this.getService(k).log("%c[WB] Calling FUNCTION: disableCommentToNearestAllowedElement","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_COMMENT_TO_NEAREST_ALLOWED_ELEMENT_TRIGGERED),this.getService(Re).disableCommentToNearestAllowedElement()}catch(o){this.getService(k).catch("Error in _disableCommentToNearestAllowedElement: ",o);return}}_enableDraftMode(){this.getService(k).log("%c[WB] Calling FUNCTION: enableDraftMode","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_DRAFT_MODE_TRIGGERED),this.getService(Re).enableDraftMode()}catch(o){this.getService(k).catch("Error in _enableDraftMode: ",o);return}}_disableDraftMode(){this.getService(k).log("%c[WB] Calling FUNCTION: disableDraftMode","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_DRAFT_MODE_TRIGGERED),this.getService(Re).disableDraftMode()}catch(o){this.getService(k).catch("Error in _disableDraftMode: ",o);return}}_enableFilterCommentsOnDom(){this.getService(k).log("%c[WB] Calling FUNCTION: enableFilterCommentsOnDom","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_FILTER_COMMENTS_ON_DOM_TRIGGERED),this.getService(Re).enableFilterCommentsOnDom()}catch(o){this.getService(k).catch("Error in _enableFilterCommentsOnDom: ",o);return}}_disableFilterCommentsOnDom(){this.getService(k).log("%c[WB] Calling FUNCTION: disableFilterCommentsOnDom","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_FILTER_COMMENTS_ON_DOM_TRIGGERED),this.getService(Re).disableFilterCommentsOnDom()}catch(o){this.getService(k).catch("Error in _disableFilterCommentsOnDom: ",o);return}}_enableReplyAvatars(){this.getService(k).log("%c[WB] Calling FUNCTION: enableReplyAvatars","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_REPLY_AVATARS_TRIGGERED),this.getService(Re).enableReplyAvatars()}catch(o){this.getService(k).catch("Error in _enableReplyAvatars: ",o);return}}_disableReplyAvatars(){this.getService(k).log("%c[WB] Calling FUNCTION: disableReplyAvatars","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_REPLY_AVATARS_TRIGGERED),this.getService(Re).disableReplyAvatars()}catch(o){this.getService(k).catch("Error in _disableReplyAvatars: ",o);return}}_setMaxReplyAvatars(o){this.getService(k).log("%c[WB] Calling FUNCTION: setMaxReplyAvatars","color: green;");try{this.trackEvent(Y.Events.Comments.SET_MAX_REPLY_AVATARS_TRIGGERED,{payload:{maxReplyAvatars:o}}),this.getService(Re).setMaxReplyAvatars(o)}catch(r){this.getService(k).catch("Error in _setMaxReplyAvatars: ",r);return}}_setSidebarButtonCountType(o){this.getService(k).log("%c[WB] Calling FUNCTION: setSidebarButtonCountType","color: green;");try{this.trackEvent(Y.Events.Comments.SET_SIDEBAR_BUTTON_COUNT_TYPE_TRIGGERED,{payload:{type:o}}),this.getService(Re).setSidebarButtonCountType(o)}catch(r){this.getService(k).catch("Error in _setSidebarButtonCountType: ",r);return}}_enableFilterGhostCommentsInSidebar(){this.getService(k).log("%c[WB] Calling FUNCTION: enableFilterGhostCommentsInSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_FILTER_GHOST_COMMENTS_IN_SIDEBAR_TRIGGERED),this.getService(Re).enableFilterGhostCommentsInSidebar()}catch(o){this.getService(k).catch("Error in _enableFilterGhostCommentsInSidebar: ",o);return}}_disableFilterGhostCommentsInSidebar(){this.getService(k).log("%c[WB] Calling FUNCTION: disableFilterGhostCommentsInSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_FILTER_GHOST_COMMENTS_IN_SIDEBAR_TRIGGERED),this.getService(Re).disableFilterGhostCommentsInSidebar()}catch(o){this.getService(k).catch("Error in _disableFilterGhostCommentsInSidebar: ",o);return}}_enableFullScreenInSidebar(){this.getService(k).log("%c[WB] Calling FUNCTION: enableFullScreenInSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_FULL_SCREEN_IN_SIDEBAR_TRIGGERED),this.getService(Re).enableFullScreenInSidebar()}catch(o){this.getService(k).catch("Error in _enableFullScreenInSidebar: ",o);return}}_disableFullScreenInSidebar(){this.getService(k).log("%c[WB] Calling FUNCTION: disableFullScreenInSidebar","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_FULL_SCREEN_IN_SIDEBAR_TRIGGERED),this.getService(Re).disableFullScreenInSidebar()}catch(o){this.getService(k).catch("Error in _disableFullScreenInSidebar: ",o);return}}_setComposerFileAttachments(o){this.getService(k).log("%c[WB] Calling FUNCTION: setComposerFileAttachments","color: green;");try{this.getService(Re).setComposerFileAttachments(o),this.trackEvent(Y.Events.Comments.SET_COMPOSER_FILE_ATTACHMENTS_TRIGGERED,{payload:{data:o}})}catch(r){this.getService(k).catch("Error in _setComposerFileAttachments: ",r);return}}_setAllowedFileTypes(o){this.getService(k).log("%c[WB] Calling FUNCTION: setAllowedFileTypes","color: green;");try{this.trackEvent(Y.Events.Comments.COMMENT_ATTACHMENT_SET_ALLOWED_FILE_TYPES_TRIGGERED,{payload:{allowedFileTypes:o}}),this.getService(Re).setAllowedFileTypes(o)}catch(r){this.getService(k).catch("Error in _setAllowedFileTypes: ",r);return}}_enableForceCloseAllOnEsc(){this.getService(k).log("%c[WB] Calling FUNCTION: enableForceCloseAllOnEsc","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_FORCE_CLOSE_ALL_ON_ESC_TRIGGERED),this.getService(Re).enableForceCloseAllOnEsc()}catch(o){this.getService(k).catch("Error in _enableForceCloseAllOnEsc: ",o);return}}_disableForceCloseAllOnEsc(){this.getService(k).log("%c[WB] Calling FUNCTION: disableForceCloseAllOnEsc","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_FORCE_CLOSE_ALL_ON_ESC_TRIGGERED),this.getService(Re).disableForceCloseAllOnEsc()}catch(o){this.getService(k).catch("Error in _disableForceCloseAllOnEsc: ",o);return}}_markAsRead(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: markAsRead","color: green;");try{this.trackEvent(Y.Events.Comments.MARK_AS_READ_TRIGGERED,{payload:{annotationId:o}}),yield this.getService(Re).markAsRead(o);return}catch(r){this.getService(k).catch("Error in _markAsRead: ",r);return}})}_markAsUnread(o){return X(this,null,function*(){this.getService(k).log("%c[WB] Calling FUNCTION: markAsUnread","color: green;");try{this.trackEvent(Y.Events.Comments.MARK_AS_UNREAD_TRIGGERED,{payload:{annotationId:o}}),yield this.getService(Re).markAsUnread(o)}catch(r){this.getService(k).catch("Error in _markAsUnread: ",r);return}})}_enableScreenshot(){this.getService(k).log("%c[WB] Calling FUNCTION: enableScreenshot","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_SCREENSHOT_TRIGGERED),this.getService(Re).enableScreenshot()}catch(o){this.getService(k).catch("Error in _enableScreenshot: ",o);return}}_disableScreenshot(){this.getService(k).log("%c[WB] Calling FUNCTION: disableScreenshot","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_SCREENSHOT_TRIGGERED),this.getService(Re).disableScreenshot()}catch(o){this.getService(k).catch("Error in _disableScreenshot: ",o);return}}_enablePaginatedContactList(){this.getService(k).log("%c[WB] Calling FUNCTION: enablePaginatedContactList","color: green;");try{this.trackEvent(Y.Events.Comments.ENABLE_PAGINATED_CONTACT_LIST_TRIGGERED),this.getService(Re).enablePaginatedContactList()}catch(o){this.getService(k).catch("Error in _enablePaginatedContactList: ",o);return}}_disablePaginatedContactList(){this.getService(k).log("%c[WB] Calling FUNCTION: disablePaginatedContactList","color: green;");try{this.trackEvent(Y.Events.Comments.DISABLE_PAGINATED_CONTACT_LIST_TRIGGERED),this.getService(Re).disablePaginatedContactList()}catch(o){this.getService(k).catch("Error in _disablePaginatedContactList: ",o);return}}};var iU=class extends Cr{constructor(o){super(o),this.getService(k).log("%c[WB] Creating CLASS: ContactElement","color: blue;"),this.isUserGlobalContact=this._isUserGlobalContact,this.onContactSelected=this._onContactSelected,this.enableAtHere=this._enableAtHere,this.setAtHereLabel=this._setAtHereLabel,this.setAtHereDescription=this._setAtHereDescription,this.disableAtHere=this._disableAtHere,this.updateContactListScopeForOrganizationUsers=this._updateContactListScopeForOrganizationUsers,this.updateContactList=this._updateContactList,this.getContactList=this._getContactList}_isUserGlobalContact(){this.getService(k).log("%c[WB] Calling FUNCTION: isUserGlobalContact","color: green;");try{return this.trackEvent(Y.Events.Contact.IS_USER_GLOBAL_CONTACT_TRIGGERED),this.getService(vn).isUserGlobalContact$()}catch(o){return this.getService(k).catch("Error in _isUserGlobalContact: ",o),ce(!1)}}_onContactSelected(){this.getService(k).log("%c[WB] Calling FUNCTION: onContactSelected","color: green;");try{return this.trackEvent(Y.Events.Contact.ON_CONTACT_SELECTED_TRIGGERED),this.getService(vn).onContactSelected$()}catch(o){return this.getService(k).catch("Error in _onContactSelected: ",o),ce(null)}}_enableAtHere(){this.getService(k).log("%c[WB] Calling FUNCTION: enableAtHere","color: green;");try{this.trackEvent(Y.Events.Contact.ENABLE_AT_HERE_TRIGGERED),this.getService(vn).enableAtHere()}catch(o){this.getService(k).catch("Error in _enableAtHere: ",o)}}_setAtHereLabel(o){this.getService(k).log("%c[WB] Calling FUNCTION: setAtHereLabel","color: green;");try{this.trackEvent(Y.Events.Contact.SET_AT_HERE_LABEL_TRIGGERED,{payload:{label:o}}),this.getService(vn).setAtHereLabel(o)}catch(r){this.getService(k).catch("Error in setAtHereLabel: ",r)}}_setAtHereDescription(o){this.getService(k).log("%c[WB] Calling FUNCTION: setAtHereDescription","color: green;");try{this.trackEvent(Y.Events.Contact.SET_AT_HERE_DESCRIPTION_TRIGGERED,{payload:{description:o}}),this.getService(vn).setAtHereDescription(o)}catch(r){this.getService(k).catch("Error in setAtHereDescription: ",r)}}_disableAtHere(){this.getService(k).log("%c[WB] Calling FUNCTION: disableAtHere","color: green;");try{this.trackEvent(Y.Events.Contact.DISABLE_AT_HERE_TRIGGERED),this.getService(vn).disableAtHere()}catch(o){this.getService(k).catch("Error in _disableAtHere: ",o)}}_updateContactListScopeForOrganizationUsers(o){this.getService(k).log("%c[WB] Calling FUNCTION: updateContactListScopeForOrganizationUsers","color: green;");try{this.trackEvent(Y.Events.Contact.UPDATE_CONTACT_LIST_SCOPE_FOR_ORGANIZATION_USERS_TRIGGERED,{payload:{scope:o}}),this.getService(vn).updateContactListScopeForOrganizationUsers(o)}catch(r){this.getService(k).catch("Error in _updateContactListScopeForOrganizationUsers: ",r)}}_updateContactList(o,r){this.getService(k).log("%c[WB] Calling FUNCTION: _updateContactList","color: green;");try{this.trackEvent(Y.Events.Contact.UPDATE_CONTACT_LIST_TRIGGERED,{payload:{userContacts:o,config:r}}),typeof o=="object"&&o instanceof Array&&(!r||r&&typeof r=="object")&&(o=JSON.parse(JSON.stringify(o)),this.getService(vn).convert(r).updateContactList(o,r))}catch(e){this.getService(k).catch("Error in _updateContactList: ",e)}}_getContactList(){this.getService(k).log("%c[WB] Calling FUNCTION: getContactList","color: green;");try{return this.trackEvent(Y.Events.Contact.GET_CONTACT_LIST_TRIGGERED),this.getService(vn).getContactList$()}catch(o){return this.getService(k).catch("Error in _getContactList: ",o),ce(null)}}};var aU=(()=>{let o=class o{constructor(e){this.loggingService=e,this.actionSubjects=new Map,this.subscriptions=[]}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new at),this.actionSubjects.get(e)?.next(t)}catch(i){this.loggingService.catch("Error in CrdtActionsService triggerAction: ",i)}}onAction(e){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new at);let t=this.actionSubjects.get(e);return t?t.asObservable():ce(null)}catch(t){return this.loggingService.catch("Error in CrdtActionsService onAction: ",t),ce(null)}}};o.\u0275fac=function(t){return new(t||o)(K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var Rs=(()=>{let o=class o{static generateKey(){return X(this,null,function*(){try{return yield window.crypto.subtle.generateKey({name:"AES-GCM",length:this.KEY_LENGTH},!1,["encrypt","decrypt"])}catch(e){return it.catch("Failed to generate key: ",e),null}})}static deriveKeyFromPassword(e,t){return X(this,null,function*(){try{if(!t){let c=yield window.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));t=new Uint8Array(c).slice(0,this.SALT_LENGTH)}let i=new TextEncoder().encode(e),a=yield window.crypto.subtle.importKey("raw",i,"PBKDF2",!1,["deriveBits","deriveKey"]);return{key:yield window.crypto.subtle.deriveKey({name:"PBKDF2",salt:t,iterations:this.PBKDF2_ITERATIONS,hash:"SHA-256"},a,{name:"AES-GCM",length:this.KEY_LENGTH},!1,["encrypt","decrypt"]),salt:t}}catch(i){return it.catch("Failed to derive key from password: ",i),null}})}static resolveKey(e){return X(this,null,function*(){try{if(e.customKey){if(e.customKey instanceof CryptoKey)return{key:e.customKey};if(typeof e.customKey=="string"){let i=yield this.deriveKeyFromPassword(e.customKey,e.customSalt);if(!i)return it.catch("Failed to derive key from password"),null;let{key:a,salt:l}=i;return{key:a,salt:l}}}let t=yield this.generateKey();return t?{key:t}:(it.catch("Failed to generate key"),null)}catch(t){return it.catch("Failed to resolve key: ",t),null}})}static encrypt(i){return X(this,arguments,function*(e,t={}){try{if(t.customEncryptCallback)try{return yield t.customEncryptCallback(e)}catch(_){return it.catch("Custom encryption callback failed: ",_),""}let a=yield this.resolveKey(t);if(!a)return it.catch("Failed to resolve key"),"";let{key:l,salt:c}=a,d;if(t.customIV){if(t.customIV.length!==this.IV_LENGTH)return it.catch(`Custom IV must be exactly ${this.IV_LENGTH} bytes`),"";d=t.customIV}else d=window.crypto.getRandomValues(new Uint8Array(this.IV_LENGTH));let m=new TextEncoder().encode(e),u={name:"AES-GCM",iv:d,tagLength:128};t.additionalData&&(u.additionalData=t.additionalData);try{let _=yield window.crypto.subtle.encrypt(u,l,m),I=new Uint8Array(d.length+_.byteLength);I.set(d,0),I.set(new Uint8Array(_),d.length);let A=8192,M=[];for(let V=0;V<I.length;V+=A){let q=I.slice(V,Math.min(V+A,I.length)),ae="";for(let ye=0;ye<q.length;ye++)ae+=String.fromCharCode(q[ye]);M.push(ae)}return btoa(M.join(""))}catch(_){return it.catch("Encryption failed: ",_),""}}catch(a){return it.catch("Failed to encrypt: ",a),null}})}static decrypt(i){return X(this,arguments,function*(e,t={}){try{if(t.customDecryptCallback)try{return yield t.customDecryptCallback(e)}catch(_){return it.catch("Custom decryption callback failed: ",_),""}let a=yield this.resolveKey(t);if(!a)return it.catch("Failed to resolve key"),"";let{key:l}=a,c=new Uint8Array(atob(e).split("").map(_=>_.charCodeAt(0)));if(c.length<this.IV_LENGTH)return it.catch("Invalid encrypted data: Too short"),"";let d;if(t.customIV){if(t.customIV.length!==this.IV_LENGTH)return it.catch(`Custom IV must be exactly ${this.IV_LENGTH} bytes`),"";d=t.customIV}else d=c.slice(0,this.IV_LENGTH);let m=c.slice(this.IV_LENGTH),u={name:"AES-GCM",iv:d,tagLength:128};t.additionalData&&(u.additionalData=t.additionalData);try{let _=yield window.crypto.subtle.decrypt(u,l,m);return new TextDecoder().decode(_)}catch(_){return it.catch("Decryption failed: ",_),""}}catch(a){return it.catch("Failed to decrypt: ",a),""}})}static encryptData(i){return X(this,arguments,function*(e,t={}){try{let a=JSON.stringify(e);return(yield this.encrypt(a,t))??""}catch(a){return it.catch("Failed to encrypt data: ",a),""}})}static decryptData(i){return X(this,arguments,function*(e,t={}){try{let a=yield this.decrypt(e,t);return JSON.parse(a)}catch(a){return it.catch("Failed to decrypt data: ",a),null}})}};o.IV_LENGTH=12,o.SALT_LENGTH=16,o.PBKDF2_ITERATIONS=1e5,o.KEY_LENGTH=256;let n=o;return n})();var Pi=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I){this.activityService=e,this.analyticsService=t,this.authService=i,this.commonDbService=a,this.commonDbUtilsService=l,this.configService=c,this.crdtActionsService=d,this.docService=m,this.domService=u,this.loggingService=_,this.notificationService=I,this.MIN_WEBHOOK_DEBOUNCE_TIME=5*1e3,this.webhookDebounceTime=this.MIN_WEBHOOK_DEBOUNCE_TIME,this.updateDataWebhookTrigger$=new at,this.updateDataWebhookDebounceSubscription=null,this.pendingWebhookEvent=null,this.webhookEnabled$=new _e(!1),this.lastCrdtDataUpdatedId=null,this.MIN_ACTIVITY_DEBOUNCE_TIME=10*1e3,this.activityDebounceTime=600*1e3,this.editorEditTrackers=new Map;try{this.loggingService.log("%c[WB] Creating CLASS: CrdtService","color: blue;"),this.authService.setCrdtService(this),this.setupUpdateDataWebhookDebounce(),this.docService.addPreDocumentIdChangeFunction("crdt-service",()=>(this.lastCrdtDataUpdatedId=null,Promise.resolve())),this.authService.addPreSignOutFuction("crdt-service",()=>(this.lastCrdtDataUpdatedId=null,Promise.resolve()))}catch(A){this.loggingService.catch("Error in CrdtService constructor: ",A)}}trackCrdtDataUpdated(e){try{if(this.lastCrdtDataUpdatedId===e)return;this.lastCrdtDataUpdatedId=e,this.analyticsService.trackEvent(Y.Events.Crdt.CRDT_DATA_UPDATED,{id:e})}catch(t){this.loggingService.catch("Error in CrdtService trackCrdtDataUpdated: ",t)}}setupUpdateDataWebhookDebounce(){try{this.updateDataWebhookDebounceSubscription&&(this.updateDataWebhookDebounceSubscription.unsubscribe(),this.updateDataWebhookDebounceSubscription=null,this.pendingWebhookEvent=null),this.updateDataWebhookDebounceSubscription=this.updateDataWebhookTrigger$.pipe(ln(e=>{this.pendingWebhookEvent=e}),Qr(this.webhookDebounceTime)).subscribe(e=>{this.pendingWebhookEvent=null,this.webhookEnabled$.value&&e&&this.triggerUpdateDataWebhook(e)},e=>{this.loggingService.catch("Error in CrdtService setupUpdateDataWebhookDebounce subscription: ",e)})}catch(e){this.loggingService.catch("Error in CrdtService setupUpdateDataWebhookDebounce: ",e)}}setWebhookDebounceTime(e){try{e<this.MIN_WEBHOOK_DEBOUNCE_TIME&&(this.loggingService.catch("Error in CrdtService setWebhookDebounceTime: Value must be at least "+this.MIN_WEBHOOK_DEBOUNCE_TIME/1e3+" seconds ("+this.MIN_WEBHOOK_DEBOUNCE_TIME+"ms). Using minimum value."),e=this.MIN_WEBHOOK_DEBOUNCE_TIME),this.pendingWebhookEvent&&this.webhookEnabled$.value&&(this.triggerUpdateDataWebhook(this.pendingWebhookEvent),this.pendingWebhookEvent=null),this.webhookDebounceTime=e,this.setupUpdateDataWebhookDebounce()}catch(t){this.loggingService.catch("Error in CrdtService setWebhookDebounceTime: ",t)}}updateData(a){return X(this,arguments,function*({id:e,state:t,data:i}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: updateData","color: green;");let l=this.docService.getDocumentPaths(),c=this.authService.getUser(),d=this.domService.getTabId();if(c?.userId&&l){let m=It(e),u=c.userId,_=It(c.userId),I=new Date().toISOString(),A=null,M=this.configService.getEncryptionProvider();if(M?.encrypt&&typeof M.encrypt=="function")A=yield M.encrypt({data:t});else{let ye={};ye.customKey=m,A=yield Rs.encryptData(t,ye)}let V={id:e,veltId:m,encryptedState:A,lastUpdate:I,lastUpdatedBy:u,lastUpdatedByVeltUserId:_,sessionId:d},q={methodName:HN.UPDATE_DATA,uniqueId:lt(),timestamp:new Date().getTime(),source:GN.INTERNAL,payload:{id:e,data:i,lastUpdatedBy:u,sessionId:d,lastUpdate:I}},ae=yield this.commonDbService.updateData({feature:"crdtData",properties:{documentId:l?.documentId??"",organizationId:l?.organizationId??"",id:m,skipFirestore:!0},data:V});return this.crdtActionsService.triggerAction(FK.UPDATE_DATA,q),this.trackCrdtDataUpdated(e),this.updateDataWebhookTrigger$.next(q?.payload),this.trackEditForActivity(e),ae}return Promise.resolve(null)}catch(l){return this.loggingService.catch("Error in CrdtService updateData: ",l),Promise.resolve(null)}})}triggerUpdateDataWebhook(e){try{this.updateNotificationsDatabase(e,UK.UPDATE_DATA)}catch(t){this.loggingService.catch("Error in CrdtService triggerUpdateDataWebhook: ",t)}}onDataChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onDataChange","color: green;");let i=It(e),a=this.docService.getDocumentPaths$().pipe(Se(l=>l?this.commonDbService.dbListener({feature:"crdtData",properties:{documentId:l?.documentId??"",organizationId:l?.organizationId??"",id:i,skipFirestore:!0}}).pipe(Se(c=>X(this,null,function*(){try{if(c?.data){if(c.data.encryptedState){let d=null,m=this.configService.getEncryptionProvider();if(m?.decrypt&&typeof m.decrypt=="function")d=yield m.decrypt({data:c.data.encryptedState});else{let u={};u.customKey=i,d=yield Rs.decryptData(c.data.encryptedState,u)}c.data.state=d,delete c.data?.encryptedState}return c}else{if(c?.encryptedState){let d=null,m=this.configService.getEncryptionProvider();if(m?.decrypt&&typeof m.decrypt=="function")d=yield m.decrypt({data:c.encryptedState});else{let u={};u.customKey=i,d=yield Rs.decryptData(c.encryptedState,u)}c.state=d,delete c?.encryptedState}return c}}catch(d){return this.loggingService.catch("Error in CrdtService onDataChange subscription: ",d),null}}))):ce(null))).subscribe(l=>{l&&(l.data?t(l.data):t(l))});return()=>a.unsubscribe()}catch(i){return this.loggingService.catch("Error in CrdtService onDataChange: ",i),()=>{}}}getData(t){return X(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getData","color: green;");let i=this.docService.getDocumentPaths();if(i){let a=It(e),l=yield this.commonDbService.getData({feature:"crdtData",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:a,skipFirestore:!0}});if(l?.encryptedState){let c=null,d=this.configService.getEncryptionProvider();if(d?.decrypt&&typeof d.decrypt=="function")c=yield d.decrypt({data:l.encryptedState});else{let m={};m.customKey=a,c=yield Rs.decryptData(l.encryptedState,m)}l.state=c,delete l?.encryptedState}return l}return Promise.resolve(null)}catch(i){return this.loggingService.catch("Error in CrdtService getData: ",i),Promise.resolve(null)}})}onStateChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onStateChange","color: green;");let i=It(e),a=this.docService.getDocumentPaths$().pipe(Se(l=>l?this.commonDbService.dbListener({feature:"crdtSyncState",properties:{documentId:l?.documentId??"",organizationId:l?.organizationId??"",id:i,skipFirestore:!0}}).pipe(Se(c=>X(this,null,function*(){try{if(c?.data){if(c.data.encryptedState){let d=null,m=this.configService.getEncryptionProvider();if(m?.decrypt&&typeof m.decrypt=="function")d=yield m.decrypt({data:c.data.encryptedState});else{let u={};u.customKey=i,d=yield Rs.decryptData(c.data.encryptedState,u)}c.data.state=d,delete c.data?.encryptedState}return c}else{if(c?.encryptedState){let d=null,m=this.configService.getEncryptionProvider();if(m?.decrypt&&typeof m.decrypt=="function")d=yield m.decrypt({data:c.encryptedState});else{let u={};u.customKey=i,d=yield Rs.decryptData(c.encryptedState,u)}c.state=d,delete c?.encryptedState}return c}}catch(d){return this.loggingService.catch("Error in CrdtService onStateChange subscription: ",d),null}}))):ce(null))).subscribe(l=>{l&&(l.data?t(l.data):t(l))});return()=>a.unsubscribe()}catch(i){return this.loggingService.catch("Error in CrdtService onStateChange: ",i),()=>{}}}updateState(i){return X(this,arguments,function*({id:e,state:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: updateState","color: green;");let a=this.docService.getDocumentPaths(),l=this.authService.getUser(),c=this.domService.getTabId();if(l?.userId&&a){let d=It(e),m=l.userId,u=It(m),_=null,I=this.configService.getEncryptionProvider();if(I?.encrypt&&typeof I.encrypt=="function")_=yield I.encrypt({data:t});else{let A={};A.customKey=d,_=yield Rs.encryptData(t,A)}return this.commonDbService.setData({feature:"crdtSyncState",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:d,skipFirestore:!0},data:{id:e,veltId:d,encryptedState:_,lastUpdate:new Date().toISOString(),lastUpdatedBy:m,lastUpdatedByVeltUserId:u,sessionId:c}})}return Promise.resolve(null)}catch(a){return this.loggingService.catch("Error in CrdtService updateState: ",a),Promise.resolve(null)}})}registerSyncUser(t){return X(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: registerSyncUser","color: green;");let i=this.authService.getUser(),a=this.docService.getDocumentPaths(),l=this.configService.getApiKey(),c=It(e),d=this.domService.getTabId();if(i?.userId&&a&&l){let m=i.userId,u=It(m),_={documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:c,userId:u,apiKey:l,skipFirestore:!0},I={userId:m,veltUserId:u,status:"online",lastSeen:Date.now(),sessionId:d};yield this.commonDbService.setData({feature:"crdtSyncPresence",properties:_,data:I});let A=this.commonDbUtilsService.getDocumentPath({feature:"crdtSyncPresence",properties:_,defaultDocumentPaths:a,apiKey:l});A&&(yield this.commonDbService.setupOnDisconnect(A,{status:"offline",lastSeen:new Date().getTime(),sessionId:d}))}}catch(i){this.loggingService.catch("Error in CrdtService registerSyncUser: ",i)}})}onRegisteredUserChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onRegisteredUserChange","color: green;");let i=It(e),a=this.docService.getDocumentPaths$().pipe(Se(l=>l?this.commonDbService.dbListener({feature:"allCrdtSyncPresence",properties:{documentId:l?.documentId??"",organizationId:l?.organizationId??"",id:i,skipFirestore:!0}}).pipe(ln(c=>{try{c?.data?t(c.data):t(c)}catch(d){this.loggingService.catch("Error in CrdtService onRegisteredUserChange subscription: ",d)}})):ce(null))).subscribe(()=>{});return()=>a.unsubscribe()}catch(i){return this.loggingService.catch("Error in CrdtService onRegisteredUserChange: ",i),()=>{}}}setPresence(t){return X(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: setPresence","color: green;");let i=this.authService.getUser(),a=this.docService.getDocumentPaths(),l=this.configService.getApiKey(),c=It(e),d=this.domService.getTabId();if(i?.userId&&a&&l){let m=i.userId,u=It(m),_={documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:c,userId:u,apiKey:l,skipFirestore:!0},I={userId:m,veltUserId:u,status:"online",lastSeen:Date.now(),sessionId:d};yield this.commonDbService.setData({feature:"crdtPresence",properties:_,data:I});let A=this.commonDbUtilsService.getDocumentPath({feature:"crdtPresence",properties:_,defaultDocumentPaths:a,apiKey:l});A&&(yield this.commonDbService.setupOnDisconnect(A,{status:"offline",lastSeen:new Date().getTime(),sessionId:d}))}}catch(i){this.loggingService.catch("Error in CrdtService setPresence: ",i)}})}onPresenceChange({id:e,callback:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onPresenceChange","color: green;");let i=It(e),a=this.docService.getDocumentPaths$().pipe(Se(l=>l?this.commonDbService.dbListener({feature:"allCrdtPresence",properties:{documentId:l?.documentId??"",organizationId:l?.organizationId??"",id:i,skipFirestore:!0}}).pipe(ln(c=>{try{c?.data?t(c.data):t(c)}catch(d){this.loggingService.catch("Error in CrdtService onPresenceChange subscription: ",d)}})):ce(null))).subscribe(()=>{});return()=>a.unsubscribe()}catch(i){return this.loggingService.catch("Error in CrdtService onPresenceChange: ",i),()=>{}}}saveVersion(l){return X(this,arguments,function*({id:e,versionId:t,versionName:i,state:a}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: saveVersion","color: green;");let c=this.docService.getDocumentPaths();if(c){let d=It(e),m="",u=this.configService.getEncryptionProvider();if(u?.encrypt&&typeof u.encrypt=="function")m=yield u.encrypt({data:a});else{let I={};I.customKey=d,m=yield Rs.encryptData(a,I)}let _={versionId:t,versionName:i,encryptedState:m,timestamp:new Date().getTime()};return this.commonDbService.setData({feature:"crdtVersion",properties:{documentId:c?.documentId??"",organizationId:c?.organizationId??"",id:d,versionId:t,skipFirestore:!0},data:h({id:e},_)})}return Promise.resolve(null)}catch(c){return this.loggingService.catch("Error in CrdtService saveVersion: ",c),Promise.resolve(null)}})}getVersion(i){return X(this,arguments,function*({id:e,versionId:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getVersion","color: green;");let a=this.docService.getDocumentPaths();if(a){let l=It(e),c=yield this.commonDbService.getData({feature:"crdtVersion",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:l,versionId:t,skipFirestore:!0}});if(c?.encryptedState){let d=null,m=this.configService.getEncryptionProvider();if(m?.decrypt&&typeof m.decrypt=="function")d=yield m.decrypt({data:c.encryptedState});else{let u={};u.customKey=l,d=yield Rs.decryptData(c.encryptedState,u)}c.state=d,delete c.encryptedState}return c}return Promise.resolve(null)}catch(a){return this.loggingService.catch("Error in CrdtService getVersion: ",a),Promise.resolve(null)}})}getVersions(t){return X(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getVersions","color: green;");let i=this.docService.getDocumentPaths();if(i){let a=It(e),l=yield this.commonDbService.getData({feature:"crdtVersions",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:a,skipFirestore:!0}}),c=null;if(l){c=[];for(let d of Object.values(l))if(d?.encryptedState){let m=null,u=this.configService.getEncryptionProvider();if(u?.decrypt&&typeof u.decrypt=="function")m=yield u.decrypt({data:d.encryptedState});else{let I={};I.customKey=a,m=yield Rs.decryptData(d.encryptedState,I)}let _=y(h({},d),{state:m});delete _?.encryptedState,c.push(_)}else c.push(d)}return c}return Promise.resolve(null)}catch(i){return this.loggingService.catch("Error in CrdtService getVersions: ",i),Promise.resolve(null)}})}encryptCrdtData(e,t){return X(this,null,function*(){try{let i=this.configService.getEncryptionProvider();if(i?.encrypt&&typeof i.encrypt=="function")return yield i.encrypt({data:e});let a={};return a.customKey=t,yield Rs.encryptData(e,a)}catch(i){return this.loggingService.catch("Error in CrdtService encryptCrdtData: ",i),null}})}decryptCrdtData(e,t){return X(this,null,function*(){try{let i=this.configService.getEncryptionProvider();if(i?.decrypt&&typeof i.decrypt=="function")return yield i.decrypt({data:e});let a={};return a.customKey=t,yield Rs.decryptData(e,a)}catch(i){return this.loggingService.catch("Error in CrdtService decryptCrdtData: ",i),null}})}pushMessage(u){return X(this,arguments,function*({id:e,data:t,yjsClientId:i,messageType:a,eventData:l,type:c,contentKey:d,source:m}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: pushMessage","color: green;");let _=this.docService.getDocumentPaths(),I=this.authService.getUser();if(I?.userId&&_){let A=It(e),M=yield this.encryptCrdtData(t,A);if(M==null)return;let V=I.userId,q=It(I.userId),ae=this.domService.getTabId();if(yield this.commonDbService.pushData({feature:"crdtMessages",properties:{documentId:_?.documentId??"",organizationId:_?.organizationId??"",id:A,skipFirestore:!0},data:{id:e,veltId:A,encryptedData:M,yjsClientId:i,messageType:a??null,type:c??null,contentKey:d??null,source:m??"unknown",updatedByUserId:V,updatedByVeltUserId:q,sessionId:ae,timestamp:this.commonDbService.getServerTimestamp()}}),a==="sync"){let ye=new Date().toISOString(),ie={methodName:HN.UPDATE_DATA,uniqueId:lt(),timestamp:new Date().getTime(),source:GN.INTERNAL,payload:{id:e,data:l,lastUpdatedBy:V,sessionId:ae,lastUpdate:ye}};this.crdtActionsService.triggerAction(FK.UPDATE_DATA,ie),this.trackCrdtDataUpdated(e),this.updateDataWebhookTrigger$.next(ie?.payload),this.trackEditForActivity(e)}}}catch(_){this.loggingService.catch("Error in CrdtService pushMessage: ",_)}})}onMessage({id:e,callback:t,afterTs:i}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: onMessage","color: green;");let a=It(e),l=this.docService.getDocumentPaths$().pipe(Se(c=>c?this.commonDbService.streamChildAdded({feature:"crdtMessages",properties:{documentId:c?.documentId??"",organizationId:c?.organizationId??"",id:a,skipFirestore:!0},afterTs:i}):ce(null))).pipe(Ge(c=>!!c),Dw(c=>X(this,null,function*(){try{if(c.encryptedData){let d=yield this.decryptCrdtData(c.encryptedData,a);if(d==null)return null;c.data=d,delete c.encryptedData}else if(!c.data)return null;return c}catch(d){return this.loggingService.catch("Error in CrdtService onMessage decryption: ",d),null}})),Ge(c=>!!c)).subscribe(c=>{try{t(c)}catch(d){this.loggingService.catch("Error in CrdtService onMessage subscription: ",d)}});return()=>l.unsubscribe()}catch(a){return this.loggingService.catch("Error in CrdtService onMessage: ",a),()=>{}}}getMessages(i){return X(this,arguments,function*({id:e,afterTs:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getMessages","color: green;");let a=this.docService.getDocumentPaths();if(a){let l=It(e),c=yield this.commonDbService.getData({feature:"crdtMessages",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:l,skipFirestore:!0}});if(!c||typeof c!="object"||c?.errorCode)return[];let d=[];for(let m of Object.keys(c)){let u=c[m];if(!(!u||typeof u!="object")&&!(t!=null&&u.timestamp!=null&&u.timestamp<=t))if(u.encryptedData){let _=yield this.decryptCrdtData(u.encryptedData,l);if(_==null)continue;d.push({data:_,yjsClientId:u.yjsClientId,timestamp:u.timestamp})}else u.data&&d.push({data:u.data,yjsClientId:u.yjsClientId,timestamp:u.timestamp})}return d.sort((m,u)=>m.timestamp-u.timestamp),d}return[]}catch(a){return this.loggingService.catch("Error in CrdtService getMessages: ",a),[]}})}getSnapshot(t){return X(this,arguments,function*({id:e}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: getSnapshot","color: green;");let i=this.docService.getDocumentPaths();if(i){let a=It(e),l=yield this.commonDbService.getData({feature:"crdtSnapshot",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:a,skipFirestore:!0}});if(!l||typeof l!="object"||Object.keys(l).length===0||l?.errorCode)return null;if(l?.encryptedState){let c=yield this.decryptCrdtData(l.encryptedState,a);if(c==null)return null;l.state=c,delete l?.encryptedState}if(l?.encryptedVector){let c=yield this.decryptCrdtData(l.encryptedVector,a);if(c==null)return null;l.vector=c,delete l?.encryptedVector}return l}return Promise.resolve(null)}catch(i){return this.loggingService.catch("Error in CrdtService getSnapshot: ",i),Promise.resolve(null)}})}saveSnapshot(d){return X(this,arguments,function*({id:e,state:t,vector:i,type:a,contentKey:l,source:c}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: saveSnapshot","color: green;");let m=this.docService.getDocumentPaths(),u=this.authService.getUser();if(u?.userId&&m){let _=It(e),I=yield this.encryptCrdtData(t,_),A=yield this.encryptCrdtData(i,_);if(I==null||A==null)return;let M=u.userId,V=It(u.userId),q=this.domService.getTabId();yield this.commonDbService.setData({feature:"crdtSnapshot",properties:{documentId:m?.documentId??"",organizationId:m?.organizationId??"",id:_,skipFirestore:!0},data:{id:e,veltId:_,encryptedState:I,encryptedVector:A,type:a??null,contentKey:l??null,source:c??"unknown",updatedByUserId:M,updatedByVeltUserId:V,sessionId:q,timestamp:this.commonDbService.getServerTimestamp()}})}}catch(m){this.loggingService.catch("Error in CrdtService saveSnapshot: ",m)}})}pruneMessages(i){return X(this,arguments,function*({id:e,beforeTs:t}){try{this.loggingService.log("%c[WB] Calling CrdtService FUNCTION: pruneMessages","color: green;");let a=this.docService.getDocumentPaths();if(a){let l=It(e),c=yield this.commonDbService.getData({feature:"crdtMessages",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:l,skipFirestore:!0}});if(c&&typeof c=="object"&&!c?.errorCode){let d=[];for(let m of Object.keys(c)){let u=c[m];u?.timestamp!=null&&u.timestamp<t&&d.push(this.commonDbService.deleteData({feature:"crdtMessage",properties:{documentId:a?.documentId??"",organizationId:a?.organizationId??"",id:l,messageId:m,skipFirestore:!0}}))}yield Promise.all(d)}}}catch(a){this.loggingService.catch("Error in CrdtService pruneMessages: ",a)}})}updateNotificationsDatabase(e,t,i={}){try{let a=h({crdtData:e,actionType:t,notificationSource:"crdt"},i);this.notificationService.updateNotificationDatabase(a)}catch(a){this.loggingService.catch("Error in CrdtService updateNotificationsDatabase: ",a)}}enableWebhook(){try{if(this.webhookEnabled$.value===!0)return;this.webhookEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in CrdtService enableWebhook: ",e)}}disableWebhook(){try{if(this.webhookEnabled$.value===!1)return;this.webhookEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in CrdtService disableWebhook: ",e)}}trackEditForActivity(e){try{let t=this.editorEditTrackers.get(e);if(!t){let i=new at,a=i.pipe(Qr(this.activityDebounceTime)).subscribe(()=>{this.flushEditorActivity(e)});t={count:0,subject$:i,subscription:a},this.editorEditTrackers.set(e,t)}t.count++,t.subject$.next()}catch(t){this.loggingService.catch("Error in CrdtService trackEditForActivity: ",t)}}flushEditorActivity(e){try{let t=this.editorEditTrackers.get(e);if(!t||t.count===0)return;let i=t.count;t.count=0;let a={featureType:"crdt",actionType:zpe.EDITOR_EDIT,targetEntityId:e,entityData:{editCount:i}};this.activityService.createActivity(a)}catch(t){this.loggingService.catch("Error in CrdtService flushEditorActivity: ",t)}}setActivityDebounceTime(e){try{e<this.MIN_ACTIVITY_DEBOUNCE_TIME&&(this.loggingService.catch("Error in CrdtService setActivityDebounceTime: Value must be at least "+this.MIN_ACTIVITY_DEBOUNCE_TIME/1e3+" seconds ("+this.MIN_ACTIVITY_DEBOUNCE_TIME+"ms). Using minimum value."),e=this.MIN_ACTIVITY_DEBOUNCE_TIME),this.flushAllEditorActivities(),this.activityDebounceTime=e}catch(t){this.loggingService.catch("Error in CrdtService setActivityDebounceTime: ",t)}}flushAllEditorActivities(){try{for(let[e,t]of this.editorEditTrackers)t.count>0&&this.flushEditorActivity(e),t.subject$.complete(),t.subscription.unsubscribe();this.editorEditTrackers.clear()}catch(e){this.loggingService.catch("Error in CrdtService flushAllEditorActivities: ",e)}}};o.\u0275fac=function(t){return new(t||o)(K(Lg),K(ct),K(qe),K(yn),K(vd),K(Ft),K(aU),K(st),K(Ve),K(k),K(mn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var lU=class extends Cr{constructor(o){super(o),this.getService(k).log("%c[WB] Creating CLASS: CrdtElement","color: blue;"),this.updateData=this._updateData,this.onDataChange=this._onDataChange,this.getData=this._getData,this.onStateChange=this._onStateChange,this.updateState=this._updateState,this.registerSyncUser=this._registerSyncUser,this.onRegisteredUserChange=this._onRegisteredUserChange,this.setPresence=this._setPresence,this.onPresenceChange=this._onPresenceChange,this.saveVersion=this._saveVersion,this.getVersion=this._getVersion,this.getVersions=this._getVersions,this.pushMessage=this._pushMessage,this.onMessage=this._onMessage,this.getMessages=this._getMessages,this.getSnapshot=this._getSnapshot,this.saveSnapshot=this._saveSnapshot,this.pruneMessages=this._pruneMessages,this.enableWebhook=this._enableWebhook,this.disableWebhook=this._disableWebhook,this.setWebhookDebounceTime=this._setWebhookDebounceTime,this.setActivityDebounceTime=this._setActivityDebounceTime,this.on=this._on}_updateData(o){this.getService(k).log("%c[WB] Calling FUNCTION: updateData","color: green;");try{return this.getService(Pi).updateData(o)}catch(r){return this.getService(k).catch("Error in updateData: ",r),Promise.resolve(null)}}_onDataChange(o){this.getService(k).log("%c[WB] Calling FUNCTION: onDataChange","color: green;");try{return this.getService(Pi).onDataChange(o)}catch(r){return this.getService(k).catch("Error in onDataChange: ",r),()=>{}}}_getData(o){this.getService(k).log("%c[WB] Calling FUNCTION: getData","color: green;");try{return this.getService(Pi).getData(o)}catch(r){return this.getService(k).catch("Error in getData: ",r),Promise.resolve(null)}}_onStateChange(o){this.getService(k).log("%c[WB] Calling FUNCTION: onStateChange","color: green;");try{return this.getService(Pi).onStateChange(o)}catch(r){return this.getService(k).catch("Error in onStateChange: ",r),()=>{}}}_updateState(o){this.getService(k).log("%c[WB] Calling FUNCTION: updateState","color: green;");try{return this.getService(Pi).updateState(o)}catch(r){return this.getService(k).catch("Error in updateState: ",r),Promise.resolve(null)}}_registerSyncUser(o){this.getService(k).log("%c[WB] Calling FUNCTION: registerSyncUser","color: green;");try{return this.getService(Pi).registerSyncUser(o)}catch(r){return this.getService(k).catch("Error in registerSyncUser: ",r),Promise.resolve()}}_onRegisteredUserChange(o){this.getService(k).log("%c[WB] Calling FUNCTION: onRegisteredUserChange","color: green;");try{return this.getService(Pi).onRegisteredUserChange(o)}catch(r){return this.getService(k).catch("Error in onRegisteredUserChange: ",r),()=>{}}}_setPresence(o){this.getService(k).log("%c[WB] Calling FUNCTION: setPresence","color: green;");try{return this.getService(Pi).setPresence(o)}catch(r){return this.getService(k).catch("Error in setPresence: ",r),Promise.resolve()}}_onPresenceChange(o){this.getService(k).log("%c[WB] Calling FUNCTION: onPresenceChange","color: green;");try{return this.getService(Pi).onPresenceChange(o)}catch(r){return this.getService(k).catch("Error in onPresenceChange: ",r),()=>{}}}_saveVersion(o){this.getService(k).log("%c[WB] Calling FUNCTION: saveVersion","color: green;");try{return this.getService(Pi).saveVersion(o)}catch(r){return this.getService(k).catch("Error in saveVersion: ",r),Promise.resolve(null)}}_getVersion(o){this.getService(k).log("%c[WB] Calling FUNCTION: getVersion","color: green;");try{return this.getService(Pi).getVersion(o)}catch(r){return this.getService(k).catch("Error in getVersion: ",r),Promise.resolve(null)}}_getVersions(o){this.getService(k).log("%c[WB] Calling FUNCTION: getVersions","color: green;");try{return this.getService(Pi).getVersions(o)}catch(r){return this.getService(k).catch("Error in getVersions: ",r),Promise.resolve(null)}}_pushMessage(o){this.getService(k).log("%c[WB] Calling FUNCTION: pushMessage","color: green;");try{return this.getService(Pi).pushMessage(o)}catch(r){return this.getService(k).catch("Error in pushMessage: ",r),Promise.resolve()}}_onMessage(o){this.getService(k).log("%c[WB] Calling FUNCTION: onMessage","color: green;");try{return this.getService(Pi).onMessage(o)}catch(r){return this.getService(k).catch("Error in onMessage: ",r),()=>{}}}_getMessages(o){this.getService(k).log("%c[WB] Calling FUNCTION: getMessages","color: green;");try{return this.getService(Pi).getMessages(o)}catch(r){return this.getService(k).catch("Error in getMessages: ",r),Promise.resolve([])}}_getSnapshot(o){this.getService(k).log("%c[WB] Calling FUNCTION: getSnapshot","color: green;");try{return this.getService(Pi).getSnapshot(o)}catch(r){return this.getService(k).catch("Error in getSnapshot: ",r),Promise.resolve(null)}}_saveSnapshot(o){this.getService(k).log("%c[WB] Calling FUNCTION: saveSnapshot","color: green;");try{return this.getService(Pi).saveSnapshot(o)}catch(r){return this.getService(k).catch("Error in saveSnapshot: ",r),Promise.resolve()}}_pruneMessages(o){this.getService(k).log("%c[WB] Calling FUNCTION: pruneMessages","color: green;");try{return this.getService(Pi).pruneMessages(o)}catch(r){return this.getService(k).catch("Error in pruneMessages: ",r),Promise.resolve()}}_enableWebhook(){this.getService(k).log("%c[WB] Calling FUNCTION: enableWebhook","color: green;");try{return this.getService(Pi).enableWebhook()}catch(o){this.getService(k).catch("Error in enableWebhook: ",o);return}}_disableWebhook(){this.getService(k).log("%c[WB] Calling FUNCTION: disableWebhook","color: green;");try{return this.getService(Pi).disableWebhook()}catch(o){this.getService(k).catch("Error in disableWebhook: ",o);return}}_setWebhookDebounceTime(o){this.getService(k).log("%c[WB] Calling FUNCTION: setWebhookDebounceTime","color: green;");try{!isNaN(o)&&o>0?this.getService(Pi).setWebhookDebounceTime(o):this.getService(k).catch("Error in setWebhookDebounceTime: ","Provided value must be a positive number greater than zero.")}catch(r){this.getService(k).catch("Error in setWebhookDebounceTime: ",r)}}_setActivityDebounceTime(o){this.getService(k).log("%c[WB] Calling FUNCTION: setActivityDebounceTime","color: green;");try{!isNaN(o)&&o>=1e4?this.getService(Pi).setActivityDebounceTime(o):this.getService(k).catch("Error in setActivityDebounceTime: ","Provided value must be a number >= 10000ms (10 seconds).")}catch(r){this.getService(k).catch("Error in setActivityDebounceTime: ",r)}}_on(o){this.getService(k).log("%c[WB] Calling FUNCTION: on","color: green;");try{return this.getService(aU).onAction(o)}catch(r){return this.getService(k).catch("Error in on: ",r),ce(null)}}};var wc=(function(n){return n.CLICK="click",n.HOVER="hover",n.SCROLL="scroll",n.NAVIGATE="navigate",n})(wc||{}),Ug=class{constructor(){this.type=wc.HOVER,this.data=null,this.pageInfo=ro(),this.timestamp=Date.now()}},cU=class{constructor(o,r){this.targetXpath=o,this.xpath=r}};var sU=class{constructor(){this.sessionId=null,this.isLeader=!1,this.lastProcessedActionTimestamp=null}};var K0=class{constructor(o){this.snippylyId=o,this.joinTimestamp=Date.now()}};var dU=class{constructor(o,r,e){this.followers=[],this.actionStack=[],this.id=lt(),this.leaderId=o,this.leaderName=r,this.followers.push(new K0(e))}};var Wbe=(()=>{let o=class o{constructor(e,t,i,a,l){this.databaseService=e,this.docService=t,this.loggingService=i,this.authService=a,this.commonDbService=l,this.currentUser$=new _e(null),this.currentSession$=new _e(null);try{this.databaseService.getDb().pipe(Ge(c=>!!c),ut(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,i){try{let a=this.docService.getDocumentPaths();a&&this.db&&this.commonDbService.dbListener({feature:"flockUser",properties:{documentId:a?.documentId,organizationId:a?.organizationId,id:e,skipFirestore:!0}}).pipe(ut(1)).subscribe(l=>{l?.data&&l?.data?.sessionId?this.subscribeToCurrentSession(l?.data?.sessionId,i):this.createFlockSession(e,t,i)})}catch(a){this.loggingService.catch("Error in FlockSessionService provisionFlockSession: ",a)}return null}swapLeader(e,t,i){try{if(this.updateRemoteFlockUser(e,{isLeader:!1}),this.updateRemoteFlockUser(t,{isLeader:!0}),this.currentSession){this.currentSession.leaderId=t,this.currentSession.leaderName=i,this.currentSession.followers.push(new K0(e));let a=this.currentSession.followers.findIndex(l=>l.snippylyId===t);a>-1&&this.currentSession.followers.splice(a,1),this.updateSession(this.currentSession.id,this.currentSession)}}catch(a){this.loggingService.catch("Error in FlockSessionService swapLeader: ",a)}}createFlockSession(e,t,i){try{let a=new dU(e,t,i);return this.updateRemoteFlockUser(e,{snippylyId:e,sessionId:a.id,isLeader:!0}),this.updateSession(a.id,a),this.subscribeToCurrentSession(a.id),a.id}catch(a){this.loggingService.catch("Error in FlockSessionService createFlockSession: ",a)}return null}removeFollowerFromCurrentSession(e){try{if(this.currentSession){this.updateRemoteFlockUser(e,{sessionId:null,lastProcessedActionTimestamp:null});let t=this.currentSession.followers.findIndex(i=>i.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 i=this.docService.getDocumentPaths();for(let a in t)t.hasOwnProperty(a)&&t[a]===void 0&&delete t[a];i&&this.db&&this.commonDbService.updateData({feature:"flockUser",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:e,skipFirestore:!0},data:JSON.parse(JSON.stringify(t))})}catch(i){this.loggingService.catch("Error in FlockSessionService updateRemoteFlockUser: ",i)}}subscribeToCurrentSession(e,t=void 0){try{let i=this.docService.getDocumentPaths();i&&this.db&&(this.sessionSub&&this.sessionSub.unsubscribe(),this.sessionSub=this.commonDbService.dbListener({feature:"flockSession",properties:{documentId:i?.documentId,organizationId:i?.organizationId,id:e,skipFirestore:!0}}).subscribe(a=>{a?.data&&typeof a?.data=="object"&&Object.keys(a?.data)?.length>0?(this.currentSession=a?.data,t!==void 0&&this.currentSession?.followers.findIndex(l=>l.snippylyId===t)===-1&&(this.currentSession.followers.push(new K0(t)),this.updateSession(this.currentSession.id,this.currentSession)),this.currentSession$.next(this.currentSession??null)):(this.currentSession=void 0,this.currentSession$.next(null))}))}catch(i){this.loggingService.catch("Error in FlockSessionService subscribeToCurrentSession: ",i)}}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(Xn(i=>(this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser: ",i),ce(null)))).subscribe(i=>{i?.data&&typeof i?.data=="object"&&Object.keys(i?.data)?.length>0&&(this.currentUser$.next(i?.data),i?.data?.sessionId&&this.subscribeToCurrentSession(i?.data?.sessionId))},i=>{this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser subscription: ",i)}))}catch(t){this.loggingService.catch("Error in FlockSessionService subscribeToCurrentFlockUser: ",t)}}updateSession(e,t={}){try{if(!e)return;let i=this.docService.getDocumentPaths();for(let a in t)t.hasOwnProperty(a)&&t[a]===void 0&&delete t[a];i&&this.db&&this.commonDbService.updateData({feature:"flockSession",properties:{documentId:i?.documentId??"",organizationId:i?.organizationId??"",id:e,skipFirestore:!0},data:JSON.parse(JSON.stringify(t))})}catch(i){this.loggingService.catch("Error in FlockSessionService updateSession: ",i)}}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(i=>{this.updateRemoteFlockUser(i.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 i=this.docService.getDocumentPaths();if(i&&this.db&&e){let a=jr(this.db,`${i.flock}/sessions/${e}/actionStack`);t0(a,l=>l?(l.unshift(t),l.slice(0,5)):[t]),t.type===wc.NAVIGATE&&this.updateSession(e,{pageInfo:t.pageInfo})}}catch(i){this.loggingService.catch("Error in FlockSessionService addActionToStack: ",i)}}};o.\u0275fac=function(t){return new(t||o)(K($n),K(st),K(k),K(qe),K(yn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();function eqe(n,o){if(n&1&&(f(0,"span",6),re(1),R(2,"translate"),S()),n&2){let r=s(2).ngIf;v(),Qi("",F(2,2,"You are following")," ",r.leaderName)}}function tqe(n,o){n&1&&(f(0,"span",6),re(1),R(2,"translate"),S()),n&2&&(v(),Ye(F(2,1,"You are leading.")))}function nqe(n,o){if(n&1){let r=Z();f(0,"div",2),z("click",function(){L(r);let t=s().ngIf,i=s();return U(t.type==="following"?i.closeOverlay():void 0)}),f(1,"div",3),p(2,eqe,3,4,"span",4)(3,tqe,3,3,"span",4),f(4,"button",5),z("click",function(){L(r);let t=s(2);return U(t.closeOverlay())}),re(5),R(6,"translate"),R(7,"translate"),S()()()}if(n&2){let r=s().ngIf;fe("no-pointer",r.type==="leading"),v(2),g("ngIf",r.type==="following"),v(),g("ngIf",r.type==="leading"),v(2),Qi("",F(6,6,"Stop")," ",F(7,8,r.type))}}function rqe(n,o){if(n&1&&(C(0),p(1,nqe,8,10,"div",1),b()),n&2){let r=o.ngIf;v(),g("ngIf",r.leaderName!==""||r.type==="leading")}}var BO=(()=>{let o=class o extends At{closeOverlay(){this.closeOverlayEvent.emit()}constructor(e,t,i,a){super(t,i),this.loggingService=e,this.elementRef=t,this.themeService=i,this.domService=a,this.closeOverlayEvent=new Ue,this.componentConfigSignal=De({leaderName:"",type:"following"})}ngOnInit(){}ngAfterViewInit(){try{this.customCssSubscription=this.domService.subscribeInjectCustomCss(this.elementRef)}catch(e){this.loggingService.catch("Error in FollowOverlayComponent ngAfterViewInit: ",e)}}setLeaderName(e){try{this.componentConfigSignal.update(t=>(t=y(h({},t),{leaderName:e}),t))}catch(t){this.loggingService.catch("Error in FollowOverlayComponent setLeaderName: ",t)}}getLeaderName(){return this.componentConfigSignal().leaderName}setType(e){try{this.componentConfigSignal.update(t=>(t=y(h({},t),{type:e}),t))}catch(t){this.loggingService.catch("Error in FollowOverlayComponent setType: ",t)}}ngOnDestroy(){try{super.ngOnDestroy(),this.customCssSubscription?.unsubscribe()}catch(e){this.loggingService.catch("Error in FollowOverlayComponent ngOnDestroy: ",e)}}};o.\u0275fac=function(t){return new(t||o)(x(k),x(Q),x(yt),x(Ve))},o.\u0275cmp=O({type:o,selectors:[["snippyly-follow-overlay"]],outputs:{closeOverlayEvent:"closeOverlayEvent"},standalone:!1,features:[P],decls:1,vars:1,consts:[[4,"ngIf"],["data-velt-ignore","","class","follow-overlay-container",3,"no-pointer","click",4,"ngIf"],["data-velt-ignore","",1,"follow-overlay-container",3,"click"],["data-velt-ignore","",1,"follow-dialog"],["data-velt-ignore","","class","follow-text",4,"ngIf"],["data-velt-ignore","",1,"follow-btn",3,"click"],["data-velt-ignore","",1,"follow-text"]],template:function(t,i){t&1&&p(0,rqe,2,1,"ng-container",0),t&2&&g("ngIf",i.componentConfigSignal())},styles:[`html{--velt-base-rem-unit: 1}*[data-snippyly-element=true],*[data-velt-element=true]{font-family:var(--velt-default-font-family)}velt-wireframe{display:none!important}body.velt-pin-dragging iframe{pointer-events:none!important}.follow-overlay-container{position:fixed;top:0;left:0;width:100%;height:100%;background-color:transparent;z-index:var(--velt-follow-mode-overlay-z-index);display:flex;justify-content:center;align-items:flex-end}.follow-overlay-container .follow-dialog{background-color:var(--legacy-velt-follow-overlay-bg-color);color:var(--legacy-velt-follow-overlay-text-color);font-size:12px;display:flex;justify-content:center;align-items:center;gap:calc((1.2rem + 0px) * var(--velt-base-rem-unit));padding:calc((.9rem + 0px) * var(--velt-base-rem-unit)) calc((1.1rem + 0px) * var(--velt-base-rem-unit));border-radius:90px;margin-bottom:calc((2rem + 0px) * var(--velt-base-rem-unit));box-shadow:0 8px 16px -8px #0f0f0f1a;border:1px solid var(--legacy-velt-follow-overlay-border-color)}.follow-overlay-container .follow-dialog .follow-btn{background-color:var(--legacy-velt-follow-overlay-btn-color);padding:8px 12px;border-radius:90px;display:inline-flex;justify-content:center;align-items:center;border:none;font-weight:600;font-size:14px;cursor:pointer;pointer-events:all}.follow-overlay-container .follow-dialog .follow-btn:hover{transition:background-color .5s;background-color:var(--legacy-velt-follow-overlay-btn-hover-color)}.follow-overlay-container.no-pointer{pointer-events:none}
501
501
  `],encapsulation:3,changeDetection:0});let n=o;return n})();var qbe=(()=>{let o=class o{constructor(e,t,i,a){this.componentFactoryResolver=e,this.applicationRef=t,this.injector=i,this.loggingService=a,this.darkMode=!1}createFollowOverlay(e,t){try{let a=this.componentFactoryResolver.resolveComponentFactory(BO).create(this.injector);a.instance.setLeaderName(e),a.instance.closeOverlayEvent.pipe(ut(1)).subscribe(()=>{this.removeOverlay(),t()}),this.applicationRef.attachView(a.hostView),this.overlayRef=a,this.overlayRef.instance.darkMode=this.darkMode;let l=this.overlayRef.location.nativeElement;l.id="snippyly-follow-overlay",l.setAttribute(N.ATTRIBUTES.VELT_IGNORE,""),document.body.appendChild(l)}catch(i){this.loggingService.catch("Error in FlockOverlayService createFollowOverlay: ",i)}}createLeaderOverlay(e){let i=this.componentFactoryResolver.resolveComponentFactory(BO).create(this.injector);i.instance.setType("leading"),i.instance.closeOverlayEvent.pipe(ut(1)).subscribe(()=>{this.removeOverlay(),e()}),this.applicationRef.attachView(i.hostView),this.overlayRef=i,this.overlayRef.instance.darkMode=this.darkMode;let a=this.overlayRef.location.nativeElement;a.id="snippyly-follow-overlay",a.setAttribute(N.ATTRIBUTES.VELT_IGNORE,""),document.body.appendChild(a)}changeLeaderName(e){this.overlayRef&&this.overlayRef.instance.setLeaderName(e)}getLeaderName(){return this.overlayRef?this.overlayRef.instance.getLeaderName():null}removeOverlay(){if(this.overlayRef){let e=this.overlayRef.location.nativeElement;this.applicationRef.detachView(this.overlayRef.hostView),this.overlayRef.destroy(),e.shadowRoot&&e.shadowRoot.removeChild(e.shadowRoot.childNodes[0]),e.remove(),this.overlayRef=void 0}}setDarkMode(e){try{this.darkMode=e,this.overlayRef&&(this.overlayRef.instance.darkMode=e)}catch(t){this.loggingService.catch("Error in FlockOverlayService setDarkMode: ",t)}}};o.\u0275fac=function(t){return new(t||o)(K(Qo),K(wr),K(Dt),K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var hv=(()=>{let o=class o{constructor(e,t,i,a,l){this.authService=e,this.domService=t,this.loggingService=i,this.flockSessionService=a,this.flockOverlayService=l,this.flockLeader$=new _e({userId:"",name:""}),this.flockMode$=new _e(!1),this.currentFlockUser=null,this.localScrollData=[],this.domSubscriptions=[],this.followOverlayCreated=!1,this.leaderOverlayCreated=!1,this.windowFocused=!0,this.tabFocused=!0,this.useHistoryAPI=!0,this.disableDefaultNavigation=!1;try{this.flockLeader$.subscribe(c=>{let{userId:d,name:m}=c,u=d;if(this.provisionFollowUser(),u&&this.currentFlockUser&&this.currentFlockUser.snippylyId)if(this.currentFlockUser.sessionId){if(this.currentFlockUser.snippylyId&&this.currentFlockUser.isLeader){this.flockSessionService.swapLeader(this.currentFlockUser.snippylyId,u,m);return}this.removeCurrentUserFromSession()}else this.flockSessionService.provisionFlockSession(u,m,this.currentFlockUser.snippylyId)},c=>{this.loggingService.catch("Error in FlockService flockLeader$ subscription: ",c)}),this.flockSessionService.currentSession$.subscribe(c=>{if(c!==null){if(this.currentFlockUser&&(this.currentFlockUser.sessionId===null||this.currentFlockUser.sessionId===void 0)&&this.currentFlockUser.snippylyId&&(this.currentFlockUser.sessionId=c.id,this.flockSessionService.updateRemoteFlockUser(this.currentFlockUser.snippylyId,this.currentFlockUser)),this.currentFlockUser&&!this.currentFlockUser.isLeader&&!this.followOverlayCreated&&(this.leaderOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.leaderOverlayCreated=!1),this.followOverlayCreated=!0,this.flockOverlayService.createFollowOverlay(c.leaderName,()=>{this.removeCurrentUserFromSession(),this.followOverlayCreated=!1})),this.currentFlockUser&&this.currentFlockUser.isLeader&&!this.leaderOverlayCreated&&(this.followOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.followOverlayCreated=!1),this.leaderOverlayCreated=!0,this.flockOverlayService.createLeaderOverlay(()=>{this.removeCurrentUserFromSession(),this.leaderOverlayCreated=!1})),this.currentFlockUser&&!this.currentFlockUser.isLeader&&c.actionStack){let d=c.actionStack[0];d&&this.currentFlockUser.lastProcessedActionTimestamp!==d.timestamp&&this.processAction(d)}if(this.currentFlockUser&&!this.currentFlockUser.isLeader&&this.followOverlayCreated&&this.flockOverlayService.getLeaderName()!==null&&c.leaderName!==this.flockOverlayService.getLeaderName()&&this.flockOverlayService.changeLeaderName(c.leaderName),this.currentFlockUser&&this.currentFlockUser.isLeader){let d=ro();if(c.pageInfo){if(d&&d.url!==c.pageInfo.url){let m=new Ug;m.type=wc.NAVIGATE,this.flockSessionService.addActionToStack(c.id,m)}}else{this.flockSessionService.updateSession(c.id,{pageInfo:d});let m=new Ug;m.type=wc.NAVIGATE,this.flockSessionService.addActionToStack(c.id,m)}}}else this.currentFlockUser&&this.leaderOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.leaderOverlayCreated=!1),this.currentFlockUser&&this.followOverlayCreated&&(this.flockOverlayService.removeOverlay(),this.followOverlayCreated=!1)}),this.flockSessionService.currentUser$.subscribe(c=>{if(c!==null&&(this.currentFlockUser&&this.currentFlockUser.isLeader!==c.isLeader&&(this.domSubscriptions.forEach(d=>d.unsubscribe()),this.domSubscriptions=[]),this.currentFlockUser=c,c.sessionId&&this.domSubscriptions.length===0))if(c.isLeader){if(!this.tabFocused||!this.windowFocused)return;this.subscribeToLeaderDOMEvents()}else this.subscribeToFollowerDOMEvents()}),gn([this.authService.getUser$(),this.getFlockMode$()]).subscribe(([c,d])=>{c&&c.userSnippylyId&&d?this.flockSessionService.startCurrentFlockUserSubscription(c):this.flockSessionService.stopCurrentFlockUserSubscription()})}catch(c){this.loggingService.catch("Error in FlockService constructor: ",c)}}provisionFollowUser(){try{if(this.currentFlockUser===null){let e=this.authService.getUser();e&&e.userSnippylyId&&(this.currentFlockUser=new sU,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(i){this.loggingService.catch("Error in FlockService startFollowingUser: ",i)}}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=(...i)=>{e.apply(window.history,i),this.onUrlChange()},window.history.replaceState=(...i)=>{t.apply(window.history,i),this.onUrlChange()},this.domSubscriptions.push({unsubscribe:()=>{window.history.pushState=e,window.history.replaceState=t}}),this.domSubscriptions.push(Er(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 Ug;e.type=wc.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 wc.CLICK:this.clickUserElement(e.data);break;case wc.HOVER:this.scrollToHoveredElement(e.data);break;case wc.SCROLL:this.scrollToFollowedUser(e.data);break;case wc.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(Er(window,"mouseover").pipe(Qr(500)).subscribe(e=>{let t=e?.target;if(t){let i=window.getComputedStyle(t);if(i.position==="fixed"||i.position==="sticky"||t.hasAttribute(N.ATTRIBUTES.VELT_IGNORE))return;t=XK(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(N.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),i=p1(e),a=this.domService.getXPath(i),l={id:Math.random().toString(36).substring(2),xpath:t,parentXpath:a},c=new Ug;c.type=wc.CLICK,c.data=l,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,c)}}catch(t){this.loggingService.catch("Error in FlockService updateClickedElement: ",t)}}updateHoveredElement(e){try{if(this.currentFlockUser&&this.currentFlockUser.sessionId){let t=this.domService.getXPath(e),i=p1(e),a=this.domService.getXPath(i),l={id:Math.random().toString(36).substring(2),xpath:t,parentXpath:a},c=new Ug;c.type=wc.HOVER,c.data=l,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,c)}}catch(t){this.loggingService.catch("Error in FlockService updateHoveredElement: ",t)}}subscribeToScrollables(){try{let e=vhe();e.push(document),e?.forEach(t=>{this.domSubscriptions.push(Er(t,"scroll").pipe(Qr(100)).subscribe(i=>{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 cU("","");if(e===document){let l=uhe();if(l){let c=XK(l);c&&(t.targetXpath=this.domService.getXPath(c))}t.xpath=""}else{let l=ghe(e);t.targetXpath=this.domService.getXPath(l),t.xpath=this.domService.getXPath(e)}let i=!1,a=!1;if(this.localScrollData.forEach((l,c)=>{l.xpath===l.xpath&&(t.targetXpath!==l.targetXpath&&(i=!0),this.localScrollData[c]=Object.assign(l,t),a=!0)}),a||this.localScrollData.push(t),i||!a){let l=new Ug;l.type=wc.SCROLL,l.data=t,this.flockSessionService.addActionToStack(this.currentFlockUser.sessionId,l)}}}catch(t){this.loggingService.catch("Error in FlockService calculateScrollPositionOfAnElement: ",t)}}enableFlockMode(e){try{if(this.flockMode$.next(!0),e){let{useHistoryAPI:t,onNavigate:i,disableDefaultNavigation:a,darkMode:l}=e;t!==void 0&&(this.useHistoryAPI=t),i!==void 0&&typeof i=="function"&&(this.onNavigate=i),a!==void 0&&(this.disableDefaultNavigation=a),this.flockOverlayService.setDarkMode(l)}}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(i=>{i.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(i=>{i.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(i){this.loggingService.catch("Error in FlockService setFlockLeader: ",i)}}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 i=ro()?.url,a=e.url;if(i!==a&&a!==void 0){let{url:l,path:c,baseUrl:d}=e;if(this.onNavigate!==void 0&&typeof this.onNavigate=="function"){this.onNavigate({url:l,path:c,baseUrl:d});return}if(this.onNavigateEmitter&&this.onNavigateEmitter.emit({url:l,path:c,baseUrl:d}),this.disableDefaultNavigation)return;window.location.href=a}}catch(t){this.loggingService.catch("Error in FlockService checkMatchingUrl: ",t)}}scrollToFollowedUser(e){try{if(e.xpath===""){let t=this.domService.getElementFromXPath(e.targetXpath);t&&aF(t)}else{let t=this.domService.getElementFromXPath(e.xpath),i=this.domService.getElementFromXPath(e.targetXpath);t&&i&&(aF(t),QK(t,i))}}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")aF(t);else{let i=this.domService.getElementFromXPath(e.parentXpath);i&&QK(i,t,!0)}}catch(t){this.loggingService.catch("Error in FlockService clickUserElement: ",t)}}};o.\u0275fac=function(t){return new(t||o)(K(qe),K(Ve),K(k),K(Wbe),K(qbe))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var ic=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A){this.analyticsService=e,this.docService=t,this.domService=i,this.authService=a,this.afAuth=l,this.iamService=c,this.databaseService=d,this.configService=m,this.avatarService=u,this.loggingService=_,this.flockService=I,this.commonDbService=A,this.db=null,this.presenceUser$=new _e(new S3),this.documentPaths=null,this.inactivityTime=300*1e3,this.offlineInactivityTime=600*1e3,this.presenceUsers$=new _e([]),this.presenceUsersSubscription=null,this.includeSelf$=new _e(!0),this.customPresenceUsers$=new _e([]),this.userIdleStateDetectionSubscription=null,this.userOfflineStateDetectionSubscription=null;try{this.loggingService.log("%c[WB] Creating CLASS: PresenceService","color: blue;"),this.databaseService.getDb().pipe(Ge(M=>!!M),ut(1)).subscribe(M=>{M&&(this.db=M,this.getUser(),this.getDocumentPaths(),this.getLocation(),this.updateOnUserDbConnectionStateChange().subscribe(()=>{},V=>{this.loggingService.catch("Error in PresenceService constructor updateOnUserDbConnectionStateChange: ",V)}),this.updateOnDatabaseDisconnect().subscribe(()=>{},V=>{this.loggingService.catch("Error in PresenceService constructor updateOnDatabaseDisconnect: ",V)}),this.updateOnDocumentFocusChange(),this.updateOnAllowedFeatureListChange())},M=>{this.loggingService.catch("Error in PresenceService constructor: ",M)}),this.authService.addPreSignOutFuction("presence-signout",this.signOutUser.bind(this)),this.presenceUsers$.pipe(Fr()).subscribe(([M,V])=>{try{V?.length>=0&&this.analyticsService.updateDefaultProperties({presenceUsersCount:V?.length}),sessionStorage.getItem(N.SESSION_STORAGE.VELT_PRESENCE_MULTIPLE_USERS_ONLINE)||V?.length>1&&M.length!==V.length&&(sessionStorage.setItem(N.SESSION_STORAGE.VELT_PRESENCE_MULTIPLE_USERS_ONLINE,"true"),this.presenceActionsService?.onMultipleUsersOnline({users:V}))}catch(q){this.loggingService.catch("Error in presenceUsers$ pairwise subscription: ",q)}}),this.authService.getUser$().pipe(Ge(M=>!!M),ut(1)).subscribe(M=>{M?(this.detectUserIdleState(),this.detectUserOfflineState()):(this.unsubscribeUserIdleStateDetectionSubscription(),this.unsubscribeUserOfflineStateDetectionSubscription())}),this.presenceUser$.subscribe(M=>{try{M?.onlineStatus&&this.presenceActionsService?.onUserStateChange({user:JSON.parse(JSON.stringify(M)),state:M?.onlineStatus})}catch(V){this.loggingService.catch("Error in presenceUser$ subscription: ",V)}},M=>{this.loggingService.catch("Error in presenceUser$ subscribe: ",M)}),this.customPresenceUsers$.subscribe(()=>{try{let M=this.presenceUsers$.value.filter(V=>!V.localOnly);this.presenceUsers$.next(this.mergeWithCustomUsers(M))}catch(M){this.loggingService.catch("Error in customPresenceUsers$ subscription: ",M)}}),this.domService.onNetworkStatusChange$().subscribe(M=>{try{!M&&this.presenceUser$?.value?.onlineStatus&&this.presenceActionsService?.onUserStateChange({user:y(h({},JSON.parse(JSON.stringify(this.presenceUser$.value))),{onlineStatus:N.PRESENCE_STATUS_OFFLINE}),state:N.PRESENCE_STATUS_OFFLINE})}catch(V){this.loggingService.catch("Error in domService.onNetworkStatusChange$ subscription: ",V)}},M=>{this.loggingService.catch("Error in domService.onNetworkStatusChange$ subscribe: ",M)})}catch(M){this.loggingService.catch("Error in PresenceService constructor: ",M)}}setPresenceActionsService(e){try{this.presenceActionsService=e}catch(t){this.loggingService.catch("Error in setPresenceActionsService: ",t)}}detectUserIdleState(){try{this.unsubscribeUserIdleStateDetectionSubscription();let e=!1;this.userIdleStateDetectionSubscription=this.domService.onWindowPointerMove$().pipe(nu(2e3),ln(()=>{this.presenceUser$.value&&e&&(this.setCurrentPresenceUserStatus(N.PRESENCE_STATUS_ONLINE),e=!1)}),Qr(this.inactivityTime),ln(()=>{this.setCurrentPresenceUserStatus(N.PRESENCE_STATUS_AWAY,{isUserIdle:!0}),e=!0})).subscribe()}catch(e){this.loggingService.catch("Error in detectUserIdleState: ",e)}}detectUserOfflineState(){try{this.unsubscribeUserOfflineStateDetectionSubscription();let e=!1;this.userOfflineStateDetectionSubscription=this.domService.onWindowPointerMove$().pipe(nu(2e3),Qr(this.offlineInactivityTime),ln(()=>{this.setCurrentPresenceUserStatus(N.PRESENCE_STATUS_OFFLINE,{isUserIdle:!0}),e=!0})).subscribe()}catch(e){this.loggingService.catch("Error in detectUserOfflineState: ",e)}}unsubscribeUserIdleStateDetectionSubscription(){try{this.userIdleStateDetectionSubscription&&(this.userIdleStateDetectionSubscription.unsubscribe(),this.userIdleStateDetectionSubscription=null)}catch(e){this.loggingService.catch("Error in unsubscribeUserIdleStateDetectionSubscription: ",e)}}unsubscribeUserOfflineStateDetectionSubscription(){try{this.userOfflineStateDetectionSubscription&&(this.userOfflineStateDetectionSubscription.unsubscribe(),this.userOfflineStateDetectionSubscription=null)}catch(e){this.loggingService.catch("Error in unsubscribeUserOfflineStateDetectionSubscription: ",e)}}getUser(){this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.authService.getUser$().pipe(Ge(e=>!!e)).subscribe(e=>{e&&this.setPresenceUser(e)},e=>{this.loggingService.catch("Error in getUser: ",e)})}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$().pipe(ln(e=>{this.documentPaths=e}),Fr(),ln(([e,t])=>{e&&this.updateUserStatusOnDocumentChange(N.PRESENCE_STATUS_OFFLINE,e),t&&this.updateUserStatusOnDocumentChange(N.PRESENCE_STATUS_ONLINE,t)})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getDocumentPaths: ",e)})}getLocation(){this.docService.getLocation$().pipe(ln(e=>{this.updateUserOnLocationChange(e)})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getLocation: ",e)})}getPresenceUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getPresenceUser","color: green;"),this.presenceUser$.asObservable()}getPresenceUserValue(){return this.presenceUser$.value}getOnlineUsersOnCurrentDocument(e){return this.loggingService.log("%c[WB] Calling FUNCTION: getOnlineUsersOnCurrentDocument","color: green;"),_r(this.afAuth).pipe(Ge(t=>!!t),Se(t=>this.isFeatureAllowed({firebaseUser:t,users:[],filteredUsers:[]})),Se(t=>t.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(i=>(t.featureAllowed=i,t))):ce(t)),Se(t=>t.featureAllowed?this.authService.isPlanExpired$().pipe(ue(i=>(t.featureAllowed=!i,t))):ce(t)),Se(t=>t.featureAllowed?ce(t).pipe(Se(i=>this.docService.getDocumentPaths$().pipe(ue(a=>(this.documentPaths=a,i.documentPaths=a,i)))),Se(i=>this.getDataFromDocumentId(e).pipe(ue(a=>(i.users=a||[],h({},i))))),ue(i=>(e?e?.statuses?.length?i.filteredUsers=i?.users?.filter(a=>e?.statuses?.includes(a?.onlineStatus)):i.filteredUsers=i?.users?.slice():i.filteredUsers=this.filterOnlineUsers(i.users,i.firebaseUser),i)),Se(i=>this.getIncludeSelf$().pipe(ue(a=>(a||(i.filteredUsers=i?.filteredUsers?.filter(l=>l?.userSnippylyId!==i.user?.userSnippylyId)),i)))),Se(i=>{let a=i?.filteredUsers||[];return this.customPresenceUsers$.pipe(ue(()=>this.mergeWithCustomUsers(a)))})):ce([])),_t(Kt))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})),Se(t=>this.authService.getUser$().pipe(ue(i=>y(h({},t),{user:i})))),Se(t=>Ao(t.config,t.user,je.PRESENCE)?ce(y(h({},t),{featureAllowed:!0})):(this.loggingService.warn("Presence feature is not allowed."),ce(y(h({},t),{featureAllowed:!1})))),_t((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ge(t=>!!t),Se(t=>{if(this.db=t,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.presence){let i=new Date(Date.now()-864e5).getTime();return this.commonDbService.dbListener({feature:"allPresence",properties:{documentId:e?.documentId??this.documentPaths?.documentId,organizationId:e?.organizationId??this.documentPaths?.organizationId,skipFirestore:!0,useQuery:!0,rtdbQuery:[e0("timestamp"),O_(i)]}}).pipe(Xn(a=>(this.loggingService.catch("Error in PresenceService getDataFromDocumentId: ",a),ce(null))),ue(a=>a?.data),ue(a=>{let l=[];if(a){let c=Object.values(a).filter(d=>typeof d=="object");for(let d of c)l.push(d)}return l}))}else return ce([])}))}filterOnlineUsers(e,t){this.loggingService.log("%c[WB] Calling FUNCTION: filterOnlineUsers","color: green;");try{let a=e.slice().filter(l=>{let c=Qu(l.timestamp);return l.userSnippylyId&&(l.onlineStatus===N.PRESENCE_STATUS_ONLINE||l.onlineStatus===N.PRESENCE_STATUS_AWAY)&&c<this.offlineInactivityTime});return this.presenceUsers$.next(this.mergeWithCustomUsers(a)),a}catch(i){return this.loggingService.catch("Error in filterOnlineUsers:",i),[]}}enableIncludeSelf(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: enableIncludeSelf","color: green;"),this.includeSelf$.value===!0)return;this.includeSelf$.next(!0)}catch(e){this.loggingService.catch("Error in PresenceService enableIncludeSelf: ",e)}}disableIncludeSelf(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: disableIncludeSelf","color: green;"),this.includeSelf$.value===!1)return;this.includeSelf$.next(!1)}catch(e){this.loggingService.catch("Error in PresenceService disableIncludeSelf: ",e)}}getIncludeSelf$(){return this.includeSelf$.asObservable()}getIncludeSelf(){return this.includeSelf$.value}getPresenceUserFromExternalId(e){try{if(this.presenceUsers$.value&&this.presenceUsers$.value.length>0){let t=this.presenceUsers$.value.find(i=>i.userId===e);if(t)return t}return null}catch(t){return this.loggingService.catch("Error in getNameFromSnippylyId:",t),null}}getAnonymousAvatarImage(){return this.loggingService.log("%c[WB] Calling FUNCTION: getAnonymousAvatarImage","color: green;"),this.avatarService.generateUserImage()}updateCurrentPresenceUser(e){return X(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateCurrentPresenceUser","color: green;");try{if(this.documentPaths?.presence&&e&&e.userId&&this.authService.isFeatureAllowed(je.PRESENCE)){if(!e.isAnonymous){e.pageInfo=new Oo,e?.onlineStatus===N.PRESENCE_STATUS_ONLINE&&(e.isTabAway=!1,e.isUserIdle=!1);let t=JSON.parse(JSON.stringify(e));this.authService.getUser()&&this.commonDbService.updateData({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:e.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(y(h({},t),{timestamp:this.timestamp})))})}this.presenceUser$.next(e)}}catch(t){this.loggingService.catch("Error in updateCurrentPresenceUser:",t)}})}setCurrentPresenceUserStatus(e,t){return X(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: setCurrentPresenceUserStatus","color: green;");try{this.loggingService.log(e);let i=this.presenceUser$.value;if(i.onlineStatus!==e){this.presenceUsersSubscription&&this.presenceUsersSubscription?.unsubscribe();let a=i.onlineStatus,l=e;this.presenceUsersSubscription=this.getPresenceUsers$().pipe(Ge(c=>!!c?.length),ut(1)).subscribe(c=>{c?.length>1&&this.analyticsService.trackEvent(Y.Events.Presence.PRESENCE_USER_STATUS_CHANGED,{oldStatus:a,newStatus:l,totalUsers:c?.length,presenceSnippylyUserIds:c?.map(d=>d.userSnippylyId),presenceClientUserIds:c?.map(d=>d.userId)})})}i.onlineStatus=e,t&&(i.isTabAway=t?.isTabAway,i.isUserIdle=t?.isUserIdle),e===N.PRESENCE_STATUS_ONLINE&&(i.isTabAway=!1,i.isUserIdle=!1),e===N.PRESENCE_STATUS_OFFLINE&&this.flockService.isInSession()&&this.flockService.removeCurrentUserFromSession(),this.updateCurrentPresenceUser(i)}catch(i){this.loggingService.catch("Error in setCurrentPresenceUserStatus:",i)}})}updateUserStatusOnDocumentChange(e,t){return X(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserStatusOnDocumentChange","color: green;");try{let i=this.presenceUser$.value;if(i.onlineStatus=e,t?.presence&&i&&i.userId&&!i.isAnonymous&&this.authService.isFeatureAllowed(je.PRESENCE)){let a=JSON.parse(JSON.stringify(i));this.commonDbService.updateData({feature:"presence",properties:{documentId:t?.documentId,organizationId:t?.organizationId,userId:i.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(a))})}}catch(i){this.loggingService.catch("Error in updateUserStatusOnDocumentChange:",i)}})}updateUserOnLocationChange(e){return X(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserOnLocationChange","color: green;");try{let t=this.presenceUser$.value;if(t.location=e?e.location:null,t.locationId=e?e?.locationId:null,this.documentPaths?.presence&&t&&t.userId&&!t.isAnonymous&&this.authService.isFeatureAllowed(je.PRESENCE)){let i=JSON.parse(JSON.stringify(t));this.commonDbService.updateData({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:t.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(i))})}}catch(t){this.loggingService.catch("Error in updateUserOnLocationChange:",t)}})}updateOnUserDbConnectionStateChange(){this.loggingService.log("%c[WB] Calling FUNCTION: updateOnUserDbConnectionStateChange","color: green;");let e=jr(this.db,".info/connected"),t=x8(e).pipe(ue(i=>i?N.PRESENCE_STATUS_ONLINE:N.PRESENCE_STATUS_OFFLINE));return _r(this.afAuth).pipe(Dd(1),Se(i=>i?t:ce(N.PRESENCE_STATUS_OFFLINE)),ln(i=>this.setCurrentPresenceUserStatus(i)))}updateOnDocumentFocusChange(){this.loggingService.log("%c[WB] Calling FUNCTION: updateOnDocumentFocusChange","color: green;");try{document&&document.addEventListener("visibilitychange",e=>{this.authService.getUser()&&(document.visibilityState==="hidden"?(this.setCurrentPresenceUserStatus(N.PRESENCE_STATUS_AWAY,{isTabAway:!0}),this.flockService.getFlockMode()&&this.flockService.setTabFocused(!1)):(this.setCurrentPresenceUserStatus(N.PRESENCE_STATUS_ONLINE),this.flockService.getFlockMode()&&this.flockService.setTabFocused(!0)))}),window&&(window.addEventListener("focus",()=>{this.authService.getUser()&&(this.setCurrentPresenceUserStatus(N.PRESENCE_STATUS_ONLINE),this.flockService.getFlockMode()&&this.flockService.setWindowFocused(!0))}),window.addEventListener("blur",()=>{this.authService.getUser()&&(document.visibilityState!=="hidden"&&this.setCurrentPresenceUserStatus(N.PRESENCE_STATUS_AWAY,{isTabAway:!0}),this.flockService.getFlockMode()&&this.flockService.setWindowFocused(!1))}))}catch(e){this.loggingService.catch("Error in updateOnDocumentFocusChange:",e)}}updateOnAllowedFeatureListChange(){try{this.configService.getConfig$().subscribe(e=>{if(e&&e.featureAllowList?.length){let t=this.presenceUser$.value,i=!1;if(e.featureAllowList.includes(je.PRESENCE)?t?.onlineStatus!==N.PRESENCE_STATUS_ONLINE&&(t.onlineStatus=N.PRESENCE_STATUS_ONLINE,i=!0):t?.onlineStatus!==N.PRESENCE_STATUS_OFFLINE&&(t.onlineStatus=N.PRESENCE_STATUS_OFFLINE,i=!0),i&&this.authService.getUser()&&this.documentPaths?.presence&&t&&t.userId&&!t.isAnonymous){let a=JSON.parse(JSON.stringify(t));this.commonDbService.updateData({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:t.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(a))})}}})}catch(e){this.loggingService.catch("Error in updateOnAllowedFeatureListChange:",e)}}updateOnDatabaseDisconnect(){return this.loggingService.log("%c[WB] Calling FUNCTION: updateOnDatabaseDisconnect","color: green;"),_r(this.afAuth).pipe(Ge(e=>!!e),Se(e=>this.docService.getDocumentPaths$().pipe(ue(t=>e))),ln(e=>X(this,null,function*(){try{if(this.documentPaths?.presence&&e){let t=yield Zv(e,!0).catch(a=>null);if(!t)return;let{user:i}=t.claims;if(!i?.isAnonymous&&this.documentPaths?.presence){this.flockService.isInSession()&&this.flockService.removeCurrentUserFromSession();let a=`${this.documentPaths.presence}/${e.uid}`;this.commonDbService.setupOnDisconnect(a,{onlineStatus:N.PRESENCE_STATUS_OFFLINE,timestamp:this.timestamp}).catch(l=>{this.loggingService.catch("Error in updateOnDatabaseDisconnect:",l)})}}}catch(t){this.loggingService.catch("Error in updateOnDatabaseDisconnect:",t)}})))}setPresenceUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: setPresenceUser","color: green;");try{let t=this.presenceUser$.value;t.userId=e?.userId,t.name=e?.name,t.email=e?.email,t.photoUrl=e?.photoUrl,t.userSnippylyId=e?.userSnippylyId,t.color=e?.color,t.textColor=e?.textColor,t.initial=e?.initial,t.timestamp=this.timestamp,t.type=e?.type,t.isReadOnly=e?.isReadOnly,t.isAnonymous=e?.isAnonymous;let i=e?.name?.split(" ");if(i&&i.length>0){let a=i[0],l=i.length>1?i[i.length-1]:null,c=l?l[0]:null;a&&(t.name=`${a} ${c?c+".":""}`)}this.updateCurrentPresenceUser(t)}catch(t){this.loggingService.catch("Error in setPresenceUser:",t)}}signOutUser(e){return new Promise((t,i)=>{try{this.documentPaths?.presence&&e?this.commonDbService.getData({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:e.uid,skipFirestore:!0}}).then(a=>{a&&(this.flockService.isInSession()&&this.flockService.removeCurrentUserFromSession(),this.commonDbService.updateData({feature:"presence",errorCallback:l=>{i(l)},callback:()=>{t(null)},properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:e.uid,skipFirestore:!0},data:JSON.parse(JSON.stringify(y(h({},a?.data??{}),{timestamp:this.timestamp,onlineStatus:N.PRESENCE_STATUS_OFFLINE})))})),t(null)}).catch(a=>{this.loggingService.catch("Error in signOutUser subscription: ",a),i(a)}):t(null)}catch(a){this.loggingService.catch("Error in signOutUser:",a),i(a)}})}setInactivityTime(e){try{this.inactivityTime=e,this.analyticsService.trackEvent(Y.Events.Presence.PRESENCE_SET_CUSTOM_INACTIVITY_TIMER,{inactivityTime:this.inactivityTime}),this.detectUserIdleState()}catch(t){this.loggingService.catch("Error in setInactivityTime: ",t)}}getInactivityTime(){return this.inactivityTime}setOfflineInactivityTime(e){try{e>=this.inactivityTime?(this.offlineInactivityTime=e,this.analyticsService.trackEvent(Y.Events.Presence.PRESENCE_SET_CUSTOM_OFFLINE_INACTIVITY_TIMER,{offlineInactivityTime:this.offlineInactivityTime}),this.detectUserOfflineState()):this.loggingService.catch("Error in setOfflineInactivityTime: ","offline-inactivity-time value is less than inactivity-time.")}catch(t){this.loggingService.catch("Error in setOfflineInactivityTime: ",t)}}getOfflineInactivityTime(){return this.offlineInactivityTime}getPresenceUsers$(){return this.presenceUsers$.asObservable()}getPresenceUsers(){return this.presenceUsers$.value}get timestamp(){return this.commonDbService.getServerTimestamp()}addCustomUser(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: addCustomUser","color: green;");let t=e?.user,i=e?.localOnly??!1;if(!t?.userId){this.loggingService.catch("Error in addCustomUser: ","userId is required");return}let a=this.buildCustomPresenceUser(t,i);if(!a)return;if(i){let l=this.customPresenceUsers$.value,c=l.findIndex(d=>d.userId===t.userId);if(c>=0){let d=[...l];d[c]=a,this.customPresenceUsers$.next(d)}else this.customPresenceUsers$.next([...l,a])}else this.persistCustomUserToDb(a)}catch(t){this.loggingService.catch("Error in addCustomUser: ",t)}}removeCustomUser(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: removeCustomUser","color: green;");let t=e?.user?.userId,i=e?.localOnly??!1;if(!t){this.loggingService.catch("Error in removeCustomUser: ","userId is required");return}if(i){let a=this.customPresenceUsers$.value,l=a.filter(c=>c.userId!==t);l.length!==a.length&&this.customPresenceUsers$.next(l)}else{let a=this.buildCustomPresenceUser(e.user,!1);a&&this.removeCustomUserFromDb(a)}}catch(t){this.loggingService.catch("Error in removeCustomUser: ",t)}}mergeWithCustomUsers(e){try{let t=this.customPresenceUsers$.value;if(t.length===0)return e;let i=new Set(e.map(l=>l.userId)),a=t.filter(l=>!i.has(l.userId));return[...e,...a]}catch(t){return this.loggingService.catch("Error in mergeWithCustomUsers: ",t),e}}buildCustomPresenceUser(e,t=!1){try{let i=this.configService.getApiKey(),a=new S3;return a.userId=e.userId,a.name=e.name||e.userId,a.email=e.email||"",a.photoUrl=e.photoUrl||"",a.onlineStatus=e.onlineStatus||N.PRESENCE_STATUS_ONLINE,a.color=e.color||this.avatarService.generateUserColor(),a.textColor=e.textColor||"",a.type="custom",a.initial=e.initial||(a.name?a.name.charAt(0).toUpperCase():"U"),a.timestamp=Date.now(),a.isReadOnly=e.isReadOnly??!1,a.isAnonymous=e.isAnonymous??!1,a.location=e.location||null,a.locationId=e.locationId??null,a.pageInfo=e.pageInfo||new Oo,a.isTabAway=!1,a.isUserIdle=!1,a.userSnippylyId=e.userSnippylyId||(i?cd(i,e.userId):`custom_${e.userId}`),a.localOnly=t,a}catch(i){return this.loggingService.catch("Error in buildCustomPresenceUser: ",i),null}}persistCustomUserToDb(e){try{if(this.documentPaths?.presence&&e?.userId&&this.authService.isFeatureAllowed(je.PRESENCE)){let t=JSON.parse(JSON.stringify(e));delete t.localOnly,this.commonDbService.updateData({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:e.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(y(h({},t),{timestamp:this.timestamp})))})}}catch(t){this.loggingService.catch("Error in persistCustomUserToDb: ",t)}}removeCustomUserFromDb(e){try{this.documentPaths?.presence&&e?.userId&&this.authService.isFeatureAllowed(je.PRESENCE)&&this.commonDbService.deleteData({feature:"presence",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,userId:e.userSnippylyId,skipFirestore:!0}})}catch(t){this.loggingService.catch("Error in removeCustomUserFromDb: ",t)}}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(st),K(Ve),K(qe),K(eo),K(Vn),K($n),K(Ft),K(fm),K(k),K(hv),K(yn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var _S=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I){this.analyticsService=e,this.configService=t,this.presenceService=i,this.docService=a,this.afAuth=l,this.iamService=c,this.domService=d,this.databaseService=m,this.authService=u,this.loggingService=_,this.commonDbService=I,this.cursorUser$=new _e(new c1),this.documentPaths=null,this.inactivityTime=120*1e3,this.allowedElementIds$=new _e([]),this.cursorTagAvailable$=new _e(!1),this.cursorTagAvailable=!1,this.cursorUsers$=new _e([]),this.loggingService.log("%c[WB] Creating CLASS: CursorService","color: blue;");try{this.checkCursorTagAvailable(),this.databaseService.getDb().pipe(Ge(A=>!!A),Se(A=>this.cursorTagAvailable$.pipe(Ge(M=>!!M),ut(1),ue(()=>A))),ut(1)).subscribe(A=>{A&&this.cursorTagAvailable&&(this.getPresenceUser(),this.getDocumentPaths(),this.getLocation(),this.updateOnDatabaseDisconnect().subscribe(()=>{},M=>{this.loggingService.catch("Error in CursorService constructor updateOnDatabaseDisconnect: ",M)}),this.addMouseMoveListener(),this.addScreenSizeChangeListener(),this.updateOnAllowedFeatureListChange())},A=>{this.loggingService.catch("Error in CursorService constructor getDb: ",A)}),this.cursorUsers$.pipe(Fr()).subscribe(([A,M])=>{sessionStorage.getItem(N.SESSION_STORAGE.VELT_CURSOR_MULTIPLE_USERS_DETECTED)||M?.length>1&&A.length!==M.length&&(this.analyticsService.trackEvent(Y.Events.Cursor.CURSOR_MULTIPLE_USERS_DETECTED,{totalUsers:M.length,cursorSnippylyUserIds:M.map(V=>V.userSnippylyId),cursorClientUserIds:M.map(V=>V.userId)}),sessionStorage.setItem(N.SESSION_STORAGE.VELT_CURSOR_MULTIPLE_USERS_DETECTED,"true"))}),this.authService.addPreSignOutFuction("cursor-signout",this.signOutUser.bind(this))}catch(A){this.loggingService.catch("Error in CursorService constructor: ",A)}}checkCursorTagAvailable(){this.loggingService.log("%c[WB] Calling FUNCTION: checkCursorTagAvailable","color: green;");try{this.cursorTagAvailable=!!document.querySelector(N.TAGS.VELT_CURSOR)||!!document.querySelector(N.TAGS.SNIPPYLY_CURSOR),this.cursorTagAvailable$.next(this.cursorTagAvailable)}catch(e){this.loggingService.catch("Error in CursorService checkCursorTagAvailable: ",e)}}addScreenSizeChangeListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addScreenSizeChangeListener","color: green;");try{this.docService.getDocumentPaths$().pipe(Ge(e=>!!e),Se(e=>this.domService.getCurrentWindowSize$("CursorService addScreenSizeChangeListener").pipe(Ge(t=>!!t)))).subscribe(e=>{this.setCurrentCursorUserScreenSize(e)},e=>{this.loggingService.catch("Error in addScreenSizeChangeListener getCurrentWindowSize: ",e)})}catch(e){this.loggingService.catch("Error in CursorService addScreenSizeChangeListener: ",e)}}addMouseMoveListener(){this.loggingService.log("%c[WB] Calling FUNCTION: addMouseMoveListener","color: green;");try{this.domService.onWindowPointerMove$().pipe(nu(50)).subscribe(e=>{e&&this.setCurrentCursorUserPosition(e.pageX,e.pageY,this.domService.getTargetElementForCursorPosition(e,!0,!1,!1,void 0,!1))},e=>{this.loggingService.catch("Error in addMouseMoveListener getCurrentMousePosition: ",e)})}catch(e){this.loggingService.catch("Error in CursorService addMouseMoveListener: ",e)}}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;");try{this.docService.getDocumentPaths$().pipe(ln(e=>{this.documentPaths=e}),Fr(),ln(([e,t])=>{e&&this.updateUserStatusOnDocumentChange(N.PRESENCE_STATUS_OFFLINE,e),t&&this.updateUserStatusOnDocumentChange(N.PRESENCE_STATUS_ONLINE,t)})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getDocumentPaths subscription: ",e)})}catch(e){this.loggingService.catch("Error in CursorService getDocumentPaths: ",e)}}getLocation(){try{this.docService.getLocation$().pipe(ln(e=>{this.updateUserOnLocationChange(e)})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getLocation subscription: ",e)})}catch(e){this.loggingService.catch("Error in CursorService getLocation: ",e)}}getCursorUser(){return this.loggingService.log("%c[WB] Calling FUNCTION: getCursorUser","color: green;"),this.cursorUser$.asObservable()}getPresenceUser(){this.loggingService.log("%c[WB] Calling FUNCTION: getPresenceUser","color: green;"),this.presenceService.getPresenceUser().pipe(Ge(e=>!!e),Xn(e=>ce(e.code))).subscribe(e=>{this.setCursorUser(e)},e=>{this.loggingService.catch("Error in getPresenceUser: ",e)})}getLiveCursorsOnCurrentDocument(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLiveCursorsOnCurrentDocument","color: green;"),_r(this.afAuth).pipe(Ge(e=>!!e),Se(e=>this.isFeatureAllowed({firebaseUser:e,users:[],filteredUsers:[]})),Se(e=>e.featureAllowed?this.iamService.isUserAllowed$().pipe(ue(t=>(e.featureAllowed=t,e))):ce(e)),Se(e=>e.featureAllowed?this.authService.isPlanExpired$().pipe(ue(t=>(e.featureAllowed=!t,e))):ce(e)),Se(e=>!e.featureAllowed||e?.user?.isAnonymous?ce([]):ce(e).pipe(Se(t=>this.docService.getDocumentPaths$().pipe(ue(i=>(this.documentPaths=i,t.documentPaths=i,t)))),Se(t=>this.getDataFromDocumentId().pipe(ue(i=>(t.users=i||[],h({},t))))),ue(t=>(t.filteredUsers=this.filterOnlineUsers(t.users,t.firebaseUser),t)),Se(t=>t?.filteredUsers?.length?this.domService.getCurrentWindowSize$("CursorService getLiveCursorsOnCurrentDocument").pipe(ue(()=>t)):ce(t)),ue(t=>(t?.filteredUsers?.forEach(i=>{this.calculateCursorUserPosition(i)}),t)),Se(t=>t?.filteredUsers?ce(t?.filteredUsers||[]):ce([])))))}isFeatureAllowed(e){return this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})),Se(t=>this.authService.getUser$().pipe(ue(i=>y(h({},t),{user:i})))),Se(t=>Ao(t.config,t.user,je.CURSOR)?ce(y(h({},t),{featureAllowed:!0})):(this.loggingService.warn("Cursor feature is not allowed."),ce(y(h({},t),{featureAllowed:!1})))),_t((t,i)=>t?.featureAllowed===i?.featureAllowed))}getDataFromDocumentId(e){return this.databaseService.getDb().pipe(Ge(t=>!!t),Se(t=>{if(this.configService?.getApiKey()&&this.documentPaths?.cursor){let i=new Date(Date.now()-864e5).getTime();return this.commonDbService.dbListener({feature:"allCursors",properties:{documentId:e??this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0,useQuery:!0,rtdbQuery:[e0("timestamp"),O_(i)]}}).pipe(Xn(a=>(this.loggingService.catch("Error in CursorService getDataFromDocumentId: ",a),ce(null))),ue(a=>a?.data),ue(a=>{let l=[];return a&&(l=Object.values(a).filter(c=>typeof c=="object")),l}))}else return ce([])}))}calculateCursorUserPosition(e){try{if(e?.targetElement){let t=this.domService.getXPath(e.targetElement?.xpath);if(t){let i=t.iterateNext();if(i&&this.isElementInsideAllowedElements(i)){let a=i.getBoundingClientRect();a&&a.width&&a.height&&(e.position={top:a.top+a.height*e.targetElement.topPercentage/100,left:a.left+a.width*e.targetElement.leftPercentage/100})}}}}catch(t){this.loggingService.catch("Error in calculateCursorUserPosition:",t)}}filterOnlineUsers(e,t){try{let a=e.slice().filter(c=>{let d=Qu(c.timestamp);return c.userSnippylyId&&c.onlineStatus===N.PRESENCE_STATUS_ONLINE&&d<this.inactivityTime});this.cursorUsers$.next(a),a=a.filter(c=>c?.userSnippylyId!==t?.uid);let l=this.docService.getLocation();return l&&l.locationId?a=a.filter(c=>c.locationId===l.locationId):a=a.filter(c=>!c.locationId),a}catch(i){return this.loggingService.catch("Error in filterOnlineUsers:",i),[]}}setCursorUser(e){this.loggingService.log("%c[WB] Calling FUNCTION: setCursorUser","color: green;");try{let t=this.cursorUser$.value;t.userId=e?.userId,t.name=e?.name,t.email=e?.email,t.photoUrl=e?.photoUrl,t.comment="",this.authService.isFeatureAllowed(je.PRESENCE)&&(t.onlineStatus=e?.onlineStatus),t.userSnippylyId=e?.userSnippylyId,t.color=e?.color,t.textColor=e?.textColor,t.initial=e?.initial,t.timestamp=this.timestamp,t.type=e?.type,t.isReadOnly=e?.isReadOnly,t.isAnonymous=e?.isAnonymous;let i=this.domService.getCurrentWindowSizeValue();t.screenWidth=i?.screenWidth,t.screenHeight=i?.screenHeight,t.screenScrollHeight=i?.screenScrollHeight,this.updateCurrentCursorUser(t)}catch(t){this.loggingService.catch("Error in setCursorUser:",t)}}setCurrentCursorUserPosition(e,t,i){try{let a=this.cursorUser$.value;a?.onlineStatus===N.PRESENCE_STATUS_ONLINE&&(a.positionX=e,a.positionY=t,i?a.targetElement=i:a.targetElement=null,this.updateCurrentCursorUser(a))}catch(a){this.loggingService.catch("Error in setCurrentCursorUserPosition:",a)}}setCurrentCursorUserScreenSize(e){try{if(e.screenWidth!==0&&e.screenHeight!==0){let t=this.cursorUser$.value;t?.onlineStatus===N.PRESENCE_STATUS_ONLINE&&(t.screenWidth=e.screenWidth,t.screenHeight=e.screenHeight,t.screenScrollHeight=e.screenScrollHeight,this.updateCurrentCursorUser(t))}}catch(t){this.loggingService.catch("Error in setCurrentCursorUserScreenSize:",t)}}updateCurrentCursorUser(e){return X(this,null,function*(){try{if(this.documentPaths&&e&&e.userId&&this.authService.isFeatureAllowed(je.CURSOR)){if(!e.isAnonymous){e.pageInfo=new Oo;let t=JSON.parse(JSON.stringify(e));this.commonDbService.updateData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(y(h({},t),{timestamp:this.timestamp})))})}this.cursorUser$.next(e)}}catch(t){this.loggingService.catch("Error in updateCurrentCursorUser:",t)}})}updateUserStatusOnDocumentChange(e,t){return X(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserStatusOnDocumentChange","color: green;");try{let i=this.cursorUser$.value;if(i.onlineStatus=e,t&&i&&i.userId&&!i.isAnonymous&&this.authService.isFeatureAllowed(je.CURSOR)){let a=JSON.parse(JSON.stringify(i));this.commonDbService.updateData({feature:"cursor",properties:{documentId:t?.documentId??"",organizationId:t?.organizationId??"",id:i.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(y(h({},a),{timestamp:this.timestamp})))})}}catch(i){this.loggingService.catch("Error in updateUserStatusOnDocumentChange:",i)}})}updateUserOnLocationChange(e){return X(this,null,function*(){this.loggingService.log("%c[WB] Calling FUNCTION: updateUserOnLocationChange","color: green;");try{let t=this.cursorUser$.value;if(t.location=e?e.location:null,t.locationId=e?e?.locationId:null,this.documentPaths&&t&&t.userId&&!t.isAnonymous&&this.authService.isFeatureAllowed(je.CURSOR)){let i=JSON.parse(JSON.stringify(t));this.commonDbService.updateData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:t.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(y(h({},i),{timestamp:this.timestamp})))})}}catch(t){this.loggingService.catch("Error in updateUserOnLocationChange:",t)}})}updateOnAllowedFeatureListChange(){try{this.configService.getConfig$().subscribe(e=>{if(e&&e.featureAllowList?.length){let t=this.cursorUser$.value,i=!1;if(e.featureAllowList.includes(je.CURSOR)?t?.onlineStatus!==N.PRESENCE_STATUS_ONLINE&&(t.onlineStatus=N.PRESENCE_STATUS_ONLINE,i=!0):t?.onlineStatus!==N.PRESENCE_STATUS_OFFLINE&&(t.onlineStatus=N.PRESENCE_STATUS_OFFLINE,i=!0),i&&this.documentPaths&&t&&t.userId&&!t.isAnonymous){let a=JSON.parse(JSON.stringify(t));this.commonDbService.updateData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:t.userSnippylyId,skipFirestore:!0},data:JSON.parse(JSON.stringify(y(h({},a),{timestamp:this.timestamp})))})}}})}catch(e){this.loggingService.catch("Error in updateOnAllowedFeatureListChange:",e)}}updateOnDatabaseDisconnect(){return this.loggingService.log("%c[WB] Calling FUNCTION: updateOnDatabaseDisconnect","color: green;"),_r(this.afAuth).pipe(Ge(e=>!!e),Se(e=>this.docService.getDocumentPaths$().pipe(ue(t=>e))),ln(e=>X(this,null,function*(){try{if(this.documentPaths&&e){let t=yield Zv(e,!0).catch(a=>null);if(!t)return;let{user:i}=t.claims;if(!i?.isAnonymous&&this.documentPaths?.cursor){let a=`${this.documentPaths.cursor}/${e.uid}`;this.commonDbService.setupOnDisconnect(a,{onlineStatus:N.PRESENCE_STATUS_OFFLINE,comment:"",timestamp:this.timestamp}).catch(l=>{this.loggingService.catch("Error in updateOnDatabaseDisconnect:",l)})}}}catch(t){this.loggingService.catch("Error in updateOnDatabaseDisconnect:",t)}})))}signOutUser(e){return new Promise((t,i)=>{try{this.documentPaths&&e?this.commonDbService.getData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:e.uid,skipFirestore:!0}}).then(a=>{a&&this.commonDbService.updateData({feature:"cursor",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",id:e.uid,skipFirestore:!0},callback:()=>{t(null)},data:JSON.parse(JSON.stringify(y(h({},a?.data??{}),{timestamp:this.timestamp,onlineStatus:N.PRESENCE_STATUS_OFFLINE})))}),t(null)}).catch(a=>{this.loggingService.catch("Error in signOutUser subscription: ",a),i(a)}):t(null)}catch(a){this.loggingService.catch("Error in signOutUser:",a),i(a)}})}setInactivityTime(e){this.inactivityTime=e,this.analyticsService.trackEvent(Y.Events.Cursor.CURSOR_SET_CUSTOM_INACTIVITY_TIMER,{inactivityTime:this.inactivityTime})}setAllowedElementIds(e){this.allowedElementIds$.next(e||[])}getAllowedElementIds(){return this.allowedElementIds$.asObservable()}isElementInsideAllowedElements(e){try{return this.domService.isElementInsideListedElementIds(e,this.allowedElementIds$.value)}catch(t){return this.loggingService.catch("Error in CursorService isElementInsideAllowedElements: ",t),!1}}get timestamp(){return this.commonDbService.getServerTimestamp()}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(Ft),K(ic),K(st),K(eo),K(Vn),K(Ve),K($n),K(qe),K(k),K(yn))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var mU=class extends Cr{constructor(o){super(o),this.getService(k).log("%c[WB] Creating CLASS: CursorElement","color: blue;"),this.getLiveCursorsOnCurrentDocument=this._getOnlineUsersOnCurrentDocument,this.getOnlineUsersOnCurrentDocument=this._getOnlineUsersOnCurrentDocument,this.setInactivityTime=this._setInactivityTime,this.allowedElementIds=this._allowedElementIds}_getOnlineUsersOnCurrentDocument(){this.getService(k).log("%c[WB] Calling FUNCTION: getOnlineUsersOnCurrentDocument","color: green;");try{return this.trackEvent(Y.Events.Cursor.GET_LIVE_CURSORS_ON_CURRENT_DOCUMENT_TRIGGERED),this.getService(_S).getLiveCursorsOnCurrentDocument()}catch(o){return this.getService(k).catch("Error in _getOnlineUsersOnCurrentDocument: ",o),ce(null)}}_setInactivityTime(o){this.getService(k).log("%c[WB] Calling FUNCTION: _setInactivityTime","color: green;");try{this.trackEvent(Y.Events.Cursor.SET_INACTIVITY_TIME_TRIGGERED,{payload:{time:o}}),isNaN(o)?this.getService(k).catch("Error in setInactivityTime: ","Provided value is not a number."):this.getService(_S).setInactivityTime(o)}catch(r){this.getService(k).catch("Error in setInactivityTime: ",r)}}_allowedElementIds(o){this.getService(k).log("%c[WB] Calling FUNCTION: allowedElementIds","color: green;");try{this.trackEvent(Y.Events.Cursor.ALLOWED_ELEMENT_IDS_TRIGGERED,{payload:{elementIds:o}}),this.getService(_S).setAllowedElementIds(o)}catch(r){this.getService(k).catch("Error in allowedElementIds: ",r)}}};var gU=class extends Cr{constructor(o){super(o),this.getService(k).log("%c[WB] Creating CLASS: DocElement","color: blue;"),this.getDocumentMetadata=this._getDocumentMetadata}_getDocumentMetadata(){this.getService(k).log("%c[WB] Calling FUNCTION: getDocumentMetadata","color: green;");try{return this.trackEvent(Y.Events.Doc.GET_DOCUMENT_METADATA_TRIGGERED),this.getService(st).getDocumentMetadata$()}catch(o){return this.getService(k).catch("Error in getDocumentMetadata: ",o),ce(null)}}};var ia=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u,_,I,A,M){this.afAuth=e,this.analyticsService=t,this.authService=i,this.databaseService=a,this.docService=l,this.configService=c,this.domService=d,this.huddleUtilsService=m,this.functions=u,this.loggingService=_,this.notificationService=I,this.commonDbService=A,this.usersService=M,this.documentPaths=null,this.localStream$=new _e(null),this.peerConnectionMap={},this.localStream=new MediaStream,this.screenSharingStream=new MediaStream,this.screenSharingStream$=new _e(null),this.remoteStreamMap={},this.remoteStreamMap$=new _e(null),this.localStreamState$=new _e({}),this.peerConnectionStateMap={},this.peerConnectionStateMap$=new _e({}),this.hudleToolComponentId$=new _e(null),this.attendees$=new _e([]),this.invitees$=new _e([]),this.huddleJoined$=new _e(!1),this.userHuddleStartTime$=new _e(null),this.messages$=new _e([]),this.messagesPanelVisible$=new _e(!1),this.huddleOnCursorMode$=new _e(!1),this.flockModeOnAvatarClickEnabled$=new _e(!1),this.chatEnabled$=new _e(!0),this.serverFallback$=new _e(!0),this.huddleOnCursorModeByAttendeeId$=new _e({}),this.huddleCursorAvailableByAttendeeId$=new _e({}),this.remoteStreamsByUserId$=new _e({}),this.messagesSubscription=null,this.huddleJoined=!1,this.onAnswerConnectionIdHistory={},this.onOfferUidHistory={},this.senders={},this.db=null,this.dbRefsRemoveOnDropCall=[],this.servers={iceServers:[{urls:["stun:stun1.l.google.com:19302","stun:stun2.l.google.com:19302"]}]},this.databaseService.getDb().pipe(Ge(V=>!!V),ut(1)).subscribe(V=>{try{V&&(this.db=V,this.isHuddleTagInstalled()&&this.getServerFallback()&&this.getTwilioIceServers(),this.getUser(),this.getDocumentPaths())}catch(q){this.loggingService.catch("Error in HuddleService getDb:",q)}},V=>{this.loggingService.catch("Error in HuddleService getDb subscription: ",V)}),this.docService.addPreDocumentIdChangeFunction("huddle-service",V=>X(this,null,function*(){this.huddleJoined$.value&&(yield this.dropCall(),yield this.removeLocalStream(),yield this.removeAttendee(),this.attendees$.next([]))})),this.getAttendees().subscribe(),this.getInvitees().subscribe(),this.localStream$.subscribe(V=>{V&&(this.localStream=V)}),this.screenSharingStream$.subscribe(V=>{V&&(this.screenSharingStream=V)}),this.configService.getConfig$().subscribe(V=>{try{!V?.featureAllowList?.find(ae=>ae===je.CURSOR)&&this.huddleOnCursorMode$.next(!1)}catch(q){this.loggingService.catch("Error in HuddleService configService.getConfig$:",q)}},V=>{this.loggingService.catch("Error in HuddleService configService.getConfig$ subscription: ",V)}),this.attendees$.subscribe(V=>{try{if(V?.length){if(this.huddleOnCursorMode$?.value){let q=this.huddleOnCursorModeByAttendeeId$.getValue()||{};V.forEach(ae=>{q[ae.userSnippylyId]=!0}),this.huddleOnCursorModeByAttendeeId$.next(q)}this.huddleJoined$?.value&&(V?.find(q=>q?.huddleOnCursorMode)?this.addCursorTag():this.removeCursorTag())}}catch(q){this.loggingService.catch("Error in HuddleService attendees$:",q)}},V=>{this.loggingService.catch("Error in HuddleService attendees$ subscription: ",V)}),gn([this.huddleJoined$,this.huddleOnCursorMode$]).subscribe(([V,q])=>{try{if(V){if(q){let ae=this.attendees$.getValue()||[],ye=this.huddleOnCursorModeByAttendeeId$.getValue()||{};ae.forEach(ie=>{ye[ie.userSnippylyId]=!0}),document?.body?.setAttribute(N.ATTRIBUTES.VELT_HUDDLE_ON_CURSOR_MODE,"true")}else this.huddleOnCursorModeByAttendeeId$.next({}),document?.body?.removeAttribute(N.ATTRIBUTES.VELT_HUDDLE_ON_CURSOR_MODE);this.updateHuddleOnCursorMode()}else this.removeCursorTag(),document?.body?.removeAttribute(N.ATTRIBUTES.VELT_HUDDLE_ON_CURSOR_MODE)}catch(ae){this.loggingService.catch("Error in HuddleService huddleJoined$:",ae)}},V=>{this.loggingService.catch("Error in HuddleService huddleJoined$ subscription: ",V)}),this.huddleOnCursorModeByAttendeeId$.subscribe(V=>{try{this.huddleJoined&&(Object.keys(V).length?this.addCursorTag():this.removeCursorTag())}catch(q){this.loggingService.catch("Error in HuddleService huddleOnCursorModeByAttendeeId$:",q)}},V=>{this.loggingService.catch("Error in HuddleService huddleOnCursorModeByAttendeeId$ subscription: ",V)}),this.authService.addPreSignOutFuction("huddle-signout",this.signOutUser.bind(this))}isHuddleTagInstalled(){try{return!!document?.querySelector(`${N.TAGS.VELT_HUDDLE}`)||!!document?.querySelector(`${N.TAGS.SNIPPYLY_HUDDLE}`)}catch(e){return this.loggingService.catch("Error in HuddleService isHuddleTagInstalled:",e),!1}}getTwilioIceServers(){return X(this,null,function*(){try{let t=(yield Yr(this.functions,Zr({url:On.cloudFunction.getIceServers,apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:12e5})())?.data;t&&t?.iceServers&&(this.servers.iceServers=t.iceServers)}catch(e){this.loggingService.catch("Error in HuddleService getTwilioIceServers:",e)}})}getRemoteStream(){return this.loggingService.log("%c[WB] Calling FUNCTION: getRemoteStream","color: green;"),this.remoteStreamMap$.asObservable()}getPeerConnectionStateMap(){return this.loggingService.log("%c[WB] Calling FUNCTION: getPeerConnectionStateMap","color: green;"),this.peerConnectionStateMap$.asObservable()}getLocalStreamState(){return this.loggingService.log("%c[WB] Calling FUNCTION: getLocalStreamState","color: green;"),this.localStreamState$.asObservable()}getScreenSharingStream(){return this.loggingService.log("%c[WB] Calling FUNCTION: getScreenSharingStream","color: green;"),this.screenSharingStream$.asObservable()}getAttendees(){return _r(this.afAuth).pipe(Ge(e=>!!e),ue(e=>({firebaseUser:e})),Se(e=>this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})))),Se(e=>this.authService.getUser$().pipe(ue(t=>y(h({},e),{user:t})))),Se(e=>Ao(e.config,e.user,je.HUDDLE)?ce(y(h({},e),{allowed:!0})):(this.loggingService.warn("Huddle feature is not allowed."),ce(y(h({},e),{allowed:!1})))),_t((e,t)=>e?.allowed===t?.allowed),Se(e=>this.docService.getDocumentPaths$().pipe(ue(t=>(this.documentPaths=t,e)))),Se(e=>e?.allowed?e?.user?.isAnonymous?ce(null):this.documentPaths?.huddle?this.commonDbService.dbListener({feature:"allHuddleAttendees",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ue(t=>t?.data),ue(t=>t?(this.attendees$.next(Object.values(t)),Object.values(t)):(this.attendees$.next([]),null))):ce(null):ce([])))}getInvitees(){try{return _r(this.afAuth).pipe(Ge(e=>!!e),ue(e=>({firebaseUser:e})),Se(e=>this.configService.getConfig$().pipe(Ge(t=>!!t),ue(t=>y(h({},e),{config:t})))),Se(e=>this.authService.getUser$().pipe(ue(t=>y(h({},e),{user:t})))),Se(e=>Ao(e.config,e.user,je.HUDDLE)?ce(y(h({},e),{allowed:!0})):(this.loggingService.warn("Huddle feature is not allowed."),ce(y(h({},e),{allowed:!1})))),_t((e,t)=>e?.allowed===t?.allowed),Se(e=>this.docService.getDocumentPaths$().pipe(ue(t=>(this.documentPaths=t,e)))),Se(e=>e?.allowed?e?.user?.isAnonymous?ce(null):this.documentPaths?.huddle?this.commonDbService.dbListener({feature:"allHuddleInvitees",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}}).pipe(ue(t=>t?.data),ue(t=>t?(this.invitees$.next(Object.values(t)),Object.values(t)):(this.invitees$.next([]),null))):ce(null):ce([])))}catch(e){return this.loggingService.catch("Error in HuddleService getInvitees:",e),ce([])}}clearHuddleInvitees(){try{this.documentPaths?.huddle&&this.commonDbService.deleteData({feature:"allHuddleInvitees",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}})}catch(e){this.loggingService.catch("Error in HuddleService clearHuddleInvitees:",e)}}getUser(){this.loggingService.log("%c[WB] Calling FUNCTION: getUser","color: green;"),this.authService.getUser$().pipe(Ge(e=>!!e)).subscribe(e=>{e&&(this.user=e)},e=>{this.loggingService.catch("Error in getUser: ",e)})}getDocumentPaths(){this.loggingService.log("%c[WB] Calling FUNCTION: getDocumentPaths","color: green;"),this.docService.getDocumentPaths$().pipe(ln(e=>{this.documentPaths=e})).subscribe(()=>{},e=>{this.loggingService.catch("Error in getDocumentPaths: ",e)})}setHuddleToolComponentId(e){this.hudleToolComponentId$.next(e||null)}getHuddleToolComponentId(){return this.hudleToolComponentId$.asObservable()}joinHuddle(e){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: joinHuddle","color: green;"),this.documentPaths?.huddle?(this.initialHuddleType=e,this.huddleJoined=!0,this.huddleJoined$.next(!0),this.initLocalStreams(),this.huddle=jr(this.db,this.documentPaths?.huddle),this.iceCandidates=jr(this.db,`${this.documentPaths?.huddle}/iceCandidates`),this.connections=jr(this.db,`${this.documentPaths?.huddle}/connections`),this.attendees=jr(this.db,`${this.documentPaths?.huddle}/attendees`),this.messages=jr(this.db,`${this.documentPaths?.huddle}/messages`),this.setHuddleListener(),this.addAttendee(),this.callExistingAttendees(),this.userHuddleStartTime$.next(new Date().getTime())):this.loggingService.catch("Error in joinHuddle: documentPaths not found")}catch(t){this.loggingService.catch("Error in HuddleService joinHuddle:",t)}})}initLocalStreams(){try{if(!this.localStream$?.value?.getTracks()?.length){let e=new MediaStream([this.silence(),this.black()]);this.localStream$.next(e)}if(!this.screenSharingStream$?.value?.getTracks()?.length){let e=new MediaStream([this.black()]);this.screenSharingStream$.next(e)}}catch(e){this.loggingService.catch("Error in HuddleService initLocalStreams:",e)}}setHuddleListener(){this.loggingService.log("%c[WB] Calling FUNCTION: setHuddleListener","color: green;"),Cg(this.connections,e=>{try{if(e.exists()){let t=e.val();Object.values(t).forEach(a=>{let l=Object.values(a);if(l&&l.length>0){let d=l[0]?.connectionId;this.onHuddleSnapshot(d,a)}}),Object.keys(this.remoteStreamMap).forEach(a=>X(this,null,function*(){t[a]||(this.remoteStreamMap[a]&&Object.values(this.remoteStreamMap[a]).forEach(l=>{l.getTracks().forEach(c=>{c.stop()})}),delete this.remoteStreamMap[a],yield this.removeIceCandidates(a))})),this.remoteStreamMap$.next(this.remoteStreamMap)}else Object.keys(this.remoteStreamMap).forEach(t=>X(this,null,function*(){Object.values(this.remoteStreamMap[t]).forEach(i=>{i.getTracks().forEach(a=>{a.stop()})}),yield this.removeIceCandidates(t)})),this.remoteStreamMap={},this.remoteStreamMap$.next(this.remoteStreamMap)}catch(t){this.loggingService.catch("Error in HuddleService setHuddleLister onValue:",t)}}),Yq(this.iceCandidates).subscribe(e=>{try{e.event==="child_added"&&this.onIceCandidateSnapshot(e.snapshot)}catch(t){this.loggingService.catch("Error in HuddleService iceCandidates stateChanges:",t)}}),Yq(this.attendees).subscribe(e=>{try{if(e.event==="child_removed"){let t=e?.snapshot?.val();if(t){delete this.onOfferUidHistory[t?.userSnippylyId];let i=this.getCombinedId(this.user.userSnippylyId,t?.userSnippylyId);delete this.onAnswerConnectionIdHistory[i],this.closeConnection(i)}}}catch(t){this.loggingService.catch("Error in HuddleService iceCandidates stateChanges:",t)}}),this.messagesSubscription&&this.messagesSubscription.unsubscribe(),this.messagesSubscription=new Vt(e=>{let t=Cg(this.messages,i=>e.next(i),i=>e.error(i));return()=>t()}).pipe(Se(e=>this.usersService.getUserById$().pipe(ue(()=>e))),Se(e=>{if(e.exists()){let t=e.val();return co(this.huddleUtilsService.resolveUsersFromHuddleMessages(Object.values(t||{})))}return ce([])}),Xn(e=>(this.loggingService.catch("Error in HuddleService messages onValue:",e),ce([])))).subscribe(e=>{this.messages$.next(e)})}onHuddleSnapshot(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: onHuddleSnapshot","color: green;"),t.offerData&&!t.answerData&&t.offerData.from!==this.user.userSnippylyId&&t.offerData.to===this.user.userSnippylyId&&!(e in this.peerConnectionMap)&&!this.onOfferUidHistory[t.offerData.from]?(this.loggingService.log("offer received"),this.loggingService.log(t),this.onOfferUidHistory[t.offerData.from]=!0,this.onOffer(e,t.offerData)):t.answerData&&t.answerData.from!==this.user.userSnippylyId&&t.answerData.to===this.user.userSnippylyId&&this.peerConnectionMap[e]&&this.peerConnectionMap[e]?.connectionState!=="connected"&&!this.onAnswerConnectionIdHistory[e]&&(this.loggingService.log("answer received"),this.loggingService.log(t),this.onAnswerConnectionIdHistory[e]=!0,this.onAnswer(e,t.answerData))}catch(i){this.loggingService.catch("Error in HuddleService onHuddleSnapshot:",i)}}onIceCandidateSnapshot(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: onIceCandidateSnapshot","color: green;"),this.loggingService.log("ice candidate received");let t=e.val(),i=t.connectionId;t?.from!==this.user.userSnippylyId&&i in this.peerConnectionMap&&this.onIceCandidateChange(i,t)}catch(t){this.loggingService.catch("Error in HuddleService onIceCandidateSnapshot:",t)}}onOffer(e,t){return X(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: onOffer","color: green;"),this.createPeerConnection(e,t.from)){this.addLocalStreamToPeerConnection(e,!0);let a=t.offer;yield this.setRemoteDescription(e,a),yield this.sendAnswer(e,t.from)}}catch(i){this.loggingService.catch("Error in HuddleService onOffer:",i)}})}sendAnswer(e,t){return X(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: sendAnswer","color: green;"),this.loggingService.log(e),this.documentPaths?.huddle&&e){let i=yield this.peerConnectionMap[e].createAnswer();yield this.setLocalDescription(e,i);let l={answer:{type:i.type,sdp:i.sdp},from:this.user.userSnippylyId,connectionId:e,to:t},c=jr(this.db,`${this.documentPaths?.huddle}/connections/${e}`);this.dbRefsRemoveOnDropCall.push({type:"connection",dbRef:c}),yield w8(c,{answerData:l}),bc(c).remove()}else this.loggingService.catch("Error in sendAnswer: documentPaths not found")}catch(i){this.loggingService.catch("Error in HuddleService onHuddleSnapshot:",i)}})}onAnswer(e,t){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: onAnswer","color: green;");let i=t.answer;yield this.setRemoteDescription(e,i)}catch(i){this.loggingService.catch("Error in HuddleService onAnswer:",i)}})}onIceCandidateChange(e,t){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: onIceCandidateChange","color: green;");let i=t.candidate;this.loggingService.log("onIceCandidateChange",i),yield this.peerConnectionMap[e].addIceCandidate(new RTCIceCandidate(i))}catch(i){this.loggingService.catch("Error in HuddleService onIceCandidateChange:",i)}})}setRemoteDescription(e,t){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setRemoteDescription","color: green;"),yield this.peerConnectionMap[e].setRemoteDescription(new RTCSessionDescription(t))}catch(i){this.loggingService.catch("Error in HuddleService setRemoteDescription:",i)}})}addAttendee(){return X(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: addAttendee","color: green;"),this.documentPaths?.huddle&&this.user?.userSnippylyId){let e=y(h({},this.user),{timestamp:this.timestamp,streamMetadata:{webcam:this.localStream?.id,screen:this.screenSharingStream?.id},initialHuddleType:this.initialHuddleType,huddleOnCursorMode:this.huddleOnCursorMode$?.value});e=this.huddleUtilsService.formatHuddleAttendeeData(e);let t=jr(this.db,`${this.documentPaths?.huddle}/attendees/${this.user.userSnippylyId}`);yield n0(t,JSON.parse(JSON.stringify(e))),this.dbRefsRemoveOnDropCall.push({type:"attendee",dbRef:t}),bc(t).remove(),yield this.updateUserHuddleState()}else this.loggingService.catch("Error in addAttendee: documentPaths not found")}catch(e){this.loggingService.catch("Error in HuddleService addAttendee:",e)}})}callExistingAttendees(){try{this.loggingService.log("%c[WB] Calling FUNCTION: callExistingAttendees","color: green;"),Ime(this.attendees).pipe(ut(1)).subscribe(e=>{e&&e.length>1?(e.forEach(t=>{t.userSnippylyId!==this.user.userSnippylyId&&!this.onOfferUidHistory[t.userSnippylyId]&&(this.loggingService.log("calling"),this.loggingService.log(t),this.initOffer(t.userSnippylyId))}),this.addLocalStreamToAllPeerConnections()):this.deleteMessages()})}catch(e){this.loggingService.catch("Error in HuddleService callExistingAttendees:",e)}}addLocalStreamToAllPeerConnections(){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: addLocalStreamToAllPeerConnections","color: green;"),Object.keys(this.senders).forEach(e=>{this.loggingService.log(this.senders[e]),this.localStream.getTracks().forEach(t=>{this.loggingService.log(t),this.senders[e].replaceTrack(t)})})}catch(e){this.loggingService.catch("Error in HuddleService addLocalStreamToAllPeerConnections:",e)}})}initOffer(e){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: initOffer","color: green;");let t=this.createPeerConnection(null,e);t&&(this.addLocalStreamToPeerConnection(t,!1),yield this.sendOffer(t,e))}catch(t){this.loggingService.catch("Error in HuddleService initOffer:",t)}})}createPeerConnection(e,t){try{return this.loggingService.log("%c[WB] Calling FUNCTION: createPeerConnection","color: green;"),e||(e=this.getCombinedId(this.user?.userSnippylyId,t)),e in this.peerConnectionMap?null:(this.loggingService.log("creating pc"),this.peerConnectionMap[e]=new RTCPeerConnection(this.servers),this.peerConnectionMap[e].onicecandidateerror=i=>{this.loggingService.log("Huddle: onicecandidateerror",i)},this.peerConnectionMap[e].onicecandidate=i=>{if(this.loggingService.log("pc onicecandidate"),i.candidate){let a={candidate:i.candidate.toJSON(),from:this.user.userSnippylyId,connectionId:e},l=I8(this.iceCandidates,a);this.dbRefsRemoveOnDropCall.push({type:"iceCandidate",dbRef:l}),bc(l).remove()}},this.peerConnectionMap[e].ontrack=i=>{this.loggingService.log("pc ontrack"),this.onTrack(e,i)},this.peerConnectionMap[e].onconnectionstatechange=i=>X(this,null,function*(){this.logStatuses("onconnectionstatechange",e,i),this.peerConnectionMap[e].connectionState==="failed"&&(this.removeConnection(e),this.closeConnection(e),this.checkForRemovingAttendee())}),this.peerConnectionMap[e].onicegatheringstatechange=i=>X(this,null,function*(){this.logStatuses("onicegatheringstatechange",e,i)}),this.peerConnectionMap[e].onsignalingstatechange=i=>X(this,null,function*(){this.logStatuses("onsignalingstatechange",e,i)}),this.peerConnectionMap[e].oniceconnectionstatechange=i=>X(this,null,function*(){this.loggingService.log("pc oniceconnectionstatechange"),this.logStatuses("oniceconnectionstatechange",e,i);try{this.peerConnectionStateMap[e]=this.peerConnectionMap[e].iceConnectionState,this.peerConnectionStateMap$.next(this.peerConnectionStateMap),this.peerConnectionMap[e]?.iceConnectionState==="connected"?(this.loggingService.log("connected"),this.updateTransceiverDirection(e)):this.peerConnectionMap[e]?.iceConnectionState==="disconnected"?this.loggingService.log("Disconnected"):this.peerConnectionMap[e].iceConnectionState==="closed"&&(this.loggingService.log("Closed"),this.closeConnection(e))}catch(a){this.loggingService.catch("Error in HuddleService oniceconnectionstatechange:",a)}}),this.peerConnectionMap[e].onnegotiationneeded=()=>{this.loggingService.log("pc onnegotiationneeded"),this.logStatuses("onnegotiationneeded",e)},e)}catch(i){return this.loggingService.catch("Error in HuddleService createPeerConnection:",i),""}}logStatuses(e,t,i){let a={};["connectionState","iceConnectionState","iceGatheringState","signalingState"].forEach(c=>{a[c]=this.peerConnectionMap[t][c]}),this.loggingService.log("Huddle: logStatues: ",t,e,a,i,this.peerConnectionMap[t])}checkForRemovingAttendee(){return X(this,null,function*(){try{this.documentPaths?.huddle&&this.user?.userSnippylyId&&(Object.keys(this.peerConnectionMap)?.length||(this.commonDbService.deleteData({feature:"huddleAttendee",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:this.user?.userSnippylyId,skipFirestore:!0}}),this.joinHuddle(this.initialHuddleType)))}catch(e){this.loggingService.catch("Error in HuddleService checkForRemovingAttendee:",e)}})}closeConnection(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: closeConnection","color: green;"),this.peerConnectionMap[e]){let t=this.peerConnectionMap[e];t.getTransceivers()?.forEach(a=>{a.stop()}),t.getReceivers()?.forEach(a=>{a.track?.stop()}),t.close(),delete this.peerConnectionMap[e],delete this.onAnswerConnectionIdHistory[e],delete this.senders[e];let i=e.split("__").find(a=>a!==this.user?.userSnippylyId);i&&delete this.onOfferUidHistory[i]}}catch(t){this.loggingService.catch("Error in HuddleService closeConnection:",t)}}removeConnection(e){return X(this,null,function*(){try{this.documentPaths?.huddle&&e&&this.commonDbService.deleteData({feature:"huddleConnection",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:e,skipFirestore:!0}})}catch(t){this.loggingService.catch("Error in HuddleService removeConnection:",t)}})}addLocalStreamToPeerConnection(e,t){try{this.loggingService.log("%c[WB] Calling FUNCTION: addLocalStreamToPeerConnection","color: green;"),t?(this.localStream.getTracks().forEach(i=>{this.peerConnectionMap[e].addTrack(i,this.localStream)}),this.screenSharingStream?.getVideoTracks()?.forEach(i=>{this.peerConnectionMap[e].addTrack(i,this.screenSharingStream)})):(this.localStream.getTracks().forEach(i=>{this.peerConnectionMap[e].addTrack(i,this.localStream)}),this.screenSharingStream?.getVideoTracks()?.forEach(i=>{this.peerConnectionMap[e].addTrack(i,this.screenSharingStream)}))}catch(i){this.loggingService.catch("Error in HuddleService addLocalStreamToPeerConnection:",i)}}updateTransceiverDirection(e){try{this.loggingService.log("%c[WB] Calling FUNCTION: updateTransceiverDirection","color: green;");let t=this.peerConnectionMap[e].getTransceivers();this.loggingService.log(t),t.map(i=>{this.loggingService.log(i.currentDirection),i.currentDirection!=="sendrecv"&&(i.direction="sendrecv"),this.senders[e]=i.sender})}catch(t){this.loggingService.catch("Error in HuddleService updateTransceiverDirection:",t)}}generateKey(){this.loggingService.log("%c[WB] Calling FUNCTION: generateKey","color: green;");let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t="";for(let i=0;i<20;i++)t+=e.charAt(Math.floor(Math.random()*e.length));return t}getCombinedId(e,t){try{return e.localeCompare(t)===-1?`${e}__${t}`:`${t}__${e}`}catch(i){return this.loggingService.catch("Error in HuddleService getCombinedId:",i),""}}sendOffer(e,t){return X(this,null,function*(){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: sendOffer","color: green;"),this.documentPaths?.huddle&&e){this.onOfferUidHistory[t]=!0;let i=yield this.peerConnectionMap[e].createOffer();yield this.setLocalDescription(e,i);let a={sdp:i.sdp,type:i.type};t||(t="all");let l={offer:a,from:this.user.userSnippylyId,connectionId:e,to:t},c=jr(this.db,`${this.documentPaths?.huddle}/connections/${e}`);yield n0(c,{offerData:l}),this.dbRefsRemoveOnDropCall.push({type:"connection",dbRef:c}),bc(c).remove()}}catch(i){this.loggingService.catch("Error in HuddleService sendOffer:",i)}})}setLocalDescription(e,t){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: setLocalDescription","color: green;"),yield this.peerConnectionMap[e].setLocalDescription(t)}catch(i){this.loggingService.catch("Error in HuddleService setLocalDescription:",i)}})}onTrack(e,t){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: onTrack","color: green;"),this.remoteStreamMap[e]||(this.remoteStreamMap[e]={}),this.loggingService.log(t.receiver.track),t?.streams?.length){this.remoteStreamMap[e][t.streams[0].id]=t.streams[0];let i=e.split("__").find(l=>l!==this.user?.userSnippylyId),a=this.attendees$.value?.find(l=>l?.userSnippylyId===i);a&&(a?.streamMetadata?.webcam===t.streams[0].id&&(this.remoteStreamMap[e].webcam=t.streams[0]),a?.streamMetadata?.screen===t.streams[0].id&&(this.remoteStreamMap[e].screen=t.streams[0])),this.remoteStreamMap$.next(this.remoteStreamMap)}}catch(i){this.loggingService.catch("Error in HuddleService onTrack:",i)}}toggleScreenSharing(e){return X(this,null,function*(){try{if(e)this.screenSharingStream=yield navigator.mediaDevices?.getDisplayMedia({video:!0}),Object.keys(this.peerConnectionMap).forEach(t=>{this.peerConnectionMap[t].getSenders().find(l=>l?.track?.kind==this.screenSharingStream?.getVideoTracks()[0].kind)?.replaceTrack(this.screenSharingStream?.getVideoTracks()[0])});else{let t=this.localStream;Object.keys(this.peerConnectionMap).forEach(i=>{this.peerConnectionMap[i].getSenders().find(c=>c?.track?.kind==t.getVideoTracks()[0].kind)?.replaceTrack(t.getVideoTracks()[0])}),this.screenSharingStream?.getTracks().forEach(i=>i.stop())}}catch(t){this.loggingService.catch("Error in HuddleService toggleScreenSharing:",t)}})}setLocalStream(e){return X(this,null,function*(){try{if(this.localStream=new MediaStream([this.silence(),this.black()]),e?.audio||e?.video){let t=e,i=lv();e?.audio&&(e?.audio instanceof Object?t.audio=y(h({},e?.audio),{deviceId:i?.selectedAudioDevice?.deviceId}):t.audio={deviceId:i?.selectedAudioDevice?.deviceId}),e?.video&&(e?.video instanceof Object?t.video=y(h({},e?.video),{deviceId:i?.selectedVideoDevice?.deviceId}):t.video={deviceId:i?.selectedVideoDevice?.deviceId});let a=yield navigator.mediaDevices.getUserMedia(t);a?.getAudioTracks()?.length&&(this.localStream.getAudioTracks().forEach(l=>this.localStream.removeTrack(l)),a.getAudioTracks().forEach(l=>this.localStream.addTrack(l))),a?.getVideoTracks()?.length&&(this.localStream.getVideoTracks().forEach(l=>this.localStream.removeTrack(l)),a.getVideoTracks().forEach(l=>this.localStream.addTrack(l)))}this.localStream$.next(this.localStream)}catch(t){this.loggingService.catch("Error in HuddleService setLocalStream:",t)}})}setScreenSharingStream(){return X(this,null,function*(){try{let e=yield navigator.mediaDevices?.getDisplayMedia({video:!0});e&&this.screenSharingStream$.next(e)}catch(e){this.loggingService.catch("Error in HuddleService setScreenSharingStream:",e)}})}removeLocalStream(){return X(this,null,function*(){try{this.localStream$?.value&&(this.localStream$.value.getTracks().forEach(t=>{t.stop()}),this.localStream$.next(null))}catch(e){this.loggingService.catch("Error in HuddleService removeLocalStream:",e)}})}toggleLocalStreamAudio(e){return X(this,null,function*(){try{let t=this.localStream$.value;if(t){let i=t.getAudioTracks()[0];if(i.enabled&&!e)i.stop(),t.getAudioTracks()?.forEach(a=>{t.removeTrack(a)}),t.addTrack(this.silence()),this.analyticsService.trackEvent(Y.Events.Huddle.HUDDLE_AUDIO_MUTED,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(a=>a?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(a=>a?.userId)});else{let a=lv(),l=yield navigator.mediaDevices.getUserMedia({audio:{deviceId:a?.selectAudioDevice?.deviceId}});l&&(t.getAudioTracks()?.forEach(c=>{t.removeTrack(c)}),l.getAudioTracks()?.forEach(c=>{t.addTrack(c)}),this.analyticsService.trackEvent(Y.Events.Huddle.HUDDLE_AUDIO_UNMUTED,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(c=>c?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(c=>c?.userId)}))}Object.keys(this.peerConnectionMap).forEach(a=>{this.peerConnectionMap[a].getSenders().find(d=>d?.track?.kind==t?.getAudioTracks()[0].kind)?.replaceTrack(t?.getAudioTracks()[0])}),this.updateUserHuddleState()}}catch(t){this.loggingService.catch("Error in HuddleService toggleLocalStreamAudio:",t)}})}toggleLocalStreamVideo(e){return X(this,null,function*(){try{let t=this.localStream$.value;if(t){let i=t.getVideoTracks()[0];if(i.enabled&&!e)i.stop(),t.getVideoTracks()?.forEach(a=>{t.removeTrack(a)}),t.addTrack(this.black()),this.analyticsService.trackEvent(Y.Events.Huddle.HUDDLE_VIDEO_TURNED_OFF,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(a=>a?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(a=>a?.userId)});else{let a=lv(),l=yield navigator.mediaDevices.getUserMedia({video:{deviceId:a?.selectedVideoDevice?.deviceId}});l&&(t.getVideoTracks()?.forEach(c=>{t.removeTrack(c)}),l.getVideoTracks()?.forEach(c=>{t.addTrack(c)}),this.analyticsService.trackEvent(Y.Events.Huddle.HUDDLE_VIDEO_TURNED_ON,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(c=>c?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(c=>c?.userId)}))}Object.keys(this.peerConnectionMap).forEach(a=>{this.peerConnectionMap[a].getSenders().find(d=>d?.track?.kind==t?.getVideoTracks()[0].kind)?.replaceTrack(t?.getVideoTracks()[0])}),this.updateUserHuddleState()}}catch(t){this.loggingService.catch("Error in HuddleService toggleLocalStreamVideo:",t)}})}toggleLocalScreenSharing(){return X(this,null,function*(){try{let e=this.screenSharingStream;if(e){if(e.getVideoTracks()[0].enabled)this.stopScreenSharingStream();else{let i=yield navigator.mediaDevices?.getDisplayMedia({video:!0});i&&(e.getVideoTracks()?.forEach(a=>{e.removeTrack(a)}),i.getVideoTracks()?.forEach(a=>{e.addTrack(a),a.onended=()=>{this.stopScreenSharingStream(),this.updateScreenSharingTracksToPeers(),this.updateUserHuddleState()}})),this.screenSharingStream$.next(e),this.analyticsService.trackEvent(Y.Events.Huddle.HUDDLE_SCREENSHARING_STARTED,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(a=>a?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(a=>a?.userId)})}this.updateScreenSharingTracksToPeers(),this.updateUserHuddleState()}}catch(e){this.loggingService.catch("Error in HuddleService toggleLocalScreenSharing:",e)}})}stopScreenSharingStream(){return X(this,null,function*(){let e=this.screenSharingStream;if(e){let t=e.getVideoTracks()[0];t.enabled&&(t.stop(),e.getVideoTracks()?.forEach(i=>{e.removeTrack(i)}),e.addTrack(this.black()),this.analyticsService.trackEvent(Y.Events.Huddle.HUDDLE_SCREENSHARING_STOPPED,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(i=>i?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(i=>i?.userId)}))}})}updateScreenSharingTracksToPeers(){return X(this,null,function*(){Object.keys(this.peerConnectionMap).forEach(e=>{let i=this.peerConnectionMap[e].getSenders().filter(a=>a?.track?.kind==this.screenSharingStream?.getVideoTracks()[0].kind);i?.length>1&&i[1]?.replaceTrack(this.screenSharingStream?.getVideoTracks()[0])})})}dropCall(){return X(this,null,function*(){try{this.messagesSubscription&&this.messagesSubscription.unsubscribe(),this.removeHuddleSessionData(),this.huddleJoined=!1,this.huddleJoined$.next(!1),this.peerConnectionMap&&Object.keys(this.peerConnectionMap).forEach(e=>{let t=this.peerConnectionMap[e];t.getTransceivers()?.forEach(i=>{i.stop()}),t.getSenders()?.forEach(i=>{i.track?.stop()}),t.getReceivers()?.forEach(i=>{i.track?.stop()}),t.close()}),this.peerConnectionMap={},this.dbRefsRemoveOnDropCall.forEach(e=>X(this,null,function*(){yield E8(e.dbRef)})),this.onOfferUidHistory={},this.onAnswerConnectionIdHistory={},this.senders={},this.peerConnectionStateMap={},this.peerConnectionStateMap$.next(this.peerConnectionStateMap),this.localStream.getTracks().forEach(e=>{e.stop()}),this.screenSharingStream.getTracks().forEach(e=>{e.stop()}),this.localStream=new MediaStream([this.silence(),this.black()]),this.screenSharingStream=new MediaStream([this.black()]),this.localStream$.next(this.localStream),this.screenSharingStream$.next(this.screenSharingStream),this.localStreamState$.next({audioState:!1,videoState:!1,screenSharingState:!1}),this.analyticsService.trackEvent(Y.Events.Huddle.HUDDLE_LEFT,{huddleType:this.initialHuddleType,totalUsers:this.getHuddleAttendees()?.length||0,totalUserHuddleDuration:this.getTotalUserHuddleDuration(),huddleSnippylyUserIds:this.getHuddleAttendees()?.map(e=>e?.userSnippylyId),huddleClientUserIds:this.getHuddleAttendees()?.map(e=>e?.userId)})}catch(e){this.loggingService.catch("Error in HuddleService dropCall:",e)}})}updateHuddleSessionData(e,t,i){try{let a=JSON.parse(sessionStorage.getItem(N.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)||"{}");i?sessionStorage.setItem(N.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA,JSON.stringify(i)):(a[e]=t,sessionStorage.setItem(N.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA,JSON.stringify(a)))}catch(a){this.loggingService.catch("Error in HuddleService updateHuddleSessionData:",a)}}getHuddleSessionData(){try{return sessionStorage.getItem(N.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)?JSON.parse(sessionStorage.getItem(N.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)):null}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleSessionData:",e),null}}removeHuddleSessionData(){try{sessionStorage.removeItem(N.SESSION_STORAGE.SNIPPYLY_HUDDLE_DATA)}catch(e){this.loggingService.catch("Error in HuddleService removeHuddleSessionData:",e)}}removeAttendee(){return X(this,null,function*(){try{if(this.documentPaths?.huddle&&this.user.userSnippylyId){yield this.commonDbService.deleteData({feature:"huddleAttendee",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:this.user?.userSnippylyId,skipFirestore:!0}});return}else return}catch(e){return this.loggingService.catch("Error in HuddleService removeAttendee:",e),Promise.resolve(null)}})}updateUserHuddleState(){return X(this,null,function*(){try{if(this.attendees&&this.user&&this.documentPaths?.huddle){let e=this.getAudioState(),t=this.getVideoState(),i=this.getScreenSharingState();this.localStreamState$.next({audioState:e,videoState:t,screenSharingState:i});let a={audioState:e,videoState:t,screenSharingState:i};yield this.commonDbService.setData({feature:"huddleAttendeeState",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:this.user?.userSnippylyId,skipFirestore:!0},data:a})}}catch(e){this.loggingService.catch("Error in HuddleService updateUserHuddleState:",e)}})}updateHuddleOnCursorMode(){return X(this,null,function*(){try{if(this.attendees&&this.user&&this.documentPaths?.huddle){let e=jr(this.db,`${this.documentPaths?.huddle}/attendees/${this.user.userSnippylyId}/huddleOnCursorMode`);yield n0(e,!!this.huddleOnCursorMode$.value)}}catch(e){this.loggingService.catch("Error in HuddleService updateHuddleOnCursorMode:",e)}})}getAudioState(){try{let e=this.localStream$.value;if(e){let t=e?.getAudioTracks();return!!(t?.length?t[0]:null)?.enabled}return!1}catch(e){return this.loggingService.catch("Error in HuddleService getAudioState:",e),!1}}getVideoState(){try{let e=this.localStream$.value;if(e){let t=e?.getVideoTracks();return!!(t?.length?t[0]:null)?.enabled}return!1}catch(e){return this.loggingService.catch("Error in HuddleService getVideoState:",e),!1}}getScreenSharingState(){try{let e=this.screenSharingStream;if(e){let t=e?.getVideoTracks();return!!(t?.length?t[0]:null)?.enabled}return!1}catch(e){return this.loggingService.catch("Error in HuddleService getVideoState:",e),!1}}removeIceCandidates(e){return X(this,null,function*(){try{if(this.documentPaths?.huddle&&e){let t=yield this.commonDbService?.getData({feature:"allHuddleIceCandidates",properties:{documentId:this.documentPaths?.documentId??"",organizationId:this.documentPaths?.organizationId??"",skipFirestore:!0}});Object.keys(t).length>0&&Object.keys(t).forEach(i=>X(this,null,function*(){t[i].connectionId===e&&this.commonDbService.deleteData({feature:"huddleIceCandidate",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:i,skipFirestore:!0}})}))}}catch(t){this.loggingService.catch("Error in HuddleService dropCall:",t)}})}get timestamp(){return this.commonDbService.getServerTimestamp()}silence(){try{let e=new AudioContext,t=e.createOscillator(),i=t.connect(e.createMediaStreamDestination());return t.start(),Object.assign(i.stream.getAudioTracks()[0],{enabled:!1})}catch(e){this.loggingService.catch("Error in HuddleService silence:",e)}}black({width:e=640,height:t=480}={}){try{let i=Object.assign(document.createElement("canvas"),{width:e,height:t});i.getContext("2d")?.fillRect(0,0,e,t);let a=i.captureStream();return Object.assign(a.getVideoTracks()[0],{enabled:!1})}catch(i){this.loggingService.catch("Error in HuddleService black:",i)}}getInitialHuddleType(){try{return this.initialHuddleType}catch(e){return this.loggingService.catch("Error in HuddleService getInitialHuddleType:",e),null}}getHuddleAttendees$(){try{return this.attendees$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleAttendees$:",e),ce([])}}getHuddleAttendees(){try{return this.attendees$.value}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleAttendees:",e),null}}getHuddleInvitees$(){try{return this.invitees$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleInvitees$:",e),ce([])}}getHuddleInvitees(){try{return this.invitees$.value}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleInvitees:",e),null}}getHuddleStartTime(){try{return this.userHuddleStartTime$.value}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleStartTime:",e),null}}getTotalUserHuddleDuration(){try{return this.userHuddleStartTime$.value?new Date().getTime()-this.userHuddleStartTime$.value:null}catch(e){return this.loggingService.catch("Error in HuddleService gettotalUserHuddleDuration:",e),null}}inviteUsers(e){try{this.updateInvitees(e);let t={};t.notificationSource="huddleInvite",t.huddleInvitees=e,t.huddleType=this.getInitialHuddleType(),this.updateNotificationsDatabase(t)}catch(t){this.loggingService.catch("Error in HuddleService inviteUsers:",t)}}updateInvitees(e){try{if(this.documentPaths?.huddle){let t={};e.forEach(i=>{if(i?.email){let a=It(i.email);t[a]=i}}),this.commonDbService.setData({feature:"allHuddleInvitees",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0},data:t})}}catch(t){this.loggingService.catch("Error in HuddleService updateInvitees:",t)}}updateNotificationsDatabase(e={}){try{let t=h({notificationSource:"huddle"},e);this.notificationService.updateNotificationDatabase(t)}catch(t){this.loggingService.catch("Error in HuddleService updateNotificationsDatabase: ",t)}}getHuddleJoined$(){try{return this.huddleJoined$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleJoined$:",e),ce(!1)}}getHuddleCursorAvailableByAttendeeId(){try{return this.huddleCursorAvailableByAttendeeId$.value}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleCursorAvailableByAttendeeId:",e),null}}getHuddleCursorAvailableByAttendeeId$(){try{return this.huddleCursorAvailableByAttendeeId$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleCursorAvailableByAttendeeId$:",e),ce({})}}updateHuddleCursorAvailableByAttendeeId(e,t){try{let i=this.huddleCursorAvailableByAttendeeId$.value;i[e]=t,this.huddleCursorAvailableByAttendeeId$.next(i)}catch(i){this.loggingService.catch("Error in HuddleService updateCursorUserAvailableByUserId:",i)}}setRemoteStreamsByUserId(e){try{this.remoteStreamsByUserId$.next(e)}catch(t){this.loggingService.catch("Error in HuddleService setRemoteStreamsByUserId:",t)}}getRemoteStreamsByUserId$(){try{return this.remoteStreamsByUserId$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getRemoteStreamsByUserId$:",e),ce({})}}enableHuddleOnCursorMode(){try{this.huddleOnCursorMode$.next(!0)}catch(e){this.loggingService.catch("Error in HuddleService enableHuddleOnCursorMode:",e)}}disableHuddleOnCursorMode(){try{this.huddleOnCursorMode$.next(!1)}catch(e){this.loggingService.catch("Error in HuddleService disableHuddleOnCursorMode:",e)}}getHuddleOnCursorMode$(){try{return this.huddleOnCursorMode$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleOnCursorMode$:",e),ce(!1)}}enableFlockModeOnAvatarClick(){try{this.flockModeOnAvatarClickEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in HuddleService enableFlockModeOnAvatarClick:",e)}}disableFlockModeOnAvatarClick(){try{this.flockModeOnAvatarClickEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in HuddleService disableFlockModeOnAvatarClick:",e)}}getFlockModeOnAvatarClick$(){try{return this.flockModeOnAvatarClickEnabled$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getFlockModeOnAvatarClick$:",e),ce(!1)}}getFlockModeOnAvatarClick(){try{return this.flockModeOnAvatarClickEnabled$.value}catch(e){return this.loggingService.catch("Error in HuddleService getFlockModeOnAvatarClick:",e),!1}}enableChat(){try{this.chatEnabled$.next(!0)}catch(e){this.loggingService.catch("Error in HuddleService enableChat:",e)}}disableChat(){try{this.chatEnabled$.next(!1)}catch(e){this.loggingService.catch("Error in HuddleService disableChat:",e)}}getChatEnabled$(){try{return this.chatEnabled$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getChatEnabled$:",e),ce(!1)}}getChatEnabled(){try{return this.chatEnabled$.value}catch(e){return this.loggingService.catch("Error in HuddleService getChatEnabled:",e),!1}}enableServerFallback(){try{if(this.serverFallback$.value===!0)return;this.serverFallback$.next(!0)}catch(e){this.loggingService.catch("Error in HuddleService enableServerFallback:",e)}}disableServerFallback(){try{if(this.serverFallback$.value===!1)return;this.serverFallback$.next(!1)}catch(e){this.loggingService.catch("Error in HuddleService disableServerFallback:",e)}}getServerFallback$(){try{return this.serverFallback$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getServerFallback$:",e),ce(!1)}}getServerFallback(){try{return this.serverFallback$.value}catch(e){return this.loggingService.catch("Error in HuddleService getServerFallback:",e),!1}}getHuddleOnCursorModeByAttendeeId$(){try{return this.huddleOnCursorModeByAttendeeId$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getHuddleOnCursorModeByAttendeeId$:",e),ce({})}}toggleHuddleOnCursorModeByAttendeeId(e){try{let t=this.huddleOnCursorModeByAttendeeId$.value;t[e]?delete t[e]:t[e]=!0,this.huddleOnCursorModeByAttendeeId$.next(t)}catch(t){this.loggingService.catch("Error in HuddleService toggleHuddleOnCursorModeByAttendeeId:",t)}}addCursorTag(){try{if(!document.querySelector(`${N.TAGS.SNIPPYLY_CURSOR}`)){let e=document.createElement(N.TAGS.SNIPPYLY_CURSOR);e.setAttribute("snippyly-temporary","true"),document.body.appendChild(e)}}catch(e){this.loggingService.catch("Error in HuddleService addCursorTag:",e)}}removeCursorTag(){try{let e=document.querySelector(`${N.TAGS.SNIPPYLY_CURSOR}`);e?.hasAttribute("snippyly-temporary")&&e.remove()}catch(e){this.loggingService.catch("Error in HuddleService removeCursorTag:",e)}}sendMessage(e){try{if(this.loggingService.log("%c[WB] Calling FUNCTION: sendMessage","color: green;"),this.documentPaths?.huddle&&this.user){let t=new NN;t.message=e,t.from=this.user,t.timestamp=this.timestamp,this.commonDbService.setData({feature:"huddleMessage",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,id:t.id,skipFirestore:!0},data:t})}}catch(t){this.loggingService.catch("Error in HuddleService sendMessage:",t)}}getMessages$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getMessages$","color: green;"),this.messages$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getMessages$:",e),ce([])}}deleteMessages(){try{this.loggingService.log("%c[WB] Calling FUNCTION: deleteMessages","color: green;"),this.documentPaths?.huddle&&this.commonDbService.deleteData({feature:"allHuddleMessages",properties:{documentId:this.documentPaths?.documentId,organizationId:this.documentPaths?.organizationId,skipFirestore:!0}})}catch(e){this.loggingService.catch("Error in HuddleService deleteMessages:",e)}}showMessagesPanel(){try{this.loggingService.log("%c[WB] Calling FUNCTION: showMessagesPanel","color: green;"),this.messagesPanelVisible$.next(!0)}catch(e){this.loggingService.catch("Error in HuddleService showMessagesPanel:",e)}}hideMessagesPanel(){try{this.loggingService.log("%c[WB] Calling FUNCTION: hideMessagesPanel","color: green;"),this.messagesPanelVisible$.next(!1)}catch(e){this.loggingService.catch("Error in HuddleService hideMessagesPanel:",e)}}toggleMessagesPanel(){try{this.loggingService.log("%c[WB] Calling FUNCTION: toggleMessagesPanel","color: green;"),this.messagesPanelVisible$.next(!this.messagesPanelVisible$.value)}catch(e){this.loggingService.catch("Error in HuddleService toggleMessagesPanel:",e)}}getMessagesPanelVisible$(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getMessagesPanelVisible$","color: green;"),this.messagesPanelVisible$.asObservable()}catch(e){return this.loggingService.catch("Error in HuddleService getMessagesPanelVisible$:",e),ce(!1)}}getMessagesPanelVisible(){try{return this.loggingService.log("%c[WB] Calling FUNCTION: getMessagesPanelVisible","color: green;"),this.messagesPanelVisible$.value}catch(e){return this.loggingService.catch("Error in HuddleService getMessagesPanelVisible:",e),!1}}signOutUser(e){return X(this,null,function*(){try{this.loggingService.log("%c[WB] Calling FUNCTION: signOutUser","color: green;"),this.huddleJoined$.value&&(yield this.dropCall(),yield this.removeLocalStream(),yield this.removeAttendee())}catch(t){this.loggingService.catch("Error in HuddleService signOutUser:",t)}})}};o.\u0275fac=function(t){return new(t||o)(K(eo),K(ct),K(qe),K($n),K(st),K(Ft),K(Ve),K(GL),K(Do),K(k),K(mn),K(yn),K(An))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var uU=class extends Cr{constructor(o){super(o),this.getService(k).log("%c[WB] Creating CLASS: HuddleElement","color: blue;"),this.enableCursorMode=this._enableCursorMode,this.disableCursorMode=this._disableCursorMode,this.enableChat=this._enableChat,this.disableChat=this._disableChat,this.enableFlockModeOnAvatarClick=this._enableFlockModeOnAvatarClick,this.disableFlockModeOnAvatarClick=this._disableFlockModeOnAvatarClick}_enableCursorMode(){this.getService(k).log("%c[WB] Calling FUNCTION: _enableCursorMode","color: green;");try{this.trackEvent(Y.Events.Huddle.ENABLE_HUDDLE_ON_CURSOR_MODE_TRIGGERED),this.getService(ia).enableHuddleOnCursorMode()}catch(o){this.getService(k).catch("Error in enableCursorMode: ",o)}}_disableCursorMode(){this.getService(k).log("%c[WB] Calling FUNCTION: _disableCursorMode","color: green;");try{this.trackEvent(Y.Events.Huddle.DISABLE_HUDDLE_ON_CURSOR_MODE_TRIGGERED),this.getService(ia).disableHuddleOnCursorMode()}catch(o){this.getService(k).catch("Error in disableCursorMode: ",o)}}_enableChat(){this.getService(k).log("%c[WB] Calling FUNCTION: _enableChat","color: green;");try{this.trackEvent(Y.Events.Huddle.ENABLE_CHAT_TRIGGERED),this.getService(ia).enableChat()}catch(o){this.getService(k).catch("Error in enableChat: ",o)}}_disableChat(){this.getService(k).log("%c[WB] Calling FUNCTION: _disableChat","color: green;");try{this.trackEvent(Y.Events.Huddle.DISABLE_CHAT_TRIGGERED),this.getService(ia).disableChat()}catch(o){this.getService(k).catch("Error in disableChat: ",o)}}_enableFlockModeOnAvatarClick(){this.getService(k).log("%c[WB] Calling FUNCTION: _enableFlockModeOnAvatarClick","color: green;");try{this.trackEvent(Y.Events.Huddle.ENABLE_FLOCK_MODE_ON_AVATAR_CLICK_TRIGGERED),this.getService(ia).enableFlockModeOnAvatarClick()}catch(o){this.getService(k).catch("Error in enableFlockModeOnAvatarClick: ",o)}}_disableFlockModeOnAvatarClick(){this.getService(k).log("%c[WB] Calling FUNCTION: _disableFlockModeOnAvatarClick","color: green;");try{this.trackEvent(Y.Events.Huddle.DISABLE_FLOCK_MODE_ON_AVATAR_CLICK_TRIGGERED),this.getService(ia).disableFlockModeOnAvatarClick()}catch(o){this.getService(k).catch("Error in disableFlockModeOnAvatarClick: ",o)}}};var pU=(()=>{let o=class o{constructor(e,t){this.analyticsService=e,this.loggingService=t,this.actionSubjects=new Map,this.subscriptions=[]}onAccessRequested(e){try{this.triggerAction(Yu.ACCESS_REQUESTED,e),this.analyticsService.trackEvent(Y.Events.LiveStateSync.SEM_ACCESS_REQUESTED,{viewerUserId:e?.viewer?.userId,editorUserId:e?.editor?.userId,timestamp:e?.timestamp,status:e?.status,totalUsers:e?.totalUsers,isMultipleUsersDetected:(e?.totalUsers??0)>1,presenceSnippylyUserIds:e?.presenceSnippylyUserIds,presenceClientUserIds:e?.presenceClientUserIds})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onAccessRequested: ",t)}}onAccessRequestCanceled(e){try{this.triggerAction(Yu.ACCESS_REQUEST_CANCELED,e),this.analyticsService.trackEvent(Y.Events.LiveStateSync.SEM_ACCESS_REQUEST_CANCELED,{viewerUserId:e?.viewer?.userId,editorUserId:e?.editor?.userId,timestamp:e?.timestamp,status:e?.status,totalUsers:e?.totalUsers,isMultipleUsersDetected:(e?.totalUsers??0)>1,presenceSnippylyUserIds:e?.presenceSnippylyUserIds,presenceClientUserIds:e?.presenceClientUserIds})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onAccessRequestCanceled: ",t)}}onAccessAccepted(e){try{this.triggerAction(Yu.ACCESS_ACCEPTED,e),this.analyticsService.trackEvent(Y.Events.LiveStateSync.SEM_ACCESS_ACCEPTED,{viewerUserId:e?.viewer?.userId,editorUserId:e?.editor?.userId,timestamp:e?.timestamp,status:e?.status,totalUsers:e?.totalUsers,isMultipleUsersDetected:(e?.totalUsers??0)>1,presenceSnippylyUserIds:e?.presenceSnippylyUserIds,presenceClientUserIds:e?.presenceClientUserIds})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onAccessAccepted: ",t)}}onAccessRejected(e){try{this.triggerAction(Yu.ACCESS_REJECTED,e),this.analyticsService.trackEvent(Y.Events.LiveStateSync.SEM_ACCESS_REJECTED,{viewerUserId:e?.viewer?.userId,editorUserId:e?.editor?.userId,timestamp:e?.timestamp,status:e?.status,totalUsers:e?.totalUsers,isMultipleUsersDetected:(e?.totalUsers??0)>1,presenceSnippylyUserIds:e?.presenceSnippylyUserIds,presenceClientUserIds:e?.presenceClientUserIds})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onAccessRejected: ",t)}}onEditorAssigned(e){try{this.triggerAction(Yu.EDITOR_ASSIGNED,e),this.analyticsService.trackEvent(Y.Events.LiveStateSync.SEM_EDITOR_ASSIGNED,{editorUserId:e?.editor?.userId,timestamp:e?.timestamp,role:e?.role,totalUsers:e?.totalUsers,isMultipleUsersDetected:(e?.totalUsers??0)>1,presenceSnippylyUserIds:e?.presenceSnippylyUserIds,presenceClientUserIds:e?.presenceClientUserIds})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onEditorAssigned: ",t)}}onEditorOnDifferentTabDetected(e){try{this.triggerAction(Yu.EDITOR_ON_DIFFERENT_TAB_DETECTED,e),this.analyticsService.trackEvent(Y.Events.LiveStateSync.SEM_EDITOR_ON_DIFFERENT_TAB_DETECTED,{editorUserId:e?.editor?.userId,timestamp:e?.timestamp,role:e?.role,totalUsers:e?.totalUsers,isMultipleUsersDetected:(e?.totalUsers??0)>1,presenceSnippylyUserIds:e?.presenceSnippylyUserIds,presenceClientUserIds:e?.presenceClientUserIds})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onEditorOnDifferentTabDetected: ",t)}}onViewerAssigned(e){try{this.triggerAction(Yu.VIEWER_ASSIGNED,e),this.analyticsService.trackEvent(Y.Events.LiveStateSync.SEM_VIEWER_ASSIGNED,{viewerUserId:e?.viewer?.userId,timestamp:e?.timestamp,role:e?.role,totalUsers:e?.totalUsers,isMultipleUsersDetected:(e?.totalUsers??0)>1,presenceSnippylyUserIds:e?.presenceSnippylyUserIds,presenceClientUserIds:e?.presenceClientUserIds})}catch(t){this.loggingService.catch("Error in LiveStateActionsService onViewerAssigned: ",t)}}triggerAction(e,t){try{this.actionSubjects.has(e)||this.actionSubjects.set(e,new at),this.actionSubjects.get(e)?.next(t)}catch(i){this.loggingService.catch("Error in LiveStateActionsService triggerAction: ",i)}}onAction(e){try{return this.actionSubjects.has(e)||this.actionSubjects.set(e,new at),this.actionSubjects.get(e)?.asObservable()}catch(t){return this.loggingService.catch("Error in LiveStateActionsService onAction: ",t),ce(null)}}};o.\u0275fac=function(t){return new(t||o)(K(ct),K(k))},o.\u0275prov=Ae({token:o,factory:o.\u0275fac,providedIn:"root"});let n=o;return n})();var hU=(()=>{let o=class o{constructor(e,t,i,a,l,c,d,m,u){this.authService=e,this.commonDbService=t,this.databaseService=i,this.docService=a,this.domService=l,this.loggingService=c,this.metadataService=d,this.commonDbUtils=m,this.configService=u,this.HEARTBEAT_DURATION=5*1e3,this.heartbeatEnabled$=new _e(!1),this.subscriptions=[],this.heartbeatCreatedTimestamps=new Map,this.initializedHeartbeatIds=new Set;try{this.loggingService.log("%c[WB] Creating CLASS: HeartbeatService","color: blue;"),this.heartbeatEnabled$.pipe(_t()).subscribe(_=>{_?this.setupHeartbeat():this.teardownHeartbeat()}),this.docService.addPreDocumentIdChangeFunction("heartbeat-service",_=>_?.documentId?this.removeDocumentHeartbeat(_):Promise.resolve())}catch(_){this.loggingService.catch("Error in HeartbeatService constructor: ",_)}}setupWebWorker(e){try{let t=`
502
502
  let intervalId;
503
503
  self.addEventListener('message', (event) => {