@veltdev/sdk 6.0.29 → 6.0.31
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/{chunk-2DMVX6Z3.js → chunk-2NF5H2TO.js} +1 -1
- package/{chunk-7ZSEYX3G.js → chunk-33RB7RGI.js} +1 -1
- package/{chunk-MFXS56C3.js → chunk-3MKOFVA4.js} +1 -1
- package/{chunk-BRCK225M.js → chunk-7LGRH5L7.js} +1 -1
- package/{chunk-7K4EA6Y5.js → chunk-BLQFOUHF.js} +1 -1
- package/{chunk-ZADJEDZT.js → chunk-BPUKSXKL.js} +1 -1
- package/{chunk-QXHO6I75.js → chunk-CE2EVKCW.js} +1 -1
- package/{chunk-EQWU2DL7.js → chunk-CNWBCCFP.js} +1 -1
- package/{chunk-DJPCTT4F.js → chunk-CWIAV54H.js} +1 -1
- package/{chunk-35XJQZ27.js → chunk-DEX3ZQW4.js} +1 -1
- package/{chunk-7DTEJ3JT.js → chunk-EB73L6PP.js} +1 -1
- package/chunk-FKN7LIYH.js +1 -0
- package/{chunk-M6J3KGG7.js → chunk-GLYC5MOA.js} +1 -1
- package/{chunk-FQILN45X.js → chunk-HS6DKXTG.js} +1 -1
- package/{chunk-T6YEK2X2.js → chunk-IYLU72I4.js} +1 -1
- package/{chunk-2YDGTFZM.js → chunk-K77GW65W.js} +1 -1
- package/{chunk-BG6LRF5O.js → chunk-N7HBSHMG.js} +1 -1
- package/chunk-O5LVBWUD.js +1 -0
- package/chunk-OSQH62D7.js +6 -0
- package/{chunk-ZAORQEEC.js → chunk-P7BCV4ME.js} +1 -1
- package/{chunk-XZCIYLEI.js → chunk-PPOB3N6B.js} +1 -1
- package/{chunk-5TCVSBJS.js → chunk-PQKCFO3O.js} +1 -1
- package/chunk-PUTCGYJV.js +1 -0
- package/{chunk-MW45OPL7.js → chunk-QFOISMJE.js} +1 -1
- package/{chunk-4QGCX4EY.js → chunk-SKSZYHHP.js} +26 -26
- package/{chunk-RIQYRZB7.js → chunk-SLCZA7OJ.js} +1 -1
- package/{chunk-ASGMGCYI.js → chunk-SO3O7X5P.js} +1 -1
- package/{chunk-Q3RXGMSF.js → chunk-SQZF6W7N.js} +2 -2
- package/{chunk-PRURFNVL.js → chunk-TUMTL6R6.js} +1 -1
- package/{chunk-DHVECNH4.js → chunk-VE4MHD5D.js} +1 -1
- package/{chunk-AOKM7YOQ.js → chunk-VTGJS3GT.js} +1 -1
- package/{chunk-STGE6CFR.js → chunk-WZXMZ7R7.js} +1 -1
- package/chunk-XLPYUWJX.js +1 -0
- package/{chunk-7WHI6IHH.js → chunk-XYFA3Q6A.js} +1 -1
- package/{chunk-333ZBMSE.js → chunk-YC3Z7OAA.js} +1 -1
- package/{chunk-CRKE5XUX.js → chunk-ZKZLKVGF.js} +1 -1
- package/package.json +1 -1
- package/velt-activity-log.js +1 -1
- package/velt-area.js +1 -1
- package/velt-arrow.js +1 -1
- package/velt-comment.js +7 -7
- package/velt-crdt.js +1 -1
- package/velt-cursor.js +1 -1
- package/velt-huddle.js +1 -1
- package/velt-live-state-sync.js +1 -1
- package/velt-notification.js +1 -1
- package/velt-portable.js +1 -1
- package/velt-presence.js +1 -1
- package/velt-reaction.js +1 -1
- package/velt-recorder.js +1 -1
- package/velt-rewriter.js +2 -2
- package/velt-selection.js +1 -1
- package/velt-tag.js +1 -1
- package/velt-user-invite.js +1 -1
- package/velt-user-request.js +1 -1
- package/velt-video-player.js +1 -1
- package/velt-views.js +1 -1
- package/velt.js +2 -2
- package/chunk-4H2TOH52.js +0 -1
- package/chunk-7DF5ZYSM.js +0 -1
- package/chunk-ESMJKCYM.js +0 -1
- package/chunk-OITZJHUL.js +0 -1
- package/chunk-TU6L6SDC.js +0 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as $,c as z,d as U,e as H,f as j}from"./chunk-RIQYRZB7.js";import{B as ee,b as Z,o as O,r as J}from"./chunk-4H2TOH52.js";import{He as K,Hi as k,Ie as V,Mj as G,Nj as q,Oj as W,Rj as _,Sj as X,Yd as S,_d as E,_j as M,a as b,ba as A,bf as x,ea as g,ee as R,g as p,i as L,na as N,ok as Q,pj as y,pk as Y,qj as w,rj as C,sa as P,tk as T,vg as F}from"./chunk-4QGCX4EY.js";var pe=1e4,ge=6e4,te=3e4,me=3e4,fe=900*1e3;function re(s){let n=Math.max(0,Math.min(Math.floor(Number.isFinite(s)?s:1)-1,16));return Math.min(me*2**n,fe)}var Ae=3600*1e3,ie=250,ne=1200*1e3,Se=1024,ve={fetch:(s,n)=>fetch(s,n)},be="The browser could not send the file to the storage URL the gateway signed. The usual cause is the CORS rules of that storage (its storage account or bucket), which must allow this page's origin for PUT; they are set by the operator of the deployment, not by the SDK.",se="The browser could not read the file from the storage URL the gateway signed. The usual cause is the CORS rules of that storage (its storage account or bucket), which must allow this page's origin for GET; they are set by the operator of the deployment, not by the SDK.",m=class extends Error{constructor(n,d){super(d),this.code=n,this.name="PortableAttachmentError"}};function v(s){return!!s&&!s.url&&s.isAttachmentResolverUsed!==!0&&typeof s.bucketPath=="string"&&s.bucketPath.length>0&&s.attachmentId!==void 0&&s.attachmentId!==null&&String(s.attachmentId).length>0}function ye(s,n,d){let e={organizationId:n,documentId:d};return typeof s?.name=="string"&&s.name.length>0&&s.name.length<=Se&&(e.fileName=s.name),typeof s?.type=="string"&&s.type.length>0&&(e.contentType=s.type),Number.isInteger(s?.size)&&s.size>=0&&(e.sizeBytes=s.size),e}function we(s){return typeof s=="string"&&/^[A-Za-z0-9._-]{1,128}$/.test(s)&&!/^\.+$/.test(s)}function Te(s){return!!s&&typeof s=="object"&&!Array.isArray(s)&&Object.values(s).every(n=>typeof n=="string")}function Ie(s){let n=s;return!n||typeof n!="object"||!we(n.attachmentId)||typeof n.key!="string"||!n.key||typeof n.url!="string"||!C(n.url)||n.method!=="PUT"||!Te(n.headers)?null:{attachmentId:n.attachmentId,key:n.key,url:n.url,method:"PUT",headers:b({},n.headers),expiresAtMs:typeof n.expiresAtMs=="number"?n.expiresAtMs:0}}function Pe(s){let n=s;return!n||typeof n!="object"||typeof n.url!="string"||!C(n.url)?null:{key:typeof n.key=="string"?n.key:"",url:n.url,expiresAtMs:typeof n.expiresAtMs=="number"&&Number.isFinite(n.expiresAtMs)?n.expiresAtMs:0}}function Ue(s,n,d){let e=Number.isFinite(s)?s-(n+(Number.isFinite(d)?d:0)):0;return n+Math.min(Math.max(e,0),Ae)}var ae=(()=>{let n=class n{constructor(e,t){this.injector=e,this.loggingService=t,this.urlGeneration=P(0),this.urlKeyVersions=new Map,this.userWatched=!1,this.watchedUserId=null,this.urlCache=new Map,this.urlInFlight=new Map,this.urlFailures=new Map,this.urlMissing=new Set,this.cacheOwner=null,this.attachmentsAnnounced=!1,this.hookedRealtime=null,this.offCapabilities=null,this.availabilityListeners=new Set,this.veltStorageRefusalsReported=new Set,this.reportedOpFailures=new Set,this.invalidReadUrlReported=!1,this.hotPathReported=new Set,this.portableSessionSeen=!1}get selector(){return this._selector??=this.injector.get(X)}get auth(){return this._auth??=this.injector.get(T)}get config(){return this._config??=this.injector.get(w)}isPortableSession(){try{if(!this.auth.getPortableBackend?.())return!1;let e=this.selector.isPortableSession()===!0;return e&&(this.portableSessionSeen=!0),e}catch(e){return this.loggingService.catch("Error in PortableAttachmentStorageService isPortableSession: ",e,void 0,!0),!1}}isPortableAttachmentDeployment(){if(this.isPortableSession())return!0;if(!this.portableSessionSeen)return!1;try{return this.config.getEnablePortableBackend()===!0}catch(e){return this.loggingService.catch("Error in PortableAttachmentStorageService isPortableAttachmentDeployment: ",e,void 0,!0),!0}}captureSessionUser(){return this.isPortableSession()?this.currentUserId():null}isSameSessionUser(e){return this.isSameSession(e??null)}isPortableAttachment(e){return v(e)&&this.isPortableSession()}upload(l){return p(this,arguments,function*({attachment:e,file:t,scope:r,sessionUserId:i}){let o=this.scopeIds(r);if(!o)throw this.notSent("upload","the comment has no organization or document id");let c=i===void 0?this.currentUserId():i;if(!c)throw this.notSent("upload","no user is signed in");if(!this.isSameSession(c))throw this.notSent("upload","the session changed before the upload started");if(!(yield this.waitForActiveBackend())||!this.isSameSession(c))throw this.notSent("upload","the portable backend is not active");let a=yield this.callOp("getUploadUrl",ye(t,o.organizationId,o.documentId));if(!this.isSameSession(c))throw this.dropped("the session changed while getUploadUrl ran; the file was not uploaded");if(!a?.ok){this.reportOpFailure("getUploadUrl",a);let u=`${a?.code??"unknown"}${a?.message?` (${a.message})`:""}`;throw new m(a?.code??"failed-precondition",O(a)?`Tier B comment attachments are not available on this deployment: getUploadUrl answered ${u}`:`Tier B getUploadUrl failed: ${u}`)}let h=Ie(a.data);if(!h){let u=new m("failed-precondition",'Tier B getUploadUrl answered a signed upload this SDK will not use (it needs method PUT, an https URL, string headers, an attachmentId of 1-128 letters, digits, ".", "_" or "-", and a key); the file was not uploaded');throw this.loggingService.catch(u.message,void 0,void 0,!0),u}if(yield this.putSignedUpload(h,t),!this.isSameSession(c))throw this.dropped("the session changed while the file uploaded; the attachment is not added");return e.attachmentId=h.attachmentId,e.bucketPath=h.key,e.url="",e.clientOrganizationId=o.organizationId,e.clientDocumentId=o.documentId,e})}putSignedUpload(e,t){return p(this,null,function*(){let r=typeof AbortController=="function"?new AbortController:null,i=null,l=new Promise((o,c)=>{i=setTimeout(()=>{r?.abort(),c(new m("put-failed",`Tier B attachment upload failed: the storage did not answer the PUT within ${ne/6e4} minutes`))},ne)});try{let o=yield Promise.race([ve.fetch(e.url,b({method:"PUT",headers:b({},e.headers),body:t.slice(0,t.size,""),redirect:"error",credentials:"omit",referrerPolicy:"no-referrer"},r?{signal:r.signal}:{})),l]);if(!o?.ok)throw new m("put-failed",`Tier B attachment upload failed: the storage answered the PUT with HTTP ${o?.status}`)}catch(o){let c=o instanceof m?o:new m("put-failed",`Tier B attachment upload failed in transport: ${o?.message??o}. ${be}`);throw this.loggingService.catch(c.message,void 0,void 0,!0),c}finally{i!==null&&clearTimeout(i)}})}refuseVeltStorage(e){let t=new m("unimplemented",`Tier B ${e} was not sent: media outside comment attachments (recorder, tag) is not served by the portable backend, and Velt's storage is never used on a portable deployment`);try{this.veltStorageRefusalsReported.has(e)?this.loggingService.log(t.message):(this.veltStorageRefusalsReported.add(e),this.loggingService.catch(t.message,void 0,void 0,!0))}catch{}return t}delete(r){return p(this,arguments,function*({attachment:e,scope:t}){try{let i=this.attachmentIds(e,t),l=e?.attachmentId;if(!i||l===void 0||l===null||String(l).length===0){this.loggingService.catch("Tier B deleteAttachment was not sent: the attachment has no id, or the comment no organization or document id",void 0,void 0,!0);return}let o=this.currentUserId();if(!o||!(yield this.waitForActiveBackend())||!this.isSameSession(o)){this.loggingService.catch("Tier B deleteAttachment was not sent: the portable backend is not active",void 0,void 0,!0);return}let c=yield this.callOp("deleteAttachment",{organizationId:i.organizationId,documentId:i.documentId,attachmentId:String(l)});c?.ok||this.reportOpFailure("deleteAttachment",c)}catch(i){this.loggingService.catch("Error in PortableAttachmentStorageService delete: ",i,void 0,!0)}})}resolveDownloadUrl(e,t){try{if(!this.isPortableAttachment(e))return Promise.resolve(e?.url||null);let r=this.urlContext(e,t);if(!r||this.urlMissing.has(r.key))return Promise.resolve(null);let i=this.urlCache.get(r.key);return i&&this.isFresh(i,Date.now())?Promise.resolve(i.url):this.fetchDownloadUrl(r.key,e,r.ids,r.userId,!1)}catch(r){return this.loggingService.catch("Error in PortableAttachmentStorageService resolveDownloadUrl: ",r,void 0,!0),Promise.resolve(null)}}getDisplayUrl(e,t){if(!v(e))return e?.url;if(this.urlGeneration(),this.watchUser(),!this.isPortableSession())return e.url;try{let r=this.urlContext(e,t);if(!r)return e.url;if(this.keyVersion(r.key),this.urlMissing.has(r.key))return"";let i=Date.now(),l=this.urlCache.get(r.key);return l&&this.isFresh(l,i)?l.url:(this.inFailureBackoff(r.key,i)||this.fetchDownloadUrl(r.key,e,r.ids,r.userId,!1),l&&i<l.expiresAtMs?l.url:"")}catch(r){return this.loggingService.catch("Error in PortableAttachmentStorageService getDisplayUrl: ",r,void 0,!0),e.url}}isDisplayPending(e,t){if(!v(e)||!this.isPortableSession())return!1;try{if(this.getDisplayUrl(e,t))return!1;let r=this.urlContext(e,t);return!!r&&!this.urlMissing.has(r.key)&&!this.inFailureBackoff(r.key,Date.now())}catch(r){return this.loggingService.catch("Error in PortableAttachmentStorageService isDisplayPending: ",r,void 0,!0),!1}}reportLoadError(e,t,r){try{if(!this.isPortableAttachment(e))return;let i=this.urlContext(e,t),l=i?this.urlCache.get(i.key):void 0;if(!i||!l||l.afterLoadError||!r||l.url!==r)return;this.urlCache.delete(i.key),this.fetchDownloadUrl(i.key,e,i.ids,i.userId,!0),this.bumpKey(i.key)}catch(i){this.loggingService.catch("Error in PortableAttachmentStorageService reportLoadError: ",i,void 0,!0)}}fetchDownloadUrl(e,t,r,i,l){let o=this.urlInFlight.get(e);if(o)return o;let c;return c=p(this,null,function*(){try{if(!(yield this.waitForActiveBackend()))return this.recordUrlFailure(e),null;if(!this.isSameSession(i))return null;let a=this.serverTimeOffsetMs(),h=yield this.callOp("getDownloadUrl",{organizationId:r.organizationId,documentId:r.documentId,attachmentId:String(t.attachmentId)}),u=yield a;if(!this.isSameSession(i))return null;if(!h?.ok)return this.reportOpFailure("getDownloadUrl",h,!0),h?.code==="not-found"?(this.urlMissing.add(e),this.urlCache.delete(e),null):(this.recordUrlFailure(e),null);let f=Pe(h.data);if(!f)return this.invalidReadUrlReported||(this.invalidReadUrlReported=!0,console.error("Velt [portable backend]: getDownloadUrl answered a read URL that is not https (loopback http excepted); the attachment is not shown. Check the storage endpoint the gateway signs URLs for.")),this.recordUrlFailure(e),null;let I=Date.now();return this.pruneUrlCache(I),this.urlCache.set(e,{url:f.url,expiresAtMs:Ue(f.expiresAtMs,I,u),receivedAtMs:I,afterLoadError:l}),this.urlFailures.delete(e),f.url}catch(a){return this.loggingService.catch("Error in PortableAttachmentStorageService getDownloadUrl: ",a,void 0,!0),this.recordUrlFailure(e),null}finally{this.urlInFlight.get(e)===c&&this.urlInFlight.delete(e),this.bumpKey(e)}}),this.urlInFlight.set(e,c),c}isFresh(e,t){return t<e.expiresAtMs-ge||t-e.receivedAtMs<te}inFailureBackoff(e,t){let r=this.urlFailures.get(e);return r!==void 0&&t-r.at<re(r.count)}keyVersion(e){let t=this.urlKeyVersions.get(e);return t||(t=P(0),this.urlKeyVersions.set(e,t)),t()}bumpKey(e){this.urlKeyVersions.get(e)?.update(t=>t+1)}recordUrlFailure(e){let t=(this.urlFailures.get(e)?.count??0)+1;this.urlFailures.set(e,{at:Date.now(),count:t}),setTimeout(()=>this.bumpKey(e),re(t)+50)}pruneUrlCache(e){if(!(this.urlCache.size<ie)){for(let[t,r]of Array.from(this.urlCache))e>=r.expiresAtMs&&e-r.receivedAtMs>=te&&this.urlCache.delete(t);for(let t of Array.from(this.urlCache.keys())){if(this.urlCache.size<2*ie)break;this.urlCache.delete(t)}}}watchUser(){if(!this.userWatched){this.userWatched=!0;try{let e=!0;this.watchedUserId=this.currentUserId(),this.auth.getUser$().subscribe(t=>{let r=typeof t?.userId=="string"&&t.userId.length>0?t.userId:null;if(e||r===this.watchedUserId){this.watchedUserId=r;return}this.watchedUserId=r,this.urlCache.clear(),this.urlFailures.clear(),this.urlMissing.clear(),this.urlKeyVersions.clear(),this.cacheOwner=r,queueMicrotask(()=>this.urlGeneration.update(i=>i+1))}),e=!1}catch(e){this.loggingService.catch("Error in PortableAttachmentStorageService watchUser: ",e,void 0,!0)}}}serverTimeOffsetMs(){return p(this,null,function*(){try{let e=yield _()?.realtime?.getServerTimeOffset?.();return typeof e=="number"&&Number.isFinite(e)?e:0}catch{return 0}})}urlContext(e,t){let r=this.attachmentIds(e,t),i=this.currentUserId();return!r||!i?null:(this.cacheOwner!==i&&(this.urlCache.clear(),this.urlFailures.clear(),this.urlMissing.clear(),this.cacheOwner=i),{ids:r,userId:i,key:`${i}\0${r.organizationId}\0${r.documentId}\0${String(e.attachmentId)}`})}attachmentsAvailable$(){return new L(e=>{let t,r=()=>{try{let o=this.evaluateAvailability();o!==t&&(t=o,e.next(o))}catch(o){this.loggingService.catch("Error in PortableAttachmentStorageService attachmentsAvailable$: ",o,void 0,!0)}};this.hookRealtime(),this.availabilityListeners.add(r);let i=q(()=>{this.hookRealtime(),r()});r();let l=null;try{l=this.auth.getUser$().subscribe(()=>r())}catch(o){this.loggingService.catch("Error in PortableAttachmentStorageService attachmentsAvailable$ user stream: ",o,void 0,!0)}return()=>{this.availabilityListeners.delete(r),i(),l?.unsubscribe()}})}isUploadUnavailable(){try{this.hookRealtime()}catch(e){this.loggingService.catch("Error in PortableAttachmentStorageService isUploadUnavailable: ",e,void 0,!0)}return!this.evaluateAvailability()}evaluateAvailability(){return this.isPortableSession()?this.attachmentsAnnounced:!this.isPortableAttachmentDeployment()}hookRealtime(){try{let e=_()?.realtime??null;if(!e||e===this.hookedRealtime)return;this.offCapabilities?.(),this.hookedRealtime=e,this.attachmentsAnnounced=e.hasCapability?.(M)===!0,this.offCapabilities=e.onCapabilitiesChanged?.(t=>{this.attachmentsAnnounced=!!t&&typeof t.has=="function"&&t.has(M),this.notifyAvailability()})??null}catch(e){this.loggingService.catch("Error in PortableAttachmentStorageService hookRealtime: ",e,void 0,!0)}}notifyAvailability(){for(let e of Array.from(this.availabilityListeners))e()}attachmentIds(e,t){return this.scopeIds({organizationId:e?.clientOrganizationId,documentId:e?.clientDocumentId})??this.scopeIds(t)}scopeIds(e){let t=typeof e?.organizationId=="string"&&e.organizationId.length>0?e.organizationId:null,r=typeof e?.documentId=="string"&&e.documentId.length>0?e.documentId:null;return t&&r?{organizationId:t,documentId:r}:null}currentUserId(){try{let e=this.auth.getUser()?.userId;return typeof e=="string"&&e.length>0?e:null}catch{return null}}isSameSession(e){return!!e&&this.isPortableSession()&&this.currentUserId()===e}waitForActiveBackend(){return p(this,null,function*(){try{return this.selector.isPortableBackendActive()===!0?!0:(this.selector.isPortableBackendPending?.()===!0&&(yield W(pe)),this.selector.isPortableBackendActive()===!0)}catch(e){return this.loggingService.catch("Error in PortableAttachmentStorageService waitForActiveBackend: ",e,void 0,!0),!1}})}callOp(e,t){return G(this.selector.resolveDbAdapter(),e,{scope:"doc",data:t})}reportOpFailure(e,t,r=!1){try{if(O(t)){let i=t?.code??"unknown";this.loggingService.log(`Tier B ${e} is not served by this deployment (${i}): comment attachments are not available`);return}if(r){let i=t?.code??"unknown",l=`${e}:${i}`;if(this.hotPathReported.has(l)){this.loggingService.log(`Tier B ${e} refused again: ${i}`);return}this.hotPathReported.add(l)}Z(e,t,{logCatch:(i,l)=>this.loggingService.catch(i,l,void 0,!0),reported:this.reportedOpFailures,isOutcomeUnknown:ee})}catch{}}notSent(e,t){let r=new m("failed-precondition",`Tier B attachment ${e} was not sent: ${t}`);return this.loggingService.catch(r.message,void 0,void 0,!0),r}dropped(e){let t=new m("failed-precondition",`Tier B attachment upload was dropped: ${e}`);return this.loggingService.catch(t.message,void 0,void 0,!0),t}};n.\u0275fac=function(t){return new(t||n)(g(N),g(y))},n.\u0275prov=A({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var le=s=>{try{let n={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 Y.sanitize(s,n)}catch(n){return S.catch("Error in File utils sanitizeSvg: ",n),""}},ce=s=>{try{return s.name.split(".").slice(0,-1).join(".")}catch(n){S.catch("Error in File utils getFileName: ",n);return}},D=s=>{try{return/(?:\.([^.]+))?$/.exec(s?.name)[1]}catch(n){S.catch("Error in File utils getFileExtension: ",n);return}},he=(s,n)=>{try{let d=s.slice(0,-1,s.type);return new File([d],n+"."+D(s),{type:s.type})}catch(d){S.catch("Error in File utils updateFile: ",d);return}};var B={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 ue=(()=>{let n=class n{getStorageInstance(e){return e?U(void 0,e):U()}ref(e,t){return H(e,t)}uploadBytesResumable(e,t,r){return j(e,t,r)}getDownloadURL(e){return z(e)}deleteObject(e){return $(e)}};n.\u0275fac=function(t){return new(t||n)},n.\u0275prov=A({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var it=(()=>{let n=class n{constructor(e,t,r,i,l,o,c){this.authService=e,this.configService=t,this.coreActionsService=r,this.loggingService=i,this.attachmentResolverService=l,this.storageAdapter=o,this.portableAttachments=c,this.storage=this.storageAdapter.getStorageInstance();try{this.configService.getApiKey$().subscribe(a=>{this.apiKey=a}),this.authService.getFirebaseConfig$().subscribe(a=>{if(a&&a.firebaseOptions?.storageBucket){this.storage=this.storageAdapter.getStorageInstance(a?.firebaseOptions?.storageBucket);let h=this.configService.getProxyConfig();h?.storageHost&&(this.storage.host=h.storageHost)}},a=>{this.loggingService.catch("Error in StorageService constructor: ",a)})}catch(a){this.loggingService.catch("Error in StorageService constructor:",a)}}createAttachment({path:e,file:t}){try{let r=new V;r.name=t.name;let i=he(t,`${r.attachmentId}_${ce(t)}`),l=`${this.apiKey}/${e}/${i?.name}`;return r.bucketPath=l,r.size=t.size,r.type=D(t),r?.type&&(r.mimeType=B[r?.type]),r}catch(r){return this.loggingService.catch("Error in StorageService createAttachment: ",r),null}}sanitizeSvgFile(e){return p(this,null,function*(){if(e.type===B.svg)try{let t=yield e.text(),r=le(t);return new File([r],e.name,{type:e.type})}catch(t){return this.loggingService.catch("Error in StorageService sanitizeSvgFile: ",t),e}return e})}uploadAttachmentToStorage(l){return p(this,arguments,function*({attachment:e,file:t,resolve:r,reject:i}){try{let o=this.storageAdapter.ref(this.storage,e.bucketPath),c=this.storageAdapter.uploadBytesResumable(o,t,{cacheControl:"public,max-age=3600"});c.on("state_changed",a=>{let h=a.bytesTransferred/a.totalBytes*100},a=>{i(a)},()=>{this.storageAdapter.getDownloadURL(c.snapshot.ref).then(a=>{e.url=a,r(e)})})}catch(o){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",o),i(o)}})}uploadToResolver(c){return p(this,arguments,function*({file:e,attachment:t,metadata:r,resolve:i,reject:l,scope:o}){try{r.attachmentId=t.attachmentId;let a={attachmentId:t.attachmentId,name:t.name,file:e,metadata:r,mimeType:t.mimeType},h=F();this.coreActionsService.triggerAction(R.ATTACHMENT_RESOLVER,{event:k.Events.Resolver.ATTACHMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:h,methodName:x.UPLOAD_TO_RESOLVER,source:"internal",payload:{attachment:a,eventType:E.ATTACHMENT_ADD}});let u=yield this.attachmentResolverService.saveAttachment({attachment:a,eventType:E.ATTACHMENT_ADD},h,o);u&&u.data?.url?(t.url=u.data?.url,i(t)):l(new Error("Failed to upload attachment to resolver"))}catch(a){this.loggingService.catch("Error in StorageService uploadToResolver: ",a),l(a)}})}uploadFile({path:e,file:t,useAttachmentResolver:r,metadata:i,attachmentScope:l,portableScope:o}){return new Promise((c,a)=>p(this,null,function*(){try{if(!this.apiKey)throw new Error("API key not configured");let h=o&&!r?this.portableAttachments.captureSessionUser():null,u=yield this.sanitizeSvgFile(t),f=this.createAttachment({path:e,file:u});if(!f)throw new Error("Attachment not created");r?this.uploadToResolver({file:u,attachment:f,metadata:i,resolve:c,reject:a,scope:l}):o&&(h||this.portableAttachments.isPortableAttachmentDeployment())?this.portableAttachments.upload({attachment:f,file:u,scope:o,sessionUserId:h??void 0}).then(c,a):this.portableAttachments.isPortableAttachmentDeployment()?a(this.portableAttachments.refuseVeltStorage("uploadFile")):this.uploadAttachmentToStorage({attachment:f,file:u,resolve:c,reject:a})}catch(h){this.loggingService.catch("Error in StorageService uploadFile:",h),a(h)}}))}uploadChunk(e,t,r,i){return new Promise((l,o)=>{try{if(i?.useAttachmentResolver){let c=this.createAttachment({path:e,file:t});if(!c){o(new Error("Attachment not created for chunk upload"));return}this.uploadToResolver({file:t,attachment:c,metadata:i.metadata,resolve:a=>l(a.url),reject:o,scope:i.attachmentScope});return}if(this.portableAttachments.isPortableAttachmentDeployment()){o(this.portableAttachments.refuseVeltStorage("uploadChunk"));return}if(this.apiKey){let c=`${this.apiKey}/${e}/${t.name}`,a=this.storageAdapter.ref(this.storage,c),h=this.storageAdapter.uploadBytesResumable(a,t,{cacheControl:"public,max-age=3600"});h.on("state_changed",u=>{let f=u.bytesTransferred/u.totalBytes*100},u=>{o(u)},()=>{this.storageAdapter.getDownloadURL(h.snapshot.ref).then(u=>{l(u)}).catch(u=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${r}:`,u),o(u)})})}else{let c=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",c),o(c)}}catch(c){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${r}: `,c),o(c)}})}downloadAttachment(e,t){try{if(this.portableAttachments.isPortableAttachment(e)){let r=this.portableAttachments.captureSessionUser();this.portableAttachments.resolveDownloadUrl(e,t).then(i=>{i&&this.portableAttachments.isSameSessionUser(r)?this.downloadFromUrl(e,i,!0):i||this.loggingService.catch("Tier B attachment download: no read URL could be resolved; nothing was downloaded")}).catch(i=>{this.loggingService.catch("Error in StorageService downloadAttachment (Tier B): ",i)});return}e.url&&this.downloadFromUrl(e,e.url)}catch(r){this.loggingService.catch("Error in StorageService downloadAttachment: ",r)}}downloadFromUrl(e,t,r=!1){try{let i=new XMLHttpRequest;i.responseType="blob",i.onload=()=>{if(r&&(i.status<200||i.status>=300)){this.loggingService.catch(`Tier B attachment download failed: the storage answered HTTP ${i.status}`);return}let l=i.response,o=document.createElement("a"),c=window.URL.createObjectURL(l);o.setAttribute("type","hidden"),o.setAttribute(K.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),o.classList.add("snippyly-overlay-panel"),o.href=c,e?.name&&(o.download=e?.name),document.body.appendChild(o);let a=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});o.dispatchEvent(a),window.URL.revokeObjectURL(c),o.remove()},i.onerror=()=>{r?(this.loggingService.catch(`Tier B attachment download failed in transport; opening it in a new tab instead. ${se}`),window.open(t,"_blank","noopener,noreferrer")):window.open(t,"_blank")},i.open("GET",t),i.send()}catch(i){this.loggingService.catch("Error in StorageService downloadAttachment: ",i)}}deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:r,attachmentScope:i,portableScope:l}){return new Promise((o,c)=>{if(r){let a=F();this.coreActionsService.triggerAction(R.ATTACHMENT_RESOLVER,{event:k.Events.Resolver.ATTACHMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:x.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:e.attachmentId,metadata:t}}),this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:t},a,i).then(()=>{o(null)}).catch(h=>{c(h)})}else if((l||v(e))&&this.portableAttachments.isPortableAttachmentDeployment())this.portableAttachments.delete({attachment:e,scope:l}).then(()=>o(null),()=>o(null));else if(this.portableAttachments.isPortableAttachmentDeployment())this.portableAttachments.refuseVeltStorage("deleteAttachment"),o(null);else{let a=this.storageAdapter.ref(this.storage,e.bucketPath);this.storageAdapter.deleteObject(a).then(()=>{o(null)}).catch(h=>{o(null)})}})}getAttachmentDisplayUrl(e,t){return this.portableAttachments.getDisplayUrl(e,t)}isAttachmentDisplayPending(e,t){return this.portableAttachments.isDisplayPending(e,t)}isPortableAttachment(e){return this.portableAttachments.isPortableAttachment(e)}resolveAttachmentUrl(e,t){return this.portableAttachments.resolveDownloadUrl(e,t)}reportAttachmentLoadError(e,t,r){this.portableAttachments.reportLoadError(e,t,r)}deleteFileFromPath(e){return new Promise((t,r)=>{if(this.portableAttachments.isPortableAttachmentDeployment()){r(this.portableAttachments.refuseVeltStorage("deleteFileFromPath"));return}let i=this.storageAdapter.ref(this.storage,e);this.storageAdapter.deleteObject(i).then(()=>{t(null)}).catch(l=>{r(l)})})}};n.\u0275fac=function(t){return new(t||n)(g(T),g(w),g(Q),g(y),g(J),g(ue),g(ae))},n.\u0275prov=A({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();export{ae as a,it as b};
|
|
1
|
+
import{b as $,c as z,d as U,e as H,f as j}from"./chunk-SLCZA7OJ.js";import{C as ee,b as Z,p as O,s as J}from"./chunk-O5LVBWUD.js";import{He as K,Ie as V,Ii as k,Nj as G,Pj as q,Qj as W,Tj as _,Uj as X,Yd as S,_d as E,a as b,ak as M,ba as A,bf as x,ea as g,ee as R,g as p,i as L,na as N,qj as y,rj as w,sa as P,sj as C,uk as Q,vg as F,vk as Y,zk as T}from"./chunk-SKSZYHHP.js";var pe=1e4,ge=6e4,te=3e4,me=3e4,fe=900*1e3;function re(s){let n=Math.max(0,Math.min(Math.floor(Number.isFinite(s)?s:1)-1,16));return Math.min(me*2**n,fe)}var Ae=3600*1e3,ie=250,ne=1200*1e3,Se=1024,ve={fetch:(s,n)=>fetch(s,n)},be="The browser could not send the file to the storage URL the gateway signed. The usual cause is the CORS rules of that storage (its storage account or bucket), which must allow this page's origin for PUT; they are set by the operator of the deployment, not by the SDK.",se="The browser could not read the file from the storage URL the gateway signed. The usual cause is the CORS rules of that storage (its storage account or bucket), which must allow this page's origin for GET; they are set by the operator of the deployment, not by the SDK.",m=class extends Error{constructor(n,d){super(d),this.code=n,this.name="PortableAttachmentError"}};function v(s){return!!s&&!s.url&&s.isAttachmentResolverUsed!==!0&&typeof s.bucketPath=="string"&&s.bucketPath.length>0&&s.attachmentId!==void 0&&s.attachmentId!==null&&String(s.attachmentId).length>0}function ye(s,n,d){let e={organizationId:n,documentId:d};return typeof s?.name=="string"&&s.name.length>0&&s.name.length<=Se&&(e.fileName=s.name),typeof s?.type=="string"&&s.type.length>0&&(e.contentType=s.type),Number.isInteger(s?.size)&&s.size>=0&&(e.sizeBytes=s.size),e}function we(s){return typeof s=="string"&&/^[A-Za-z0-9._-]{1,128}$/.test(s)&&!/^\.+$/.test(s)}function Te(s){return!!s&&typeof s=="object"&&!Array.isArray(s)&&Object.values(s).every(n=>typeof n=="string")}function Ie(s){let n=s;return!n||typeof n!="object"||!we(n.attachmentId)||typeof n.key!="string"||!n.key||typeof n.url!="string"||!C(n.url)||n.method!=="PUT"||!Te(n.headers)?null:{attachmentId:n.attachmentId,key:n.key,url:n.url,method:"PUT",headers:b({},n.headers),expiresAtMs:typeof n.expiresAtMs=="number"?n.expiresAtMs:0}}function Pe(s){let n=s;return!n||typeof n!="object"||typeof n.url!="string"||!C(n.url)?null:{key:typeof n.key=="string"?n.key:"",url:n.url,expiresAtMs:typeof n.expiresAtMs=="number"&&Number.isFinite(n.expiresAtMs)?n.expiresAtMs:0}}function Ue(s,n,d){let e=Number.isFinite(s)?s-(n+(Number.isFinite(d)?d:0)):0;return n+Math.min(Math.max(e,0),Ae)}var ae=(()=>{let n=class n{constructor(e,t){this.injector=e,this.loggingService=t,this.urlGeneration=P(0),this.urlKeyVersions=new Map,this.userWatched=!1,this.watchedUserId=null,this.urlCache=new Map,this.urlInFlight=new Map,this.urlFailures=new Map,this.urlMissing=new Set,this.cacheOwner=null,this.attachmentsAnnounced=!1,this.hookedRealtime=null,this.offCapabilities=null,this.availabilityListeners=new Set,this.veltStorageRefusalsReported=new Set,this.reportedOpFailures=new Set,this.invalidReadUrlReported=!1,this.hotPathReported=new Set,this.portableSessionSeen=!1}get selector(){return this._selector??=this.injector.get(X)}get auth(){return this._auth??=this.injector.get(T)}get config(){return this._config??=this.injector.get(w)}isPortableSession(){try{if(!this.auth.getPortableBackend?.())return!1;let e=this.selector.isPortableSession()===!0;return e&&(this.portableSessionSeen=!0),e}catch(e){return this.loggingService.catch("Error in PortableAttachmentStorageService isPortableSession: ",e,void 0,!0),!1}}isPortableAttachmentDeployment(){if(this.isPortableSession())return!0;if(!this.portableSessionSeen)return!1;try{return this.config.getEnablePortableBackend()===!0}catch(e){return this.loggingService.catch("Error in PortableAttachmentStorageService isPortableAttachmentDeployment: ",e,void 0,!0),!0}}captureSessionUser(){return this.isPortableSession()?this.currentUserId():null}isSameSessionUser(e){return this.isSameSession(e??null)}isPortableAttachment(e){return v(e)&&this.isPortableSession()}upload(l){return p(this,arguments,function*({attachment:e,file:t,scope:r,sessionUserId:i}){let o=this.scopeIds(r);if(!o)throw this.notSent("upload","the comment has no organization or document id");let c=i===void 0?this.currentUserId():i;if(!c)throw this.notSent("upload","no user is signed in");if(!this.isSameSession(c))throw this.notSent("upload","the session changed before the upload started");if(!(yield this.waitForActiveBackend())||!this.isSameSession(c))throw this.notSent("upload","the portable backend is not active");let a=yield this.callOp("getUploadUrl",ye(t,o.organizationId,o.documentId));if(!this.isSameSession(c))throw this.dropped("the session changed while getUploadUrl ran; the file was not uploaded");if(!a?.ok){this.reportOpFailure("getUploadUrl",a);let u=`${a?.code??"unknown"}${a?.message?` (${a.message})`:""}`;throw new m(a?.code??"failed-precondition",O(a)?`Tier B comment attachments are not available on this deployment: getUploadUrl answered ${u}`:`Tier B getUploadUrl failed: ${u}`)}let h=Ie(a.data);if(!h){let u=new m("failed-precondition",'Tier B getUploadUrl answered a signed upload this SDK will not use (it needs method PUT, an https URL, string headers, an attachmentId of 1-128 letters, digits, ".", "_" or "-", and a key); the file was not uploaded');throw this.loggingService.catch(u.message,void 0,void 0,!0),u}if(yield this.putSignedUpload(h,t),!this.isSameSession(c))throw this.dropped("the session changed while the file uploaded; the attachment is not added");return e.attachmentId=h.attachmentId,e.bucketPath=h.key,e.url="",e.clientOrganizationId=o.organizationId,e.clientDocumentId=o.documentId,e})}putSignedUpload(e,t){return p(this,null,function*(){let r=typeof AbortController=="function"?new AbortController:null,i=null,l=new Promise((o,c)=>{i=setTimeout(()=>{r?.abort(),c(new m("put-failed",`Tier B attachment upload failed: the storage did not answer the PUT within ${ne/6e4} minutes`))},ne)});try{let o=yield Promise.race([ve.fetch(e.url,b({method:"PUT",headers:b({},e.headers),body:t.slice(0,t.size,""),redirect:"error",credentials:"omit",referrerPolicy:"no-referrer"},r?{signal:r.signal}:{})),l]);if(!o?.ok)throw new m("put-failed",`Tier B attachment upload failed: the storage answered the PUT with HTTP ${o?.status}`)}catch(o){let c=o instanceof m?o:new m("put-failed",`Tier B attachment upload failed in transport: ${o?.message??o}. ${be}`);throw this.loggingService.catch(c.message,void 0,void 0,!0),c}finally{i!==null&&clearTimeout(i)}})}refuseVeltStorage(e){let t=new m("unimplemented",`Tier B ${e} was not sent: media outside comment attachments (recorder, tag) is not served by the portable backend, and Velt's storage is never used on a portable deployment`);try{this.veltStorageRefusalsReported.has(e)?this.loggingService.log(t.message):(this.veltStorageRefusalsReported.add(e),this.loggingService.catch(t.message,void 0,void 0,!0))}catch{}return t}delete(r){return p(this,arguments,function*({attachment:e,scope:t}){try{let i=this.attachmentIds(e,t),l=e?.attachmentId;if(!i||l===void 0||l===null||String(l).length===0){this.loggingService.catch("Tier B deleteAttachment was not sent: the attachment has no id, or the comment no organization or document id",void 0,void 0,!0);return}let o=this.currentUserId();if(!o||!(yield this.waitForActiveBackend())||!this.isSameSession(o)){this.loggingService.catch("Tier B deleteAttachment was not sent: the portable backend is not active",void 0,void 0,!0);return}let c=yield this.callOp("deleteAttachment",{organizationId:i.organizationId,documentId:i.documentId,attachmentId:String(l)});c?.ok||this.reportOpFailure("deleteAttachment",c)}catch(i){this.loggingService.catch("Error in PortableAttachmentStorageService delete: ",i,void 0,!0)}})}resolveDownloadUrl(e,t){try{if(!this.isPortableAttachment(e))return Promise.resolve(e?.url||null);let r=this.urlContext(e,t);if(!r||this.urlMissing.has(r.key))return Promise.resolve(null);let i=this.urlCache.get(r.key);return i&&this.isFresh(i,Date.now())?Promise.resolve(i.url):this.fetchDownloadUrl(r.key,e,r.ids,r.userId,!1)}catch(r){return this.loggingService.catch("Error in PortableAttachmentStorageService resolveDownloadUrl: ",r,void 0,!0),Promise.resolve(null)}}getDisplayUrl(e,t){if(!v(e))return e?.url;if(this.urlGeneration(),this.watchUser(),!this.isPortableSession())return e.url;try{let r=this.urlContext(e,t);if(!r)return e.url;if(this.keyVersion(r.key),this.urlMissing.has(r.key))return"";let i=Date.now(),l=this.urlCache.get(r.key);return l&&this.isFresh(l,i)?l.url:(this.inFailureBackoff(r.key,i)||this.fetchDownloadUrl(r.key,e,r.ids,r.userId,!1),l&&i<l.expiresAtMs?l.url:"")}catch(r){return this.loggingService.catch("Error in PortableAttachmentStorageService getDisplayUrl: ",r,void 0,!0),e.url}}isDisplayPending(e,t){if(!v(e)||!this.isPortableSession())return!1;try{if(this.getDisplayUrl(e,t))return!1;let r=this.urlContext(e,t);return!!r&&!this.urlMissing.has(r.key)&&!this.inFailureBackoff(r.key,Date.now())}catch(r){return this.loggingService.catch("Error in PortableAttachmentStorageService isDisplayPending: ",r,void 0,!0),!1}}reportLoadError(e,t,r){try{if(!this.isPortableAttachment(e))return;let i=this.urlContext(e,t),l=i?this.urlCache.get(i.key):void 0;if(!i||!l||l.afterLoadError||!r||l.url!==r)return;this.urlCache.delete(i.key),this.fetchDownloadUrl(i.key,e,i.ids,i.userId,!0),this.bumpKey(i.key)}catch(i){this.loggingService.catch("Error in PortableAttachmentStorageService reportLoadError: ",i,void 0,!0)}}fetchDownloadUrl(e,t,r,i,l){let o=this.urlInFlight.get(e);if(o)return o;let c;return c=p(this,null,function*(){try{if(!(yield this.waitForActiveBackend()))return this.recordUrlFailure(e),null;if(!this.isSameSession(i))return null;let a=this.serverTimeOffsetMs(),h=yield this.callOp("getDownloadUrl",{organizationId:r.organizationId,documentId:r.documentId,attachmentId:String(t.attachmentId)}),u=yield a;if(!this.isSameSession(i))return null;if(!h?.ok)return this.reportOpFailure("getDownloadUrl",h,!0),h?.code==="not-found"?(this.urlMissing.add(e),this.urlCache.delete(e),null):(this.recordUrlFailure(e),null);let f=Pe(h.data);if(!f)return this.invalidReadUrlReported||(this.invalidReadUrlReported=!0,console.error("Velt [portable backend]: getDownloadUrl answered a read URL that is not https (loopback http excepted); the attachment is not shown. Check the storage endpoint the gateway signs URLs for.")),this.recordUrlFailure(e),null;let I=Date.now();return this.pruneUrlCache(I),this.urlCache.set(e,{url:f.url,expiresAtMs:Ue(f.expiresAtMs,I,u),receivedAtMs:I,afterLoadError:l}),this.urlFailures.delete(e),f.url}catch(a){return this.loggingService.catch("Error in PortableAttachmentStorageService getDownloadUrl: ",a,void 0,!0),this.recordUrlFailure(e),null}finally{this.urlInFlight.get(e)===c&&this.urlInFlight.delete(e),this.bumpKey(e)}}),this.urlInFlight.set(e,c),c}isFresh(e,t){return t<e.expiresAtMs-ge||t-e.receivedAtMs<te}inFailureBackoff(e,t){let r=this.urlFailures.get(e);return r!==void 0&&t-r.at<re(r.count)}keyVersion(e){let t=this.urlKeyVersions.get(e);return t||(t=P(0),this.urlKeyVersions.set(e,t)),t()}bumpKey(e){this.urlKeyVersions.get(e)?.update(t=>t+1)}recordUrlFailure(e){let t=(this.urlFailures.get(e)?.count??0)+1;this.urlFailures.set(e,{at:Date.now(),count:t}),setTimeout(()=>this.bumpKey(e),re(t)+50)}pruneUrlCache(e){if(!(this.urlCache.size<ie)){for(let[t,r]of Array.from(this.urlCache))e>=r.expiresAtMs&&e-r.receivedAtMs>=te&&this.urlCache.delete(t);for(let t of Array.from(this.urlCache.keys())){if(this.urlCache.size<2*ie)break;this.urlCache.delete(t)}}}watchUser(){if(!this.userWatched){this.userWatched=!0;try{let e=!0;this.watchedUserId=this.currentUserId(),this.auth.getUser$().subscribe(t=>{let r=typeof t?.userId=="string"&&t.userId.length>0?t.userId:null;if(e||r===this.watchedUserId){this.watchedUserId=r;return}this.watchedUserId=r,this.urlCache.clear(),this.urlFailures.clear(),this.urlMissing.clear(),this.urlKeyVersions.clear(),this.cacheOwner=r,queueMicrotask(()=>this.urlGeneration.update(i=>i+1))}),e=!1}catch(e){this.loggingService.catch("Error in PortableAttachmentStorageService watchUser: ",e,void 0,!0)}}}serverTimeOffsetMs(){return p(this,null,function*(){try{let e=yield _()?.realtime?.getServerTimeOffset?.();return typeof e=="number"&&Number.isFinite(e)?e:0}catch{return 0}})}urlContext(e,t){let r=this.attachmentIds(e,t),i=this.currentUserId();return!r||!i?null:(this.cacheOwner!==i&&(this.urlCache.clear(),this.urlFailures.clear(),this.urlMissing.clear(),this.cacheOwner=i),{ids:r,userId:i,key:`${i}\0${r.organizationId}\0${r.documentId}\0${String(e.attachmentId)}`})}attachmentsAvailable$(){return new L(e=>{let t,r=()=>{try{let o=this.evaluateAvailability();o!==t&&(t=o,e.next(o))}catch(o){this.loggingService.catch("Error in PortableAttachmentStorageService attachmentsAvailable$: ",o,void 0,!0)}};this.hookRealtime(),this.availabilityListeners.add(r);let i=q(()=>{this.hookRealtime(),r()});r();let l=null;try{l=this.auth.getUser$().subscribe(()=>r())}catch(o){this.loggingService.catch("Error in PortableAttachmentStorageService attachmentsAvailable$ user stream: ",o,void 0,!0)}return()=>{this.availabilityListeners.delete(r),i(),l?.unsubscribe()}})}isUploadUnavailable(){try{this.hookRealtime()}catch(e){this.loggingService.catch("Error in PortableAttachmentStorageService isUploadUnavailable: ",e,void 0,!0)}return!this.evaluateAvailability()}evaluateAvailability(){return this.isPortableSession()?this.attachmentsAnnounced:!this.isPortableAttachmentDeployment()}hookRealtime(){try{let e=_()?.realtime??null;if(!e||e===this.hookedRealtime)return;this.offCapabilities?.(),this.hookedRealtime=e,this.attachmentsAnnounced=e.hasCapability?.(M)===!0,this.offCapabilities=e.onCapabilitiesChanged?.(t=>{this.attachmentsAnnounced=!!t&&typeof t.has=="function"&&t.has(M),this.notifyAvailability()})??null}catch(e){this.loggingService.catch("Error in PortableAttachmentStorageService hookRealtime: ",e,void 0,!0)}}notifyAvailability(){for(let e of Array.from(this.availabilityListeners))e()}attachmentIds(e,t){return this.scopeIds({organizationId:e?.clientOrganizationId,documentId:e?.clientDocumentId})??this.scopeIds(t)}scopeIds(e){let t=typeof e?.organizationId=="string"&&e.organizationId.length>0?e.organizationId:null,r=typeof e?.documentId=="string"&&e.documentId.length>0?e.documentId:null;return t&&r?{organizationId:t,documentId:r}:null}currentUserId(){try{let e=this.auth.getUser()?.userId;return typeof e=="string"&&e.length>0?e:null}catch{return null}}isSameSession(e){return!!e&&this.isPortableSession()&&this.currentUserId()===e}waitForActiveBackend(){return p(this,null,function*(){try{return this.selector.isPortableBackendActive()===!0?!0:(this.selector.isPortableBackendPending?.()===!0&&(yield W(pe)),this.selector.isPortableBackendActive()===!0)}catch(e){return this.loggingService.catch("Error in PortableAttachmentStorageService waitForActiveBackend: ",e,void 0,!0),!1}})}callOp(e,t){return G(this.selector.resolveDbAdapter(),e,{scope:"doc",data:t})}reportOpFailure(e,t,r=!1){try{if(O(t)){let i=t?.code??"unknown";this.loggingService.log(`Tier B ${e} is not served by this deployment (${i}): comment attachments are not available`);return}if(r){let i=t?.code??"unknown",l=`${e}:${i}`;if(this.hotPathReported.has(l)){this.loggingService.log(`Tier B ${e} refused again: ${i}`);return}this.hotPathReported.add(l)}Z(e,t,{logCatch:(i,l)=>this.loggingService.catch(i,l,void 0,!0),reported:this.reportedOpFailures,isOutcomeUnknown:ee})}catch{}}notSent(e,t){let r=new m("failed-precondition",`Tier B attachment ${e} was not sent: ${t}`);return this.loggingService.catch(r.message,void 0,void 0,!0),r}dropped(e){let t=new m("failed-precondition",`Tier B attachment upload was dropped: ${e}`);return this.loggingService.catch(t.message,void 0,void 0,!0),t}};n.\u0275fac=function(t){return new(t||n)(g(N),g(y))},n.\u0275prov=A({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var le=s=>{try{let n={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 Y.sanitize(s,n)}catch(n){return S.catch("Error in File utils sanitizeSvg: ",n),""}},ce=s=>{try{return s.name.split(".").slice(0,-1).join(".")}catch(n){S.catch("Error in File utils getFileName: ",n);return}},D=s=>{try{return/(?:\.([^.]+))?$/.exec(s?.name)[1]}catch(n){S.catch("Error in File utils getFileExtension: ",n);return}},he=(s,n)=>{try{let d=s.slice(0,-1,s.type);return new File([d],n+"."+D(s),{type:s.type})}catch(d){S.catch("Error in File utils updateFile: ",d);return}};var B={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 ue=(()=>{let n=class n{getStorageInstance(e){return e?U(void 0,e):U()}ref(e,t){return H(e,t)}uploadBytesResumable(e,t,r){return j(e,t,r)}getDownloadURL(e){return z(e)}deleteObject(e){return $(e)}};n.\u0275fac=function(t){return new(t||n)},n.\u0275prov=A({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();var it=(()=>{let n=class n{constructor(e,t,r,i,l,o,c){this.authService=e,this.configService=t,this.coreActionsService=r,this.loggingService=i,this.attachmentResolverService=l,this.storageAdapter=o,this.portableAttachments=c,this.storage=this.storageAdapter.getStorageInstance();try{this.configService.getApiKey$().subscribe(a=>{this.apiKey=a}),this.authService.getFirebaseConfig$().subscribe(a=>{if(a&&a.firebaseOptions?.storageBucket){this.storage=this.storageAdapter.getStorageInstance(a?.firebaseOptions?.storageBucket);let h=this.configService.getProxyConfig();h?.storageHost&&(this.storage.host=h.storageHost)}},a=>{this.loggingService.catch("Error in StorageService constructor: ",a)})}catch(a){this.loggingService.catch("Error in StorageService constructor:",a)}}createAttachment({path:e,file:t}){try{let r=new V;r.name=t.name;let i=he(t,`${r.attachmentId}_${ce(t)}`),l=`${this.apiKey}/${e}/${i?.name}`;return r.bucketPath=l,r.size=t.size,r.type=D(t),r?.type&&(r.mimeType=B[r?.type]),r}catch(r){return this.loggingService.catch("Error in StorageService createAttachment: ",r),null}}sanitizeSvgFile(e){return p(this,null,function*(){if(e.type===B.svg)try{let t=yield e.text(),r=le(t);return new File([r],e.name,{type:e.type})}catch(t){return this.loggingService.catch("Error in StorageService sanitizeSvgFile: ",t),e}return e})}uploadAttachmentToStorage(l){return p(this,arguments,function*({attachment:e,file:t,resolve:r,reject:i}){try{let o=this.storageAdapter.ref(this.storage,e.bucketPath),c=this.storageAdapter.uploadBytesResumable(o,t,{cacheControl:"public,max-age=3600"});c.on("state_changed",a=>{let h=a.bytesTransferred/a.totalBytes*100},a=>{i(a)},()=>{this.storageAdapter.getDownloadURL(c.snapshot.ref).then(a=>{e.url=a,r(e)})})}catch(o){this.loggingService.catch("Error in StorageService uploadAttachmentToStorage: ",o),i(o)}})}uploadToResolver(c){return p(this,arguments,function*({file:e,attachment:t,metadata:r,resolve:i,reject:l,scope:o}){try{r.attachmentId=t.attachmentId;let a={attachmentId:t.attachmentId,name:t.name,file:e,metadata:r,mimeType:t.mimeType},h=F();this.coreActionsService.triggerAction(R.ATTACHMENT_RESOLVER,{event:k.Events.Resolver.ATTACHMENT_SAVE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:h,methodName:x.UPLOAD_TO_RESOLVER,source:"internal",payload:{attachment:a,eventType:E.ATTACHMENT_ADD}});let u=yield this.attachmentResolverService.saveAttachment({attachment:a,eventType:E.ATTACHMENT_ADD},h,o);u&&u.data?.url?(t.url=u.data?.url,i(t)):l(new Error("Failed to upload attachment to resolver"))}catch(a){this.loggingService.catch("Error in StorageService uploadToResolver: ",a),l(a)}})}uploadFile({path:e,file:t,useAttachmentResolver:r,metadata:i,attachmentScope:l,portableScope:o}){return new Promise((c,a)=>p(this,null,function*(){try{if(!this.apiKey)throw new Error("API key not configured");let h=o&&!r?this.portableAttachments.captureSessionUser():null,u=yield this.sanitizeSvgFile(t),f=this.createAttachment({path:e,file:u});if(!f)throw new Error("Attachment not created");r?this.uploadToResolver({file:u,attachment:f,metadata:i,resolve:c,reject:a,scope:l}):o&&(h||this.portableAttachments.isPortableAttachmentDeployment())?this.portableAttachments.upload({attachment:f,file:u,scope:o,sessionUserId:h??void 0}).then(c,a):this.portableAttachments.isPortableAttachmentDeployment()?a(this.portableAttachments.refuseVeltStorage("uploadFile")):this.uploadAttachmentToStorage({attachment:f,file:u,resolve:c,reject:a})}catch(h){this.loggingService.catch("Error in StorageService uploadFile:",h),a(h)}}))}uploadChunk(e,t,r,i){return new Promise((l,o)=>{try{if(i?.useAttachmentResolver){let c=this.createAttachment({path:e,file:t});if(!c){o(new Error("Attachment not created for chunk upload"));return}this.uploadToResolver({file:t,attachment:c,metadata:i.metadata,resolve:a=>l(a.url),reject:o,scope:i.attachmentScope});return}if(this.portableAttachments.isPortableAttachmentDeployment()){o(this.portableAttachments.refuseVeltStorage("uploadChunk"));return}if(this.apiKey){let c=`${this.apiKey}/${e}/${t.name}`,a=this.storageAdapter.ref(this.storage,c),h=this.storageAdapter.uploadBytesResumable(a,t,{cacheControl:"public,max-age=3600"});h.on("state_changed",u=>{let f=u.bytesTransferred/u.totalBytes*100},u=>{o(u)},()=>{this.storageAdapter.getDownloadURL(h.snapshot.ref).then(u=>{l(u)}).catch(u=>{this.loggingService.catch(`[uploadChunk] Error getting download URL for chunk ${r}:`,u),o(u)})})}else{let c=new Error("API key not available");this.loggingService.catch("[uploadChunk] API key not available",c),o(c)}}catch(c){this.loggingService.catch(`[uploadChunk] Error in StorageService uploadChunk for chunk ${r}: `,c),o(c)}})}downloadAttachment(e,t){try{if(this.portableAttachments.isPortableAttachment(e)){let r=this.portableAttachments.captureSessionUser();this.portableAttachments.resolveDownloadUrl(e,t).then(i=>{i&&this.portableAttachments.isSameSessionUser(r)?this.downloadFromUrl(e,i,!0):i||this.loggingService.catch("Tier B attachment download: no read URL could be resolved; nothing was downloaded")}).catch(i=>{this.loggingService.catch("Error in StorageService downloadAttachment (Tier B): ",i)});return}e.url&&this.downloadFromUrl(e,e.url)}catch(r){this.loggingService.catch("Error in StorageService downloadAttachment: ",r)}}downloadFromUrl(e,t,r=!1){try{let i=new XMLHttpRequest;i.responseType="blob",i.onload=()=>{if(r&&(i.status<200||i.status>=300)){this.loggingService.catch(`Tier B attachment download failed: the storage answered HTTP ${i.status}`);return}let l=i.response,o=document.createElement("a"),c=window.URL.createObjectURL(l);o.setAttribute("type","hidden"),o.setAttribute(K.ATTRIBUTES.VELT_DOWNLOAD_BUTTON,"true"),o.classList.add("snippyly-overlay-panel"),o.href=c,e?.name&&(o.download=e?.name),document.body.appendChild(o);let a=new MouseEvent("click",{view:window,bubbles:!0,cancelable:!1});o.dispatchEvent(a),window.URL.revokeObjectURL(c),o.remove()},i.onerror=()=>{r?(this.loggingService.catch(`Tier B attachment download failed in transport; opening it in a new tab instead. ${se}`),window.open(t,"_blank","noopener,noreferrer")):window.open(t,"_blank")},i.open("GET",t),i.send()}catch(i){this.loggingService.catch("Error in StorageService downloadAttachment: ",i)}}deleteAttachment({attachment:e,metadata:t,useAttachmentResolver:r,attachmentScope:i,portableScope:l}){return new Promise((o,c)=>{if(r){let a=F();this.coreActionsService.triggerAction(R.ATTACHMENT_RESOLVER,{event:k.Events.Resolver.ATTACHMENT_DELETE_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:a,methodName:x.DELETE_ATTACHMENT,source:"internal",payload:{attachmentId:e.attachmentId,metadata:t}}),this.attachmentResolverService.deleteAttachment({attachmentId:e.attachmentId,metadata:t},a,i).then(()=>{o(null)}).catch(h=>{c(h)})}else if((l||v(e))&&this.portableAttachments.isPortableAttachmentDeployment())this.portableAttachments.delete({attachment:e,scope:l}).then(()=>o(null),()=>o(null));else if(this.portableAttachments.isPortableAttachmentDeployment())this.portableAttachments.refuseVeltStorage("deleteAttachment"),o(null);else{let a=this.storageAdapter.ref(this.storage,e.bucketPath);this.storageAdapter.deleteObject(a).then(()=>{o(null)}).catch(h=>{o(null)})}})}getAttachmentDisplayUrl(e,t){return this.portableAttachments.getDisplayUrl(e,t)}isAttachmentDisplayPending(e,t){return this.portableAttachments.isDisplayPending(e,t)}isPortableAttachment(e){return this.portableAttachments.isPortableAttachment(e)}resolveAttachmentUrl(e,t){return this.portableAttachments.resolveDownloadUrl(e,t)}reportAttachmentLoadError(e,t,r){this.portableAttachments.reportLoadError(e,t,r)}deleteFileFromPath(e){return new Promise((t,r)=>{if(this.portableAttachments.isPortableAttachmentDeployment()){r(this.portableAttachments.refuseVeltStorage("deleteFileFromPath"));return}let i=this.storageAdapter.ref(this.storage,e);this.storageAdapter.deleteObject(i).then(()=>{t(null)}).catch(l=>{r(l)})})}};n.\u0275fac=function(t){return new(t||n)(g(T),g(w),g(Q),g(y),g(J),g(ue),g(ae))},n.\u0275prov=A({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();export{ae as a,it as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{He as h,Vg as a,Yd as c}from"./chunk-
|
|
1
|
+
import{He as h,Vg as a,Yd as c}from"./chunk-SKSZYHHP.js";var T=(t,n)=>{try{let e=d(t),r=[],o=[];return e.forEach(i=>{i?.parentElement?.closest(h.TAGS.SNIPPYLY_TEXT_HIGHLIGHT)?i?.parentElement?.normalize():i?.data&&o.push(i)}),o.forEach(i=>{let s=l(i,n);s&&r.push(s)}),r}catch(e){return c.catch("Error in highlighter highlightRange: ",e),[]}},d=t=>{try{if(t.collapsed)return[];let n=t.commonAncestorContainer;if(t.commonAncestorContainer.nodeType!==Node.ELEMENT_NODE&&(n=t.commonAncestorContainer.parentElement),!n)return[];let e=[],r=n.ownerDocument.createNodeIterator(n,NodeFilter.SHOW_TEXT),o,i=!1;for(;o=r.nextNode();)if(t.intersectsNode(o)){if(a(o))continue;let s=o?.length;if(t.startContainer===o&&t.startOffset>=s||t.endContainer===o&&t.endOffset===0)continue;t.startContainer===o&&t.startOffset>0&&(o.splitText(t.startOffset),i=!0),t.endContainer===o&&t.endOffset<s&&o.splitText(t.endOffset),e.push(o)}return i&&e.shift(),e}catch(n){return c.catch("Error in highlighter getTextNodesInRange: ",n),[]}},l=(t,n)=>{try{let e=document.createElement(n||h.TAGS.SNIPPYLY_TEXT_HIGHLIGHT),r=t.splitText(0);return r.parentNode?.replaceChild(e,r),e.appendChild(r),e.__veltPageTextNode=t,e}catch(e){return c.catch("Error in highlighter highlightNode: ",e),null}},u=(t,n)=>{try{if(!t)return;let e=n??(t.textContent?document.createTextNode(t.textContent):null),r=t.__veltPageTextNode;if(r){if(r.parentNode!==t.parentNode){t.remove();return}if(e?.nodeType===Node.TEXT_NODE){r.data||(r.data=e.data),t.remove();return}}e?t.replaceWith(e):t.remove()}catch(e){c.catch("Error in highlighter unwrapHighlightElement: ",e)}};export{T as a,u as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as L}from"./chunk-
|
|
1
|
+
import{b as L}from"./chunk-2NF5H2TO.js";import{Ha as z,Ja as B}from"./chunk-OSQH62D7.js";import{Bb as c,Ha as r,Ia as S,Ic as N,Mb as T,Pb as f,Qb as D,Ra as s,Sb as h,Wa as I,_a as O,a as y,ab as m,b as u,ja as w,ka as _,mc as v,nb as p,nc as g,ob as a,pb as d,qj as j,sa as C,ub as E,vb as k,xb as F,ya as b,yk as V,zb as x}from"./chunk-SKSZYHHP.js";function A(t,i){if(t&1&&(a(0,"span",6),f(1),v(2,"translate"),d()),t&2){let o=c(2).ngIf;r(),h("",g(2,2,"You are following")," ",o.leaderName)}}function P(t,i){t&1&&(a(0,"span",6),f(1),v(2,"translate"),d()),t&2&&(r(),D(g(2,1,"You are leading.")))}function R(t,i){if(t&1){let o=F();a(0,"div",2),x("click",function(){w(o);let e=c().ngIf,l=c();return _(e.type==="following"?l.closeOverlay():void 0)}),a(1,"div",3),m(2,A,3,4,"span",4)(3,P,3,3,"span",4),a(4,"button",5),x("click",function(){w(o);let e=c(2);return _(e.closeOverlay())}),f(5),v(6,"translate"),v(7,"translate"),d()()()}if(t&2){let o=c().ngIf;T("no-pointer",o.type==="leading"),r(2),p("ngIf",o.type==="following"),r(),p("ngIf",o.type==="leading"),r(2),h("",g(6,6,"Stop")," ",g(7,8,o.type))}}function Y(t,i){if(t&1&&(E(0),m(1,R,8,10,"div",1),k()),t&2){let o=i.ngIf;r(),p("ngIf",o.leaderName!==""||o.type==="leading")}}var te=(()=>{let i=class i extends B{closeOverlay(){this.closeOverlayEvent.emit()}constructor(n,e,l,M){super(e,l),this.loggingService=n,this.elementRef=e,this.themeService=l,this.domService=M,this.closeOverlayEvent=new S,this.componentConfigSignal=C({leaderName:"",type:"following"})}ngOnInit(){}ngAfterViewInit(){try{this.customCssSubscription=this.domService.subscribeInjectCustomCss(this.elementRef)}catch(n){this.loggingService.catch("Error in FollowOverlayComponent ngAfterViewInit: ",n)}}setLeaderName(n){try{this.componentConfigSignal.update(e=>(e=u(y({},e),{leaderName:n}),e))}catch(e){this.loggingService.catch("Error in FollowOverlayComponent setLeaderName: ",e)}}getLeaderName(){return this.componentConfigSignal().leaderName}setType(n){try{this.componentConfigSignal.update(e=>(e=u(y({},e),{type:n}),e))}catch(e){this.loggingService.catch("Error in FollowOverlayComponent setType: ",e)}}ngOnDestroy(){try{super.ngOnDestroy(),this.customCssSubscription?.unsubscribe()}catch(n){this.loggingService.catch("Error in FollowOverlayComponent ngOnDestroy: ",n)}}};i.\u0275fac=function(e){return new(e||i)(s(j),s(b),s(z),s(V))},i.\u0275cmp=I({type:i,selectors:[["snippyly-follow-overlay"]],outputs:{closeOverlayEvent:"closeOverlayEvent"},standalone:!1,features:[O],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(e,l){e&1&&m(0,Y,2,1,"ng-container",0),e&2&&p("ngIf",l.componentConfigSignal())},dependencies:[N,L],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}
|
|
2
2
|
`],encapsulation:3,changeDetection:0});let t=i;return t})();export{te as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as li}from"./chunk-FKN7LIYH.js";import{a as ci}from"./chunk-XLPYUWJX.js";import{A as nt,B as si,E as ni,F as ai,c as oi,k as ht,o as ri,q as ot,r as rt,t as st,y as mt}from"./chunk-O5LVBWUD.js";import{Bj as Wt,Cj as Jt,Dg as zt,Di as Lt,E as w,Eg as gt,Ej as Kt,G as _,Gd as yt,Gj as dt,He as P,Ii as j,Ji as q,Jj as Qt,K as k,Kg as X,Li as _t,Lj as Xt,M as W,Mj as Zt,Ni as jt,O as at,Pj as ut,Q as Nt,Qd as Dt,Qf as Ut,U as It,Uf as Et,Uj as qt,V as O,Wf as $t,Xf as wt,Y as Ot,Yi as Ht,Zd as Ct,Zf as ct,_f as R,_i as Vt,a as I,ag as Pt,b as T,ba as J,cg as lt,ck as ti,di as Bt,ea as S,ee as At,fa as bt,g as y,i as vt,l as b,mi as ft,oi as Z,oj as tt,p as Y,pj as Yt,q as G,qi as xt,qj as it,r as D,re as Tt,rj as Gt,tf as K,uf as Q,ug as Rt,uk as ii,v as N,vg as Ft,w as V,wj as kt,x as pt,yg as Mt,yk as ei,zk as et}from"./chunk-SKSZYHHP.js";var gi=(()=>{let m=class m{constructor(t,i,e,o,r,n,s){this.commentUtilsService=t,this.loggingService=i,this.usersService=e,this.authService=o,this.commentAnnotationsResolverService=r,this.notificationResolverService=n,this.serviceBook=s,this.serviceBook.set(jt,this)}getUserIdsToResolveFromNotifications(t){try{let i=new Set;for(let e of t){let{notification:o}=e;switch(o?.actionUser?.userId&&i.add(o?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.actionUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.actionUser?.userId),o?.displayHeadlineMessageTemplateData?.recipientUser?.userId&&i.add(o?.displayHeadlineMessageTemplateData?.recipientUser?.userId),o?.notificationSource){case"comment":if(o?.notificationSourceData){let r=this.commentUtilsService.getUserIdsToResolveFromComments([o?.notificationSourceData]);for(let n of r)i.add(n)}break}}return Array.from(i)}catch(i){return this.loggingService.catch("Error in ReactionUtilsService getUserIdsToResolveFromRecorders:",i),[]}}mergeStrippedDataWithNotification(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeStrippedDataWithNotification","color: green;"),!this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable())return t;let i=this.commentAnnotationsResolverService.getAnnotationById(t?.notification?.targetAnnotationId),e=t?.raw?.targetAnnotationData?.commentId,o=i?.comments?.[e]?.commentText,r=i?.comments?.[e]?.commentHtml;return o&&r&&t?.raw?.notificationSource==="comment"&&(t.notification.displayBodyMessageTemplate=o,t.raw.targetAnnotationData.commentText=o,t.raw.targetAnnotationData.commentHtml=r),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeStrippedDataWithNotification:",i),t}}mergeLocationWithNotification(t,i){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeLocationWithNotification","color: green;");let e=t?.notification?.notificationSourceData?.location?.id,o=t?.notification?.notificationSourceData?.metadata?.documentId;if(!e||!o)return t;let r=i?.[o]?.[e];return r&&(t.notification.notificationSourceData.location=r?.location,t?.raw?.annotationData?.location&&(t.raw.annotationData.location=r?.location)),t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService mergeLocationWithNotification:",e),t}}mergeNotificationWithUser(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeNotificationWithUser","color: green;");let{notification:i}=t;if(i?.actionUser?.userId){let e=this.usersService.getUserById(i?.actionUser?.userId);e&&(i.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.actionUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.actionUser?.userId);e&&(i.displayHeadlineMessageTemplateData.actionUser=e)}if(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId){let e=this.usersService.getUserById(i?.displayHeadlineMessageTemplateData?.recipientUser?.userId);e&&(i.displayHeadlineMessageTemplateData.recipientUser=e)}return i?.notificationSource==="comment"&&i?.notificationSourceData&&this.commentUtilsService.mergeCommentWithUser(i?.notificationSourceData),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeNotificationWithUser:",i),t}}formatNotification(t,i){try{if(typeof t=="object"&&(t=JSON.parse(JSON.stringify(t))),this.usersService.userDataProviderAvailable()&&t?.actionUser&&(t.actionUser={userId:t.actionUser.userId}),this.usersService.userResolverConfigured?.()&&t&&typeof t=="object")for(let e of Object.keys(t))e!=="annotationData"&&e!=="targetAnnotationData"&&Lt(t[e])&&(t[e]=xt(t[e],Et));switch(t.notificationSource){case"comment":this.commentUtilsService.formatCommentData(t.annotationData),this.commentUtilsService.formatCommentThreadData(t.targetAnnotationData),t=this.commentUtilsService.stripCommentNotificationPayload(t);break;default:m.carriesCommentPayload(t)&&(t=this.commentUtilsService.stripCommentNotificationPayload(t));break;case"recorder":this.serviceBook.get(Ht)?.formatRecorderData(t.annotationData,i);break}return t}catch(e){return this.loggingService.catch("Error in NotificationUtilsService formatNotification: ",e),m.carriesCommentPayload(t)?this.commentUtilsService?.stripCommentNotificationPayload?.(I({},t))??t:t}}static carriesCommentPayload(t){return!t||typeof t!="object"?!1:t.notificationSource==="comment"||t.notificationSource===void 0&&Array.isArray(t.annotationData?.comments)}getTargetAnnotationIdsFromNotifications(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getTargetAnnotationIdsFromNotifications","color: green;");let i=[];return Object.values(t).forEach(e=>{e?.notification?.targetAnnotationId&&e?.raw?.notificationSource==="comment"&&i.push(e.notification.targetAnnotationId)}),i}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getTargetAnnotationIdsFromNotifications:",i),[]}}handleNotificationEncryption(i){return y(this,arguments,function*({data:t}){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: handleNotificationEncryption","color: green;");let e="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??"");return yield zt(t,e)}catch(e){return this.loggingService.catch("Error in NotificationUtilsService handleNotificationEncryption:",e),t}})}getCustomNotificationIdsToResolve(t){try{this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: getCustomNotificationIdsToResolve","color: green;");let i=new Set,e=Array.isArray(t)?t:Object.values(t||{});for(let o of e)if(o?.raw?.notificationSource==="custom"){let r=o?.notification?.id||o?.notificationId;r&&i.add(r)}return Array.from(i)}catch(i){return this.loggingService.catch("Error in NotificationUtilsService getCustomNotificationIdsToResolve:",i),[]}}mergeResolvedNotificationData(t){try{if(this.loggingService.log("%c[WB] Calling NotificationUtilsService FUNCTION: mergeResolvedNotificationData","color: green;"),!this.notificationResolverService.notificationDataProviderAvailable()||t?.raw?.notificationSource!=="custom")return t;let i=t?.notification?.id||t?.notificationId;if(!i)return t;let e=this.notificationResolverService.getNotificationById(i);if(!e)return t;let o=["displayHeadlineMessageTemplate","displayHeadlineMessageTemplateData","displayBodyMessage","displayBodyMessageTemplate","displayBodyMessageTemplateData","notificationSourceData"];for(let r of o)e[r]!==void 0&&(t.notification&&(t.notification[r]=e[r]),t.raw&&(t.raw[r]=e[r]));return Object.keys(e).forEach(r=>{!o.includes(r)&&r!=="notificationId"&&(t.notification&&(t.notification[r]=e[r]),t.raw&&(t.raw[r]=e[r]))}),t.notification&&(t.notification.isNotificationResolverUsed=!0),t}catch(i){return this.loggingService.catch("Error in NotificationUtilsService mergeResolvedNotificationData:",i),t}}};m.\u0275fac=function(i){return new(i||m)(S(st),S(it),S(ot),S(et),S(rt),S(nt),S(tt))},m.\u0275prov=J({token:m,factory:m.\u0275fac,providedIn:"root"});let v=m;return v})();function St(v,m=new Date){let F=v>0?v:15,t=new Date(m.getTime());return t.setDate(t.getDate()-F),t.getTime()}function fi(v){let m={startAtTimestamp:v.startAtTimestamp};return v.currentDocumentOnly&&v.currentDocumentId&&(m.documentId=v.currentDocumentId),v.currentDocumentOnly||(m.limit=v.limit),m}function di(v,m){let F=[];if(!v||typeof v!="object")return{};for(let e of Object.keys(v)){let o=v[e];if(!o||typeof o!="object")continue;let r=o.timestamp;typeof r!="number"||Number.isNaN(r)||!(r>=m.startAtTimestamp)||m.documentId!==void 0&&o.metadata?.documentId!==m.documentId||F.push({id:e,timestamp:r,row:v[e]})}let t=F;m.limit!==void 0&&(t=[...F].sort((e,o)=>o.timestamp-e.timestamp||(e.id<o.id?1:e.id>o.id?-1:0)).slice(0,Math.max(0,m.limit)));let i={};for(let e of t)i[e.id]=e.row;return i}function ui(v){if(typeof v!="number"||!Number.isFinite(v))return 25;let t=Math.floor(v);return t<1?25:Math.min(200,t)}function hi(v,m){let F=t=>!!t&&typeof t=="object"&&Object.keys(t).length>0;return F(v)?v:F(m)?m:{}}var ge=(()=>{let m=class m{constructor(t,i,e,o,r,n,s,a,c,l,g,f,d,p,h,A,U,z,B,x,M,H){this.afAuth=t,this.analyticsService=i,this.authService=e,this.configService=o,this.commonDbService=r,this.commonDbUtilsService=n,this.commentUtilsService=s,this.commentAnnotationsResolverService=a,this.notificationResolverService=c,this.databaseService=l,this.docService=g,this.domService=f,this.iamService=d,this.loggingService=p,this.notificationUtilsService=h,this.usersService=A,this.functions=U,this.userPermissionService=z,this.coreActionsService=B,this.serviceBook=x,this.realtimeAdapter=M,this.adapterSelectorService=H,this.endpointsService=bt(kt),this.db=null,this.notificationsDb=null,this.documentPaths=null,this.notifications$=new b([]),this.rawNotificationsByIdMap$=new b(new Map),this.processedNotifications$=new b([]),this.userNotificationsFromServer$=new b(null),this.readNotificationsOnForYouTab$=new b(!1),this.currentDocumentOnly$=new b(!1),this.notificationViews$=new b({}),this.notificationsByIdMap$=new b(new Map),this.historyPanelVisible$=new b(!1),this.notificationsForYou$=new b(null),this.notificationsByDocumentIdMap$=new b(null),this.notificationsByDocumentIdSubscription={},this.notificationsHubDisabled=!1,this.reportedDroppedHubPushes=new Set,this.allowedDocumentMetadataMap$=new b(null),this.documentIdsPipelineOnPortableTrigger=!1,this.maxNotificationDays$=new b(15),this.tabConfig$=new b({people:{enable:!1}}),this.settingsConfig$=new b(null),this.setSettingsConfigByOrganization$=new b(!1),this.muteAllNotifications$=new b(!1),this.enableSettings$=new b(!1),this.selfNotifications$=new b(!1),this.userScopedNotifications$=new b({enabled:!1,limit:25}),this.settingsInitialConfig$=new b([{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.notificationListGeneration=0,this.notificationsPanelVisible$=new b(!1),this.crossOrganizationConfig$=new b({enabled:!1}),this.crossOrgNotifications$=new b([]),this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1,this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=0,this.CROSS_ORG_FETCH_WINDOW_MS=500,this.CROSS_ORG_PAGE_SIZE=50,this.crossOrgGeneration=0,this.crossOrgResolveRoundInFlight=!1,this.crossOrgStragglerRetryUsed=!1,this.CROSS_ORG_STRAGGLER_RETRY_MS=3e4;try{this.serviceBook.set(_t,this),this.serviceBook.observe(Vt).subscribe(u=>{this.commentService=u??void 0}),this.subscribeNotificationsData().subscribe(),this.commentUtilsService.setNotificationService(this),this.databaseService.getDb().pipe(w(u=>!!u),k(1)).subscribe(u=>{if(u){this.db=u;try{let C=this.configService.getProxyConfig(),E=this.endpointsService.getNotificationsDbUrl();$t(E)?(this.notificationsDb=null,this.notificationsHubDisabled=!0):(C?.v1DbHost&&E&&(E=wt(E,C.v1DbHost)),this.notificationsDb=this.realtimeAdapter.getDatabaseInstance(E),C?.v1DbHost&&E&&this.databaseService.lockDatabaseHost(this.notificationsDb))}catch(C){this.loggingService.catch("Error initializing notifications DB, using default: ",C),this.notificationsDb=u}this.getDocumentIds(),this.subscribeGetNotificationsForYou()}},u=>{this.loggingService.catch("Error in NotificationService getDb subscription: ",u)}),this.authService.getUser$().subscribe(u=>{u?(this.subscribeGetNotificationsForYou(),this.getDocumentIds(),this.subscribeToUserSettings()):(Object.keys(this.notificationsByDocumentIdSubscription).forEach(C=>{this.notificationsByDocumentIdSubscription[C]?.unsubscribe()}),this.notificationForYouSubscription?.unsubscribe(),this.documentIdsSubscription?.unsubscribe(),this.resetCacheData())}),ut(()=>{try{if(this.adapterSelectorService?.isPortableBackendActive()){if(this.documentIdsPipelineOnPortableTrigger)return;this.getDocumentIds()}}catch(u){this.loggingService.catch("Error re-evaluating portable notification list on chunk registration: ",u)}}),this.docService.getLocationMetadata$().subscribe(u=>{if(u){let C=this.notificationsByDocumentIdMap$.getValue()?JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue())):null;Object.keys(u||{}).forEach(E=>{let L=C?.[E]?.notifications;L?.length&&L.forEach($=>{this.notificationUtilsService.mergeLocationWithNotification({notification:$},u)?.notification})}),this.notificationsByDocumentIdMap$.next(C)}})}catch(u){this.loggingService.catch("Error in NotificationService constructor: ",u)}}setDBConfigDataToInitialConfig(t){try{let i=JSON.parse(JSON.stringify(this.settingsConfig$.getValue()??{}));Object.entries(t||{}).forEach(([e,o])=>{i[e]=o}),this.settingsConfig$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setDBConfigDataToInitialConfig: ",i)}}getInitialConfigFromDB(t){return y(this,null,function*(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: getInitialConfigFromDB","color: green;");let i=++this.settingsConfigGeneration,e=R(this.authService.getUser()?.userId??""),o,r=!0;if(this.commonDbService?.isPortableSession?.()===!0){let n=yield this.readPortableSettingsConfig(t,e);o=n.data,r=n.answered}else o=yield this.commonDbService.getData({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:this.getSettingsConfigByOrganization()?void 0:t?.documentId,organizationId:t?.organizationId??this.docService.getOrganizationConfig()?.organizationId,userId:e}});if(i!==this.settingsConfigGeneration)return;if(o?.notificationsConfig)this.setDBConfigDataToInitialConfig(o?.notificationsConfig);else if(!r)this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue()),this.setDBConfigDataToInitialConfig(this.buildDefaultSettingsConfig());else{this.setSettingsInitialConfig(this.settingsInitialConfig$.getValue());let n=this.buildDefaultSettingsConfig();yield this.updateSettingsConfigToDb(n)}}catch(i){this.loggingService.catch("Error in NotificationService getInitialConfigFromDB: ",i)}})}buildDefaultSettingsConfig(){let t={};this.settingsInitialConfig$.getValue().forEach(e=>{if(e.enable){let o=e?.values?.find(r=>r.id===e.default);t[e.id]=o||e?.values?.[0]||{id:"NONE",name:"None"}}});let i={};return Object.keys(t).forEach(e=>{i[e]=t[e].id}),i}readPortableSettingsConfig(t,i){return y(this,null,function*(){try{let e=this.resolvePortableSettingsTarget(t,this.getSettingsConfigByOrganization(),this.docService.getOrganizationConfig(),i);return e?yield this.commonDbService.readPortableDoc(e.feature,e.properties):{answered:!1}}catch(e){return this.loggingService.catch("Error in NotificationService readPortableSettingsConfig: ",e),{answered:!1}}})}resolvePortableSettingsTarget(t,i,e,o){if(!this.authService.getUser()?.userId)return null;let r=t?.organizationId??e?.organizationId;return i?this.commonDbService.announcesPortableCapability(ti)?{feature:"organizationUserConfig",properties:{organizationId:r,userId:o}}:null:t?.documentId?{feature:"userConfig",properties:{id:t.documentId,organizationId:r,userId:o}}:null}portableUserSettingsListener$(t,i,e,o){let r=this.resolvePortableSettingsTarget(t,i,e,o);return r?this.commonDbService.dbListener({feature:r.feature,properties:r.properties}):D(void 0)}subscribeToUserSettings(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: subscribeToUserSettings","color: green;"),this.userSettingsSubscription&&this.userSettingsSubscription.unsubscribe();let t=R(this.authService.getUser()?.userId??"");this.userSettingsSubscription=this.enableSettings$.pipe(w(i=>i===!0),O(()=>V([this.docService.getDocumentPaths$(),this.getSettingsConfigByOrganization$(),this.docService.getOrganizationConfig$()]).pipe(w(([i,e,o])=>(e||!!i)&&!!o?.organizationId),O(([i,e,o])=>{let r=N(n=>{n?.data?.notificationsConfig&&!X(n?.data?.notificationsConfig??{},this.settingsConfig$.getValue()??{})&&this.setDBConfigDataToInitialConfig(n?.data?.notificationsConfig)});return this.commonDbService?.isPortableSession?.()===!0?this.commonDbService.portableConnectionChanges$().pipe(O(()=>G(this.getInitialConfigFromDB(i)).pipe(O(()=>this.portableUserSettingsListener$(i,e,o,t).pipe(r))))):G(this.getInitialConfigFromDB(i)).pipe(O(()=>this.commonDbService.dbListener({feature:"userConfig",properties:{useCollectionGroup:!1,isCollection:!1,documentId:e?void 0:i?.documentId,organizationId:i?.organizationId??o?.organizationId,userId:t}}).pipe(r)))})))).subscribe()}catch(t){this.loggingService.catch("Error in NotificationService subscribeToUserSettings: ",t)}}resetCacheData(){try{this.loggingService.log("%c[WB] Calling NotificationService FUNCTION: resetCacheData","color: green;"),this.setUserNotificationsFromServer(null),this.notificationsByDocumentIdMap$.next(null),this.notificationsForYou$.next(null),this.settingsConfig$.next(null),this.resetCrossOrgForUser()}catch(t){this.loggingService.catch("Error in NotificationService resetCacheData: ",t)}}subscribeGetNotificationsForYou(){try{this.notificationForYouSubscription&&this.notificationForYouSubscription.unsubscribe(),this.notificationForYouSubscription=this.getNotificationsForYou().subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getNotificationsForYou subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService subscriveGetNotificationsForYou: ",t)}}setCommentService(t){try{this.commentService=t}catch(i){this.loggingService.catch("Error in NotificationService setCommentService: ",i)}}getDocumentIds(){try{this.documentIdsSubscription&&this.documentIdsSubscription.unsubscribe(),this.documentIdsSubscription=pt(()=>{let t=!!this.adapterSelectorService?.isPortableBackendActive();return this.documentIdsPipelineOnPortableTrigger=t,this.notificationListPipeline$(t)}).subscribe(()=>{},t=>{this.loggingService.catch("Error in NotificationService getDocumentIds subscription: ",t)})}catch(t){this.loggingService.catch("Error in NotificationService getDocumentIds: ",t)}}notificationListPipeline$(t=!1){return this.selfNotifications$.pipe(O(()=>this.getCurrentDocumentOnly$().pipe(O(i=>i?this.docService.getDocumentPaths$().pipe(N(e=>{})):D(void 0)))),Ot(()=>{this.notificationListGeneration++,this.notificationsByDocumentIdMap$.next(null)}),O(()=>this.getDocumentIdsByLastNotificationTimestamp(void 0,t).pipe(at(),N(([i,e])=>{let o=i?.map(c=>c.documentId),r=e?.map(c=>c.documentId),n=o?.filter(c=>!r?.includes(c)),s=r?.map(c=>({documentId:c,timestamp:e?.find(l=>l.documentId===c)?.timestamp})).filter(c=>!o?.includes(c.documentId)),a=r?.map(c=>{let l=e?.find(g=>g.documentId===c)?.timestamp;return{documentId:c,timestamp:l}}).filter(c=>{let l=i?.find(g=>g.documentId===c.documentId)?.timestamp;return l&&c.timestamp&&l!==c.timestamp});s?.length&&this.fetchNotificationsForDocumentIds(s),a?.length&&this.fetchNotificationsForDocumentIds(a,1),n?.forEach(c=>{this.removeNotificationsForDocumentId(c)}),e&&!e?.length&&!this.notificationsByDocumentIdMap$.getValue()&&(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([]))}))))}portableNotificationTriggerRows$(t,i){return new vt(e=>{let o=!1,r=null,n=()=>{try{r?.unsubscribe()}catch(c){this.loggingService.catch("Error releasing the notification trigger subscription: ",c)}r=null},s=()=>{o||(n(),r=this.openPortableNotificationTrigger(t,c=>e.next(c),i))},a=ut(s);return s(),()=>{o=!0;try{a()}catch(c){this.loggingService.catch("Error disposing the notification trigger registration listener: ",c)}n()}})}openPortableNotificationTrigger(t,i,e){try{let o=ri(ht,{apiKey:this.configService.getApiKey(),organizationId:t}),r=this.adapterSelectorService?.resolveRealtimeAdapter?.();if(!o||!r)return null;let n=Xt(o.feature)?.mode??"persistent",s={},a={},c=!1,l=!1;return r.subscribe(o,n,g=>{try{if(l)return;if(typeof g.seq=="number"){let f=a[g.id];if(f!==void 0&&g.seq<=f)return;a[g.id]=g.seq}g.type==="removed"?delete s[g.id]:s[g.id]=g.data,c&&typeof g.seq=="number"&&i(I({},s))}catch(f){this.loggingService.catch("Error materializing a notification trigger delta: ",f)}},I({onSnapshotComplete:g=>{try{if(l)return;if(g?.full===!0)for(let f of Object.keys(a))delete a[f];c=!0,i(I({},s))}catch(f){this.loggingService.catch("Error completing the notification trigger snapshot: ",f)}},onError:g=>{l=!0,this.loggingService.catch(`Portable channel denied for ${ht}: `,{ok:!1,code:g})}},e?{documentId:e}:{}))}catch(o){return this.loggingService.catch("Error subscribing the notification trigger channel: ",o),null}}getDocumentIdsByLastNotificationTimestamp(t=15,i=!1){try{return this.authService.getUser$().pipe(O(e=>this.docService.getOrganizationConfig$().pipe(N(o=>{let r=null,n=this.configService.getApiKey(),s=o?.organizationId||e?.organizationId,a=o?.clientOrganizationId||e?.clientOrganizationId||"";return n&&s&&(r=new mt({apiKey:n,organizationId:s})),{user:e,documentPaths:r,clientOrganizationId:a}}))),O(e=>{let{user:o,documentPaths:r,clientOrganizationId:n}=e;if(this.getCurrentDocumentOnly()&&!this.docService?.getDocumentPaths()?.documentId)return D(null);if(o&&r?.organizationNotificationsLastNotificationTimestamp){let s=St(this.maxNotificationDays$.getValue()),a=fi({startAtTimestamp:s,currentDocumentOnly:this.getCurrentDocumentOnly(),currentDocumentId:this.docService.getDocumentPaths()?.documentId,limit:t}),c=o?.userId??"";return G(this.userPermissionService?.getUserPermissionsFromCacheOrFetch({organizationId:n})??Promise.resolve({})).pipe(O(l=>c&&n&&l?.[c]?.organization?.[n]?.errorCode===Ut.PERMISSION_DENIED?D(null):this.lastNotificationTimestampRows$(r,a,i).pipe(N(g=>{let f=()=>i||this.commonDbService.shouldUseFirestore(),d=[];return Object.keys(g||{}).forEach(p=>{let h=f()?g[p]?.timestamp??0:g[p],A=f()?g[p]?.deletedNotification??!1:!1;if(A&&A.id&&A?.timestamp===h){let U=A.id,z=g[p]?.metadata?.documentId,B=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()??{})),x=B?.[z]??{documentMetadata:null,notifications:[]},M=x.notifications??[],H=M?.findIndex(u=>u.id===U);H!==-1&&(M.splice(H,1),this.notificationsByDocumentIdMap$.next(T(I({},B),{[z]:T(I({},x),{notifications:M})}))),this.notificationResolverService.notificationDataProviderAvailable()&&this.notificationResolverService.getNotificationById(U)&&this.notificationResolverService.deleteNotification(U,this.docService.getDocumentPaths()?.clientOrganizationId??"")}d.push({documentId:p,timestamp:h})}),d}),_(g=>(this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",g),D([]))))))}return D(null)}))}catch(e){return this.loggingService.catch("Error in NotificationService getDocumentIdsByLastNotificationTimestamp: ",e),D([])}}lastNotificationTimestampRows$(t,i,e=!1){return e?this.portableNotificationTriggerRows$(t?.organizationId,i.documentId).pipe(N(o=>di(o,i)),It(void 0)):this.commonDbService.dbListener({feature:"allLastNotificationTimestamp",properties:{organizationId:t?.organizationId,isCollection:!0,useQuery:!0,firestoreQuery:this.toFirestoreTriggerQuery(i)}}).pipe(N(o=>o?.data))}toFirestoreTriggerQuery(t){let i=[Wt(dt("timestamp",">=",t.startAtTimestamp),...t.documentId!==void 0?[dt("metadata.documentId","==",t.documentId)]:[])];return t.limit!==void 0&&(i.push(Kt("timestamp","desc")),i.push(Jt(t.limit))),i}resolveAndUpdateDocumentNotifications(t,i,e){try{if(e!==void 0&&e!==this.notificationListGeneration)return;Object.keys(t).forEach(o=>{let r=t[o]?.documentMetadata||this.docService.getAllDocumentMetadataMap()?.[o]||{},n;if(i==="user")n=this.commonDbUtilsService.mergeUsersWithData({feature:"allDocNotifications",data:t[o]?.notifications||[]});else if(i==="notification"){let s=t[o]?.notifications?.reduce((c,l)=>(c[l.notificationId]=l,c),{}),a=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allDocNotifications",data:s});n=Object.values(a??{})}else{let s=t[o]?.notifications?.reduce((c,l)=>(c[l.notificationId]=l,c),{}),a=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allDocNotifications",data:s});n=Object.values(a??{})}n.forEach(s=>{s.notification=this.getClientNotificationObject(s)}),this.setNotificationForDocumentIdInCache(o,r,n)})}catch(o){this.loggingService.catch("Error in NotificationService resolveAndUpdateDocumentNotifications: ",o)}}resolveAndMergeUserNotifications(t,i,e=!1,o){try{if(o!==void 0&&o!==this.notificationListGeneration)return;let r=t;if(e&&i==="comment"){let l=this.getUserNotificationsFromServer()??[],g=new Set(t.map(f=>f.notificationId));r=l.filter(f=>g.has(f.notificationId)).concat(t.filter(f=>!l.some(d=>d.notificationId===f.notificationId)))}let n=r.reduce((l,g)=>(l[g.notificationId]=g,l),{}),s;if(i==="user"){let l=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:n});s=Object.values(l??{})}else if(i==="notification"){let l=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:n});s=Object.values(l??{})}else{let l=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:n});s=Object.values(l??{})}s.forEach(l=>{l.notification=this.getClientNotificationObject(l)});let a=this.getUserNotificationsFromServer()??[],c=new Map(a.map(l=>[l.notificationId,l]));s.forEach(l=>{c.set(l.notificationId,l)}),this.setUserNotificationsFromServer(Array.from(c.values()))}catch(r){this.loggingService.catch("Error in NotificationService resolveAndMergeUserNotifications: ",r)}}fetchNotificationsForDocumentIds(t,i=15){return y(this,null,function*(){try{if(t?.length){let e=this.notificationListGeneration,o=this.docService.getOrganizationConfig()?.organizationId??"";if(!o)return[];let r=this.getStartAtTimestamp(),n={};t.forEach(h=>{if(h?.documentId){let A=this.getAllowedDocumentMetadataByDocumentId(h.documentId);A&&(n[h.documentId]=A)}}),this.userPermissionService?.isPermissionProviderAvailable()&&(t=yield this.filterDocumentIdsByPermissionProvider(t));let s=this.userScopedNotifications$.getValue(),a=!!s?.enabled&&i!==1&&!this.getCurrentDocumentOnly();if(!t.length&&(this.notificationsByDocumentIdMap$.getValue()||(this.notificationsByDocumentIdMap$.next({}),this.setUserNotificationsFromServer([])),!a))return[];let c=this.userPermissionService?.getPermissionsCache()?.filter(h=>h.type===Q.CONTEXT),l=I({organizationId:o,documentIds:t.filter(h=>!!h.documentId&&!!h.timestamp).map(h=>({documentId:h.documentId,timestamp:h.timestamp??0})),timestamp:r,limitToLast:i,selfNotifications:this.selfNotifications$.value,isPermissionProviderUsed:this.userPermissionService?.isPermissionProviderAvailable(),getUserNotifications:!0,isContextEnabled:this.userPermissionService?.getIsContextEnabled(),cachedData:c,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig()},a&&{getUserNotificationsForOrganization:!0,userNotificationsLimitToLast:ui(s?.limit)}),{notificationsByDocumentId:g,userNotifications:f=[],userNotificationIdsInDocNotifications:d=[],permissionResults:p=[]}=yield this.callGetNotificationsForDocuments(l);if(e!==this.notificationListGeneration)return[];if(this.userPermissionService?.getIsContextEnabled()){let h=[...this.userPermissionService?.getPermissionsCache()??[],...p??[]];this.userPermissionService?.setPermissionsCache(h)}if(g&&typeof g=="object"){let h=this.usersService.userDataProviderAvailable(),A=this.commentAnnotationsResolverService.commentAnnotationDataProviderAvailable(),U=this.notificationResolverService.notificationDataProviderAvailable(),z=[],B=[],x=[];Object.keys(g).forEach((u,C)=>{let E=g[u].documentMetadata??this.docService.getAllDocumentMetadataMap()?.[u];if(E){let $=this.allowedDocumentMetadataMap$.value||{};(!$?.[u]||!X($?.[u],E))&&this.allowedDocumentMetadataMap$.next(T(I({},$),{[u]:E}))}let L=g[u].notifications||[];L.forEach($=>{d.includes($.notificationId)&&!f.find(mi=>mi.notificationId===$.notificationId)&&f.push(JSON.parse(JSON.stringify($))),$.notification=this.getClientNotificationObject($)}),this.setNotificationForDocumentIdInCache(u,E,L),h&&(z.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:L,shouldAwait:!0,forceResolve:!0})),z.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:f,shouldAwait:!0,forceResolve:!0}))),A&&(B.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:L,shouldCommentAnnotationsResolverAwait:!0})),B.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:f,shouldCommentAnnotationsResolverAwait:!0}))),U&&(x.push(this.commonDbUtilsService.formatResponse({feature:"allDocNotifications",data:L,shouldNotificationResolverAwait:!0})),x.push(this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:f,shouldNotificationResolverAwait:!0})))});let M=JSON.parse(JSON.stringify(f));if(a){let u=new Map((this.getUserNotificationsFromServer()??[]).map(C=>[C?.notificationId,C]));f.forEach(C=>u.set(C?.notificationId,C)),this.setUserNotificationsFromServer(Array.from(u.values()))}else this.setUserNotificationsFromServer([...this.getUserNotificationsFromServer()??[],...f]);(U||h||A)&&(()=>{let u=Promise.resolve();if(U&&(u=u.then(()=>Promise.allSettled(x)).then(()=>{this.resolveAndUpdateDocumentNotifications(g,"notification",e),this.resolveAndMergeUserNotifications(M,"notification",!1,e)})),h&&(u=u.then(()=>Promise.allSettled(z)).then(()=>{this.resolveAndUpdateDocumentNotifications(g,"user",e),this.resolveAndMergeUserNotifications(M,"user",!1,e)})),A){let C=U||h;u=u.then(()=>Promise.allSettled(B)).then(()=>{this.resolveAndUpdateDocumentNotifications(g,"comment",e),this.resolveAndMergeUserNotifications(M,"comment",C,e)})}return u})().catch(u=>{this.loggingService.catch("Error in NotificationService resolveChain: ",u)})}}}catch(e){return this.loggingService.catch("Error in NotificationService fetchNotificationsForDocumentIds: ",e),[]}})}filterDocumentIdsByPermissionProvider(t){return y(this,null,function*(){try{let i=[];if(t.forEach(s=>{this.docService.getDocumentMetadata(s.documentId)||i.push(s.documentId)}),i.length){let s=this.authService.getUser(),a={type:"getDocumentMetadataFromIds",metadata:{organizationId:s?.clientOrganizationId,folderId:this.documentPaths?.folderId},documentIds:i},c=!!this.adapterSelectorService?.isPortableBackendActive(),l=c?void 0:q(this.functions,Z({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));try{let g=c?yield this.invokePortableSdkProxyOp("getDocumentMetadataFromIds",a):yield ft({methodName:"getDocumentMetadataFromIds",data:a,getSdkProxy:l,userId:s?.userId??""});if(g?.data?.length){let f={};g.data.forEach(d=>{d?.documentId&&(f[d.documentId]=d)}),this.docService.setAllDocumentMetadata(I(I({},this.docService.getAllDocumentMetadataMap()),f))}}catch(g){this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",g)}}let e=[],o=[];t.forEach(s=>{let a=this.docService.getDocumentMetadata(s.documentId);a?.clientDocumentId?e.push({userId:this.authService.getUser()?.userId??"",resource:I({id:a.clientDocumentId,type:Q.DOCUMENT,source:K.GET_NOTIFICATIONS,organizationId:this.docService.getOrganizationConfig()?.clientOrganizationId??""},a.folderId&&{parentFolderId:a.folderId})}):o.push(s.documentId)}),o.length&&(t=t.filter(s=>!o.includes(s.documentId)));let r=Ft();this.coreActionsService.triggerAction(At.PERMISSION_PROVIDER,{event:j.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_FORMED,timestamp:new Date().getTime(),uniqueId:r,methodName:K.GET_NOTIFICATIONS,source:"internal",payload:{requests:e}});let n=yield this.userPermissionService?.onResourceAccessRequired({requests:e,uniqueId:r,methodName:K.GET_NOTIFICATIONS});return n?.success&&n?.data?.length?n.data.forEach(s=>{!s.hasAccess&&s.resourceId&&(t=t.filter(a=>a.documentId!==Pt(s.resourceId)))}):t=[],t}catch(i){return this.loggingService.warn("Error in NotificationService fetchNotificationsForDocumentIds: ",i),[]}})}callGetNotificationsForDocuments(t){return y(this,null,function*(){if(this.adapterSelectorService?.isPortableBackendActive())return this.callPortableGetNotificationsForDocuments(t);let i=q(this.functions,Z({url:this.endpointsService.getCloudFunctionUrl("getNotificationsForDocuments"),apiProxyDomain:this.configService?.getApiProxyDomain()}),{timeout:1200*1e3}),e=yield this.notificationUtilsService.handleNotificationEncryption({data:t}),o=yield i({veltData:e}),r=o?.data?.data?.veltData||{},n=o?.data?.data?.veltAdditionalData||{},s="notificationwithdocumentidstoencryptanddecryptonsdk"+(this.authService.getUser()?.userId??""),a=yield gt(r,s),{userNotifications:c,userNotificationIdsInDocNotifications:l,permissionResults:g}=yield gt(n,s);return{notificationsByDocumentId:a,userNotifications:c,userNotificationIdsInDocNotifications:l,permissionResults:g}})}callPortableGetNotificationsForDocuments(t){return y(this,null,function*(){let i=yield this.adapterSelectorService.resolveDbAdapter().getNotificationsForDocuments({scope:"org",data:t});if(!i?.ok)throw new Error(`getNotificationsForDocuments failed on the portable gateway: ${i?.code??"unknown"}`);let e=i.data??{},o=e.veltData??{},{userNotifications:r,userNotificationIdsInDocNotifications:n,permissionResults:s}=e.veltAdditionalData??{};return{notificationsByDocumentId:o,userNotifications:r,userNotificationIdsInDocNotifications:n,permissionResults:s}})}invokePortableSdkProxyOp(t,i){return y(this,null,function*(){try{let e=yield this.adapterSelectorService.resolveDbAdapter()[t]({scope:"org",data:i});return e?.ok?e.data?.veltData:(this.loggingService.catch(`Error in NotificationService ${t} (portable gateway): `,e),i)}catch(e){return this.loggingService.catch(`Error in NotificationService ${t} (portable gateway): `,e),i}})}getUserNotificationsFromServer$(){return this.userNotificationsFromServer$.asObservable()}setUserNotificationsFromServer(t){try{let i=JSON.parse(JSON.stringify(t));i=i?.filter((e,o,r)=>o===r.findIndex(n=>n.notificationId===e.notificationId)),this.userNotificationsFromServer$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService setUserNotificationsFromServer: ",i)}}getUserNotificationsFromServer(){return this.userNotificationsFromServer$.getValue()}setNotificationForDocumentIdInCache(t,i,e,o){try{let r=this.docService.getOrganizationConfig()?.organizationId??"",n=this.docService.getOrganizationMetadata(r);i||(i=this.getOwnDocumentMetadata(t)),n||(n=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(r)||{})));let s=this.notificationsByDocumentIdMap$.getValue(),a=s?.[t]?.notifications||[],c=this.docService.getLocationMetadatas(),l=e?.map(d=>{let p=d?.notification;return p?(p.metadata&&(p.metadata.documentName=i?.documentName||p.metadata.documentName,p.metadata.organizationMetadata=n||p.metadata.organizationMetadata,p.metadata.documentMetadata=hi(i,p.metadata.documentMetadata)),c&&(p=this.notificationUtilsService.mergeLocationWithNotification({notification:p},c)?.notification),p):null})?.filter(d=>!!d)||[],g=new Map(a.map(d=>[d.id,d]));l.forEach(d=>{g.set(d.id,d)});let f=Array.from(g.values()).sort((d,p)=>(p.timestamp||0)-(d.timestamp||0));this.notificationsByDocumentIdMap$.next(T(I({},s),{[t]:{notifications:f,documentMetadata:i||{}}}))}catch(r){this.loggingService.catch("Error in NotificationService setNotificationForDocumentIdInCache: ",r)}}removeNotificationsForDocumentId(t){try{this.notificationsByDocumentIdSubscription[t]&&this.notificationsByDocumentIdSubscription[t].unsubscribe();let i=this.notificationsByDocumentIdMap$.getValue();delete i?.[t],this.notificationsByDocumentIdMap$.next(i)}catch(i){this.loggingService.catch("Error in NotificationService removeNotificationsForDocumentId: ",i)}}getStartAtTimestamp(){try{return St(this.maxNotificationDays$.getValue())}catch(t){return this.loggingService.catch("Error in NotificationService getStartAtTimestamp: ",t),0}}getCurrentOrgNotificationsForYou(){try{return this.getUserNotificationsFromServer$().pipe(O(t=>D(t).pipe(w(i=>!!i),N(i=>{let e=this.usersService.userDataProviderAvailable(),o=this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable(),r=this.notificationResolverService?.notificationDataProviderAvailable();if(r||e||o){let s=i?.reduce((a,c)=>(a[c.notificationId]=c,a),{});r&&(s=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:s||[]})),e&&(s=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:s||[]})),o&&(s=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:s||[]})),i=Object.values(s??{})}return i.forEach(s=>{s.notification=this.getClientNotificationObject(s)}),i.sort((s,a)=>a.timestamp-s.timestamp),i.map(s=>s.notification).filter(s=>!!s)}),O(i=>{let e={data:i?.reduce((o,r)=>(o[r.id]={notification:r},o),{}),operation:null};return this.commonDbUtilsService.mergeLocationMetadataWithData$({data:e,feature:"allUserNotifications"}).pipe(N(o=>Object.values(o?.data||{}).map(r=>r?.notification)))}))),O(t=>{let i=this.docService.getOrganizationConfig()?.organizationId??"";return this.docService.getOrganizationMetadata$(i).pipe(N(()=>t))}),O(t=>this.allowedDocumentMetadataMap$.pipe(N(()=>t))),N(t=>(t?.length&&(t=t.map(i=>{if(i?.metadata){let e=this.docService.getOrganizationConfig()?.organizationId??"",o=this.getAllowedDocumentMetadataByDocumentId(i.metadata.documentId),r=this.docService.getOrganizationMetadata(e);o||(o=this.getOwnDocumentMetadata(i.metadata.documentId)),r||(r=JSON.parse(JSON.stringify(this.docService.getOrganizationMetadata(e)||{}))),i.metadata.documentName=o?.documentName||i.metadata.documentName,i.metadata.organizationMetadata=r||i.metadata.organizationMetadata,i.metadata.documentMetadata=hi(o,i.metadata.documentMetadata)}return i})),t)))}catch(t){return this.loggingService.catch("Error in NotificationService getCurrentOrgNotificationsForYou: ",t),D(null)}}getNotificationsForYou(){try{return V([this.getCurrentOrgNotificationsForYou(),this.crossOrgNotifications$.asObservable()]).pipe(N(([t,i])=>{let e=this.mergeCrossOrgForYou(t,i);return e===null?this.notificationsForYou$.next(null):e?.length?this.notificationsForYou$.next(JSON.parse(JSON.stringify(e))):this.notificationsForYou$.next([]),e}))}catch(t){return this.loggingService.catch("Error in NotificationService getNotificationsForYou: ",t),D({})}}mergeCrossOrgForYou(t,i){try{let e=Array.isArray(i)?i:[];if(!e.length)return t;let o=Array.isArray(t)?t:[],r=a=>a?.id??a?.notificationId,n=new Set;o.forEach(a=>{let c=r(a);c!=null&&n.add(c)});let s=[...o];return e.forEach(a=>{let c=r(a);c!=null&&n.has(c)||(c!=null&&n.add(c),s.push(a))}),s.sort((a,c)=>(c?.timestamp||0)-(a?.timestamp||0))}catch(e){return this.loggingService.catch("Error in NotificationService mergeCrossOrgForYou: ",e),t}}enableCrossOrganization(t){try{if(t&&typeof t=="object"&&t.enabled===!1){this.disableCrossOrganization();return}this.setCrossOrganizationConfig(T(I({},t||{}),{enabled:!0})),this.crossOrgUserSubscription?this.crossOrgIndexSubscription&&(this.crossOrgInitialFetchDone=!1,this.scheduleCrossOrgFetch()):this.attachCrossOrgIndexListener()}catch(i){this.loggingService.catch("Error in NotificationService enableCrossOrganization: ",i)}}disableCrossOrganization(){try{this.teardownCrossOrg();let t=this.crossOrganizationConfig$.getValue();this.crossOrganizationConfig$.next(T(I({},t||{}),{enabled:!1}))}catch(t){this.loggingService.catch("Error in NotificationService disableCrossOrganization: ",t)}}setCrossOrganizationConfig(t){try{let i=t||{},e=Array.isArray(i.feeds)&&i.feeds.length?i.feeds:["forYou"];e.includes("all")&&this.loggingService.warn('NotificationService: cross-organization notifications only support the "forYou" feed; ignoring "all".'),e=e.filter(r=>r==="forYou"),e.length||(e=["forYou"]);let o={enabled:i.enabled??!0,organizationIds:i.organizationIds,excludeOrganizationIds:i.excludeOrganizationIds,feeds:e};this.crossOrganizationConfig$.next(o)}catch(i){this.loggingService.catch("Error in NotificationService setCrossOrganizationConfig: ",i)}}getCrossOrganizationConfig(){return this.crossOrganizationConfig$.getValue()}getCrossOrganizationConfig$(){return this.crossOrganizationConfig$.asObservable()}attachCrossOrgIndexListener(){try{this.teardownCrossOrgUserWatcher(),this.crossOrgUserSubscription=this.authService.getUser$().pipe(N(t=>t?.userId),W(),w(t=>!!t),_(t=>(this.loggingService.catch("Error in NotificationService cross-org user watcher: ",t),Y))).subscribe(t=>{try{this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([]),this.bindCrossOrgListenersForUser(t)}catch(i){this.loggingService.catch("Error in NotificationService cross-org user-change handler: ",i)}})}catch(t){this.loggingService.catch("Error in NotificationService attachCrossOrgIndexListener: ",t)}}bindCrossOrgListenersForUser(t){this.crossOrgIndexSubscription=this.commonDbService.dbListener({feature:"userNotificationIndex",properties:{id:R(t),isCollection:!1,useCollectionGroup:!1}}).pipe(_(i=>(this.loggingService.catch("Error in NotificationService cross-org index listener: ",i),Y))).subscribe(i=>{try{let e=this.extractIndexOrgTimestamps(i);this.crossOrgIndexTimestamps=e;let o=Object.keys(e);this.crossOrgIndexOrgs=o,this.pruneCrossOrgBufferToAllowedOrgs(),o.length&&this.scheduleCrossOrgFetch()}catch(e){this.loggingService.catch("Error in NotificationService cross-org index snapshot: ",e)}}),this.crossOrgOrgSwitchSubscription=this.docService.getOrganizationConfig$().pipe(N(i=>i?.organizationId??""),W(),at(),w(([i])=>!!i),_(i=>(this.loggingService.catch("Error in NotificationService cross-org org-switch listener: ",i),Y))).subscribe(()=>{this.crossOrgInitialFetchDone=!1,this.crossOrgSeenTimestamps={},this.scheduleCrossOrgFetch()})}extractIndexOrgTimestamps(t){let i={};try{let e=t?.data??t,o=e?.organizationIds??e?.orgs;return Array.isArray(o)?(o.forEach(r=>{typeof r=="string"&&r.length&&(i[r]=0)}),i):(o&&typeof o=="object"&&Object.keys(o).forEach(r=>{if(typeof r=="string"&&r.length){let n=Number(o[r]);i[r]=Number.isFinite(n)?n:0}}),i)}catch(e){return this.loggingService.catch("Error in NotificationService extractIndexOrgTimestamps: ",e),i}}scheduleCrossOrgFetch(){try{let t=Date.now();t-this.lastCrossOrgFetchTime>=this.CROSS_ORG_FETCH_WINDOW_MS?(this.lastCrossOrgFetchTime=t,this.crossOrgFetchPending=!1,this.fetchCrossOrgUserNotifications(),this.armCrossOrgTrailingTimer()):this.crossOrgFetchPending=!0}catch(t){this.loggingService.catch("Error in NotificationService scheduleCrossOrgFetch: ",t)}}pruneCrossOrgBufferToAllowedOrgs(){try{let t=this.crossOrgNotifications$.getValue();if(!t.length)return;let i=this.crossOrgIndexOrgs||[];if(!i.length){this.crossOrgNotifications$.next([]);return}let e=t.filter(o=>i.includes(o?.metadata?.organizationId));e.length!==t.length&&this.crossOrgNotifications$.next(e)}catch(t){this.loggingService.catch("Error in NotificationService pruneCrossOrgBufferToAllowedOrgs: ",t)}}armCrossOrgTrailingTimer(){this.crossOrgFetchTimer&&clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=setTimeout(()=>{this.crossOrgFetchPending&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())},this.CROSS_ORG_FETCH_WINDOW_MS)}toCrossOrgClientNotification(t){try{if(!t)return null;if(t.notification){let e=this.getClientNotificationObject(t);if(!e)return null;let o=t?.metadata?.organizationId??e?.metadata?.organizationId;return o!=null&&(e.metadata=T(I({},e.metadata||{}),{organizationId:o})),e}let i=t.id??t.notificationId;return i==null?null:t.id!=null?t:T(I({},t),{id:i})}catch(i){return this.loggingService.catch("Error in NotificationService toCrossOrgClientNotification: ",i),null}}resolveCrossOrgSelfHostedData(t){return y(this,null,function*(){try{if(!t?.length)return t;let i=!!this.notificationResolverService?.notificationDataProviderAvailable?.(),e=!!this.usersService?.userDataProviderAvailable?.(),o=!!this.commentAnnotationsResolverService?.commentAnnotationDataProviderAvailable?.();if(!i&&!e&&!o)return t;let r=this.commonDbService?.isPortableSession?.()===!0,n=new Map;for(let a of t){let c=r?a?.metadata?.clientOrganizationId??"":a?.metadata?.clientOrganizationId??a?.metadata?.organizationId??"",l=n.get(c);l?l.push(a):n.set(c,[a])}let s=[];for(let[a,c]of n){if(r&&!a){s.push(...c);continue}let l=c.reduce((f,d,p)=>{let h=d?.notificationId??d?.id??`__cross_org_${p}`;return f[h]=d,f},{});yield this.commonDbUtilsService.formatResponse({feature:"allUserNotifications",data:l,organizationId:a||void 0,shouldAwait:!0,shouldNotificationResolverAwait:!0,shouldCommentAnnotationsResolverAwait:!0});let g=l;i&&(g=this.commonDbUtilsService.mergeNotificationsWithResolvedData({feature:"allUserNotifications",data:g??{}})),e&&(g=this.commonDbUtilsService.mergeUsersWithData({feature:"allUserNotifications",data:g??{}})),o&&(g=this.commonDbUtilsService.mergeCommentAnnotationsWithData({feature:"allUserNotifications",data:g??{}})),s.push(...Object.values(g??{}))}return s}catch(i){return this.loggingService.catch("Error in NotificationService resolveCrossOrgSelfHostedData: ",i),t}})}fetchCrossOrgUserNotifications(){return y(this,null,function*(){let t=this.crossOrgGeneration;if(this.crossOrgResolveRoundInFlight){this.crossOrgFetchPending=!0;return}this.crossOrgResolveRoundInFlight=!0;try{let i=this.crossOrganizationConfig$.getValue(),e=this.docService.getOrganizationConfig()?.organizationId??"",o=!this.crossOrgInitialFetchDone,r=this.crossOrgIndexTimestamps||{},n=o?[]:Object.keys(r).filter(f=>f!==e&&(r[f]??0)>(this.crossOrgSeenTimestamps[f]??-1));if(!o&&!n.length)return;let s=this.buildCrossOrgRequestData(i,e,{isInitial:o,bumpedOrgs:n}),a=yield this.callGetCrossOrgUserNotifications(s);if(t!==this.crossOrgGeneration)return;let c=Array.isArray(a?.pendingPermissionQueries)?a.pendingPermissionQueries:[],l=!!this.userPermissionService?.isClientDevResolverActive?.(),g=!c.length||!l;if(yield this.processCrossOrgResponse(a,{fetchGeneration:t,currentOrg:e,isInitial:o,indexTimestamps:r,advanceCursors:g}),t!==this.crossOrgGeneration||g){g&&t===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry();return}yield this.runCrossOrgResolveRound(c,{fetchGeneration:t,config:i,currentOrg:e,isInitial:o,bumpedOrgs:n,indexTimestamps:r})}catch(i){this.loggingService.catch("Error in NotificationService fetchCrossOrgUserNotifications: ",i)}finally{this.crossOrgResolveRoundInFlight=!1,this.crossOrgFetchPending&&t===this.crossOrgGeneration&&(this.crossOrgFetchPending=!1,this.lastCrossOrgFetchTime=Date.now(),this.fetchCrossOrgUserNotifications())}})}runCrossOrgResolveRound(t,i){return y(this,null,function*(){try{let e=yield this.userPermissionService.resolveClientSidePermissions(t);if(i.fetchGeneration!==this.crossOrgGeneration)return;let o=this.buildCrossOrgRequestData(i.config,i.currentOrg,{isInitial:i.isInitial,bumpedOrgs:i.bumpedOrgs});o.clientResolvedResults=e;let r=yield this.callGetCrossOrgUserNotifications(o);if(i.fetchGeneration!==this.crossOrgGeneration)return;yield this.processCrossOrgResponse(r,{fetchGeneration:i.fetchGeneration,currentOrg:i.currentOrg,isInitial:i.isInitial,indexTimestamps:i.indexTimestamps,advanceCursors:!0}),i.fetchGeneration===this.crossOrgGeneration&&this.clearCrossOrgStragglerRetry()}catch(e){this.loggingService.catch("Error in NotificationService runCrossOrgResolveRound: ",e),this.armCrossOrgStragglerRetry(i.fetchGeneration)}})}processCrossOrgResponse(t,i){return y(this,null,function*(){if(this.userPermissionService?.getIsContextEnabled?.()&&t?.permissionResults?.length){let l=[...this.userPermissionService?.getPermissionsCache?.()??[],...t.permissionResults];this.userPermissionService?.setPermissionsCache?.(l)}let e=Array.isArray(t?.forYou)?t.forYou:[],o=this.crossOrgIndexOrgs||[],r=l=>o.includes(l),n=e.filter(l=>{let g=l?.metadata?.organizationId;if(g===i.currentOrg)return this.loggingService.log("%c[WB] Cross-org: dropping current-org echo: "+g,"color: orange;"),!1;let f=r(g);return f||this.loggingService.log("%c[WB] Cross-org: dropping entry from un-indexed org: "+g,"color: orange;"),f}),s=yield this.resolveCrossOrgSelfHostedData(n);if(i.fetchGeneration!==this.crossOrgGeneration)return;let a=s.map(l=>this.toCrossOrgClientNotification(l)).filter(l=>!!l),c;i.isInitial?c=a:c=this.mergeCrossOrgForYou(a,this.crossOrgNotifications$.getValue()).filter(l=>r(l?.metadata?.organizationId)),i.advanceCursors&&(Object.keys(i.indexTimestamps).forEach(l=>{this.crossOrgSeenTimestamps[l]=i.indexTimestamps[l]}),this.crossOrgInitialFetchDone=!0),this.crossOrgNotifications$.next(c)})}armCrossOrgStragglerRetry(t){this.crossOrgStragglerRetryUsed||(this.crossOrgStragglerRetryUsed=!0,this.crossOrgStragglerRetryTimer&&clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=setTimeout(()=>{this.crossOrgStragglerRetryTimer=void 0,t===this.crossOrgGeneration&&this.fetchCrossOrgUserNotifications()},this.CROSS_ORG_STRAGGLER_RETRY_MS))}clearCrossOrgStragglerRetry(){this.crossOrgStragglerRetryUsed=!1,this.crossOrgStragglerRetryTimer&&(clearTimeout(this.crossOrgStragglerRetryTimer),this.crossOrgStragglerRetryTimer=void 0)}callGetCrossOrgUserNotifications(t){return y(this,null,function*(){if(this.adapterSelectorService?.isPortableBackendActive())return this.invokePortableSdkProxyOp("getCrossOrgUserNotifications",I({type:"getCrossOrgUserNotifications"},t));let i=this.authService.getUser(),e=q(this.functions,Z({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield ft({methodName:"getCrossOrgUserNotifications",data:I({type:"getCrossOrgUserNotifications"},t),getSdkProxy:e,userId:i?.userId??""})})}buildCrossOrgRequestData(t,i,e){let o=t||{},r=e?.isInitial??!0,n=e?.bumpedOrgs??[],s=Array.isArray(o.organizationIds),a=s?o.organizationIds.filter(d=>!!d).map(d=>lt(d)):[],c=(o.excludeOrganizationIds||[]).filter(d=>!!d).map(d=>lt(d)),l=new Set(c);i&&l.add(i);let g=this.userPermissionService?.getPermissionsCache?.()?.filter(d=>d?.type===Q.CONTEXT),f={organizationId:i,excludeOrganizationIds:Array.from(l),timestamp:this.getStartAtTimestamp(),limitToLast:this.CROSS_ORG_PAGE_SIZE,isContextEnabled:this.userPermissionService?.getIsContextEnabled?.(),cachedData:g,isSettingsConfigByOrganization:this.getSettingsConfigByOrganization(),retryConfig:this.userPermissionService?.getPermissionProviderRetryConfig?.()};if(this.userPermissionService?.isClientDevResolverActive?.()&&(f.clientResolverAvailable=!0),r)s&&(f.organizationIds=this.dedupeIncludeOrgs(a,l));else{let d=n.filter(h=>!!h&&!l.has(h));if(s){let h=new Set(a);d=d.filter(A=>h.has(A))}d=Array.from(new Set(d)),f.organizationIds=d;let p={};d.forEach(h=>{p[h]=this.crossOrgSeenTimestamps[h]??this.getStartAtTimestamp()}),f.orgTimestamps=p}return f}dedupeIncludeOrgs(t,i){let e=new Set;return t.filter(o=>o==null||i.has(o)||e.has(o)?!1:(e.add(o),!0))}teardownCrossOrgPerUserListeners(){this.crossOrgGeneration++,this.crossOrgIndexSubscription&&(this.crossOrgIndexSubscription.unsubscribe(),this.crossOrgIndexSubscription=void 0),this.crossOrgOrgSwitchSubscription&&(this.crossOrgOrgSwitchSubscription.unsubscribe(),this.crossOrgOrgSwitchSubscription=void 0),this.crossOrgFetchTimer&&(clearTimeout(this.crossOrgFetchTimer),this.crossOrgFetchTimer=void 0),this.crossOrgFetchPending=!1,this.clearCrossOrgStragglerRetry()}teardownCrossOrgUserWatcher(){this.teardownCrossOrgPerUserListeners(),this.crossOrgUserSubscription&&(this.crossOrgUserSubscription.unsubscribe(),this.crossOrgUserSubscription=void 0)}resetCrossOrgDeltaState(){this.crossOrgIndexOrgs=[],this.crossOrgIndexTimestamps={},this.crossOrgSeenTimestamps={},this.crossOrgInitialFetchDone=!1}resetCrossOrgForUser(){this.teardownCrossOrgPerUserListeners(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.getValue().length&&this.crossOrgNotifications$.next([])}teardownCrossOrg(){this.teardownCrossOrgUserWatcher(),this.resetCrossOrgDeltaState(),this.crossOrgNotifications$.next([])}markCrossOrgEntriesRead(t){try{let i=this.crossOrgNotifications$.getValue();if(!i?.length)return;let e=new Set((t||[]).map(s=>s?.id??s?.notificationId).filter(s=>s!=null));if(!e.size)return;let o=!this.getReadNotificationsOnForYouTab(),r=!1,n=o?i.filter(s=>{let a=s?.id??s?.notificationId,c=a!=null&&e.has(a);return c&&(r=!0),!c}):i.map(s=>{let a=s?.id??s?.notificationId;return a!=null&&e.has(a)&&s?.isUnread!==!1?(r=!0,T(I({},s),{isUnread:!1})):s});r&&this.crossOrgNotifications$.next(n)}catch(i){this.loggingService.catch("Error in NotificationService markCrossOrgEntriesRead: ",i)}}subscribeNotificationsData(t,i){this.loggingService.log("%c[WB] Calling FUNCTION: subscribeViewsData","color: green;");let e,o;try{if(t&&(o=ct(t)),i&&typeof i=="object"){let r=Mt(i);e=ct(JSON.stringify(r))}}catch(r){this.loggingService.catch("Error in ViewsService subscribeViewsData: ",r)}return this.authService.getAuthState$().pipe(w(r=>!!r),O(r=>this.isFeatureAllowed({firebaseUser:r})),O(r=>r.featureAllowed?this.iamService.isUserAllowed$().pipe(N(n=>(r.featureAllowed=n,r))):D(r)),O(r=>!r.featureAllowed||r?.user?.organizationId?(this.notifications$.next([]),this.rawNotificationsByIdMap$.next(new Map),this.processedNotifications$.next([]),this.notificationsByIdMap$.next(new Map),this.notificationViews$.next({}),this.setNotificationsByIdMap(),D([])):D(r).pipe(O(n=>this.docService.getDocumentPaths$().pipe(N(s=>(this.documentPaths=s,n.documentPaths=s,n)))),O(n=>this.getDataFromDocumentId(o)))))}isFeatureAllowed(t){return this.configService.getConfig$().pipe(w(i=>!!i),N(i=>T(I({},t),{config:i})),O(i=>this.authService.getUser$().pipe(N(e=>T(I({},i),{user:e})))),O(i=>Rt(i.config,i.user,Tt.NOTIFICATION)?D(T(I({},i),{featureAllowed:!0})):(this.loggingService.warn("Notification feature is not allowed."),D(T(I({},i),{featureAllowed:!1})))))}getDataFromDocumentId(t){return this.databaseService.getDb().pipe(w(i=>!!i),O(i=>{if(this.db=i,this.loggingService.log(this.db),this.configService?.getApiKey()&&this.documentPaths?.views){let e=`${this.configService.getApiKey()}`;this.documentPaths?.organizationId&&(e+=`/${P.FIREBASE_PARTIAL_PATH_ORGANIZATIONS}/${this.documentPaths.organizationId}`);let o=this.realtimeAdapter.rtdbRef(this.db,`${t?e+"/"+P.FIREBASE_PARTIAL_PATH_DOCS+"/"+t+"/"+P.FIREBASE_PARTIAL_PATH_VIEWS+"/":this.documentPaths?.notifications}`);return this.realtimeAdapter.rtdbObjectVal$("notification",o).pipe(_(r=>(this.loggingService.catch("Error in NotificationService getDataFromDocumentId: ",r),D(null))),N(r=>{let n=[],s=new Map;r?.raw&&(Object.keys(r?.raw||{}).forEach(c=>{let l=r?.raw[c];l?.id&&n.push(l)}),n.forEach(c=>{c.id&&s.set(c.id,c)})),this.notifications$.next(n),this.rawNotificationsByIdMap$.next(s);let a=[];r?.processed&&Object.keys(r?.processed||{}).forEach(c=>{let l=r?.processed[c];l?.id&&a.push(l)}),this.processedNotifications$.next(a),this.setNotificationsByIdMap()}))}else return D(null)}))}setNotificationsByIdMap(){try{let t=this.authService.getUser();if(t){let i=this.notificationViews$.getValue(),e;t?.email&&(e=R(t?.email));let o;t?.userId&&(o=R(t?.userId));let r=new Map;this.processedNotifications$.getValue().forEach(s=>{if(s.id&&s?.displayHeadlineMessageTemplate){let a=!1;(e&&s.notifyUsers?.[e]||o&&s.notifyUsers?.[o])&&(a=!0);let c={id:s.id,notificationSource:s.notificationSource,actionType:s.actionType,actionUser:s.actionUser,timestamp:s.timestamp,targetAnnotationId:s.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(s),displayBodyMessage:this.getNotificationBodyMessage(s),forYou:a,notificationSourceData:s.notificationSourceData},l=this.getRawNotificationById(c.id);if(l?.metadata&&(c.metadata={apiKey:l.metadata.apiKey,organizationId:l.metadata.organizationId,clientOrganizationId:l.metadata.clientOrganizationId,documentId:l.metadata.documentId,clientDocumentId:l.metadata.clientDocumentId,location:l?.location,locationId:l?.locationId}),c?.notificationSource==="comment"&&c?.targetAnnotationId){let g=this.commentService?.getAnnotationById(c.targetAnnotationId);g||l?.annotationData&&(g=l.annotationData),g&&(c.notificationSourceData=this.commentService?.getCommentAnnotationForClient(g))}r.set(s.id,c)}}),r.forEach((s,a)=>{s.isUnread=s?.actionUser?.userSnippylyId!==t?.userSnippylyId&&!i?.notification?.[a]?.views?.[t?.userSnippylyId],r.set(a,s)}),this.notificationsByIdMap$.next(r)}}catch(t){this.loggingService.catch("Error in NotificationService setNotificationsByIdMap: ",t)}}getClientNotificationObject({processed:t,raw:i,metadata:e,views:o,notification:r}){try{let n=this.authService.getUser(),s=r||t;if(s.id&&s?.displayHeadlineMessageTemplate&&n){let a=null;n?.email&&(a=R(n?.email));let c=null;n?.userId&&(c=R(n?.userId));let l=!1,g=!0;(a&&s.notifyUsers?.[a]||c&&s.notifyUsersByUserId?.[c])&&(l=!0),c&&o?.[c]&&(g=!1);let f={id:s.id};if(r?f=T(I(I({},f),r),{displayHeadlineMessage:this.getNotificationHeadlineMessage(r),displayBodyMessage:this.getNotificationBodyMessage(r),forYou:l,isUnread:g}):f={id:t.id,notificationSource:t.notificationSource,actionType:t.actionType,actionUser:t.actionUser,timestamp:t.timestamp,targetAnnotationId:t.targetAnnotationId,displayHeadlineMessage:this.getNotificationHeadlineMessage(t),displayBodyMessage:this.getNotificationBodyMessage(t),forYou:l,isUnread:g,metadata:e},f?.notificationSource==="comment"&&f?.targetAnnotationId){let d=this.commentService?.getAnnotationById(f.targetAnnotationId);d||r?.notificationSourceData&&(d=r?.notificationSourceData),d||i?.annotationData&&(d=i.annotationData),d&&(f.notificationSourceData=this.commentService?.getCommentAnnotationForClient(d))}return i?.targetAnnotationData?.isCommentResolverUsed&&(f.isCommentResolverUsed=i?.targetAnnotationData?.isCommentResolverUsed),r?.isNotificationResolverUsed&&(f.isNotificationResolverUsed=r.isNotificationResolverUsed),f}return}catch(n){this.loggingService.catch("Error in NotificationService getClientNotificationObject: ",n);return}}getNotificationsForYou$(){return this.notificationsForYou$.asObservable()}getNotificationsByDocumentId$(){return this.notificationsByDocumentIdMap$.asObservable().pipe(N(t=>t?Object.keys(t??{}).map(i=>{let e=t[i].notifications||[],o=e.filter(n=>n.isUnread).length,r=e.length>0&&e[0]?.timestamp||0;return{documentId:i,notifications:t[i]?.notifications,unreadNotificationsCount:o,latestNotificationTimestamp:r,documentMetadata:t[i]?.documentMetadata}}).filter(i=>i.notifications?.length>0).sort((i,e)=>e.latestNotificationTimestamp-i.latestNotificationTimestamp):null))}getAllNotifications$(){return V([this.getNotificationsByDocumentId$(),this.crossOrgNotifications$.asObservable(),this.getUserScopedAllTabRows$()]).pipe(N(([t,i,e])=>{let o=Array.isArray(i)?i:[],r=Array.isArray(e)?e:[],n=null;if(t&&(n=[],t.forEach(a=>{a.notifications.forEach(c=>{n?.push(c)})})),!o.length&&!r.length)return t?n.sort((a,c)=>c.timestamp-a.timestamp):null;if(!t)return null;let s=n||[];return r.length&&(s=this.mergeCrossOrgForYou(s,r)),o.length&&(s=this.mergeCrossOrgForYou(s,o)),s}))}getUserScopedAllTabRows$(){return V([this.userScopedNotifications$,this.userNotificationsFromServer$.asObservable()]).pipe(N(([t,i])=>!t?.enabled||!i?.length?[]:i.map(e=>e?.notification??this.getClientNotificationObject(e)).filter(e=>!!e)))}processNotificationData(t){try{let i=t?.annotationData?.metadata,e=this.docService.getOrganizationConfig()?.organizationId;t.metadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t.metadata||(t.metadata={},this.loggingService.catch("Warning in NotificationService updateNotificationDatabase: ","Document metadata not found")),delete t.metadata.locations,t.metadata.documentMetadata=JSON.parse(JSON.stringify(this.docService.getDocumentMetadata(i?.documentId)||{})),t?.metadata?.documentMetadata?.clientDocumentId&&t?.metadata?.documentMetadata?.documentId&&(t.metadata.documentMetadata.documentId=t?.metadata?.documentMetadata?.clientDocumentId),delete t.metadata.documentMetadata.locations,t.metadata.organizationMetadata=JSON.parse(JSON.stringify(e?this.docService.getOrganizationMetadata(e)||{}:{})),t?.metadata?.organizationMetadata?.clientOrganizationId&&t?.metadata?.organizationMetadata?.organizationId&&(t.metadata.organizationMetadata.organizationId=t?.metadata?.organizationMetadata?.clientOrganizationId);let o=this.configService.getApiKey();t.metadata.apiKey=o,t.platform=this.configService.getSF()?"sf":"sdk",t.actionUser=this.authService.getUser();let r=i?.documentId?new mt({apiKey:o,documentId:i.documentId,organizationId:i?.organizationId}):this.docService.getDocumentPaths();t?.actionUser?.organizationId&&(t.metadata.organizationId=r?.organizationId||t.actionUser.organizationId,t.metadata.clientOrganizationId=r?.clientOrganizationId||t.actionUser.clientOrganizationId);let n=this.docService.getLocation();n&&(t.location=n?.location,t.locationId=n?.locationId),this.loggingService.log(`[NOTIFICATION] ${t?.notificationSource} ${t?.actionType}`,t);let s=this.commonDbService.getServerTimestamp(),a=this.notificationUtilsService.formatNotification(t,s);return JSON.parse(JSON.stringify(a))}catch(i){return this.loggingService.catch("Error in NotificationService processNotificationData: ",i),null}}reportDroppedHubPush(t){try{if(!this.notificationsHubDisabled)return;let i=String(t?.notificationSource??"comment");if(this.isCarriedByPortableDeleteOp(t)||this.reportedDroppedHubPushes.has(i))return;this.reportedDroppedHubPushes.add(i),this.loggingService.catch(`Velt [self-hosted]: a client-side notification-hub push (source '${i}') was dropped \u2014 the notifications hub is deliberately disabled on this deployment (no-egress). Whatever this push fed (in-app notification, email, or webhook fan-out) will not happen for this source.`,void 0,void 0,!0)}catch{}}isCarriedByPortableDeleteOp(t){try{return t?.notificationSource==="comment"&&t?.actionType===Ct.DELETED&&!t?.annotationData?.isDraft&&!!this.adapterSelectorService?.isPortableBackendActive()}catch{return!1}}updateNotificationDatabase(t){try{if(!this.notificationsDb){this.reportDroppedHubPush(t);return}let i=this.realtimeAdapter.rtdbRef(this.notificationsDb),e=oi(t,o=>this.processNotificationData(o),o=>{this.loggingService.catch("Error applying notification visibility in updateNotificationDatabase: ",o)});this.realtimeAdapter.rtdbPush("notificationIndex",i,JSON.parse(JSON.stringify(e)))}catch(i){this.loggingService.catch("Error in NotificationService updateNotificationDatabase: ",i)}}getRawNotifications$(){return this.notifications$.asObservable()}getProcessedNotifications$(){return this.processedNotifications$.asObservable()}getNotifications$(t){return this.authService.getUser$().pipe(O(i=>i?i.organizationId?this.getAllNotifications$().pipe(O(e=>this.notificationsForYou$.pipe(N(o=>{if(e||o){let r=new Map;return(!t?.type||["all","documents"].includes(t.type))&&(e||[]).forEach(n=>{n.id&&r.set(n.id,n)}),(!t?.type||["all","forYou"].includes(t.type))&&(o||[]).forEach(n=>{n.id&&!r.has(n.id)&&r.set(n.id,n)}),Array.from(r.values()).sort((n,s)=>(s.timestamp||0)-(n.timestamp||0))}else return null})))):this.notificationsByIdMap$.asObservable().pipe(N(e=>Array.from(e.values())),N(e=>e.sort((o,r)=>r.timestamp-o.timestamp)),Nt()):D(null)),W(Bt))}getRawNotificationById(t){try{return this.rawNotificationsByIdMap$.getValue()?.get(t)}catch(i){this.loggingService.catch("Error in NotificationService getRawNotificationById: ",i);return}}setNotificationViews(t){try{this.notificationViews$.next(t),this.setNotificationsByIdMap()}catch(i){this.loggingService.catch("Error in NotificationService setNotificationViews: ",i)}}getNotificationHeadlineMessage(t){try{let i=this.authService.getUser();if(t?.displayHeadlineMessageTemplate&&t?.displayHeadlineMessageTemplateData){let e=t.displayHeadlineMessageTemplate,o=t.displayHeadlineMessageTemplateData,r=/\{(\w+)\}/g,n=e.replace(r,(s,a)=>(a==="actionUser"||a==="recipientUser")&&o[a]?i?.email&&o[a].email===i?.email||i?.userId&&o[a]?.userId===i?.userId?"You":o[a].name||o[a].email||' <velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader> ':o[a]?o[a]:s);return this.domService.sanitizeHtml(n)}return this.domService.sanitizeHtml(t.displayHeadlineMessageTemplate||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationHeadlineMessage: ",i),""}}getNotificationBodyMessage(t){try{if(t?.displayBodyMessageTemplate&&t?.displayBodyMessageTemplateData){let i=t?.displayBodyMessageTemplate;return t?.displayBodyMessageTemplateData&&t?.displayBodyMessageTemplateData?.users?.forEach(e=>{if(e?.userId){let o=this.usersService.getUserById(e?.userId);i=i?.replaceAll(`{{${e.userId}}}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>'),i=i?.replaceAll(`@User ${e.userId}`,o?.name||o?.email||'<velt-skeleton-loader width="50px" height="20px" border-radius="4px"></velt-skeleton-loader>')}}),this.domService.sanitizeHtml(i)}return this.domService.sanitizeHtml(t.displayBodyMessage||"")}catch(i){return this.loggingService.catch("Error in NotificationService getNotificationBodyMessage: ",i),""}}setHistoryPanelVisibility(t,i=!1,e=!1){try{t?document.querySelector(P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?this.historyPanelVisible$.next(t):this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`):this.historyPanelVisible$.next(t),t?this.analyticsService.trackEvent(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_OPENED):this.analyticsService.trackEvent(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_CLOSED)}catch{this.loggingService.catch("Error in NotificationService setHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}toggleHistoryPanelVisibility(t=!1,i=!1){try{this.historyPanelVisible$.value?this.historyPanelVisible$.next(!this.historyPanelVisible$.value):document.querySelector(P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL)?(this.historyPanelVisible$.next(!this.historyPanelVisible$.value),this.historyPanelVisible$.value?this.analyticsService.trackEvent(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"closed"}):this.analyticsService.trackEvent(j.Events.Notifications.NOTIFICATION_HISTORY_PANEL_TOGGLED,{action:"opened"})):this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}catch{this.loggingService.catch("Error in NotificationService toggleHistoryPanelVisibility: ",`<${P.TAGS.VELT_NOTIFICATIONS_HISTORY_PANEL}> tag is not added.`)}}getHistoryPanelVisibility$(){return this.historyPanelVisible$.asObservable()}setNotificationsAsRead(t){return y(this,null,function*(){try{let i=JSON.parse(JSON.stringify(this.getUserNotificationsFromServer()??[]));if(t?.length){for(let n=0;n<t.length;n+=50){let a=t.slice(n,n+50).filter(g=>g?.id),c=a.map(g=>this.setNotificationAsRead({notification:g,userNotifications:JSON.parse(JSON.stringify(i))})),l=yield Promise.all(c);a.forEach((g,f)=>{let d=l[f];if(!d.some(h=>h.notificationId===g.id))i=i.filter(h=>h.notificationId!==g.id);else{let h=i.find(U=>U.notificationId===g.id),A=d.find(U=>U.notificationId===g.id);h&&A?.views&&(h.views=A.views)}})}let o=JSON.parse(JSON.stringify(this.notificationsByDocumentIdMap$.getValue()||{}));t.forEach(n=>{let s=n.metadata?.documentId;if(s&&o?.[s]){let a=o?.[s]?.notifications||[],c=a.find(l=>l.id===n.id);c&&(c.isUnread=!1),o[s].notifications=a}}),this.notificationsByDocumentIdMap$.next(o),this.markCrossOrgEntriesRead(t),!X(i,this.getUserNotificationsFromServer())&&this.setUserNotificationsFromServer(i)}}catch(i){this.loggingService.catch("Error in NotificationService setNotificationsAsRead: ",i)}})}setAllNotificationsAsRead(t){return y(this,null,function*(){try{if(t?.tabId==="for-you"){let i=this.notificationsForYou$.value||[];this.setNotificationsAsRead(i)}else this.getNotifications$().pipe(k(1)).subscribe(i=>{i&&this.setNotificationsAsRead(i)})}catch(i){this.loggingService.catch("Error in NotificationService setAllNotificationsAsRead: ",i)}})}getUnreadNotificationsCount$(){try{return this.notificationsForYou$.pipe(N(t=>t?.filter(e=>e?.isUnread)?.length??null),O(t=>this.getNotifications$().pipe(N(i=>{let e=i?.filter(o=>o?.isUnread)?.length??null;return{forYou:t,all:e}}))))}catch(t){return this.loggingService.catch("Error in NotificationService getUnreadNotificationsCount$: ",t),D({forYou:null,all:null})}}setNotificationAsRead(e){return y(this,arguments,function*({notification:t,userNotifications:i}){try{let o=this.authService.getUser();if(o&&t?.id){let r=R(o?.userId),{metadata:n}=t;if(n){let{apiKey:s,organizationId:a,documentId:c}=n;if(s&&a&&c&&r){let l=yield this.commonDbService.getData({feature:"docNotification",properties:{id:t.id,organizationId:a,documentId:c,apiKey:s}});l?.notificationId&&(l?.views?.[r]||(l.views||(l.views={}),l.views[r]={timestamp:Date.now()},this.commonDbService.updateData({feature:"docNotificationViews",properties:{id:t.id,organizationId:a,documentId:c,apiKey:s},data:l})));let g=yield this.commonDbService.getData({feature:"userNotification",properties:{id:t.id,userId:r,documentId:c,organizationId:a}});if(g?.notificationId){if(!this.getReadNotificationsOnForYouTab())yield this.commonDbService.deleteData({feature:"userNotification",properties:{id:t.id,userId:r,documentId:c,organizationId:a}}),i=i.filter(f=>f.notificationId!==t.id);else if(!g?.views?.[r]){g.views||(g.views={}),g.views[r]={timestamp:Date.now()};let f=i.find(d=>d.notificationId===t.id);f&&(f.views=g.views),this.commonDbService.updateData({feature:"userNotificationViews",properties:{id:t.id,userId:r,documentId:c,organizationId:a},data:g})}}}}}return i}catch(o){return this.loggingService.catch("Error in NotificationService setNotificationAsRead: ",o),i}})}setMaxDays(t){try{t>0?this.maxNotificationDays$.next(t):this.maxNotificationDays$.next(15)}catch(i){this.loggingService.catch("Error in NotificationService setMaxDays: ",i)}}setTabConfig(t){try{t&&this.tabConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setTabConfig: ",i)}}getTabConfig$(){return this.tabConfig$.asObservable()}getTabConfig(){return this.tabConfig$.value}enableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!0)}disableReadNotificationsOnForYouTab(){this.readNotificationsOnForYouTab$.next(!1)}getReadNotificationsOnForYouTab$(){return this.readNotificationsOnForYouTab$.asObservable()}getReadNotificationsOnForYouTab(){return this.readNotificationsOnForYouTab$.value}enableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!0)return;this.currentDocumentOnly$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableCurrentDocumentOnly: ",t)}}disableCurrentDocumentOnly(){try{if(this.currentDocumentOnly$.value===!1)return;this.currentDocumentOnly$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableCurrentDocumentOnly: ",t)}}getCurrentDocumentOnly$(){return this.currentDocumentOnly$.asObservable()}getCurrentDocumentOnly(){return this.currentDocumentOnly$.value}markNotificationAsReadById(t){return y(this,null,function*(){try{this.getNotifications$().pipe(k(1)).subscribe(i=>{if(i){let e=i.filter(o=>o.id===t);this.setNotificationsAsRead(e)}})}catch(i){this.loggingService.catch("Error in NotificationService markNotificationAsReadById: ",i)}})}getOwnDocumentMetadata(t){try{let i=t==null||t===""?null:this.docService.getDocumentMetadata(String(t));return i?JSON.parse(JSON.stringify(i)):null}catch(i){return this.loggingService.catch("Error in NotificationService getOwnDocumentMetadata: ",i),null}}getAllowedDocumentMetadataByDocumentId(t){try{return this.allowedDocumentMetadataMap$.value?.[t]||null}catch(i){return this.loggingService.catch("Error in NotificationService getAllowedDocumentMetadataByDocumentId: ",i),null}}setSettingsConfig(t){try{this.enableSettings$.value&&this.settingsConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfig: ",i)}}setSettingsConfigWithDB(t){try{this.enableSettings$.value&&(this.settingsConfig$.next(t),this.updateSettingsConfigToDb())}catch(i){this.loggingService.catch("Error in NotificationService setSettingsConfigWithDB: ",i)}}getSettingsConfig$(){return this.settingsConfig$.asObservable()}getSettingsConfig(){return this.settingsConfig$.value}setMuteAllNotifications(){try{this.muteAllNotifications$.value!==!0&&this.muteAllNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService setSettingsMuteAll: ",t)}}getMuteAllNotifications$(){return this.muteAllNotifications$.asObservable()}getMuteAllNotifications(){return this.muteAllNotifications$.value}enableSettings(){try{this.enableSettings$.value!==!0&&this.enableSettings$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettings: ",t)}}enableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!0&&this.setSettingsConfigByOrganization$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSettingsConfigByOrganization: ",t)}}disableSettingsConfigByOrganization(){try{this.getSettingsConfigByOrganization()!==!1&&this.setSettingsConfigByOrganization$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettingsConfigByOrganization: ",t)}}getSettingsConfigByOrganization$(){return this.setSettingsConfigByOrganization$.asObservable()}getSettingsConfigByOrganization(){return this.setSettingsConfigByOrganization$.value}enableSelfNotifications(){try{this.selfNotifications$.value!==!0&&this.selfNotifications$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService enableSelfNotifications: ",t)}}disableSelfNotifications(){try{this.selfNotifications$.value!==!1&&this.selfNotifications$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSelfNotifications: ",t)}}enableUserScopedNotifications(t){try{if(t&&typeof t=="object"&&t.enabled===!1){this.disableUserScopedNotifications();return}this.userScopedNotifications$.next({enabled:!0,limit:ui(t?.limit)})}catch(i){this.loggingService.catch("Error in NotificationService enableUserScopedNotifications: ",i)}}disableUserScopedNotifications(){try{this.userScopedNotifications$.value.enabled!==!1&&this.userScopedNotifications$.next({enabled:!1,limit:this.userScopedNotifications$.value.limit})}catch(t){this.loggingService.catch("Error in NotificationService disableUserScopedNotifications: ",t)}}disableSettings(){try{this.enableSettings$.value!==!1&&this.enableSettings$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService disableSettings: ",t)}}getEnableSettings$(){return this.enableSettings$.asObservable()}getEnableSettings(){return this.enableSettings$.value}setSettingsInitialConfig(t){try{let i=!1;if(t.forEach(e=>{["email","inbox"].includes(e.id)&&(i=!e.values?.every(o=>["ALL","NONE","MINE"].includes(o.id)))}),i){this.loggingService.catch("Invalid config values for email or inbox, It should have only ALL, NONE, MINE values");return}this.settingsInitialConfig$.next(t)}catch(i){this.loggingService.catch("Error in NotificationService setSettingsInitialConfig: ",i)}}getSettingsInitialConfig$(){return this.settingsInitialConfig$.asObservable()}getSettingsInitialConfig(){return this.settingsInitialConfig$.value}updateSettingsConfigToDb(t){return y(this,null,function*(){try{let i=this.authService.getUser(),e=R(i?.userId??""),o=this.docService.getDocumentPaths(),r=this.docService.getOrganizationConfig(),n=o?.organizationId??r?.organizationId,s=o?.clientOrganizationId??r?.clientOrganizationId,a={apiKey:this.configService.getApiKey(),organizationId:n,documentId:o?.documentId,clientOrganizationId:s,clientDocumentId:o?.clientDocumentId,userId:e,clientUserId:this.authService.getUser()?.userId};e&&this.getEnableSettings()&&this.enableSettings$.value&&(this.getSettingsConfigByOrganization()?this.docService.addUserInfoToOrganization({organizationId:s??i?.clientOrganizationId??"",user:{userId:i?.userId??""},notificationsConfig:t||this.settingsConfig$.getValue()}):o?.documentId&&(yield this.commonDbService.updateData({feature:"userConfig",properties:I({documentId:o?.documentId,userId:e},this.commonDbService?.isPortableSession?.()===!0?{id:o.documentId}:{}),data:{id:o?.documentId,notificationsConfig:t||this.settingsConfig$.getValue(),metadata:a}})))}catch(i){this.loggingService.catch("Error in NotificationService updateSettingsConfigToDb: ",i)}})}openNotificationsPanel(){try{this.notificationsPanelVisible$.next(!0)}catch(t){this.loggingService.catch("Error in NotificationService openNotificationsPanel: ",t)}}closeNotificationsPanel(){try{this.notificationsPanelVisible$.next(!1)}catch(t){this.loggingService.catch("Error in NotificationService closeNotificationsPanel: ",t)}}getNotificationsPanelVisible$(){return this.notificationsPanelVisible$.asObservable()}getNotificationsPanelVisible(){return this.notificationsPanelVisible$.value}};m.\u0275fac=function(i){return new(i||m)(S(yt),S(Yt),S(et),S(Gt),S(ni),S(si),S(st),S(rt),S(nt),S(Qt),S(ai),S(ei),S(ci),S(it),S(gi),S(ot),S(Dt),S(li),S(ii),S(tt),S(Zt),S(qt))},m.\u0275prov=J({token:m,factory:m.\u0275fac,providedIn:"root"});let v=m;return v})();export{gi as a,ge as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Ra as s,Za as a,Zc as c,
|
|
1
|
+
import{Ra as s,Za as a,Zc as c,yk as n}from"./chunk-SKSZYHHP.js";var f=(()=>{let i=class i{constructor(t,r){this.domService=t,this.sanitizer=r}transform(t,r=!0){try{let o=r?this.domService.sanitizeHtml(t):t;return this.sanitizer.bypassSecurityTrustHtml(o)}catch{return t}}};i.\u0275fac=function(r){return new(r||i)(s(n,16),s(c,16))},i.\u0275pipe=a({name:"safeHtml",type:i,pure:!0});let e=i;return e})();export{f as a};
|