@veltdev/sdk 6.0.25 → 6.0.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/app/models/element/comment-element.model.d.ts +5 -2
- package/app/utils/constants.d.ts +8 -0
- package/{chunk-TMLYEZEQ.js → chunk-2C7WPTQD.js} +1 -1
- package/{chunk-ZH5R4MP6.js → chunk-2MYJTN75.js} +1 -1
- package/{chunk-JICLHDU3.js → chunk-4CPJN52I.js} +1 -1
- package/{chunk-G3BZ4EU4.js → chunk-4GWTY2QW.js} +1 -1
- package/{chunk-YRE3NGCE.js → chunk-4JE45AVC.js} +1 -1
- package/chunk-72TEWHMQ.js +1 -0
- package/{chunk-2JSXDPYO.js → chunk-7J6SWBKB.js} +1 -1
- package/{chunk-DLN23S5M.js → chunk-ABA7YQYU.js} +1 -1
- package/{chunk-UFOCUTLN.js → chunk-BTJTZEPV.js} +1 -1
- package/{chunk-FJ6KQ3QL.js → chunk-CXZSNTWV.js} +1 -1
- package/{chunk-VYZZWZPY.js → chunk-DF2C2V7B.js} +1 -1
- package/chunk-DKI2JSNJ.js +6 -0
- package/{chunk-BJ5O5D7F.js → chunk-FHFEI7VF.js} +1 -1
- package/chunk-G6V3RCTP.js +1 -0
- package/{chunk-7O3OJVW3.js → chunk-HV37SAIK.js} +1 -1
- package/{chunk-AP33ZJ2C.js → chunk-IVZBIMXH.js} +1 -1
- package/{chunk-CNB6D3KX.js → chunk-J3DYWDYQ.js} +25 -25
- package/{chunk-LM54BOTU.js → chunk-JR3BVUP3.js} +1 -1
- package/{chunk-AWNCHHGK.js → chunk-K6LCTVYG.js} +1 -1
- package/{chunk-GB46XS3O.js → chunk-KHGHU7FE.js} +1 -1
- package/chunk-KWZM6CNH.js +1 -0
- package/{chunk-B3ZPP3EZ.js → chunk-M3XIT6ZY.js} +1 -1
- package/chunk-NZUJK3CJ.js +1 -0
- package/{chunk-MEI3IAPO.js → chunk-PBA6NIAI.js} +1 -1
- package/{chunk-FJAMH4UH.js → chunk-PIBUTN6R.js} +1 -1
- package/{chunk-LCACRBV3.js → chunk-QQIKH4VS.js} +1 -1
- package/chunk-T32PAZYN.js +193 -0
- package/{chunk-VX7YLWTK.js → chunk-UKCZENKX.js} +1 -1
- package/{chunk-JAKGBQ5D.js → chunk-V2VL4H4R.js} +1 -1
- package/{chunk-W47H5WHD.js → chunk-WBOPOSCN.js} +1 -1
- package/{chunk-CLRO2X6T.js → chunk-WNH4SCIB.js} +1 -1
- package/chunk-WWK6NPFJ.js +1 -0
- package/{chunk-R4FWZKFA.js → chunk-YI3LAD3Z.js} +1 -1
- package/{chunk-NJW4C3A2.js → chunk-YUGCY3BB.js} +1 -1
- package/{chunk-NNZNLREA.js → chunk-Z7CCKSEO.js} +1 -1
- package/{chunk-6BTXSFDP.js → chunk-ZVRUGR3J.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 +1 -1
- package/velt-selection.js +1 -1
- package/velt-tag.js +1 -1
- package/velt-user-invite.js +1 -1
- package/velt-user-request.js +1 -1
- package/velt-video-player.js +1 -1
- package/velt-views.js +3 -3
- package/velt.js +2 -2
- package/chunk-BR7AO7YV.js +0 -1
- package/chunk-CCZ3WXF4.js +0 -1
- package/chunk-IXIU5ZJS.js +0 -1
- package/chunk-JPOBXW24.js +0 -1
- package/chunk-NY2Q7SEG.js +0 -6
- package/chunk-TN7X7OZD.js +0 -1
- package/chunk-Z7JR4TW6.js +0 -193
package/chunk-CCZ3WXF4.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Fa as F}from"./chunk-NY2Q7SEG.js";import{C,D as w}from"./chunk-BR7AO7YV.js";import{E as h,G as d,Gi as D,He as $,K as v,M as l,Nj as k,V as n,_f as g,ba as A,bi as I,ck as U,ea as s,l as p,nf as M,nj as E,oj as R,pj as y,r as u,v as c,we as a,xe as m}from"./chunk-CNB6D3KX.js";var Z=(()=>{let o=class o{constructor(e,t,r,b,f,W,T,j){this.analyticsService=e,this.authService=t,this.contactService=r,this.databaseService=b,this.docService=f,this.configService=W,this.loggingService=T,this.commonDbService=j,this.documentIAM$=new p(null),this.workspaceIAM$=new p(null),this.roles$=new p([]),this.getDocumentIamSubscription=null,this.getOrganizationIamSubscription=null,this.getWorkspaceIamSubscription=null;try{this.authService.setIamService(this),this.databaseService.getDb().pipe(h(i=>!!i),v(1)).subscribe(i=>{i&&(this.getUser(),this.getDocumentPaths())},i=>{this.loggingService.catch("Error in CommentService getDb subscription: ",i)}),this.getRole$().pipe(v(1)).subscribe(i=>{this.authService?.getUser()&&!i&&this.analyticsService.trackEvent(D.Events.Iam.USER_ACCESS_DENIED)}),this.documentIAM$.subscribe(i=>{i?.accessType&&this.contactService.setDocumentAccessType(i.accessType)})}catch(i){this.loggingService.catch("Error in IamService constructor: ",i)}}clearCache(){this.loggingService.log("%c[WB] Calling FUNCTION: clearCache in IamService","color: green;");try{this.documentIAM$.next(null),this.workspaceIAM$.next(null),this.roles$.next([]),this.documentPaths=null}catch(e){this.loggingService.catch("Error in IamService clearCache: ",e)}}getUser(){try{this.authService.getUser$().pipe(h(e=>!!e)).subscribe(e=>{this.user=e,this.user?this.getDocumentIam():(this.getDocumentIamSubscription?.unsubscribe(),this.getOrganizationIamSubscription?.unsubscribe(),this.getWorkspaceIamSubscription?.unsubscribe())},e=>{this.loggingService.catch("Error in IamService getUser$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getUser: ",e)}}getDocumentPaths(){try{this.docService.getDocumentPaths$().pipe(h(e=>!!e)).subscribe(e=>{this.documentPaths=e,this.getDocumentIam(),this.getWorkspaceIam()},e=>{this.loggingService.catch("Error in IamService getDocumentPaths$ subscription: ",e)})}catch(e){this.loggingService.catch("Error in IamService getDocumentPaths: ",e)}}getDocumentIam(){try{this.getDocumentIamSubscription&&(this.getDocumentIamSubscription.unsubscribe(),this.getDocumentIamSubscription=null),this.user?this.getDocumentIamSubscription=this.docService.getDocumentIam$().subscribe(e=>{let t=e||new M;this.documentIAM$.next(t)},e=>{this.loggingService.catch("Error in IamService getDocumentIam$ subscription: ",e)}):this.documentIAM$.next(null)}catch(e){this.loggingService.catch("Error in IamService getDocumentIam: ",e)}}getWorkspaceIam(){try{this.getWorkspaceIamSubscription||(this.getWorkspaceIamSubscription=this.commonDbService.dbListener({feature:"workspaceIam",properties:{skipFirestore:!0}}).pipe(d(e=>u(null))).subscribe(e=>{this.workspaceIAM$.next(e?.data),this.roles$.next(e?.data?.roles||[])}))}catch(e){this.loggingService.catch("Error in IamService getWorkspaceIam: ",e)}}isUserAllowed$(){return this.getRole$().pipe(c(e=>!!e),l())}getDocumentIAM$(){return this.documentIAM$.asObservable()}getRoles$(){return this.roles$.asObservable().pipe(c(e=>e?.length?e:$.WorkspaceRoles))}getFeaturesAccessLevel$(){return this.documentIAM$.asObservable().pipe(c(e=>e?.features),n(e=>this.getRole$().pipe(c(t=>(t===a.ADMIN&&(e=e&&JSON.parse(JSON.stringify(e||{})),e?.all?.disabled&&(e.all.disabled=!1)),e)))))}hasRole(e){try{return e===this.getRole()}catch(t){return this.loggingService.catch("Error in IamService hasRole: ",t),!1}}hasRoleAny(e=[]){try{return e?.includes(this.getRole()||"")}catch(t){return this.loggingService.catch("Error in IamService hasRoleAny: ",t),!1}}hasRole$(e){try{return this.authService.getUser$().pipe(n(()=>this.documentIAM$.pipe(h(t=>!!t),n(()=>this.workspaceIAM$.pipe(c(()=>e===this.getRole()))))))}catch(t){return this.loggingService.catch("Error in IamService hasRole$: ",t),u(!1)}}getRole$(){try{return this.authService.getUser$().pipe(n(()=>this.configService.getSF$()),n(()=>this.configService.getSF()?this.contactService.isUserGlobalContact$():u(null)),n(()=>this.configService.getSF()?this.documentIAM$.pipe(h(e=>!!e),l(I)):u(null)),n(()=>this.workspaceIAM$.pipe(l(I))),c(()=>this.getRole()))}catch(e){return this.loggingService.catch("Error in IamService getRole$: ",e),u(null)}}getRole(){try{let e=this.configService.getSF();if(this.user?.isAdmin)return a.ADMIN;return a.COMMENTER;if(this.user)switch((this.documentIAM$.value?this.documentIAM$.value?.features?.all?.restricted:!1)?m.RESTRICTED:this.documentIAM$.value?this.documentIAM$.value?.documentAccessType||m.PUBLIC:null){case m.PUBLIC:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||a.COMMENTER;break;case m.RESTRICTED:r=this.getUserFromDocumentIAM(this.user?.email,this.user?.userId),r||(r=this.getUserFromWorkspaceIAM(this.user?.email,this.user?.userId)),t=r?.role?.name||null;break;default:break}}catch(e){this.loggingService.catch("Error in IamService getRole: ",e)}return null}isUserAdmin$(){return this.getRole$().pipe(c(e=>e===a.ADMIN),l())}isUserAdmin(){try{return this.getRole()===a.ADMIN}catch(e){return this.loggingService.catch("Error in IamService isUserAdmin: ",e),!1}}getUserFromDocumentIAM(e,t){try{if(e||t){let r;return e&&(r=this.documentIAM$.value?.users?.[g(e)]),!r&&t&&(r=this.documentIAM$.value?.users?.[g(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromDocumentIAM: ",r)}}getUserFromWorkspaceIAM(e,t){try{if(e||t){let r;return e&&(r=this.workspaceIAM$.value?.users?.[g(e)]),!r&&t&&(r=this.workspaceIAM$.value?.users?.[g(t)]),r}else return}catch(r){this.loggingService.catch("Error in IamService getUserFromWorkspaceIAM: ",r)}}};o.\u0275fac=function(t){return new(t||o)(s(E),s(U),s(F),s(k),s(w),s(y),s(R),s(C))},o.\u0275prov=A({token:o,factory:o.\u0275fac,providedIn:"root"});let S=o;return S})();export{Z as a};
|
package/chunk-IXIU5ZJS.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as $,c as z,d as U,e as H,f as j}from"./chunk-AP33ZJ2C.js";import{A as J,b as Y,n as O,q as Z}from"./chunk-BR7AO7YV.js";import{Ej as _,Gi as k,He as K,Ie as V,Rj as G,Sj as q,Vj as M,Wj as W,Yd as S,Zj as X,_d as E,_j as Q,a as b,ba as A,bf as x,ck as T,ea as g,ee as R,g as p,i as L,na as N,oj as y,pj as w,qj as C,sa as P,ug as F}from"./chunk-CNB6D3KX.js";var de=1e4,pe=6e4,ee=3e4,ge=3e4,me=900*1e3;function te(s){let n=Math.max(0,Math.min(Math.floor(Number.isFinite(s)?s:1)-1,16));return Math.min(ge*2**n,me)}var fe=3600*1e3,re=250,ie=1200*1e3,Ae=1024,Se={fetch:(s,n)=>fetch(s,n)},ve="The browser could not send the file to the storage URL the gateway signed. The usual cause is the storage account's CORS rules, which must allow this page's origin for PUT; they are set by the operator of the deployment, not by the SDK.",oe="The browser could not read the file from the storage URL the gateway signed. The usual cause is the storage account's CORS rules, 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 be(s,n,d){let e={organizationId:n,documentId:d};return typeof s?.name=="string"&&s.name.length>0&&s.name.length<=Ae&&(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 ye(s){return typeof s=="string"&&/^[A-Za-z0-9._-]{1,128}$/.test(s)&&!/^\.+$/.test(s)}function we(s){return!!s&&typeof s=="object"&&!Array.isArray(s)&&Object.values(s).every(n=>typeof n=="string")}function Te(s){let n=s;return!n||typeof n!="object"||!ye(n.attachmentId)||typeof n.key!="string"||!n.key||typeof n.url!="string"||!C(n.url)||n.method!=="PUT"||!we(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 Ie(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 Pe(s,n,d){let e=Number.isFinite(s)?s-(n+(Number.isFinite(d)?d:0)):0;return n+Math.min(Math.max(e,0),fe)}var se=(()=>{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(W)}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",be(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=Te(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 ${ie/6e4} minutes`))},ie)});try{let o=yield Promise.race([Se.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}. ${ve}`);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=Ie(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:Pe(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-pe||t-e.receivedAtMs<ee}inFailureBackoff(e,t){let r=this.urlFailures.get(e);return r!==void 0&&t-r.at<te(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),te(t)+50)}pruneUrlCache(e){if(!(this.urlCache.size<re)){for(let[t,r]of Array.from(this.urlCache))e>=r.expiresAtMs&&e-r.receivedAtMs>=ee&&this.urlCache.delete(t);for(let t of Array.from(this.urlCache.keys())){if(this.urlCache.size<2*re)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 M()?.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=G(()=>{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=M()?.realtime??null;if(!e||e===this.hookedRealtime)return;this.offCapabilities?.(),this.hookedRealtime=e,this.attachmentsAnnounced=e.hasCapability?.(_)===!0,this.offCapabilities=e.onCapabilitiesChanged?.(t=>{this.attachmentsAnnounced=!!t&&typeof t.has=="function"&&t.has(_),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 q(de)),this.selector.isPortableBackendActive()===!0)}catch(e){return this.loggingService.catch("Error in PortableAttachmentStorageService waitForActiveBackend: ",e,void 0,!0),!1}})}callOp(e,t){let r=this.selector.resolveDbAdapter(),i=r?.[e];return typeof i!="function"?Promise.resolve({ok:!1,code:"unimplemented",message:`the portable adapter does not implement '${e}'`}):i.call(r,{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)}Y(e,t,{logCatch:(i,l)=>this.loggingService.catch(i,l,void 0,!0),reported:this.reportedOpFailures,isOutcomeUnknown:J})}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 ae=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 Q.sanitize(s,n)}catch(n){return S.catch("Error in File utils sanitizeSvg: ",n),""}},le=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}},ce=(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 he=(()=>{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 rt=(()=>{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=ce(t,`${r.attachmentId}_${le(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=ae(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. ${oe}`),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(X),g(y),g(Z),g(he),g(se))},n.\u0275prov=A({token:n,factory:n.\u0275fac,providedIn:"root"});let s=n;return s})();export{se as a,rt as b};
|
package/chunk-JPOBXW24.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Fa as ce}from"./chunk-NY2Q7SEG.js";import{C as oe,D as ne,k as re,l as se,o as te,r as ie}from"./chunk-BR7AO7YV.js";import{$f as A,Gi as S,He as D,Hi as $,M as b,Pf as E,Qd as W,Qf as u,Wj as Z,Zj as Q,_f as L,a as f,b as y,ba as K,bg as N,bi as z,cg as T,ck as ee,ea as R,ee as v,ei as j,fa as M,fi as J,g,ii as X,jg as B,ki as G,l as _,mi as V,oj as H,pj as q,sf as U,tf as P,tj as Y,uf as p,ug as F,v as x}from"./chunk-CNB6D3KX.js";var C="public",k=100,Ne=(()=>{let I=class I{constructor(e,r,s,t,o,i,c,a,n,d){this.authService=e,this.docService=r,this.loggingService=s,this.commonDbService=t,this.usersService=o,this.commentUtilsService=i,this.coreActionsService=c,this.functions=a,this.configService=n,this.contactService=d,this.endpointsService=M(Y),this.adapterSelectorService=M(Z),this.currentUserPermissions$=new _(null),this.permissionsCache$=new _(null),this.permissionProvider$=new _(null),this.clientResolverProdWarned=!1,this.clientResolverNoResolverWarned=!1,this.requestKeyedPermissionsCache=new Map,this.inFlightPermissionsRequests=new Map,this.permissionsCacheGeneration=0,this.REVOKE_DELAY_MS=3e3,this.pendingRevokeRequests=new Map,this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="",this.reportedUnknownFolderErrorCodes=new Set;try{this.docService.setUserPermissionService(this),this.authService.setUserPermissionService(this),this.commentUtilsService.setUserPermissionService(this),this.contactService.setUserPermissionService(this)}catch(h){this.loggingService.catch("Error in UserPermissionService constructor:",h)}}ngOnDestroy(){try{this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(e){this.loggingService.catch("Error in UserPermissionService ngOnDestroy:",e)}}collectRevokeRequest(e,r,s,t,o,i){try{return e.find(a=>a.resourceId===s&&a.type===t&&a.organizationId===o&&a.userId===i)?(r.push({userId:i,resourceId:s,organizationId:o,type:t,hasAccess:!1}),e.filter(a=>!(a.resourceId===s&&a.type===t&&a.organizationId===o&&a.userId===i))):e}catch(c){return this.loggingService.catch("Error in UsersPermissionService collectRevokeRequest:",c),e}}hasUserContextAccess({userId:e,accessFields:r}){try{if(!this.getIsContextEnabled()||r.includes(D.DEFAULT_VELT_CONTEXT))return!0;let s=r.filter(o=>!B(o));if(!s.length){if(r.some(c=>c.startsWith(D.VISIBILITY_ORG_PREFIX)))return!0;let i=`${D.VISIBILITY_SELF_PREFIX}${L(e).toString()}`;return r.includes(i)}let t=this.contactService.getUserAccessFieldsByUserId(e);return t?.length?s.every(o=>t.includes(o)):!0}catch(s){return this.loggingService.catch("Error in UserPermissionService hasUserContextAccess:",s),!1}}isMetadataProbeUnanswerable(e){try{return this.adapterSelectorService?.isPortableBackendActive()?!re(e)&&!se(e):!1}catch(r){return this.loggingService.catch("Error in UserPermissionService isMetadataProbeUnanswerable: ",r),!1}}organizationDetails(e){return g(this,null,function*(){try{if(this.isMetadataProbeUnanswerable("organizationMetadata"))return{error:!1};let r=yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{organizationId:e,suppressError:!0}});return r&&r?.errorCode?{errorCode:u.PERMISSION_DENIED,error:!0}:r&&!r?.metadata?{errorCode:u.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(r){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",r),{errorCode:u.SOMETHING_WENT_WRONG,error:!0}}})}documentDetails(s){return g(this,arguments,function*({documentId:e,organizationId:r}){try{if(this.isMetadataProbeUnanswerable("documentMetadata"))return{error:!1};let t=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:r,suppressError:!0}});if(t&&t?.errorCode)return{errorCode:u.PERMISSION_DENIED,error:!0};if(t&&!t?.metadata)return{errorCode:u.DOES_NOT_EXIST,error:!0};let o=this.docService.getDocumentMetadata(e)??{};this.docService.setDocumentMetadata(e,f(f({},o),t?.metadata??{}));let i,c=t?.metadata?.veltFolderId;if(c)try{i=(yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:c,organizationId:r}}))?.folderIamConfig?.accessType}catch(a){this.loggingService.catch("Error fetching folder accessType for document:",a)}return i||(i=t?.docIamConfig?.accessType),{error:!1,accessType:i}}catch(t){return this.loggingService.catch("Error in UserPermissionService documentDetails:",t),{errorCode:u.SOMETHING_WENT_WRONG,error:!0}}})}folderDetails(s){return g(this,arguments,function*({folderId:e,organizationId:r}){try{if(this.isMetadataProbeUnanswerable("folderMetadata"))return{error:!1};let t=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:r,suppressError:!0}});return t&&t?.errorCode?{errorCode:u.PERMISSION_DENIED,error:!0}:t&&!t?.metadata?{errorCode:u.DOES_NOT_EXIST,error:!0}:{error:!1,accessType:t?.folderIamConfig?.accessType}}catch(t){return this.loggingService.catch("Error in UserPermissionService folderDetails:",t),{errorCode:u.SOMETHING_WENT_WRONG,error:!0}}})}getUserPermissions(e){return g(this,null,function*(){let r=this.permissionsCacheGeneration;try{if(!this.authService.getUser())return this.loggingService.catch("User not set. [source: getUserPermissions]",void 0,void 0,!0),{};let s=this.authService.getUser()?.userId,t=this.extractResourceIds(e);if(!t.clientOrganizationId||!t.organizationId)return this.loggingService.catch("Client organization id or organization id not set during getUserPermissions",void 0,void 0,!0),{};let o=yield this.validateResources(t),[i,c]=yield this.fetchUserPermissionsFromDB(t),a=this.authService.getUser()?.userId;if(s!==a)return{};let n=this.buildPermissionsResponse(t,o,i,c);if(Object.keys(n).length>0){if(!e)this.setCurrentUserPermissions(n);else if(this.permissionsCacheGeneration===r){let d=this.buildPermissionsCacheKey(e);d!==null&&this.requestKeyedPermissionsCache.set(d,JSON.parse(JSON.stringify(n)))}}return n}catch(s){return this.loggingService.catch("Error in UserPermissionService getUserPermissions:",s),{}}})}getUserPermissionsFromCacheOrFetch(e){return g(this,null,function*(){try{if(!e)return yield this.getUserPermissions(e);let r=this.buildPermissionsCacheKey(e);if(r===null)return yield this.getUserPermissions(e);let s=this.permissionsCacheGeneration,t=this.requestKeyedPermissionsCache.get(r);if(t)return JSON.parse(JSON.stringify(t));let o=this.inFlightPermissionsRequests.get(r);if(o){let a=yield o;return this.permissionsCacheGeneration!==s?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(a))}let i=this.getUserPermissions(e);this.inFlightPermissionsRequests.set(r,i),i.finally(()=>{this.inFlightPermissionsRequests.get(r)===i&&this.inFlightPermissionsRequests.delete(r)}).catch(()=>{});let c=yield i;return this.permissionsCacheGeneration!==s?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(c))}catch(r){return this.loggingService.catch("Error in UserPermissionService getUserPermissionsFromCacheOrFetch:",r),{}}})}clearRequestKeyedPermissionsCache(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService clearRequestKeyedPermissionsCache:",e)}}invalidateAllPermissionsState(){try{this.requestKeyedPermissionsCache.clear(),this.inFlightPermissionsRequests.clear(),this.permissionsCacheGeneration++}catch(e){this.loggingService.catch("Error in UserPermissionService invalidateAllPermissionsState:",e)}}buildPermissionsCacheKey(e){try{let r={};return Object.keys(e).sort().forEach(s=>{let t=e[s];t!==void 0&&(r[s]=Array.isArray(t)?[...t].sort():t)}),r.__userId=this.authService.getUser()?.userId??null,JSON.stringify(r)}catch(r){return this.loggingService.catch("Error in UserPermissionService buildPermissionsCacheKey:",r),null}}extractResourceIds(e){let r=this.docService.getDocumentPaths(),s=this.docService.getDocumentIds();if(e){let i=e.organizationId??r?.clientOrganizationId;return{folderIds:e.folderIds??[],documentIds:e.documentIds??[],clientOrganizationId:i,organizationId:i?N(i):void 0}}let t=r?.clientOrganizationId;return{folderIds:r?.folderId?[r.folderId]:[],documentIds:s.map(i=>i.clientDocumentId),clientOrganizationId:t,organizationId:t?N(t):void 0}}validateResources(e){return g(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:t,clientOrganizationId:o}=e,i=[],c=[],a=r.length>0||s.length>0;t&&!a&&(i.push(this.organizationDetails(t)),c.push({id:o??"",type:"organization"})),r.forEach(l=>{i.push(this.folderDetails({folderId:T(l),organizationId:t??""})),c.push({id:l,type:"folder"})}),s.forEach(l=>{i.push(this.documentDetails({documentId:A(l),organizationId:t??""})),c.push({id:l,type:"document"})});let[n,d]=yield Promise.all([Promise.allSettled(i),this.getDefaultDocumentAccessType()]),h=this.processValidationResults(n,c);return y(f({},this.suppressResolverGrantedFailures(h,o)),{defaultDocumentAccessType:d})})}suppressResolverGrantedFailures(e,r){try{let s=this.authService.getUser()?.userId;if(!s)return e;let t=this.getPermissionsCache()??[];if(t.length===0)return e;let o=(n,d,h)=>t.some(l=>l?.userId===s&&l?.resourceId===n&&l?.type===d&&(!h||l?.organizationId===h)&&l?.hasAccess===!0),i=e.failedDocumentIds.filter(n=>!(n.errorCode===u.PERMISSION_DENIED&&o(n.id,p.DOCUMENT,r))),c=e.failedFolderIds.filter(n=>!(n.errorCode===u.PERMISSION_DENIED&&o(n.id,p.FOLDER,r))),a=e.failedOrganizationId;return a&&a.errorCode===u.PERMISSION_DENIED&&r&&o(r,p.ORGANIZATION,r)&&(a=void 0),{failedFolderIds:c,failedDocumentIds:i,failedOrganizationId:a,folderAccessTypes:e.folderAccessTypes,documentAccessTypes:e.documentAccessTypes}}catch(s){return this.loggingService.catch("Error in UserPermissionService suppressResolverGrantedFailures:",s),e}}getDefaultDocumentAccessType(){return g(this,null,function*(){try{return(yield this.commonDbService?.getData({feature:"apiKeyMetadata",properties:{}}))?.defaultDocumentAccessType}catch(e){this.loggingService.catch("Error fetching defaultDocumentAccessType:",e);return}})}processValidationResults(e,r){let s=[],t=[],o,i={},c={};for(let a=0;a<e.length;a++){let n=e[a],d=r[a];if(n.status==="rejected"||n.status==="fulfilled"&&n.value.error){let l=n.status==="fulfilled"?n.value.errorCode??u.SOMETHING_WENT_WRONG:u.SOMETHING_WENT_WRONG,m={id:d.id,errorCode:l};switch(d.type){case"organization":if(o=m,l===u.DOES_NOT_EXIST)throw new Error(`Organization with id '${d.id}' does not exist`);break;case"folder":s.push(m);break;case"document":t.push(m);break}}else if(n.status==="fulfilled")switch(d.type){case"folder":n.value.accessType&&(i[d.id]=n.value.accessType);break;case"document":n.value.accessType&&(c[d.id]=n.value.accessType);break}}return{failedFolderIds:s,failedDocumentIds:t,failedOrganizationId:o,folderAccessTypes:i,documentAccessTypes:c}}fetchUserPermissionsFromDB(e){return g(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:t}=e,o=[this.authService.getUser()?.userId??""],i=[...r.map(n=>T(n)),...s.map(n=>A(n)),t??""],[c,a]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:o,organizationId:t}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:o,organizationId:t,resourceIds:i})]);return[c.status==="fulfilled"?c.value:[],a.status==="fulfilled"?a.value:[]]})}buildPermissionsResponse(e,r,s,t){let{folderIds:o,documentIds:i,clientOrganizationId:c,organizationId:a}=e,{failedFolderIds:n,failedDocumentIds:d,failedOrganizationId:h}=r,l={};return this.processRegularUserPermissions(l,s,o,i,c??"",a??"",n,d,h,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.ensureCurrentUserFailuresRecorded(l,c??"",n,d,h,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.processTemporaryUserPermissions(l,t),this.processContextPermissions(l),l}processContextPermissions(e){try{let r=this.authService.getUser()?.userId;if(r){let s=this.contactService.getUserAccessFieldsByUserId(r);s?.length&&(e[r]||(e[r]={}),e[r].context={accessFields:s})}}catch(r){this.loggingService.catch("Error in UserPermissionService processContextPermissions:",r);return}}processRegularUserPermissions(e,r,s,t,o,i,c,a,n,d,h,l){for(let m of r)for(let O of m)O?.user?.userId&&(e[O.user.userId]=y(f({},s.length&&{folders:this.buildFolderPermissions(s,O,c,d,l)}),{documents:this.buildDocumentPermissions(t,O,a,h,l),organization:{[o]:this.buildOrganizationPermission(i,O,n)}}))}ensureCurrentUserFailuresRecorded(e,r,s,t,o,i,c,a){try{let n=this.authService.getUser()?.userId;if(!n)return;let d=!!o&&!!r,h=(s?.length??0)>0,l=(t?.length??0)>0;if(!d&&!h&&!l)return;if(e[n]||(e[n]={}),d&&(e[n].organization||(e[n].organization={}),e[n].organization[r]||(e[n].organization[r]={error:this.getErrorMessage(o.errorCode,"organization"),errorCode:o.errorCode})),h){e[n].folders||(e[n].folders={});for(let m of s)e[n].folders[m.id]||(e[n].folders[m.id]=f({error:this.getErrorMessage(m.errorCode,"folder"),errorCode:m.errorCode},m.errorCode===u.PERMISSION_DENIED&&{accessType:i[m.id]??a??C}))}if(l){e[n].documents||(e[n].documents={});for(let m of t)e[n].documents[m.id]||(e[n].documents[m.id]=f({error:this.getErrorMessage(m.errorCode,"document"),errorCode:m.errorCode},m.errorCode===u.PERMISSION_DENIED&&{accessType:c[m.id]??a??C}))}}catch(n){this.loggingService.catch("Error in UserPermissionService ensureCurrentUserFailuresRecorded:",n)}}getErrorMessage(e,r){try{switch(this.loggingService.log(`Error in UserPermissionService getErrorMessage: ${e} ${r}`),e){case u.DOES_NOT_EXIST:return`${r} does not exist`;case u.PERMISSION_DENIED:return`User does not have access to ${r}`;case u.SOMETHING_WENT_WRONG:return"Something went wrong";default:return"Something went wrong"}}catch(s){return this.loggingService.catch("Error in UserPermissionService getErrorMessage:",s),"Something went wrong"}}buildFolderPermissions(e,r,s,t,o){return e.reduce((i,c)=>{let a=s.find(n=>n.id===c);return a?i[c]=f({error:this.getErrorMessage(a.errorCode,"folder"),errorCode:a.errorCode},a.errorCode===u.PERMISSION_DENIED&&{accessType:t[c]??o??C}):i[c]={accessRole:r.viewerFolderIds?.includes(T(c))?E.VIEWER:E.EDITOR,accessType:t[c]??o??C},i},{})}buildDocumentPermissions(e,r,s,t,o){return e.reduce((i,c)=>{let a=s.find(n=>n.id===c);return a?i[c]=f({error:this.getErrorMessage(a.errorCode,"document"),errorCode:a.errorCode},a.errorCode===u.PERMISSION_DENIED&&{accessType:t[c]??o??C}):i[c]={accessRole:r.viewerDocumentIds?.includes(A(c))?E.VIEWER:E.EDITOR,accessType:t[c]??o??C},i},{})}buildOrganizationPermission(e,r,s){return s?{error:this.getErrorMessage(s.errorCode,"organization"),errorCode:s.errorCode}:{accessRole:r.viewerOrganizationIds?.includes(e)?E.VIEWER:E.EDITOR}}processTemporaryUserPermissions(e,r){for(let s of r)if(s?.userId)switch(this.ensureUserPermissionStructure(e,s.userId),s.type){case"folder":this.addTemporaryFolderPermission(e,s);break;case"document":this.addTemporaryDocumentPermission(e,s);break;case"organization":this.addTemporaryOrganizationPermission(e,s);break}}ensureUserPermissionStructure(e,r){e[r]||(e[r]={})}addTemporaryFolderPermission(e,r){let{userId:s,resourceId:t,role:o,expiresAt:i}=r;e[s].folders||(e[s].folders={}),e[s].folders[t]={accessRole:o??E.EDITOR,expiresAt:i}}addTemporaryDocumentPermission(e,r){let{userId:s,resourceId:t,role:o,expiresAt:i}=r;e[s].documents||(e[s].documents={}),e[s].documents[t]={accessRole:o??E.EDITOR,expiresAt:i}}addTemporaryOrganizationPermission(e,r){let{userId:s,resourceId:t,role:o,expiresAt:i}=r;e[s].organization||(e[s].organization={}),e[s].organization[t]={accessRole:o??E.EDITOR,expiresAt:i}}hasEditAccess({organizationId:e,folderId:r,documentId:s}){try{let t=!0,o=this.getCurrentUserPermissionsWithServerIds(),i=this.authService.getUser()?.userId??"";return o&&(e&&typeof e=="string"&&o?.[i]?.organization?.[e]&&(o?.[i]?.organization?.[e]?.accessRole===E.VIEWER||o?.[i]?.organization?.[e]?.errorCode===u.PERMISSION_DENIED)&&(t=!1),r&&typeof r=="string"&&o?.[i]?.folders?.[r]&&(o?.[i]?.folders?.[r]?.accessRole===E.VIEWER||o?.[i]?.folders?.[r]?.errorCode===u.PERMISSION_DENIED)&&(t=!1),s&&typeof s=="string"&&o?.[i]?.documents?.[s]&&(o?.[i]?.documents?.[s]?.accessRole===E.VIEWER||o?.[i]?.documents?.[s]?.errorCode===u.PERMISSION_DENIED)&&(t=!1)),t}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(b(z))}getCurrentUserPermissions(){return this.currentUserPermissions$.value}refactorPermissionsWithServerIds(e){try{let r=JSON.parse(JSON.stringify(e??{})),s=this.authService.getUser()?.userId??"";if(r?.[s]){let t=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(r?.[s]?.organization?.[t]){let o=N(t);r[s].organization&&(r[s].organization[o]=r[s].organization[t],delete r[s].organization[t])}r?.[s]?.folders&&(r[s].folders=Object.fromEntries(Object.entries(r?.[s]?.folders??{}).map(([o,i])=>[T(o),i]))),r?.[s]?.documents&&(r[s].documents=Object.fromEntries(Object.entries(r?.[s]?.documents??{}).map(([o,i])=>[A(o),i])))}return r}catch(r){return this.loggingService.catch("Error in UsersPermissionService refactorPermissionsWithServerIds:",r),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(x(e=>this.refactorPermissionsWithServerIds(e)),b(z))}getCurrentUserPermissionsWithServerIds(){return this.refactorPermissionsWithServerIds(this.currentUserPermissions$.value)}setCurrentUserPermissions(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setCurrentUserPermissions","color: green;");let r=null;e&&(r=JSON.parse(JSON.stringify(e))),this.currentUserPermissions$.next(r)}catch(r){this.loggingService.catch("Error in UsersPermissionService setCurrentUserPermissions:",r)}}getIsContextEnabled(){return this.loggingService.log("%c[WB] Calling FUNCTION: getIsContextEnabled","color: green;"),this.permissionProvider$.value?.isContextEnabled??!1}setPermissionProvider(e){try{this.loggingService.log("%c[WB] Calling UsersService FUNCTION: setPermissionProvider","color: green;"),this.clientResolverProdWarned=!1,this.clientResolverNoResolverWarned=!1,this.permissionProvider$.next(e)}catch(r){this.loggingService.catch("Error in UsersPermissionService setPermissionProvider:",r)}}get isRevokeAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.DOCUMENT_UNSET)??!1}get isRevokeAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.USER_LOGOUT)??!1}get isRevokeOrganizationAccessOnUserLogoutEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.USER_LOGOUT&&e.revokeOrganizationAccess)??!1}get isRevokeOrganizationAccessOnDocumentUnsetEnabled(){return this.permissionProvider$.value?.revokeAccessOn?.some(e=>e.type===U.DOCUMENT_UNSET&&e.revokeOrganizationAccess)??!1}getPermissionProviderRetryConfig(){return this.permissionProvider$.value?.retryConfig??{retryCount:0,retryDelay:0}}revokeAccessOnUserLogout(){return g(this,null,function*(){let e=F();try{if(this.isRevokeAccessOnUserLogoutEnabled){let r=[],s=this.authService.getUser()?.userId??"";if((this.getPermissionsCache()??[]).forEach(o=>{o.userId===s&&o.hasAccess&&(o.type===p.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&r.push(y(f({},o),{hasAccess:!1})):r.push(y(f({},o),{hasAccess:!1})))}),r.length>0){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_FORMED,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}}),this.setPermissionsCache([]),this.clearRequestKeyedPermissionsCache(),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_TRIGGERED,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}});let o=yield this.revokeAccess({requests:r,userId:this.authService.getUser()?.userId??""});o.success?this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:o,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:o,success:!1,statusCode:500}}})}}}catch(r){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{error:r}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnUserLogout:",r)}})}getRevokeKey(e){try{return`${e.userId}_${e.resourceId}_${e.type}_${e.organizationId}`}catch(r){return this.loggingService.catch("Error in UsersPermissionService getRevokeKey:",r),""}}cancelPendingRevokes(e){try{e.forEach(r=>{let s=this.getRevokeKey({userId:r.userId,resourceId:r.resource.id,type:r.resource.type,organizationId:r.resource.organizationId});this.pendingRevokeRequests.has(s)&&this.pendingRevokeRequests.delete(s)}),this.pendingRevokeRequests.size===0&&this.pendingRevokeTimeoutId&&(clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=null)}catch(r){this.loggingService.catch("Error in UsersPermissionService cancelPendingRevokes:",r)}}flushPendingRevokes(){return g(this,null,function*(){let e=this.pendingRevokeUniqueId,r=this.pendingRevokeUserId;try{let s=Array.from(this.pendingRevokeRequests.values());if(this.pendingRevokeRequests.clear(),this.pendingRevokeTimeoutId=null,this.pendingRevokeUniqueId="",this.pendingRevokeUserId="",s.length===0)return;let t=this.getPermissionsCache()??[];s.forEach(c=>{t=t.filter(a=>!(a.resourceId===c.resourceId&&a.type===c.type&&a.organizationId===c.organizationId&&a.userId===c.userId))}),this.setPermissionsCache(t);let o=this.docService.getDocContext(),i=yield this.revokeAccess({requests:s,userId:r,currentContext:o});i.success?this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:i,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:i,success:!1,statusCode:500}}})}catch(s){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:s}}),this.loggingService.catch("Error in UsersPermissionService flushPendingRevokes:",s)}})}revokeAccessOnDocumentUnset(t){return g(this,arguments,function*({documentIds:e,folderId:r,context:s}){let o=F();try{if(this.isRevokeAccessOnDocumentUnsetEnabled){let i=[],c=this.docService.getOrganizationConfig()?.clientOrganizationId??"",a=this.authService.getUser()?.userId??"",n=this.getPermissionsCache()??[];e.forEach(d=>{n=this.collectRevokeRequest(n,i,d.clientDocumentId,p.DOCUMENT,c,a)}),r&&(n=this.collectRevokeRequest(n,i,r,p.FOLDER,c,a)),c&&this.isRevokeOrganizationAccessOnDocumentUnsetEnabled&&(n=this.collectRevokeRequest(n,i,c,p.ORGANIZATION,c,a)),s&&this.getIsContextEnabled()&&X({input:s}).forEach(h=>{let l=JSON.stringify(h.access);n=this.collectRevokeRequest(n,i,l,p.CONTEXT,c,a)}),this.setPermissionsCache(n),i.length>0&&(this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_FORMED,timestamp:new Date().getTime(),uniqueId:o,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:i}}),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_TRIGGERED,timestamp:new Date().getTime(),uniqueId:o,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:i}}),i.forEach(d=>{this.pendingRevokeRequests.set(this.getRevokeKey(d),d)}),this.pendingRevokeUniqueId=o,this.pendingRevokeUserId=a,this.pendingRevokeTimeoutId&&clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=setTimeout(()=>this.flushPendingRevokes(),this.REVOKE_DELAY_MS))}}catch(i){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:o,methodName:P.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:i}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnDocumentUnset:",i)}})}getAccess(s){return g(this,arguments,function*({requests:e,userId:r}){let t={retryConfig:this.getPermissionProviderRetryConfig()};return this.isClientDevResolverActive()?t.clientResolvedResults=yield this.resolveClientSide(e):this.getPermissionProvider()?.dev&&this.warnNoResolverOnce(),this.sendGetAccessToProxy({requests:e,userId:r,metadata:t})})}sendGetAccessToProxy(t){return g(this,arguments,function*({requests:e,userId:r,metadata:s}){if(this.adapterSelectorService?.isPortableBackendActive())return this.sendGetAccessToPortableGateway({requests:e,retryConfig:s?.retryConfig});let o=$(this.functions,V({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield G({methodName:"getAccess",data:{type:"getAccess",data:e,metadata:s},getSdkProxy:o,userId:r})})}sendGetAccessToPortableGateway(s){return g(this,arguments,function*({requests:e,retryConfig:r}){try{let t=this.adapterSelectorService.resolveDbAdapter(),o=[];for(let i=0;i<e.length;i+=k){let c=e.slice(i,i+k),a=yield t.getAccess(r===void 0?{scope:"org",data:c}:{scope:"org",data:c,metadata:{retryConfig:r}});if(!a?.ok){let d=a?.code;return this.loggingService.catch("Tier B getAccess denied/failed at the gateway: ",a),{data:[],success:!1,statusCode:this.denialCodeToStatusCode(d)}}let n=a.data?.data??[];o.push(...this.dropUnrequestedEntries(n,c))}return{data:this.skipNotProvidedFolderEntries(o),success:!0,statusCode:200}}catch(t){return this.loggingService.catch("Error in UserPermissionService sendGetAccessToPortableGateway: ",t),{data:[],success:!1,statusCode:500}}})}skipNotProvidedFolderEntries(e){try{this.reportUnrecognizedFolderErrorCodes(e);let r=e.filter(s=>!(s?.type===p.FOLDER&&s?.errorCode==="not_provided"));return r.length!==e.length&&this.loggingService.log(`[WB] Tier B getAccess: ${e.length-r.length} folder answer(s) skipped (errorCode 'not_provided' \u2014 folder subsystem not provisioned on this gateway)`),r}catch(r){return this.loggingService.catch("Error in UserPermissionService skipNotProvidedFolderEntries: ",r),e}}dropUnrequestedEntries(e,r){try{if(!e?.length)return e??[];let s=i=>`${i?.userId}|${i?.resourceId}|${i?.organizationId}|${i?.type}`,t=new Set((r??[]).map(i=>`${i?.userId}|${i?.resource?.id}|${i?.resource?.organizationId}|${i?.resource?.type}`)),o=e.filter(i=>t.has(s(i)));return o.length!==e.length&&this.loggingService.catch("Tier B getAccess returned entries that were not requested \u2014 dropped before the permissions cache: ",e.filter(i=>!t.has(s(i))),void 0,!0),o}catch(s){return this.loggingService.catch("Error in UserPermissionService dropUnrequestedEntries: ",s),e}}reportUnrecognizedFolderErrorCodes(e){try{for(let r of e??[]){let s=r?.errorCode;!s||r?.type!==p.FOLDER||s==="not_provided"||this.reportedUnknownFolderErrorCodes.has(s)||(this.reportedUnknownFolderErrorCodes.add(s),console.warn(`Velt [portable backend]: a folder permission entry carried an unrecognised errorCode '${s}'. It is being consumed verbatim (hasAccess is honoured as sent). If your gateway means the folder subsystem is not provisioned, the expected literal is the exact lowercase 'not_provided' \u2014 anything else reads as a REAL denial and will withhold folder-scoped access.`))}}catch(r){this.loggingService.catch("Error in UserPermissionService reportUnrecognizedFolderErrorCodes: ",r)}}denialCodeToStatusCode(e){switch(e){case"unauthenticated":return 401;case"permission-denied":return 403;case"not-found":return 404;case"invalid-argument":return 400;case"failed-precondition":return 412;case"resource-exhausted":return 429;case"unimplemented":return 501;default:return 500}}isClientDevResolverActive(){return!!this.getPermissionProvider()?.dev&&this.isClientDevResolverConfigured()}resolveClientSidePermissions(e){return g(this,null,function*(){if(!this.isClientDevResolverActive())throw new Error("Client-side dev permission resolver is not active");return this.resolveClientSide(e)})}isClientDevResolverConfigured(){let e=this.getPermissionProvider();return e?!!e.endpointConfig?.url?.trim()||typeof e.resolvePermissions=="function":!1}resolveClientSide(e){return g(this,null,function*(){this.warnClientResolverEnabledOnce();let r=this.getPermissionProvider(),s=this.getPermissionProviderRetryConfig(),t=r?.resolveTimeout??6e4,o=yield j(()=>this.withResolverTimeout(()=>this.invokeResolver(e,r),t),"clientPermissionResolver",{retryCount:s?.retryCount??0,retryDelay:s?.retryDelay??0});if(!o||!o.success||o.statusCode!==200)throw new Error(o?.message??"Client permission resolver failed");let i=o.data;if(!Array.isArray(i))throw new Error("Client permission resolver returned a malformed payload");return i})}invokeResolver(e,r){return g(this,null,function*(){let s={data:{requests:e}},t=r.endpointConfig?.url?.trim();if(t)return J(t,r.endpointConfig?.headers,s,!0,r.endpointConfig?.credentials);let o=yield r.resolvePermissions(s);if(Array.isArray(o))return{data:o,success:!0,statusCode:200};let i=o,c=i?.statusCode??(i?.success===!1?500:200),a=i?.success!==!1&&c===200;return{data:Array.isArray(i?.data)?i.data:void 0,success:a,statusCode:a?200:c===200?500:c,message:i?.message}})}withResolverTimeout(e,r){return g(this,null,function*(){if(!r||r<=0)return e();let s,t=new Promise((o,i)=>{s=setTimeout(()=>i(new Error("Client permission resolver timed out")),r)});try{return yield Promise.race([e(),t])}finally{s&&clearTimeout(s)}})}warnClientResolverEnabledOnce(){this.clientResolverProdWarned||(this.clientResolverProdWarned=!0,console.warn("[Velt] Client-side dev permission resolver is enabled (dev: true). Permissions are resolved in the browser for local development only \u2014 DO NOT use this in production. Production API keys ignore browser-resolved results and fall back to the server-side permission provider."))}warnNoResolverOnce(){this.clientResolverNoResolverWarned||(this.clientResolverNoResolverWarned=!0,console.warn("[Velt] setPermissionProvider was called with dev: true but no endpointConfig.url or resolvePermissions callback was provided. Falling back to the server-side permission provider."))}revokeAccess(t){return g(this,arguments,function*({requests:e,userId:r,currentContext:s}){if(this.adapterSelectorService?.isPortableBackendActive())return this.sendRevokeAccessToPortableGateway({requests:e,metadata:this.buildRevokeAccessMetadata(s)});let o=$(this.functions,V({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield G({methodName:"revokeAccess",data:{type:"revokeAccess",data:e,metadata:this.buildRevokeAccessMetadata(s)},getSdkProxy:o,userId:r})})}buildRevokeAccessMetadata(e){return f({retryConfig:this.getPermissionProviderRetryConfig()},e?.access&&{currentContext:e})}sendRevokeAccessToPortableGateway(s){return g(this,arguments,function*({requests:e,metadata:r}){try{let t=this.adapterSelectorService.resolveDbAdapter();for(let o=0;o<e.length;o+=k){let i=e.slice(o,o+k),c=yield t.revokeAccess({scope:"org",data:i,metadata:r});if(!c?.ok)return this.loggingService.catch("Tier B revokeAccess denied/failed at the gateway: ",c),{success:!1}}return{success:!0}}catch(t){return this.loggingService.catch("Error in UserPermissionService sendRevokeAccessToPortableGateway: ",t),{success:!1}}})}onResourceAccessRequired(i){return g(this,arguments,function*({requests:e,uniqueId:r,methodName:s,userId:t,fromCache:o=!0}){try{if(!e?.length)return;let c=[],a=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&o&&(e.forEach(n=>{let d=a?.find(h=>h.resourceId===n.resource.id&&h.type===n.resource.type&&h.userId===n.userId&&h.organizationId===n.resource.organizationId);d&&c.push(d)}),c.length>0&&(e=e.filter(n=>!c.find(d=>d.resourceId===n.resource.id&&d.type===n.resource.type&&d.userId===n.userId&&d.organizationId===n.resource.organizationId)))),e.length>0){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:r,methodName:s,source:"internal",payload:{requests:e,fromCache:o,clientResolved:this.isClientDevResolverActive()}});let n=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??t??""});return this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.RESOURCE_ACCESS_RESULT,timestamp:new Date().getTime(),uniqueId:r,methodName:s,source:"internal",payload:{result:n,clientResolved:this.isClientDevResolverActive()}}),n?.success&&n?.data?.length&&(this.setPermissionsCache([...a,...n.data]),n.data=[...c,...n.data]),n}else if(c.length>0)return this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.RESOURCE_ACCESS_RESULT_FROM_CACHE,timestamp:new Date().getTime(),methodName:s,source:"internal",uniqueId:r,payload:{results:{data:c,success:!0,statusCode:200}}}),{data:c,success:!0,statusCode:200};return}catch(c){this.loggingService.catch("Error in UsersPermissionService onResourceAccessRequired:",c),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:S.Events.PermissionProvider.RESOURCE_ACCESS_ERROR,timestamp:new Date().getTime(),methodName:s,source:"internal",uniqueId:r,payload:{error:c,requests:e,fromCache:o}});return}})}getPermissionsCache(){return this.forceRefreshPermissions()?[]:this.permissionsCache$.getValue()}forceRefreshPermissions(){return this.getPermissionProvider()?.forceRefresh??!1}setPermissionsCache(e){try{let r=new Map;e.forEach(t=>{let o=`${t.userId}_${t.resourceId}_${t.organizationId}_${t.type}`;r.set(o,t)});let s=JSON.parse(JSON.stringify(Array.from(r.values())));this.permissionsCache$.next(s)}catch(r){this.loggingService.catch("Error in UsersPermissionService setPermissionsCache:",r)}}isPermissionProviderAvailable(){try{return!!this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService isPermissionProviderAvailable:",e),!1}}getPermissionProvider(){try{return this.permissionProvider$.getValue()}catch(e){return this.loggingService.catch("Error in UsersPermissionService getPermissionProvider:",e),null}}getPermissionProvider$(){return this.permissionProvider$.asObservable()}};I.\u0275fac=function(r){return new(r||I)(R(ee),R(ne),R(H),R(oe),R(te),R(ie),R(Q),R(W),R(q),R(ce))},I.\u0275prov=K({token:I,factory:I.\u0275fac,providedIn:"root"});let w=I;return w})();export{Ne as a};
|