@veltdev/sdk
Version:
Velt is an SDK to add collaborative features to your product within minutes. Example: Comments like Figma, Frame.io, Google docs or sheets, Recording like Loom, Huddles like Slack and much more.
2 lines (1 loc) • 31 kB
JavaScript
import{ca as re}from"./chunk-KU45CEXD.js";import{$ as G,$e as R,Ai as Q,Df as _,Ee as W,Ef as N,Ff as D,Ii as ee,L as w,Od as x,Of as k,_e as U,a as f,af as I,b as y,be as v,ca as P,da as K,di as J,ei as B,g,hi as q,jh as M,ji as H,l as T,mh as $,mi as X,nh as L,ph as j,qh as b,sh as z,tf as S,uf as l,v as V,vh as E,wh as F,yi as Y,zi as Z}from"./chunk-GR3NESUB.js";var p="public",pe=(()=>{let O=class O{constructor(e,r,s,i,t,o,c,a,n,d){this.authService=e,this.docService=r,this.loggingService=s,this.commonDbService=i,this.usersService=t,this.commentUtilsService=o,this.coreActionsService=c,this.functions=a,this.configService=n,this.contactService=d,this.endpointsService=K(q),this.currentUserPermissions$=new T(null),this.permissionsCache$=new T(null),this.permissionProvider$=new T(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="";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,i,t,o){try{return e.find(a=>a.resourceId===s&&a.type===i&&a.organizationId===t&&a.userId===o)?(r.push({userId:o,resourceId:s,organizationId:t,type:i,hasAccess:!1}),e.filter(a=>!(a.resourceId===s&&a.type===i&&a.organizationId===t&&a.userId===o))):e}catch(c){return this.loggingService.catch("Error in UsersPermissionService collectRevokeRequest:",c),e}}hasUserContextAccess({userId:e,accessFields:r}){try{if(!this.getIsContextEnabled()||r.includes(W.DEFAULT_VELT_CONTEXT))return!0;let s=this.contactService.getUserAccessFieldsByUserId(e);return s?r.every(i=>s.includes(i)):!0}catch(s){return this.loggingService.catch("Error in UserPermissionService hasUserContextAccess:",s),!1}}organizationDetails(e){return g(this,null,function*(){try{let r=yield this.commonDbService?.getData({feature:"organizationMetadata",properties:{organizationId:e,suppressError:!0}});return r&&r?.errorCode?{errorCode:l.PERMISSION_DENIED,error:!0}:r&&!r?.metadata?{errorCode:l.DOES_NOT_EXIST,error:!0}:{error:!1}}catch(r){return this.loggingService.catch("Error in UserPermissionService organizationDetails:",r),{errorCode:l.SOMETHING_WENT_WRONG,error:!0}}})}documentDetails(s){return g(this,arguments,function*({documentId:e,organizationId:r}){try{let i=yield this.commonDbService?.getData({feature:"documentMetadata",properties:{documentId:e,organizationId:r,suppressError:!0}});if(i&&i?.errorCode)return{errorCode:l.PERMISSION_DENIED,error:!0};if(i&&!i?.metadata)return{errorCode:l.DOES_NOT_EXIST,error:!0};let t=this.docService.getDocumentMetadata(e)??{};this.docService.setDocumentMetadata(e,f(f({},t),i?.metadata??{}));let o,c=i?.metadata?.veltFolderId;if(c)try{o=(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 o||(o=i?.docIamConfig?.accessType),{error:!1,accessType:o}}catch(i){return this.loggingService.catch("Error in UserPermissionService documentDetails:",i),{errorCode:l.SOMETHING_WENT_WRONG,error:!0}}})}folderDetails(s){return g(this,arguments,function*({folderId:e,organizationId:r}){try{let i=yield this.commonDbService?.getData({feature:"folderMetadata",properties:{folderId:e,organizationId:r,suppressError:!0}});return i&&i?.errorCode?{errorCode:l.PERMISSION_DENIED,error:!0}:i&&!i?.metadata?{errorCode:l.DOES_NOT_EXIST,error:!0}:{error:!1,accessType:i?.folderIamConfig?.accessType}}catch(i){return this.loggingService.catch("Error in UserPermissionService folderDetails:",i),{errorCode:l.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,i=this.extractResourceIds(e);if(!i.clientOrganizationId||!i.organizationId)return this.loggingService.catch("Client organization id or organization id not set during getUserPermissions",void 0,void 0,!0),{};let t=yield this.validateResources(i),[o,c]=yield this.fetchUserPermissionsFromDB(i),a=this.authService.getUser()?.userId;if(s!==a)return{};let n=this.buildPermissionsResponse(i,t,o,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,i=this.requestKeyedPermissionsCache.get(r);if(i)return JSON.parse(JSON.stringify(i));let t=this.inFlightPermissionsRequests.get(r);if(t){let a=yield t;return this.permissionsCacheGeneration!==s?yield this.getUserPermissions(e):JSON.parse(JSON.stringify(a))}let o=this.getUserPermissions(e);this.inFlightPermissionsRequests.set(r,o),o.finally(()=>{this.inFlightPermissionsRequests.get(r)===o&&this.inFlightPermissionsRequests.delete(r)}).catch(()=>{});let c=yield o;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 i=e[s];i!==void 0&&(r[s]=Array.isArray(i)?[...i].sort():i)}),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 o=e.organizationId??r?.clientOrganizationId;return{folderIds:e.folderIds??[],documentIds:e.documentIds??[],clientOrganizationId:o,organizationId:o?N(o):void 0}}let i=r?.clientOrganizationId;return{folderIds:r?.folderId?[r.folderId]:[],documentIds:s.map(o=>o.clientDocumentId),clientOrganizationId:i,organizationId:i?N(i):void 0}}validateResources(e){return g(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:i,clientOrganizationId:t}=e,o=[],c=[],a=r.length>0||s.length>0;i&&!a&&(o.push(this.organizationDetails(i)),c.push({id:t??"",type:"organization"})),r.forEach(u=>{o.push(this.folderDetails({folderId:D(u),organizationId:i??""})),c.push({id:u,type:"folder"})}),s.forEach(u=>{o.push(this.documentDetails({documentId:_(u),organizationId:i??""})),c.push({id:u,type:"document"})});let[n,d]=yield Promise.all([Promise.allSettled(o),this.getDefaultDocumentAccessType()]),h=this.processValidationResults(n,c);return y(f({},this.suppressResolverGrantedFailures(h,t)),{defaultDocumentAccessType:d})})}suppressResolverGrantedFailures(e,r){try{let s=this.authService.getUser()?.userId;if(!s)return e;let i=this.getPermissionsCache()??[];if(i.length===0)return e;let t=(n,d,h)=>i.some(u=>u?.userId===s&&u?.resourceId===n&&u?.type===d&&(!h||u?.organizationId===h)&&u?.hasAccess===!0),o=e.failedDocumentIds.filter(n=>!(n.errorCode===l.PERMISSION_DENIED&&t(n.id,I.DOCUMENT,r))),c=e.failedFolderIds.filter(n=>!(n.errorCode===l.PERMISSION_DENIED&&t(n.id,I.FOLDER,r))),a=e.failedOrganizationId;return a&&a.errorCode===l.PERMISSION_DENIED&&r&&t(r,I.ORGANIZATION,r)&&(a=void 0),{failedFolderIds:c,failedDocumentIds:o,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=[],i=[],t,o={},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 u=n.status==="fulfilled"?n.value.errorCode??l.SOMETHING_WENT_WRONG:l.SOMETHING_WENT_WRONG,m={id:d.id,errorCode:u};switch(d.type){case"organization":if(t=m,u===l.DOES_NOT_EXIST)throw new Error(`Organization with id '${d.id}' does not exist`);break;case"folder":s.push(m);break;case"document":i.push(m);break}}else if(n.status==="fulfilled")switch(d.type){case"folder":n.value.accessType&&(o[d.id]=n.value.accessType);break;case"document":n.value.accessType&&(c[d.id]=n.value.accessType);break}}return{failedFolderIds:s,failedDocumentIds:i,failedOrganizationId:t,folderAccessTypes:o,documentAccessTypes:c}}fetchUserPermissionsFromDB(e){return g(this,null,function*(){let{folderIds:r,documentIds:s,organizationId:i}=e,t=[this.authService.getUser()?.userId??""],o=[...r.map(n=>D(n)),...s.map(n=>_(n)),i??""],[c,a]=yield Promise.allSettled([this.usersService.getUsersFromDBWithBatching({userIds:t,organizationId:i}),this.usersService.getTemporaryUsersFromDBWithBatching({userIds:t,organizationId:i,resourceIds:o})]);return[c.status==="fulfilled"?c.value:[],a.status==="fulfilled"?a.value:[]]})}buildPermissionsResponse(e,r,s,i){let{folderIds:t,documentIds:o,clientOrganizationId:c,organizationId:a}=e,{failedFolderIds:n,failedDocumentIds:d,failedOrganizationId:h}=r,u={};return this.processRegularUserPermissions(u,s,t,o,c??"",a??"",n,d,h,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.ensureCurrentUserFailuresRecorded(u,c??"",n,d,h,r.folderAccessTypes,r.documentAccessTypes,r.defaultDocumentAccessType),this.processTemporaryUserPermissions(u,i),this.processContextPermissions(u),u}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,i,t,o,c,a,n,d,h,u){for(let m of r)for(let C of m)C?.user?.userId&&(e[C.user.userId]=y(f({},s.length&&{folders:this.buildFolderPermissions(s,C,c,d,u)}),{documents:this.buildDocumentPermissions(i,C,a,h,u),organization:{[t]:this.buildOrganizationPermission(o,C,n)}}))}ensureCurrentUserFailuresRecorded(e,r,s,i,t,o,c,a){try{let n=this.authService.getUser()?.userId;if(!n)return;let d=!!t&&!!r,h=(s?.length??0)>0,u=(i?.length??0)>0;if(!d&&!h&&!u)return;if(e[n]||(e[n]={}),d&&(e[n].organization||(e[n].organization={}),e[n].organization[r]||(e[n].organization[r]={error:this.getErrorMessage(t.errorCode,"organization"),errorCode:t.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===l.PERMISSION_DENIED&&{accessType:o[m.id]??a??p}))}if(u){e[n].documents||(e[n].documents={});for(let m of i)e[n].documents[m.id]||(e[n].documents[m.id]=f({error:this.getErrorMessage(m.errorCode,"document"),errorCode:m.errorCode},m.errorCode===l.PERMISSION_DENIED&&{accessType:c[m.id]??a??p}))}}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 l.DOES_NOT_EXIST:return`${r} does not exist`;case l.PERMISSION_DENIED:return`User does not have access to ${r}`;case l.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,i,t){return e.reduce((o,c)=>{let a=s.find(n=>n.id===c);return a?o[c]=f({error:this.getErrorMessage(a.errorCode,"folder"),errorCode:a.errorCode},a.errorCode===l.PERMISSION_DENIED&&{accessType:i[c]??t??p}):o[c]={accessRole:r.viewerFolderIds?.includes(D(c))?S.VIEWER:S.EDITOR,accessType:i[c]??t??p},o},{})}buildDocumentPermissions(e,r,s,i,t){return e.reduce((o,c)=>{let a=s.find(n=>n.id===c);return a?o[c]=f({error:this.getErrorMessage(a.errorCode,"document"),errorCode:a.errorCode},a.errorCode===l.PERMISSION_DENIED&&{accessType:i[c]??t??p}):o[c]={accessRole:r.viewerDocumentIds?.includes(_(c))?S.VIEWER:S.EDITOR,accessType:i[c]??t??p},o},{})}buildOrganizationPermission(e,r,s){return s?{error:this.getErrorMessage(s.errorCode,"organization"),errorCode:s.errorCode}:{accessRole:r.viewerOrganizationIds?.includes(e)?S.VIEWER:S.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:i,role:t,expiresAt:o}=r;e[s].folders||(e[s].folders={}),e[s].folders[i]={accessRole:t??S.EDITOR,expiresAt:o}}addTemporaryDocumentPermission(e,r){let{userId:s,resourceId:i,role:t,expiresAt:o}=r;e[s].documents||(e[s].documents={}),e[s].documents[i]={accessRole:t??S.EDITOR,expiresAt:o}}addTemporaryOrganizationPermission(e,r){let{userId:s,resourceId:i,role:t,expiresAt:o}=r;e[s].organization||(e[s].organization={}),e[s].organization[i]={accessRole:t??S.EDITOR,expiresAt:o}}hasEditAccess({organizationId:e,folderId:r,documentId:s}){try{let i=!0,t=this.getCurrentUserPermissionsWithServerIds(),o=this.authService.getUser()?.userId??"";return t&&(e&&typeof e=="string"&&t?.[o]?.organization?.[e]&&(t?.[o]?.organization?.[e]?.accessRole===S.VIEWER||t?.[o]?.organization?.[e]?.errorCode===l.PERMISSION_DENIED)&&(i=!1),r&&typeof r=="string"&&t?.[o]?.folders?.[r]&&(t?.[o]?.folders?.[r]?.accessRole===S.VIEWER||t?.[o]?.folders?.[r]?.errorCode===l.PERMISSION_DENIED)&&(i=!1),s&&typeof s=="string"&&t?.[o]?.documents?.[s]&&(t?.[o]?.documents?.[s]?.accessRole===S.VIEWER||t?.[o]?.documents?.[s]?.errorCode===l.PERMISSION_DENIED)&&(i=!1)),i}catch{return!0}}getCurrentUserPermissions$(){return this.currentUserPermissions$.asObservable().pipe(w(M))}getCurrentUserPermissions(){return this.currentUserPermissions$.value}refactorPermissionsWithServerIds(e){try{let r=JSON.parse(JSON.stringify(e??{})),s=this.authService.getUser()?.userId??"";if(r?.[s]){let i=this.docService.getDocumentPaths()?.clientOrganizationId??"";if(r?.[s]?.organization?.[i]){let t=N(i);r[s].organization&&(r[s].organization[t]=r[s].organization[i],delete r[s].organization[i])}r?.[s]?.folders&&(r[s].folders=Object.fromEntries(Object.entries(r?.[s]?.folders??{}).map(([t,o])=>[D(t),o]))),r?.[s]?.documents&&(r[s].documents=Object.fromEntries(Object.entries(r?.[s]?.documents??{}).map(([t,o])=>[_(t),o])))}return r}catch(r){return this.loggingService.catch("Error in UsersPermissionService refactorPermissionsWithServerIds:",r),e}}getCurrentUserPermissionsWithServerIds$(){return this.currentUserPermissions$.asObservable().pipe(V(e=>this.refactorPermissionsWithServerIds(e)),w(M))}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=k();try{if(this.isRevokeAccessOnUserLogoutEnabled){let r=[],s=this.authService.getUser()?.userId??"";if((this.getPermissionsCache()??[]).forEach(t=>{t.userId===s&&t.hasAccess&&(t.type===I.ORGANIZATION?this.isRevokeOrganizationAccessOnUserLogoutEnabled&&r.push(y(f({},t),{hasAccess:!1})):r.push(y(f({},t),{hasAccess:!1})))}),r.length>0){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_FORMED,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}}),this.setPermissionsCache([]),this.clearRequestKeyedPermissionsCache(),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_TRIGGERED,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{requests:r}});let t=yield this.revokeAccess({requests:r,userId:this.authService.getUser()?.userId??""});t.success?this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:t,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_USER_LOGOUT,source:"internal",payload:{result:{data:t,success:!1,statusCode:500}}})}}}catch(r){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_USER_LOGOUT_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.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 i=this.getPermissionsCache()??[];s.forEach(c=>{i=i.filter(a=>!(a.resourceId===c.resourceId&&a.type===c.type&&a.organizationId===c.organizationId&&a.userId===c.userId))}),this.setPermissionsCache(i);let t=this.docService.getDocContext(),o=yield this.revokeAccess({requests:s,userId:r,currentContext:t});o.success?this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_RESULT,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:o,success:!0,statusCode:200}}}):this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{result:{data:o,success:!1,statusCode:500}}})}catch(s){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:e,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:s}}),this.loggingService.catch("Error in UsersPermissionService flushPendingRevokes:",s)}})}revokeAccessOnDocumentUnset(i){return g(this,arguments,function*({documentIds:e,folderId:r,context:s}){let t=k();try{if(this.isRevokeAccessOnDocumentUnsetEnabled){let o=[],c=this.docService.getOrganizationConfig()?.clientOrganizationId??"",a=this.authService.getUser()?.userId??"",n=this.getPermissionsCache()??[];e.forEach(d=>{n=this.collectRevokeRequest(n,o,d.clientDocumentId,I.DOCUMENT,c,a)}),r&&(n=this.collectRevokeRequest(n,o,r,I.FOLDER,c,a)),c&&this.isRevokeOrganizationAccessOnDocumentUnsetEnabled&&(n=this.collectRevokeRequest(n,o,c,I.ORGANIZATION,c,a)),s&&this.getIsContextEnabled()&&j({input:s}).forEach(h=>{let u=JSON.stringify(h.access);n=this.collectRevokeRequest(n,o,u,I.CONTEXT,c,a)}),this.setPermissionsCache(n),o.length>0&&(this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_FORMED,timestamp:new Date().getTime(),uniqueId:t,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:o}}),this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_TRIGGERED,timestamp:new Date().getTime(),uniqueId:t,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{requests:o}}),o.forEach(d=>{this.pendingRevokeRequests.set(this.getRevokeKey(d),d)}),this.pendingRevokeUniqueId=t,this.pendingRevokeUserId=a,this.pendingRevokeTimeoutId&&clearTimeout(this.pendingRevokeTimeoutId),this.pendingRevokeTimeoutId=setTimeout(()=>this.flushPendingRevokes(),this.REVOKE_DELAY_MS))}}catch(o){this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.Events.PermissionProvider.REVOKE_ACCESS_ON_DOCUMENT_UNSET_ERROR,timestamp:new Date().getTime(),uniqueId:t,methodName:R.REVOKE_ACCESS_ON_DOCUMENT_UNSET,source:"internal",payload:{error:o}}),this.loggingService.catch("Error in UsersPermissionService revokeAccessOnDocumentUnset:",o)}})}getAccess(s){return g(this,arguments,function*({requests:e,userId:r}){let i={retryConfig:this.getPermissionProviderRetryConfig()};return this.isClientDevResolverActive()?i.clientResolvedResults=yield this.resolveClientSide(e):this.getPermissionProvider()?.dev&&this.warnNoResolverOnce(),this.sendGetAccessToProxy({requests:e,userId:r,metadata:i})})}sendGetAccessToProxy(i){return g(this,arguments,function*({requests:e,userId:r,metadata:s}){let t=F(this.functions,z({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield b({methodName:"getAccess",data:{type:"getAccess",data:e,metadata:s},getSdkProxy:t,userId:r})})}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(),i=r?.resolveTimeout??6e4,t=yield $(()=>this.withResolverTimeout(()=>this.invokeResolver(e,r),i),"clientPermissionResolver",{retryCount:s?.retryCount??0,retryDelay:s?.retryDelay??0});if(!t||!t.success||t.statusCode!==200)throw new Error(t?.message??"Client permission resolver failed");let o=t.data;if(!Array.isArray(o))throw new Error("Client permission resolver returned a malformed payload");return o})}invokeResolver(e,r){return g(this,null,function*(){let s={data:{requests:e}},i=r.endpointConfig?.url?.trim();if(i)return L(i,r.endpointConfig?.headers,s,!0,r.endpointConfig?.credentials);let t=yield r.resolvePermissions(s);if(Array.isArray(t))return{data:t,success:!0,statusCode:200};let o=t,c=o?.statusCode??(o?.success===!1?500:200),a=o?.success!==!1&&c===200;return{data:Array.isArray(o?.data)?o.data:void 0,success:a,statusCode:a?200:c===200?500:c,message:o?.message}})}withResolverTimeout(e,r){return g(this,null,function*(){if(!r||r<=0)return e();let s,i=new Promise((t,o)=>{s=setTimeout(()=>o(new Error("Client permission resolver timed out")),r)});try{return yield Promise.race([e(),i])}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(i){return g(this,arguments,function*({requests:e,userId:r,currentContext:s}){let t=F(this.functions,z({url:this.endpointsService.getCloudFunctionUrl("sdkProxy"),apiProxyDomain:this.configService?.getApiProxyDomain()}));return yield b({methodName:"revokeAccess",data:{type:"revokeAccess",data:e,metadata:f({retryConfig:this.getPermissionProviderRetryConfig()},s?.access&&{currentContext:s})},getSdkProxy:t,userId:r})})}onResourceAccessRequired(o){return g(this,arguments,function*({requests:e,uniqueId:r,methodName:s,userId:i,fromCache:t=!0}){try{if(!e?.length)return;let c=[],a=this.getPermissionsCache()??[];if(!this.forceRefreshPermissions()&&t&&(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:E.Events.PermissionProvider.RESOURCE_ACCESS_REQUEST_TRIGGERED,timestamp:new Date().getTime(),uniqueId:r,methodName:s,source:"internal",payload:{requests:e,fromCache:t,clientResolved:this.isClientDevResolverActive()}});let n=yield this.getAccess({requests:e,userId:this.authService.getUser()?.userId??i??""});return this.coreActionsService.triggerAction(v.PERMISSION_PROVIDER,{event:E.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:E.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:E.Events.PermissionProvider.RESOURCE_ACCESS_ERROR,timestamp:new Date().getTime(),methodName:s,source:"internal",uniqueId:r,payload:{error:c,requests:e,fromCache:t}});return}})}getPermissionsCache(){return this.forceRefreshPermissions()?[]:this.permissionsCache$.getValue()}forceRefreshPermissions(){return this.getPermissionProvider()?.forceRefresh??!1}setPermissionsCache(e){try{let r=new Map;e.forEach(i=>{let t=`${i.userId}_${i.resourceId}_${i.organizationId}_${i.type}`;r.set(t,i)});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()}};O.\u0275fac=function(r){return new(r||O)(P(X),P(Y),P(J),P(ee),P(Z),P(Q),P(H),P(x),P(B),P(re))},O.\u0275prov=G({token:O,factory:O.\u0275fac,providedIn:"root"});let A=O;return A})();export{pe as a};