@rpcbase/db 0.138.0 → 0.140.0
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/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/migrations/20260816090000-runtime-rts-retention.d.ts +3 -0
- package/dist/migrations/20260816090000-runtime-rts-retention.d.ts.map +1 -0
- package/dist/migrations/baselineResources.d.ts +2 -0
- package/dist/migrations/baselineResources.d.ts.map +1 -0
- package/dist/migrations/currentResources.d.ts.map +1 -1
- package/dist/migrations/index.d.ts +2 -2
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/migrations/index.js +130 -54
- package/dist/migrations/index.js.map +1 -1
- package/dist/migrations/runtimeRtsRetentionResources.d.ts +2 -0
- package/dist/migrations/runtimeRtsRetentionResources.d.ts.map +1 -0
- package/dist/tenantProvisioning.d.ts +3 -0
- package/dist/tenantProvisioning.d.ts.map +1 -1
- package/package.json +5 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["Schema","z","ZRBUser","object","email","string","optional","password","name","phone","tenants","array","tenantRoles","record","oauthProviders","subject","accessToken","refreshToken","idToken","scope","tokenType","expiresAt","date","rawUserInfo","unknown","createdAt","updatedAt","emailVerificationCode","length","emailVerificationExpiresAt","passwordResetCode","passwordResetCodeExpiresAt","passwordResetToken","passwordResetTokenExpiresAt","IRBUser","infer","RBUserSchema","type","String","unique","sparse","required","index","Map","of","default","Date","Types","Mixed","_id","Schema","z","ZRBTenant","object","tenantId","string","parentTenantId","optional","name","provisioningStatus","enum","provisioningError","provisioningStartedAt","date","provisionedAt","IRBTenant","infer","RBTenantSchema","type","String","required","unique","index","Date","Schema","z","SUBSCRIPTION_CHANGE_DIRECTIONS","SUBSCRIPTION_EVENT_TYPES","SUBSCRIPTION_INTERVAL_UNITS","SUBSCRIPTION_SCOPES","SUBSCRIPTION_STATUSES","SUBSCRIPTION_TYPES","ZRBTenantSubscriptionStatus","enum","ZRBTenantSubscriptionIntervalUnit","ZRBTenantSubscriptionType","ZRBTenantSubscriptionScope","ZRBTenantSubscriptionEventType","ZRBTenantSubscriptionEventSource","ZRBTenantSubscriptionChangeDirection","subscriptionEventBaseSchema","object","tenantId","string","trim","min","subscriptionId","occurredAt","date","effectiveAt","subscriptionType","parentSubscriptionId","optional","scope","scopeId","fromPlanKey","toPlanKey","fromStatus","toStatus","fromModules","array","toModules","fromIntervalUnit","toIntervalUnit","fromIntervalCount","number","int","toIntervalCount","fromPriceId","toPriceId","billingAnchor","supersedesEventId","idempotencyKey","direction","actorUserId","source","reason","provider","providerEventId","providerPayload","unknown","metadata","record","subscriptionCreatedEventSchema","extend","type","literal","subscriptionPlanChangedEventSchema","subscriptionStatusChangedEventSchema","subscriptionResumedEventSchema","subscriptionCanceledEventSchema","subscriptionRenewedEventSchema","ZRBTenantSubscriptionEvent","discriminatedUnion","superRefine","event","ctx","addIssue","code","message","path","IRBTenantSubscriptionEvent","infer","SubscriptionEventDocument","requiredForEventTypes","types","Array","requiredForEventType","this","Boolean","includes","RBTenantSubscriptionEventSchema","String","required","index","options","Date","default","now","undefined","Number","Types","Mixed","unique","partialFilterExpression","$type","Schema","z","ZRBTenantSubscriptionIntervalUnit","ZRBTenantSubscriptionScope","ZRBTenantSubscriptionStatus","ZRBTenantSubscriptionType","ZRBTenantSubscriptionProjection","object","tenantId","string","subscriptionId","type","parentSubscriptionId","optional","scope","scopeId","planKey","priceId","status","intervalUnit","intervalCount","number","int","min","modules","array","billingAnchor","date","currentPeriodStart","currentPeriodEnd","cancelAtPeriodEnd","boolean","cancelAt","canceledAt","scheduledPlanKey","scheduledPlanEffectiveAt","provider","latestEventId","latestEventAt","projectedAt","IRBTenantSubscriptionProjection","infer","RBTenantSubscriptionProjectionSchema","String","required","index","enum","options","Number","default","Date","Boolean","unique","Schema","z","ZRBRtsCounter","object","_id","string","seq","number","int","min","IRBRtsCounter","infer","RBRtsCounterSchema","type","String","required","Number","default","versionKey","Schema","z","rtsChangesTtlSeconds","ZRBRtsChangeOp","enum","ZRBRtsChange","object","seq","number","int","min","modelName","string","op","docId","optional","ts","date","IRBRtsChange","infer","RBRtsChangeSchema","type","Number","required","String","index","options","Date","default","now","versionKey","unique","expireAfterSeconds","Schema","z","AclPolicy","ZRBUploadSessionStatus","enum","ZRBUploadAccessScope","ZRBUploadDeduplication","object","namespace","string","algorithm","literal","hash","key","pipelineVersion","number","int","min","ZRBUploadSession","_id","userId","optional","ownerKeyHash","filename","mimeType","totalSize","chunkSize","chunksTotal","status","createdAt","date","expiresAt","fileId","isPublic","boolean","accessScope","deduplication","deduplicated","error","IRBUploadSession","infer","RBUploadSessionSchema","type","String","required","index","Number","options","Date","default","now","Boolean","versionKey","expireAfterSeconds","RBUploadSessionPolicy","subject","define","builder","ctx","can","uploadKeyHash","claims","trim","Schema","z","ZRBUploadChunk","object","uploadId","string","index","number","int","min","data","unknown","size","sha256","optional","createdAt","date","expiresAt","IRBUploadChunk","infer","RBUploadChunkSchema","type","String","required","Number","Buffer","Date","default","now","versionKey","unique","expireAfterSeconds","Schema","z","AclPolicy","ZStringMap","record","string","ZRBNotificationPlatformPayload","object","webpush","unknown","optional","fcmOptions","android","apns","passthrough","IRBNotificationPlatformPayload","infer","ZRBNotification","userId","topic","tag","deliveryId","title","body","image","data","platform","drawerActive","boolean","createdAt","date","seenAt","readAt","archivedAt","IRBNotification","TTL_90_DAYS_S","RBNotificationSchema","type","String","required","index","Types","Mixed","Boolean","Date","default","now","versionKey","unique","partialFilterExpression","$exists","expireAfterSeconds","RBNotificationPolicy","subject","define","builder","ctx","can","Schema","z","AclPolicy","ZRBNotificationPlatformPayload","ZStringMap","record","string","ZRBNotificationDelivery","object","userId","notificationId","optional","deliveryId","topic","tag","title","body","image","data","platform","createdAt","date","IRBNotificationDelivery","infer","TTL_90_DAYS_S","RBNotificationDeliverySchema","type","String","required","index","unique","Types","Mixed","Date","default","now","versionKey","expireAfterSeconds","RBNotificationDeliveryPolicy","subject","define","builder","ctx","can","Schema","z","AclPolicy","ZRBNotificationDigestFrequency","enum","ZRBNotificationTopicPreference","object","topic","string","inApp","boolean","emailDigest","push","ZRBNotificationSettings","userId","digestFrequency","topicPreferences","array","optional","lastDigestSentAt","date","IRBNotificationSettings","infer","TopicPreferenceSchema","type","String","required","Boolean","default","_id","RBNotificationSettingsSchema","options","Date","versionKey","timestamps","index","unique","RBNotificationSettingsPolicy","subject","define","builder","ctx","can","Schema","z","ZRBOAuthRequest","object","_id","string","providerId","codeVerifier","returnTo","optional","createdAt","date","expiresAt","IRBOAuthRequest","infer","RBOAuthRequestSchema","type","String","required","index","Date","default","now","versionKey","expireAfterSeconds","Schema","MongooseSchemaExtension","Parameters","extendMongooseSchema","baseSchema","TSchema","extensions","schema","clone","forEach","extension","add","omitMongooseSchemaPaths","paths","path","remove","Schema","SchemaTypeOptions","LocalizedString","withLocalizedStringFallback","localizedStringField","options","Omit","userGet","get","type","Types","Mixed","value","PaginationErrorCode","PaginationValidationError","Error","code","statusCode","constructor","message","options","ErrorOptions","name","isPaginationValidationError","error","anyError","Partial","PaginationDirection","PaginationOrder","PaginationSpec","PaginationValidationError","DISALLOWED_MONGO_FIELD_SEGMENTS","Set","PAGINATION_LIMIT_MAX","NormalizedPaginationSpec","Omit","direction","limit","sort","Array","field","order","normalizePaginationSpec","spec","options","maxLimit","normalizeLimit","normalizeMaxLimit","isArray","length","map","assertSafeMongoFieldPath","normalizeOrder","seenFields","has","add","primaryOrder","push","undefined","Number","isSafeInteger","isFinite","isInteger","startsWith","parts","split","part","test","createHmac","timingSafeEqual","Types","PaginationSpec","PaginationValidationError","normalizePaginationSpec","CursorValue","$date","$oid","CursorPayloadV1","v","values","Record","PaginationCursorCodecOptions","signingSecret","Buffer","maxLimit","encodePaginationCursor","spec","node","options","normalized","Object","create","field","sort","value","readFieldValue","Error","encodeCursorValue","payload","payloadB64","from","JSON","stringify","toString","sigB64","signCursorPayloadB64","decodePaginationCursor","cursor","rest","split","length","verifyCursorSignature","payloadRaw","payloadUnknown","parse","Partial","decoded","prototype","hasOwnProperty","call","encodedValue","decodeCursorValue","secret","update","digest","expectedSigB64","a","b","unwrapCursorComparableValue","Date","ObjectId","current","depth","_id","comparableValue","toHexString","toISOString","d","Number","isNaN","getTime","isValid","undefined","get","path","reduce","acc","key","PaginationOrder","PaginationSpec","PaginationCursorCodecOptions","decodePaginationCursor","PaginationValidationError","NormalizedPaginationSpec","normalizePaginationSpec","CompiledMongoPagination","spec","mongoFilterDelta","Record","mongoSort","mongoLimit","CompileMongoPaginationOptions","cursor","compileMongoPagination","options","normalized","maxLimit","limit","toMongoSort","length","cursorValues","buildKeysetFilterDelta","Object","create","field","order","sort","forQueryOrder","direction","invertOrder","branches","i","current","and","j","prev","eq","push","op","getKeysetOp","cmpOp","cmp","$and","$or","PaginationResponse","PaginationCursorCodecOptions","encodePaginationCursor","CompiledMongoPagination","MaterializePaginationOptions","cursor","includeCursors","materializeMongoPagination","compiled","fetchedNodes","TNode","options","limit","spec","hasMore","length","trimmed","slice","nodes","direction","reverse","hasPrevPage","Boolean","hasNextPage","pageInfo","prevCursor","nextCursor","CompiledMongoPagination","MongoQueryLike","where","delta","Record","sort","limit","MongoAdapter","applyPagination","query","TQuery","compiled","mongoFilterDelta","mongoSort","mongoLimit","PaginationResponse","PaginationSpec","PaginationCursorCodecOptions","compileMongoPagination","materializeMongoPagination","MongoAdapter","MongoPaginateQueryLike","where","delta","Record","sort","limit","exec","Promise","TNode","PaginateMongoQueryOptions","cursor","includeCursors","paginateMongoQuery","query","pagination","options","compiled","applyPagination","fetchedNodes","Array","isArray","Error","mongoose","PaginationResponse","PaginationSpec","PaginationCursorCodecOptions","paginateMongoQuery","mongoPaginationPluginBrand","QueryOptionsLike","Record","getQueryOptions","query","undefined","getOptions","getPaginationFromOptions","options","pagination","getCursorFromOptions","paginationCursor","MongoPaginationPluginOptions","cursor","includeCursors","QueryResultNode","TResult","Array","TNode","Query","DocType","THelpers","RawDocType","QueryOp","TDocOverrides","paginate","Promise","ResultType","mongoPaginationPlugin","schema","Schema","pluginOptions","this","spec","Error","signingSecret","MongoDbLike","databaseName","command","Record","Promise","SearchTextStageOptions","index","query","path","highlightPath","SearchTextStage","$search","text","highlight","buildSearchTextStage","options","trim","Error","stage","searchMetaProjection","score","$meta","highlights","const","EnsureSearchIndexParams","db","collection","name","definition","listResultHasIndex","listResult","cursor","firstBatch","Array","isArray","some","idx","isIndexAlreadyExistsError","error","codeName","undefined","message","String","test","ensureSearchIndex","params","created","listSearchIndexes","createSearchIndexes","indexes","getAppName","env","NodeJS","ProcessEnv","process","appName","APP_NAME","trim","Error","GLOBAL_DB_SUFFIX","getGlobalDbName","getTenantDbName","tenantId","mongoose","isRecord","value","Record","Boolean","Array","isArray","mergeMongoQuery","left","right","TypeError","leftQuery","Object","keys","length","$and","cloneMongoValue","TValue","Date","getTime","Buffer","isBuffer","from","map","entry","prototype","getPrototypeOf","copy","create","key","entries","castMongoQuery","model","Model","query","casted","find","cast","modelName","mongoose","accessibleBy","hasRegisteredPolicy","castMongoQuery","isRecord","mergeMongoQuery","AclAction","AclSubjectType","AppAbility","PipelineStageLike","Record","allowedAggregateStages","Set","injectAggregateMatch","pipeline","match","Object","keys","length","unshift","$match","first","geoNear","$geoNear","query","splice","containsSearchMetadataReference","value","startsWith","Array","isArray","some","values","getModelCollectionName","model","Model","collection","collectionName","name","resolveAggregateModel","sourceModel","candidates","Map","connectionModels","db","models","typedModel","set","modelName","size","Error","assertAllowedAggregateStage","stage","stageNames","stageName","has","secureTargetPipeline","targetModel","ability","secureAggregateStages","accessQuery","ofType","$lookup","lookup","nestedPipeline","from","undefined","$unionWith","coll","unionWith","$graphLookup","graphLookup","targetAccessQuery","restrictSearchWithMatch","$facet","secureAggregatePipeline","action","AsyncLocalStorage","AppAbility","MongooseAclDriverContext","mode","ability","contextStorage","collectionContexts","WeakMap","rawConnections","unsafeMongooseAclDriverContext","Object","freeze","unboundMongooseAclDriverContext","bindMongooseAclDriverContext","value","context","set","getMongooseAclDriverContext","get","undefined","getStore","bindMongooseAclRawConnection","scopedConnection","rawConnection","getMongooseAclRawConnection","connection","TConnection","runWithMongooseAclDriverContext","callback","TResult","run","mongoose","ForbiddenError","subject","accessibleBy","secureAggregatePipeline","getMongooseAclDriverContext","runWithMongooseAclDriverContext","unsafeMongooseAclDriverContext","MongooseAclDriverContext","castMongoQuery","cloneMongoValue","isRecord","mergeMongoQuery","hasRegisteredPolicy","AclAction","AclSubject","AclSubjectType","AppAbility","NativeMongooseCollection","Collection","collection","conn","Connection","modelName","NativeMongooseCollectionConstructor","name","connection","options","Record","MongooseDriver","base","Mongoose","key","NativeMethod","args","NativeDriverAccessor","driver","get","nativeDriver","NativeCollection","rawCollections","WeakMap","rawCollectionProxies","raw","proxy","blockedNativeCollectionProperties","Set","PropertyKey","blockedCursorProperties","aggregateCursorMutationMethods","dataMethods","readFilterArgumentByMethod","Partial","count","countDocuments","distinct","find","findOne","writeFilterActionByMethod","deleteMany","deleteOne","findOneAndDelete","findOneAndReplace","findOneAndUpdate","replaceOne","updateMany","updateOne","getCollectionName","value","collectionName","getModelCollectionName","model","Model","getCollectionModels","Map","candidates","Object","values","models","typedModel","set","getCollectionModelName","size","keys","getProtectedCollectionModelNames","filter","hasSecuredCollectionBoundary","context","mode","some","getCollectionModel","Error","getAccessQuery","ability","action","ofType","assertCanCreate","rawValue","Document","toObject","document","from","throwUnlessCan","materializeBsonValue","seen","has","toBSON","placeholder","create","materialized","Reflect","apply","result","entry","entries","Date","Buffer","isBuffer","RegExp","ArrayBuffer","isView","_bsontype","Array","isArray","copy","push","materializeInsertDocument","safeExplainVerbosities","isSafeExplainVerbosity","verbosity","assertSafeExplainVerbosity","assertSafeExplainOptions","hasOwn","explain","assertNoUpsert","methodName","upsert","secureBulkWriteOperations","TypeError","map","operation","operationActions","supportedKeys","length","insertOne","details","secureCollectionArguments","input","readFilterIndex","undefined","writeAction","documents","pipeline","wrapFindCursor","cursor","Proxy","target","prop","String","wrapCursorStream","stream","wrapAggregateCursor","wrapCursorResult","then","Promise","resolve","resolved","invokeSafeUnprotectedCollectionMethod","rawCollection","Exclude","method","invokeNativeCollectionMethod","protectedModelNames","collectionModels","join","getRawCollectionProxy","cached","installRawCollectionAccessor","initialRawCollection","defineProperty","configurable","enumerable","delete","AclMongooseCollection","constructor","ACL_DRIVER_GLOBAL_KEY","Symbol","for","installMongooseAclDriver","globalState","globalThis","installedInstances","WeakSet","setDriver","add","runWithUnsafeMongooseAclDriver","callback","TResult","_private","mongoose","installMongooseAclDriver","getMongoDirectConnection","getMongoUrl","connections","Map","Connection","rootConnection","CONNECTION_MAX_LISTENERS","waitForOpen","connection","Promise","readyState","getMaxListeners","setMaxListeners","resolve","reject","once","ensureMongooseConnection","dbName","normalizedDbName","trim","Error","existing","get","mongoUrl","manageResourcesWithMigrations","process","env","NODE_ENV","createConnection","sanitizeFilter","directConnection","autoCreate","autoIndex","name","useDb","useCache","set","mongoose","getMongooseAclRawConnection","GLOBAL_DB_SUFFIX","RBRtsChangeSchema","IRBRtsChange","RBRtsCounterSchema","IRBRtsCounter","RtsChangeOp","RTS_COUNTER_ID","EXCLUDED_MODEL_NAMES","Set","maxDeleteIdsRaw","process","env","RB_RTS_DELETE_LOG_MAX_IDS","maxDeleteIds","Number","isFinite","Math","max","floor","DeleteMeta","modelName","ids","reset","session","ClientSession","deleteMetaByQuery","WeakMap","hasToString","value","toString","maybe","normalizeId","id","getDbName","db","name","databaseName","raw","isGlobalDb","endsWith","RtsCounterDoc","RtsChangeDoc","getQuerySession","query","MongooseQuery","opts","getOptions","undefined","getRtsModels","Connection","rawDb","RtsCounter","models","RBRtsCounter","Model","model","RtsChange","RBRtsChange","allocateSeqRange","count","Promise","start","end","updated","findOneAndUpdate","_id","$inc","seq","upsert","returnDocument","setDefaultsOnInsert","projection","lean","insertChanges","changes","Array","op","docId","length","ts","Date","docs","map","c","insertMany","recordDeleteChanges","uniqueIds","from","filter","Boolean","idx","recordResetModel","Query","find","getFilter","getQuery","captureDeleteMeta","mode","String","startsWith","has","findQuery","s","limit","n","isArray","d","trimmedIds","meta","set","flushDeleteMeta","get","delete","rtsChangeLogPlugin","schema","Schema","pre","document","this","post","doc","_private","mongoose","accessibleRecordsPlugin","frameworkSchemas","rtsChangeLogPlugin","registerPoliciesFromModules","installMongooseAclDriver","runWithUnsafeMongooseAclDriver","mongoPaginationPlugin","ModelModules","Record","ModelsScope","RegisterModelsOptions","allowReservedRbModelNames","RegisteredSchemas","Schema","RegisteredModels","tenant","global","cachedModels","DEFAULT_GLOBAL_RB_MODEL_NAMES_SET","Set","assertSchema","exportName","value","Error","join","getFrameworkSchemaForModelName","modelName","applyTenantPlugins","schema","plugin","registerSchema","target","other","scope","buildSchemasFromModules","modules","Array","Object","entries","filter","key","endsWith","map","schemaValue","replace","getFrameworkModelSchemas","cloned","clone","has","registerModels","options","tenantSchemas","globalSchemas","startsWith","frameworkSchema","allSchemas","models","model","getRegisteredModels","mongoose","AclMongooseCollection","installMongooseAclDriver","bindMongooseAclRawConnection","bindMongooseAclDriverContext","unboundMongooseAclDriverContext","unsafeMongooseAclDriverContext","MongooseAclDriverContext","hasRegisteredPolicy","AppAbility","mongooseAclModelBrand","Model","TRawDocType","TQueryHelpers","TInstanceMethods","TVirtuals","THydratedDocumentType","TSchema","TLeanResultType","acl","ability","SubclassableModel","TModel","__subclass","connection","Connection","schema","Schema","collectionName","scopedModelsByAbility","WeakMap","unboundModels","unsafeModels","collectionTargets","blockedModelMethods","Set","PropertyKey","blockedCollectionProperties","blockedConnectionMethods","blockedConnectionProperties","blockedMongooseMethods","blockedMongooseProperties","allowedDbProperties","getModelCollectionName","model","collection","name","value","resolveModelNameForCollection","candidates","Object","values","models","typedModel","add","modelName","size","undefined","detachMongooseSubclassRetention","rawModel","scopedModel","symbol","getOwnPropertySymbols","find","entry","description","subclasses","Record","Array","isArray","index","lastIndexOf","splice","getCachedModel","context","mode","get","cacheModel","set","lockModelCapability","target","property","descriptor","getOwnPropertyDescriptor","defineProperty","configurable","enumerable","Error","String","createAclModelWithContext","cached","rawConnection","db","primaryCollectionName","collections","Map","mongooseProxy","Mongoose","collectionsProxy","Collection","modelsProxy","dbProxy","getMongooseProxy","rawMongoose","base","Proxy","prop","has","Reflect","args","result","apply","_target","createCollectionProxy","proxy","connectionProxy","getCollection","options","existing","exposedCollection","getRelatedModel","relatedModel","getModelsProxy","receiver","hasOwn","deleteProperty","getCollectionsProxy","getDbProxy","rawDb","getClient","bind","length","then","Promise","resolve","resolved","scopedCollection","prototype","rawDiscriminators","discriminators","generatedDiscriminators","scopedDiscriminators","discriminator","entries","generated","methodName","createAclMongooseModel","AclMongooseModel","createAclMongooseModelGateway","createUnsafeMongooseModel","installMongooseAclModelFactory","modelConstructor","this","_private","setNativeCollection","nativeCollection","assert","getGlobalDbName","getTenantDbName","ensureMongooseConnection","getRegisteredModels","registerModels","ModelsScope","AppAbility","createAclMongooseModel","createAclMongooseModelGateway","createUnsafeMongooseModel","runWithUnsafeMongooseAclDriver","LoadModelCtx","tenantId","req","session","user","currentTenantId","ability","loadModelFromDb","modelName","dbName","scope","schemas","schema","Object","keys","join","modelConnection","models","process","env","NODE_ENV","set","model","init","normalizeTenantId","value","trim","getTenantIdFromLoadModelCtx","ctx","register","getUnsafe","get","getGlobal","const","LoadModelCtx","ModelModules","RegisterModelsOptions","frameworkSchemas","models","registerModels","ExtractModelNamesFromSchemas","TModules","K","Name","FrameworkModelName","RpcbaseGlobalModelName","Extract","TenantModelName","TTenantModules","GlobalModelName","TGlobalModules","LoadedTenantModel","Awaited","ReturnType","LoadedGlobalModel","ModelsGetFn","modelName","ctx","modelNames","TNames","Promise","ModelsGetUnsafeFn","ModelsGetGlobalFn","ModelsConfig","tenant","global","ModelsClient","register","modules","options","get","getUnsafe","getGlobal","createModels","Record","modelNameOrNames","Array","isArray","all","map","nextModules","nextOptions","assert","mongoose","ensureMongooseConnection","getTenantIdFromLoadModelCtx","LoadModelCtx","getAppName","appName","process","env","APP_NAME","trim","normalizeTenantId","tenantId","normalized","getTenantFilesystemDbName","getTenantFilesystemDb","Promise","Connection","getTenantFilesystemDbFromCtx","ctx","mongoose","ClientSession","getGlobalDbName","getTenantDbName","ensureMongooseConnection","getTenantIdFromLoadModelCtx","LoadModelCtx","getTenantFilesystemDbName","MongooseTransactionOptions","Parameters","TenantGlobalFilesystemTransactionCtx","tenantId","session","ctx","tenant","global","db","Connection","filesystem","WithTransactionScope","buildTenantLoadModelCtx","req","user","currentTenantId","withTransaction","fn","Promise","T","options","scope","normalizedTenantId","trim","Error","tenantDbName","globalDbName","filesystemDbName","tenantDb","globalDb","filesystemDb","startSession","tenantCtx","globalCtx","endSession","ClientSession","BillingStorage","BillingStorageTransaction","PersistedSubscriptionEvent","StoredSubscriptionProjection","SubscriptionEvent","ZRBTenantSubscriptionEvent","LoadModelCtx","models","withTransaction","MongoBillingTransaction","session","SubscriptionEventDocument","Record","_id","getTransactionSession","transaction","undefined","toSubscriptionEvent","document","parsed","parse","Error","id","String","getExistingEventQuery","event","tenantId","idempotencyKey","isDuplicateKeyError","error","Boolean","code","toProjectionDocument","projection","subscriptionId","type","parentSubscriptionId","scope","scopeId","planKey","priceId","status","intervalUnit","intervalCount","modules","billingAnchor","currentPeriodStart","currentPeriodEnd","cancelAtPeriodEnd","cancelAt","canceledAt","scheduledPlanKey","scheduledPlan","scheduledPlanEffectiveAt","effectiveAt","provider","latestEventId","latestEventAt","projectedAt","createTenantBillingStorage","params","ctx","findExistingEvent","query","Promise","EventModel","get","request","findOne","lean","runInTransaction","operation","createEvent","existingQuery","existing","eventDocument","documents","create","toObject","duplicate","listEvents","find","sort","occurredAt","map","upsertProjection","ProjectionModel","replaceOne","upsert","runValidators","mongoose","defineMongoResources","MigrationScope","MongoIndexResource","MongoResources","ExtractMongoResourcesOptions","scope","schemas","Readonly","Record","collectionNameForModel","modelName","schema","Schema","configured","options","collection","trim","pluralize","generatedIndexName","key","Object","entries","map","path","direction","String","join","observableIndexOptions","Set","extractMongoResourcesFromSchemas","filter","entry","exportName","replace","const","collections","name","indexes","indexOptions","documentKey","normalizedOptions","fromEntries","option","value","has","undefined","push","keys","length","TenantProvisioner","tenantId","Promise","TenantModel","create","document","Record","updateOne","filter","update","matchedCount","tenantProvisioner","configureTenantMigrationProvisioner","provisioner","undefined","errorMessage","error","Error","message","String","slice","createProvisionedTenant","Tenant","tenant","name","parentTenantId","provisioningStatus","provisioningStartedAt","Date","process","env","NODE_ENV","activation","$set","provisionedAt","$unset","provisioningError"],"sources":["../src/models/RBUser.ts","../src/models/RBTenant.ts","../src/models/RBTenantSubscriptionEvent.ts","../src/models/RBTenantSubscriptionProjection.ts","../src/models/RBRtsCounter.ts","../src/models/RBRtsChange.ts","../src/models/RBUploadSession.ts","../src/models/RBUploadChunk.ts","../src/models/RBNotification.ts","../src/models/RBNotificationDelivery.ts","../src/models/RBNotificationSettings.ts","../src/models/RBOAuthRequest.ts","../src/models/index.ts","../src/mongoose/extendMongooseSchema.ts","../src/mongoose/localizedStringField.ts","../src/mongoose/index.ts","../src/pagination/errors.ts","../src/pagination/normalizeSpec.ts","../src/pagination/cursor.ts","../src/pagination/compileMongoPagination.ts","../src/pagination/materializePagination.ts","../src/pagination/mongoAdapter.ts","../src/pagination/paginateMongoQuery.ts","../src/pagination/mongoPaginationPlugin.ts","../src/search/index.ts","../src/dbNames.ts","../src/acl/mongooseAclUtils.ts","../src/acl/mongooseAclAggregate.ts","../src/acl/mongooseAclDriverContext.ts","../src/acl/mongooseAclDriver.ts","../src/ensureMongooseConnection.ts","../src/rtsChangeLogPlugin.ts","../src/registerModels.ts","../src/acl/mongooseAclModel.ts","../src/modelsApi.ts","../src/createModels.ts","../src/tenantFilesystemDb.ts","../src/transactions.ts","../src/billingStorage.ts","../src/mongoResources.ts","../src/tenantProvisioning.ts"],"sourcesContent":["import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBUser = z.object({\n email: z.string().email().optional(),\n password: z.string(),\n name: z.string().optional(),\n phone: z.string().optional(),\n tenants: z.array(z.string()),\n tenantRoles: z.record(z.string(), z.array(z.string())).optional(),\n oauthProviders: z.record(z.string(), z.object({\n subject: z.string(),\n email: z.string().email().optional(),\n name: z.string().optional(),\n accessToken: z.string().optional(),\n refreshToken: z.string().optional(),\n idToken: z.string().optional(),\n scope: z.string().optional(),\n tokenType: z.string().optional(),\n expiresAt: z.date().optional(),\n rawUserInfo: z.unknown().optional(),\n createdAt: z.date().optional(),\n updatedAt: z.date().optional(),\n })).optional(),\n emailVerificationCode: z.string().length(6).optional(),\n emailVerificationExpiresAt: z.date().optional(),\n passwordResetCode: z.string().length(6).optional(),\n passwordResetCodeExpiresAt: z.date().optional(),\n passwordResetToken: z.string().optional(),\n passwordResetTokenExpiresAt: z.date().optional(),\n})\n\nexport type IRBUser = z.infer<typeof ZRBUser>;\n\nexport const RBUserSchema: Schema = new Schema({\n email: { type: String, unique: true, sparse: true },\n phone: { type: String, unique: true, sparse: true },\n password: { type: String, required: true },\n name: String,\n tenants: { type: [String], index: true, required: true },\n tenantRoles: { type: Map, of: [String], required: false, default: {} },\n oauthProviders: {\n type: Map,\n of: new Schema({\n subject: { type: String, required: true },\n email: { type: String, required: false },\n name: { type: String, required: false },\n accessToken: { type: String, required: false },\n refreshToken: { type: String, required: false },\n idToken: { type: String, required: false },\n scope: { type: String, required: false },\n tokenType: { type: String, required: false },\n expiresAt: { type: Date, required: false },\n rawUserInfo: { type: Schema.Types.Mixed, required: false },\n createdAt: { type: Date, required: false },\n updatedAt: { type: Date, required: false },\n }, { _id: false }),\n default: {},\n required: false,\n },\n emailVerificationCode: { type: String, required: false },\n emailVerificationExpiresAt: { type: Date, required: false },\n passwordResetCode: { type: String, required: false },\n passwordResetCodeExpiresAt: { type: Date, required: false },\n passwordResetToken: { type: String, required: false },\n passwordResetTokenExpiresAt: { type: Date, required: false },\n})\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBTenant = z.object({\n tenantId: z.string(),\n parentTenantId: z.string().optional(),\n name: z.string().optional(),\n provisioningStatus: z.enum([\"initializing\", \"active\", \"failed\"]).optional(),\n provisioningError: z.string().optional(),\n provisioningStartedAt: z.date().optional(),\n provisionedAt: z.date().optional(),\n})\n\nexport type IRBTenant = z.infer<typeof ZRBTenant>;\n\nexport const RBTenantSchema: Schema = new Schema({\n tenantId: { type: String, required: true, unique: true, index: true },\n parentTenantId: { type: String },\n name: { type: String },\n provisioningStatus: { type: String, enum: [\"initializing\", \"active\", \"failed\"] },\n provisioningError: { type: String },\n provisioningStartedAt: { type: Date },\n provisionedAt: { type: Date },\n})\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\nimport {\n SUBSCRIPTION_CHANGE_DIRECTIONS,\n SUBSCRIPTION_EVENT_TYPES,\n SUBSCRIPTION_INTERVAL_UNITS,\n SUBSCRIPTION_SCOPES,\n SUBSCRIPTION_STATUSES,\n SUBSCRIPTION_TYPES,\n} from \"@rpcbase/billing\"\n\n\nexport const ZRBTenantSubscriptionStatus = z.enum(SUBSCRIPTION_STATUSES)\n\nexport const ZRBTenantSubscriptionIntervalUnit = z.enum(SUBSCRIPTION_INTERVAL_UNITS)\n\nexport const ZRBTenantSubscriptionType = z.enum(SUBSCRIPTION_TYPES)\n\nexport const ZRBTenantSubscriptionScope = z.enum(SUBSCRIPTION_SCOPES)\n\nexport const ZRBTenantSubscriptionEventType = z.enum(SUBSCRIPTION_EVENT_TYPES)\n\n\nexport const ZRBTenantSubscriptionEventSource = z.enum([\n \"admin\",\n \"system\",\n \"webhook\",\n \"user\",\n])\n\nexport const ZRBTenantSubscriptionChangeDirection = z.enum(SUBSCRIPTION_CHANGE_DIRECTIONS)\n\nconst subscriptionEventBaseSchema = z.object({\n tenantId: z.string().trim().min(1),\n subscriptionId: z.string().trim().min(1),\n occurredAt: z.date(),\n effectiveAt: z.date(),\n subscriptionType: ZRBTenantSubscriptionType,\n parentSubscriptionId: z.string().optional(),\n scope: ZRBTenantSubscriptionScope,\n scopeId: z.string().optional(),\n fromPlanKey: z.string().optional(),\n toPlanKey: z.string().optional(),\n fromStatus: ZRBTenantSubscriptionStatus.optional(),\n toStatus: ZRBTenantSubscriptionStatus.optional(),\n fromModules: z.array(z.string()).optional(),\n toModules: z.array(z.string()).optional(),\n fromIntervalUnit: ZRBTenantSubscriptionIntervalUnit.optional(),\n toIntervalUnit: ZRBTenantSubscriptionIntervalUnit.optional(),\n fromIntervalCount: z.number().int().min(1).optional(),\n toIntervalCount: z.number().int().min(1).optional(),\n fromPriceId: z.string().optional(),\n toPriceId: z.string().optional(),\n billingAnchor: z.date().optional(),\n supersedesEventId: z.string().optional(),\n idempotencyKey: z.string().trim().min(1),\n direction: ZRBTenantSubscriptionChangeDirection.optional(),\n actorUserId: z.string().optional(),\n source: ZRBTenantSubscriptionEventSource.optional(),\n reason: z.string().optional(),\n provider: z.string().optional(),\n providerEventId: z.string().optional(),\n providerPayload: z.unknown().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n\nconst subscriptionCreatedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"created\"),\n toPlanKey: z.string().trim().min(1),\n toStatus: ZRBTenantSubscriptionStatus,\n toModules: z.array(z.string()),\n toIntervalUnit: ZRBTenantSubscriptionIntervalUnit,\n toIntervalCount: z.number().int().min(1),\n billingAnchor: z.date(),\n})\n\nconst subscriptionPlanChangedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"plan_changed\"),\n fromPlanKey: z.string().trim().min(1),\n toPlanKey: z.string().trim().min(1),\n fromModules: z.array(z.string()),\n toModules: z.array(z.string()),\n fromIntervalUnit: ZRBTenantSubscriptionIntervalUnit,\n toIntervalUnit: ZRBTenantSubscriptionIntervalUnit,\n fromIntervalCount: z.number().int().min(1),\n toIntervalCount: z.number().int().min(1),\n})\n\nconst subscriptionStatusChangedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"status_changed\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: ZRBTenantSubscriptionStatus,\n})\n\nconst subscriptionResumedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"resumed\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: z.literal(\"active\"),\n})\n\nconst subscriptionCanceledEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"canceled\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: z.literal(\"canceled\"),\n})\n\nconst subscriptionRenewedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"renewed\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: ZRBTenantSubscriptionStatus,\n})\n\nexport const ZRBTenantSubscriptionEvent = z.discriminatedUnion(\"type\", [\n subscriptionCreatedEventSchema,\n subscriptionPlanChangedEventSchema,\n subscriptionStatusChangedEventSchema,\n subscriptionResumedEventSchema,\n subscriptionCanceledEventSchema,\n subscriptionRenewedEventSchema,\n]).superRefine((event, ctx) => {\n if (event.subscriptionType === \"addon\" && !event.parentSubscriptionId?.trim()) {\n ctx.addIssue({\n code: \"custom\",\n message: \"parentSubscriptionId is required for add-on subscriptions\",\n path: [\"parentSubscriptionId\"],\n })\n }\n if (event.scope !== \"tenant\" && !event.scopeId?.trim()) {\n ctx.addIssue({\n code: \"custom\",\n message: \"scopeId is required for non-tenant subscriptions\",\n path: [\"scopeId\"],\n })\n }\n})\n\nexport type IRBTenantSubscriptionEvent = z.infer<typeof ZRBTenantSubscriptionEvent>\n\ntype SubscriptionEventDocument = {\n type?: typeof SUBSCRIPTION_EVENT_TYPES[number]\n subscriptionType?: typeof SUBSCRIPTION_TYPES[number]\n scope?: typeof SUBSCRIPTION_SCOPES[number]\n}\n\nconst requiredForEventTypes = (...types: Array<typeof SUBSCRIPTION_EVENT_TYPES[number]>) =>\n function requiredForEventType(this: SubscriptionEventDocument): boolean {\n return Boolean(this.type && types.includes(this.type))\n }\n\nexport const RBTenantSubscriptionEventSchema: Schema = new Schema(\n {\n tenantId: { type: String, required: true, index: true },\n subscriptionId: { type: String, required: true, index: true },\n type: { type: String, required: true, enum: ZRBTenantSubscriptionEventType.options },\n occurredAt: { type: Date, required: true, default: Date.now },\n effectiveAt: { type: Date, required: true },\n subscriptionType: { type: String, required: true, enum: ZRBTenantSubscriptionType.options },\n parentSubscriptionId: {\n type: String,\n required(this: SubscriptionEventDocument) {\n return this.subscriptionType === \"addon\"\n },\n },\n scope: { type: String, required: true, enum: ZRBTenantSubscriptionScope.options },\n scopeId: {\n type: String,\n required(this: SubscriptionEventDocument) {\n return Boolean(this.scope && this.scope !== \"tenant\")\n },\n },\n fromPlanKey: { type: String, required: requiredForEventTypes(\"plan_changed\") },\n toPlanKey: { type: String, required: requiredForEventTypes(\"created\", \"plan_changed\") },\n fromStatus: {\n type: String,\n required: requiredForEventTypes(\"status_changed\", \"resumed\", \"canceled\", \"renewed\"),\n enum: ZRBTenantSubscriptionStatus.options,\n },\n toStatus: {\n type: String,\n required: requiredForEventTypes(\"created\", \"status_changed\", \"resumed\", \"canceled\", \"renewed\"),\n enum: ZRBTenantSubscriptionStatus.options,\n },\n fromModules: { type: [String], required: requiredForEventTypes(\"plan_changed\"), default: undefined },\n toModules: { type: [String], required: requiredForEventTypes(\"created\", \"plan_changed\"), default: undefined },\n fromIntervalUnit: {\n type: String,\n required: requiredForEventTypes(\"plan_changed\"),\n enum: ZRBTenantSubscriptionIntervalUnit.options,\n },\n toIntervalUnit: {\n type: String,\n required: requiredForEventTypes(\"created\", \"plan_changed\"),\n enum: ZRBTenantSubscriptionIntervalUnit.options,\n },\n fromIntervalCount: { type: Number, required: requiredForEventTypes(\"plan_changed\"), min: 1 },\n toIntervalCount: { type: Number, required: requiredForEventTypes(\"created\", \"plan_changed\"), min: 1 },\n fromPriceId: { type: String },\n toPriceId: { type: String },\n billingAnchor: { type: Date, required: requiredForEventTypes(\"created\") },\n supersedesEventId: { type: String },\n idempotencyKey: { type: String, required: true },\n direction: { type: String, enum: ZRBTenantSubscriptionChangeDirection.options },\n actorUserId: { type: String },\n source: { type: String, enum: ZRBTenantSubscriptionEventSource.options },\n reason: { type: String },\n provider: { type: String },\n providerEventId: { type: String },\n providerPayload: { type: Schema.Types.Mixed },\n metadata: { type: Schema.Types.Mixed },\n },\n)\n\nRBTenantSubscriptionEventSchema.index({ tenantId: 1, subscriptionId: 1, effectiveAt: 1, occurredAt: 1 })\nRBTenantSubscriptionEventSchema.index(\n { provider: 1, providerEventId: 1 },\n {\n unique: true,\n partialFilterExpression: {\n provider: { $type: \"string\" },\n providerEventId: { $type: \"string\" },\n },\n },\n)\nRBTenantSubscriptionEventSchema.index({ tenantId: 1, idempotencyKey: 1 }, { unique: true })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport {\n ZRBTenantSubscriptionIntervalUnit,\n ZRBTenantSubscriptionScope,\n ZRBTenantSubscriptionStatus,\n ZRBTenantSubscriptionType,\n} from \"./RBTenantSubscriptionEvent\"\n\n\nexport const ZRBTenantSubscriptionProjection = z.object({\n tenantId: z.string(),\n subscriptionId: z.string(),\n type: ZRBTenantSubscriptionType,\n parentSubscriptionId: z.string().optional(),\n scope: ZRBTenantSubscriptionScope,\n scopeId: z.string().optional(),\n planKey: z.string(),\n priceId: z.string().optional(),\n status: ZRBTenantSubscriptionStatus,\n intervalUnit: ZRBTenantSubscriptionIntervalUnit,\n intervalCount: z.number().int().min(1),\n modules: z.array(z.string()),\n billingAnchor: z.date(),\n currentPeriodStart: z.date(),\n currentPeriodEnd: z.date(),\n cancelAtPeriodEnd: z.boolean(),\n cancelAt: z.date().optional(),\n canceledAt: z.date().optional(),\n scheduledPlanKey: z.string().optional(),\n scheduledPlanEffectiveAt: z.date().optional(),\n provider: z.string().optional(),\n latestEventId: z.string(),\n latestEventAt: z.date(),\n projectedAt: z.date(),\n})\n\nexport type IRBTenantSubscriptionProjection = z.infer<typeof ZRBTenantSubscriptionProjection>\n\nexport const RBTenantSubscriptionProjectionSchema: Schema = new Schema({\n tenantId: { type: String, required: true, index: true },\n subscriptionId: { type: String, required: true },\n type: { type: String, required: true, enum: ZRBTenantSubscriptionType.options },\n parentSubscriptionId: { type: String },\n scope: { type: String, required: true, enum: ZRBTenantSubscriptionScope.options },\n scopeId: { type: String },\n planKey: { type: String, required: true },\n priceId: { type: String },\n status: { type: String, required: true, enum: ZRBTenantSubscriptionStatus.options },\n intervalUnit: { type: String, required: true, enum: ZRBTenantSubscriptionIntervalUnit.options },\n intervalCount: { type: Number, required: true, min: 1 },\n modules: { type: [String], required: true, default: [] },\n billingAnchor: { type: Date, required: true },\n currentPeriodStart: { type: Date, required: true },\n currentPeriodEnd: { type: Date, required: true },\n cancelAtPeriodEnd: { type: Boolean, required: true, default: false },\n cancelAt: { type: Date },\n canceledAt: { type: Date },\n scheduledPlanKey: { type: String },\n scheduledPlanEffectiveAt: { type: Date },\n provider: { type: String },\n latestEventId: { type: String, required: true },\n latestEventAt: { type: Date, required: true },\n projectedAt: { type: Date, required: true },\n})\n\nRBTenantSubscriptionProjectionSchema.index({ tenantId: 1, subscriptionId: 1 }, { unique: true })\nRBTenantSubscriptionProjectionSchema.index({ tenantId: 1, scope: 1, scopeId: 1 })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBRtsCounter = z.object({\n _id: z.string(),\n seq: z.number().int().min(0),\n})\n\nexport type IRBRtsCounter = z.infer<typeof ZRBRtsCounter>\n\nexport const RBRtsCounterSchema: Schema = new Schema(\n {\n _id: { type: String, required: true },\n seq: { type: Number, required: true, default: 0 },\n },\n {\n versionKey: false,\n },\n)\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport { rtsChangesTtlSeconds } from \"../migrations/rtsChanges\"\n\n\nexport const ZRBRtsChangeOp = z.enum([\"delete\", \"reset_model\"])\n\nexport const ZRBRtsChange = z.object({\n seq: z.number().int().min(0),\n modelName: z.string(),\n op: ZRBRtsChangeOp,\n docId: z.string().optional(),\n ts: z.date(),\n})\n\nexport type IRBRtsChange = z.infer<typeof ZRBRtsChange>\n\nexport const RBRtsChangeSchema: Schema = new Schema(\n {\n seq: { type: Number, required: true },\n modelName: { type: String, required: true, index: true },\n op: { type: String, required: true, enum: ZRBRtsChangeOp.options },\n docId: { type: String, required: false },\n ts: { type: Date, required: true, default: Date.now },\n },\n {\n versionKey: false,\n },\n)\n\nRBRtsChangeSchema.index({ seq: 1 }, { unique: true })\nRBRtsChangeSchema.index({ ts: 1 }, { expireAfterSeconds: rtsChangesTtlSeconds })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\n\n\nexport const ZRBUploadSessionStatus = z.enum([\"uploading\", \"assembling\", \"done\", \"error\"])\nexport const ZRBUploadAccessScope = z.enum([\"owner\", \"tenant\", \"public\"])\n\nexport const ZRBUploadDeduplication = z.object({\n namespace: z.string(),\n algorithm: z.literal(\"sha256\"),\n hash: z.string(),\n key: z.string(),\n pipelineVersion: z.number().int().min(1),\n})\n\nexport const ZRBUploadSession = z.object({\n _id: z.string(),\n userId: z.string().optional(),\n ownerKeyHash: z.string().optional(),\n filename: z.string(),\n mimeType: z.string(),\n totalSize: z.number().int().min(0),\n chunkSize: z.number().int().min(1),\n chunksTotal: z.number().int().min(1),\n status: ZRBUploadSessionStatus,\n createdAt: z.date(),\n expiresAt: z.date(),\n fileId: z.string().optional(),\n isPublic: z.boolean().optional(),\n accessScope: ZRBUploadAccessScope.optional(),\n deduplication: ZRBUploadDeduplication.optional(),\n deduplicated: z.boolean().optional(),\n error: z.string().optional(),\n})\n\nexport type IRBUploadSession = z.infer<typeof ZRBUploadSession>\n\nexport const RBUploadSessionSchema: Schema = new Schema(\n {\n _id: { type: String, required: true },\n userId: { type: String, required: false, index: true },\n ownerKeyHash: { type: String, required: false },\n filename: { type: String, required: true },\n mimeType: { type: String, required: true },\n totalSize: { type: Number, required: true },\n chunkSize: { type: Number, required: true },\n chunksTotal: { type: Number, required: true },\n status: { type: String, required: true, enum: ZRBUploadSessionStatus.options },\n createdAt: { type: Date, required: true, default: Date.now },\n expiresAt: { type: Date, required: true },\n fileId: { type: String, required: false },\n isPublic: { type: Boolean, required: false },\n accessScope: { type: String, required: false, enum: ZRBUploadAccessScope.options },\n deduplication: {\n type: new Schema(\n {\n namespace: { type: String, required: true },\n algorithm: { type: String, required: true, enum: [\"sha256\"] },\n hash: { type: String, required: true },\n key: { type: String, required: true },\n pipelineVersion: { type: Number, required: true },\n },\n { _id: false },\n ),\n required: false,\n },\n deduplicated: { type: Boolean, required: false },\n error: { type: String, required: false },\n },\n {\n versionKey: false,\n },\n)\n\nRBUploadSessionSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 })\n\nexport const RBUploadSessionPolicy: AclPolicy = {\n subject: \"RBUploadSession\",\n define: (builder, ctx) => {\n builder.can(\"create\", \"RBUploadSession\")\n\n if (ctx.userId) {\n builder.can(\"read\", \"RBUploadSession\", { userId: ctx.userId })\n builder.can(\"update\", \"RBUploadSession\", { userId: ctx.userId })\n builder.can(\"delete\", \"RBUploadSession\", { userId: ctx.userId })\n }\n\n const uploadKeyHash = typeof ctx.claims?.uploadKeyHash === \"string\" ? ctx.claims.uploadKeyHash.trim() : \"\"\n if (uploadKeyHash) {\n builder.can(\"read\", \"RBUploadSession\", { ownerKeyHash: uploadKeyHash })\n builder.can(\"update\", \"RBUploadSession\", { ownerKeyHash: uploadKeyHash })\n builder.can(\"delete\", \"RBUploadSession\", { ownerKeyHash: uploadKeyHash })\n }\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBUploadChunk = z.object({\n uploadId: z.string(),\n index: z.number().int().min(0),\n data: z.unknown(),\n size: z.number().int().min(0),\n sha256: z.string().optional(),\n createdAt: z.date(),\n expiresAt: z.date(),\n})\n\nexport type IRBUploadChunk = z.infer<typeof ZRBUploadChunk>\n\nexport const RBUploadChunkSchema: Schema = new Schema(\n {\n uploadId: { type: String, required: true, index: true },\n index: { type: Number, required: true },\n data: { type: Buffer, required: true },\n size: { type: Number, required: true },\n sha256: { type: String, required: false },\n createdAt: { type: Date, required: true, default: Date.now },\n expiresAt: { type: Date, required: true },\n },\n {\n versionKey: false,\n },\n)\n\nRBUploadChunkSchema.index({ uploadId: 1, index: 1 }, { unique: true })\nRBUploadChunkSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\n\n\nconst ZStringMap = z.record(z.string(), z.string())\n\nexport const ZRBNotificationPlatformPayload = z.object({\n webpush: z.record(z.string(), z.unknown()).optional(),\n fcmOptions: z.record(z.string(), z.unknown()).optional(),\n android: z.record(z.string(), z.unknown()).optional(),\n apns: z.record(z.string(), z.unknown()).optional(),\n}).passthrough()\n\nexport type IRBNotificationPlatformPayload = z.infer<typeof ZRBNotificationPlatformPayload>\n\nexport const ZRBNotification = z.object({\n userId: z.string(),\n topic: z.string().optional(),\n tag: z.string().optional(),\n deliveryId: z.string().optional(),\n title: z.string(),\n body: z.string().optional(),\n image: z.string().optional(),\n data: ZStringMap.optional(),\n platform: ZRBNotificationPlatformPayload.optional(),\n drawerActive: z.boolean().optional(),\n createdAt: z.date(),\n seenAt: z.date().optional(),\n readAt: z.date().optional(),\n archivedAt: z.date().optional(),\n})\n\nexport type IRBNotification = z.infer<typeof ZRBNotification>\n\nconst TTL_90_DAYS_S = 60 * 60 * 24 * 90\n\nexport const RBNotificationSchema: Schema = new Schema(\n {\n userId: { type: String, required: true, index: true },\n topic: { type: String, required: false, index: true },\n tag: { type: String, required: false },\n deliveryId: { type: String, required: false },\n title: { type: String, required: true },\n body: { type: String, required: false },\n image: { type: String, required: false },\n data: { type: Schema.Types.Mixed, required: false },\n platform: { type: Schema.Types.Mixed, required: false },\n drawerActive: { type: Boolean, required: false },\n createdAt: { type: Date, required: true, default: Date.now, index: true },\n seenAt: { type: Date, required: false, index: true },\n readAt: { type: Date, required: false, index: true },\n archivedAt: { type: Date, required: false },\n },\n {\n versionKey: false,\n },\n)\n\nRBNotificationSchema.index({ userId: 1, archivedAt: 1, createdAt: -1 })\nRBNotificationSchema.index({ userId: 1, seenAt: 1, archivedAt: 1, createdAt: -1 })\nRBNotificationSchema.index({ userId: 1, readAt: 1, archivedAt: 1, createdAt: -1 })\nRBNotificationSchema.index(\n { userId: 1, tag: 1 },\n { unique: true, partialFilterExpression: { tag: { $exists: true }, drawerActive: true } },\n)\nRBNotificationSchema.index({ archivedAt: 1 }, { expireAfterSeconds: TTL_90_DAYS_S })\n\nexport const RBNotificationPolicy: AclPolicy = {\n subject: \"RBNotification\",\n define: (builder, ctx) => {\n if (!ctx.userId) return\n builder.can(\"create\", \"RBNotification\")\n builder.can(\"read\", \"RBNotification\", { userId: ctx.userId })\n builder.can(\"update\", \"RBNotification\", { userId: ctx.userId })\n builder.can(\"delete\", \"RBNotification\", { userId: ctx.userId })\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\nimport { ZRBNotificationPlatformPayload } from \"./RBNotification\"\n\n\nconst ZStringMap = z.record(z.string(), z.string())\n\nexport const ZRBNotificationDelivery = z.object({\n userId: z.string(),\n notificationId: z.string().optional(),\n deliveryId: z.string(),\n topic: z.string().optional(),\n tag: z.string().optional(),\n title: z.string(),\n body: z.string().optional(),\n image: z.string().optional(),\n data: ZStringMap.optional(),\n platform: ZRBNotificationPlatformPayload.optional(),\n createdAt: z.date(),\n})\n\nexport type IRBNotificationDelivery = z.infer<typeof ZRBNotificationDelivery>\n\nconst TTL_90_DAYS_S = 60 * 60 * 24 * 90\n\nexport const RBNotificationDeliverySchema: Schema = new Schema(\n {\n userId: { type: String, required: true, index: true },\n notificationId: { type: String, required: false },\n deliveryId: { type: String, required: true, unique: true },\n topic: { type: String, required: false },\n tag: { type: String, required: false },\n title: { type: String, required: true },\n body: { type: String, required: false },\n image: { type: String, required: false },\n data: { type: Schema.Types.Mixed, required: false },\n platform: { type: Schema.Types.Mixed, required: false },\n createdAt: { type: Date, required: true, default: Date.now },\n },\n {\n versionKey: false,\n },\n)\n\nRBNotificationDeliverySchema.index({ userId: 1, createdAt: -1 })\nRBNotificationDeliverySchema.index({ createdAt: 1 }, { expireAfterSeconds: TTL_90_DAYS_S })\n\nexport const RBNotificationDeliveryPolicy: AclPolicy = {\n subject: \"RBNotificationDelivery\",\n define: (builder, ctx) => {\n if (!ctx.userId) return\n builder.can(\"create\", \"RBNotificationDelivery\")\n builder.can(\"read\", \"RBNotificationDelivery\", { userId: ctx.userId })\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\n\n\nexport const ZRBNotificationDigestFrequency = z.enum([\"off\", \"daily\", \"weekly\"])\n\nexport const ZRBNotificationTopicPreference = z.object({\n topic: z.string(),\n inApp: z.boolean(),\n emailDigest: z.boolean(),\n push: z.boolean(),\n})\n\nexport const ZRBNotificationSettings = z.object({\n userId: z.string(),\n digestFrequency: ZRBNotificationDigestFrequency,\n topicPreferences: z.array(ZRBNotificationTopicPreference).optional(),\n lastDigestSentAt: z.date().optional(),\n})\n\nexport type IRBNotificationSettings = z.infer<typeof ZRBNotificationSettings>\n\nconst TopicPreferenceSchema = new Schema(\n {\n topic: { type: String, required: true },\n inApp: { type: Boolean, required: true, default: true },\n emailDigest: { type: Boolean, required: true, default: true },\n push: { type: Boolean, required: true, default: false },\n },\n { _id: false },\n)\n\nexport const RBNotificationSettingsSchema: Schema = new Schema(\n {\n userId: { type: String, required: true },\n digestFrequency: {\n type: String,\n required: true,\n enum: ZRBNotificationDigestFrequency.options,\n default: \"weekly\",\n },\n topicPreferences: {\n type: [TopicPreferenceSchema],\n default: [],\n },\n lastDigestSentAt: { type: Date, required: false },\n },\n {\n versionKey: false,\n timestamps: true,\n },\n)\n\nRBNotificationSettingsSchema.index({ userId: 1 }, { unique: true })\nRBNotificationSettingsSchema.index({ userId: 1, \"topicPreferences.topic\": 1 })\n\nexport const RBNotificationSettingsPolicy: AclPolicy = {\n subject: \"RBNotificationSettings\",\n define: (builder, ctx) => {\n if (!ctx.userId) return\n builder.can(\"create\", \"RBNotificationSettings\")\n builder.can(\"read\", \"RBNotificationSettings\", { userId: ctx.userId })\n builder.can(\"update\", \"RBNotificationSettings\", { userId: ctx.userId })\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBOAuthRequest = z.object({\n _id: z.string(),\n providerId: z.string(),\n codeVerifier: z.string(),\n returnTo: z.string().optional(),\n createdAt: z.date(),\n expiresAt: z.date(),\n})\n\nexport type IRBOAuthRequest = z.infer<typeof ZRBOAuthRequest>\n\nexport const RBOAuthRequestSchema: Schema = new Schema(\n {\n _id: { type: String, required: true },\n providerId: { type: String, required: true, index: true },\n codeVerifier: { type: String, required: true },\n returnTo: { type: String, required: false },\n createdAt: { type: Date, required: true, default: Date.now },\n expiresAt: { type: Date, required: true },\n },\n { versionKey: false },\n)\n\nRBOAuthRequestSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 })\n","export * from \"./RBUser\"\nexport * from \"./RBTenant\"\nexport * from \"./RBTenantSubscriptionEvent\"\nexport * from \"./RBTenantSubscriptionProjection\"\nexport * from \"./RBRtsCounter\"\nexport * from \"./RBRtsChange\"\nexport * from \"./RBUploadSession\"\nexport * from \"./RBUploadChunk\"\nexport * from \"./RBNotification\"\nexport * from \"./RBNotificationDelivery\"\nexport * from \"./RBNotificationSettings\"\nexport * from \"./RBOAuthRequest\"\n","import { Schema } from \"mongoose\"\n\n\ntype MongooseSchemaExtension = Parameters<Schema[\"add\"]>[0]\n\nexport function extendMongooseSchema<TSchema extends Schema>(\n baseSchema: TSchema,\n ...extensions: MongooseSchemaExtension[]\n): TSchema {\n const schema = baseSchema.clone() as TSchema\n\n extensions.forEach((extension) => schema.add(extension))\n\n return schema\n}\n\nexport function omitMongooseSchemaPaths<TSchema extends Schema>(\n schema: TSchema,\n paths: string[],\n): TSchema {\n const clone = schema.clone() as TSchema\n paths.forEach((path) => clone.remove(path))\n return clone\n}\n","import { Schema } from \"mongoose\"\nimport type { SchemaTypeOptions } from \"mongoose\"\n\nimport type { LocalizedString } from \"../zod/localizedString\"\nimport { withLocalizedStringFallback } from \"../zod/localizedString\"\n\n\nexport function localizedStringField(\n options?: Omit<SchemaTypeOptions<LocalizedString>, \"type\">\n): SchemaTypeOptions<LocalizedString> {\n const userGet = options?.get\n\n return {\n ...options,\n type: Schema.Types.Mixed,\n get: (value: unknown) => withLocalizedStringFallback(userGet ? userGet(value) : value),\n }\n}\n","import mongoose from \"mongoose\"\nimport type { InferSchemaType } from \"mongoose\"\n\n\nconst { Schema, model } = mongoose\n\nexport { Schema, model, mongoose, type InferSchemaType }\nexport * from \"./extendMongooseSchema\"\nexport * from \"./localizedStringField\"\n","export type PaginationErrorCode = \"invalid_pagination\"\n\nexport class PaginationValidationError extends Error {\n readonly code: PaginationErrorCode = \"invalid_pagination\"\n readonly statusCode = 400\n\n constructor(message: string, options?: ErrorOptions) {\n super(message, options)\n this.name = \"PaginationValidationError\"\n }\n}\n\nexport const isPaginationValidationError = (error: unknown): error is PaginationValidationError => {\n if (!error || typeof error !== \"object\") return false\n const anyError = error as Partial<PaginationValidationError>\n return (\n anyError.name === \"PaginationValidationError\" &&\n anyError.code === \"invalid_pagination\" &&\n anyError.statusCode === 400\n )\n}\n","import type { PaginationDirection, PaginationOrder, PaginationSpec } from \"@rpcbase/api\"\n\nimport { PaginationValidationError } from \"./errors\"\n\n\nconst DISALLOWED_MONGO_FIELD_SEGMENTS = new Set([\"__proto__\", \"constructor\", \"prototype\"])\nconst PAGINATION_LIMIT_MAX = 128\nexport type NormalizedPaginationSpec = Omit<PaginationSpec, \"direction\" | \"sort\" | \"limit\"> & {\n direction: PaginationDirection;\n limit: number;\n sort: Array<{\n field: string;\n order: PaginationOrder;\n }>;\n}\n\nexport const normalizePaginationSpec = (\n spec: PaginationSpec,\n options: { maxLimit?: number } = {},\n): NormalizedPaginationSpec => {\n if (!spec || typeof spec !== \"object\") throw new PaginationValidationError(\"Invalid PaginationSpec\")\n\n const limit = normalizeLimit(spec.limit, normalizeMaxLimit(options.maxLimit))\n const direction = spec.direction ?? \"next\"\n if (direction !== \"next\" && direction !== \"prev\") throw new PaginationValidationError(\"Invalid pagination direction\")\n\n if (!Array.isArray(spec.sort) || spec.sort.length === 0) throw new PaginationValidationError(\"Invalid pagination sort\")\n\n const sort: NormalizedPaginationSpec[\"sort\"] = spec.sort.map(({ field, order }) => ({\n field: assertSafeMongoFieldPath(field),\n order: normalizeOrder(order),\n }))\n\n const seenFields = new Set<string>()\n for (const { field } of sort) {\n if (seenFields.has(field)) throw new PaginationValidationError(`Duplicate pagination sort field: ${field}`)\n seenFields.add(field)\n }\n\n const primaryOrder = sort[0]?.order\n\n if (!seenFields.has(\"_id\")) {\n sort.push({ field: \"_id\", order: primaryOrder })\n }\n\n return {\n ...spec,\n limit,\n direction,\n sort,\n }\n}\n\nconst normalizeMaxLimit = (maxLimit: unknown): number => {\n if (maxLimit === undefined) return PAGINATION_LIMIT_MAX\n if (!Number.isSafeInteger(maxLimit) || (maxLimit as number) <= 0) {\n throw new PaginationValidationError(\"Invalid pagination max limit\")\n }\n return maxLimit as number\n}\n\nconst normalizeLimit = (limit: unknown, maxLimit: number): number => {\n if (typeof limit !== \"number\" || !Number.isFinite(limit) || !Number.isInteger(limit) || limit <= 0) {\n throw new PaginationValidationError(\"Invalid pagination limit\")\n }\n if (limit > maxLimit) {\n throw new PaginationValidationError(\"Invalid pagination limit\")\n }\n return limit\n}\n\nconst normalizeOrder = (order: unknown): PaginationOrder => {\n if (order !== \"asc\" && order !== \"desc\") throw new PaginationValidationError(\"Invalid pagination order\")\n return order\n}\n\nconst assertSafeMongoFieldPath = (field: unknown): string => {\n if (typeof field !== \"string\" || field.length === 0) throw new PaginationValidationError(\"Invalid pagination sort field\")\n if (field.startsWith(\"$\")) throw new PaginationValidationError(\"Invalid pagination sort field\")\n\n const parts = field.split(\".\")\n for (const part of parts) {\n if (part.length === 0) throw new PaginationValidationError(\"Invalid pagination sort field\")\n if (DISALLOWED_MONGO_FIELD_SEGMENTS.has(part)) throw new PaginationValidationError(\"Invalid pagination sort field\")\n if (!/^[a-zA-Z0-9_]+$/.test(part)) throw new PaginationValidationError(\"Invalid pagination sort field\")\n }\n\n return field\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\"\n\nimport { Types } from \"mongoose\"\nimport type { PaginationSpec } from \"@rpcbase/api\"\n\nimport { PaginationValidationError } from \"./errors\"\nimport { normalizePaginationSpec } from \"./normalizeSpec\"\n\n\ntype CursorValue =\n | null\n | string\n | number\n | boolean\n | { $date: string }\n | { $oid: string }\n\ntype CursorPayloadV1 = {\n v: 1;\n values: Record<string, CursorValue>;\n}\n\nexport type PaginationCursorCodecOptions = {\n signingSecret: string | Buffer;\n maxLimit?: number;\n}\n\nexport const encodePaginationCursor = (\n spec: PaginationSpec,\n node: unknown,\n options: PaginationCursorCodecOptions,\n): string => {\n const normalized = normalizePaginationSpec(spec, { maxLimit: options.maxLimit })\n\n const values = Object.create(null) as Record<string, CursorValue>\n for (const { field } of normalized.sort) {\n const value = readFieldValue(node, field)\n if (typeof value === \"undefined\") {\n throw new Error(`Pagination cursor encode failed (missing field: ${field})`)\n }\n values[field] = encodeCursorValue(field, value)\n }\n\n const payload: CursorPayloadV1 = { v: 1, values }\n const payloadB64 = Buffer.from(JSON.stringify(payload), \"utf8\").toString(\"base64url\")\n\n const sigB64 = signCursorPayloadB64(payloadB64, options.signingSecret)\n return `${payloadB64}.${sigB64}`\n}\n\nexport const decodePaginationCursor = (\n spec: PaginationSpec,\n cursor: string,\n options: PaginationCursorCodecOptions,\n): Record<string, unknown> => {\n const normalized = normalizePaginationSpec(spec, { maxLimit: options.maxLimit })\n\n const [payloadB64, sigB64, ...rest] = cursor.split(\".\")\n if (rest.length > 0) throw new PaginationValidationError(\"Invalid pagination cursor format\")\n if (!sigB64) throw new PaginationValidationError(\"Invalid pagination cursor format\")\n verifyCursorSignature(payloadB64, sigB64, options.signingSecret)\n\n const payloadRaw = Buffer.from(payloadB64, \"base64url\").toString(\"utf8\")\n\n let payloadUnknown: unknown\n try {\n payloadUnknown = JSON.parse(payloadRaw)\n } catch {\n throw new PaginationValidationError(\"Invalid pagination cursor payload\")\n }\n\n if (!payloadUnknown || typeof payloadUnknown !== \"object\") throw new PaginationValidationError(\"Invalid pagination cursor payload\")\n const payload = payloadUnknown as Partial<CursorPayloadV1>\n\n if (payload.v !== 1) throw new PaginationValidationError(\"Unsupported pagination cursor version\")\n if (!payload.values || typeof payload.values !== \"object\") throw new PaginationValidationError(\"Invalid pagination cursor payload\")\n\n const decoded = Object.create(null) as Record<string, unknown>\n for (const { field } of normalized.sort) {\n if (!Object.prototype.hasOwnProperty.call(payload.values, field)) {\n throw new PaginationValidationError(`Pagination cursor missing field: ${field}`)\n }\n const encodedValue = (payload.values as Record<string, CursorValue>)[field]\n decoded[field] = decodeCursorValue(field, encodedValue)\n }\n\n return decoded\n}\n\nconst signCursorPayloadB64 = (payloadB64: string, secret: string | Buffer): string => {\n return createHmac(\"sha256\", secret).update(payloadB64, \"utf8\").digest(\"base64url\")\n}\n\nconst verifyCursorSignature = (payloadB64: string, sigB64: string, secret: string | Buffer): void => {\n const expectedSigB64 = signCursorPayloadB64(payloadB64, secret)\n const a = Buffer.from(sigB64, \"utf8\")\n const b = Buffer.from(expectedSigB64, \"utf8\")\n if (a.length !== b.length || !timingSafeEqual(a, b)) {\n throw new PaginationValidationError(\"Invalid pagination cursor signature\")\n }\n}\n\nconst unwrapCursorComparableValue = (value: unknown): unknown => {\n if (value === null || typeof value !== \"object\") return value\n if (value instanceof Date || value instanceof Types.ObjectId) return value\n\n let current: unknown = value\n for (let depth = 0; depth < 4; depth += 1) {\n if (!current || typeof current !== \"object\") return current\n if (current instanceof Date || current instanceof Types.ObjectId) return current\n if (!(\"_id\" in current)) return current\n current = (current as { _id: unknown })._id\n }\n\n return current\n}\n\nconst encodeCursorValue = (field: string, value: unknown): CursorValue => {\n const comparableValue = unwrapCursorComparableValue(value)\n\n if (comparableValue === null) return null\n\n if (field === \"_id\") {\n if (comparableValue instanceof Types.ObjectId) return { $oid: comparableValue.toHexString() }\n if (typeof comparableValue === \"string\") return comparableValue\n throw new Error(\"Pagination cursor encode failed (_id must be an ObjectId or string)\")\n }\n\n if (comparableValue instanceof Date) return { $date: comparableValue.toISOString() }\n\n if (\n typeof comparableValue === \"string\" ||\n typeof comparableValue === \"number\" ||\n typeof comparableValue === \"boolean\"\n ) {\n return comparableValue\n }\n\n if (comparableValue instanceof Types.ObjectId) return { $oid: comparableValue.toHexString() }\n\n throw new Error(`Unsupported pagination cursor value type for field: ${field}`)\n}\n\nconst decodeCursorValue = (field: string, value: CursorValue): unknown => {\n if (value === null) return null\n\n if (typeof value === \"string\") {\n return value\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\") return value\n\n if (!value || typeof value !== \"object\") throw new PaginationValidationError(`Invalid pagination cursor value for field: ${field}`)\n\n if (\"$date\" in value) {\n if (typeof value.$date !== \"string\") throw new PaginationValidationError(`Invalid pagination cursor date for field: ${field}`)\n const d = new Date(value.$date)\n if (Number.isNaN(d.getTime())) throw new PaginationValidationError(`Invalid pagination cursor date for field: ${field}`)\n return d\n }\n\n if (\"$oid\" in value) {\n if (typeof value.$oid !== \"string\" || !Types.ObjectId.isValid(value.$oid)) {\n throw new PaginationValidationError(`Invalid pagination cursor ObjectId for field: ${field}`)\n }\n return new Types.ObjectId(value.$oid)\n }\n\n throw new PaginationValidationError(`Invalid pagination cursor value for field: ${field}`)\n}\n\nconst readFieldValue = (node: unknown, field: string): unknown => {\n if (!node || typeof node !== \"object\") return undefined\n\n if (\"get\" in node && typeof (node as { get?: unknown }).get === \"function\") {\n return (node as { get: (path: string) => unknown }).get(field)\n }\n\n return field.split(\".\").reduce((acc, key) => {\n if (!acc || typeof acc !== \"object\") return undefined\n return (acc as Record<string, unknown>)[key]\n }, node as unknown)\n}\n","import type { PaginationOrder, PaginationSpec } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { decodePaginationCursor } from \"./cursor\"\nimport { PaginationValidationError } from \"./errors\"\nimport type { NormalizedPaginationSpec } from \"./normalizeSpec\"\nimport { normalizePaginationSpec } from \"./normalizeSpec\"\n\n\nexport type CompiledMongoPagination = {\n spec: NormalizedPaginationSpec;\n mongoFilterDelta: Record<string, unknown>;\n mongoSort: Record<string, 1 | -1>;\n mongoLimit: number;\n}\n\nexport type CompileMongoPaginationOptions = {\n cursor: PaginationCursorCodecOptions;\n}\n\nexport const compileMongoPagination = (\n spec: PaginationSpec,\n options: CompileMongoPaginationOptions,\n): CompiledMongoPagination => {\n const normalized = normalizePaginationSpec(spec, { maxLimit: options.cursor.maxLimit })\n\n const mongoLimit = normalized.limit + 1\n const mongoSort = toMongoSort(normalized)\n\n if (normalized.cursor == null) {\n return {\n spec: normalized,\n mongoFilterDelta: {},\n mongoSort,\n mongoLimit,\n }\n }\n\n if (typeof normalized.cursor !== \"string\" || normalized.cursor.length === 0) {\n throw new PaginationValidationError(\"Invalid pagination cursor\")\n }\n\n const cursorValues = decodePaginationCursor(normalized, normalized.cursor, options.cursor)\n const mongoFilterDelta = buildKeysetFilterDelta(normalized, cursorValues)\n\n return {\n spec: normalized,\n mongoFilterDelta,\n mongoSort,\n mongoLimit,\n }\n}\n\nconst toMongoSort = (spec: NormalizedPaginationSpec): Record<string, 1 | -1> => {\n const mongoSort = Object.create(null) as Record<string, 1 | -1>\n for (const { field, order } of spec.sort) {\n const forQueryOrder = spec.direction === \"prev\" ? invertOrder(order) : order\n mongoSort[field] = forQueryOrder === \"asc\" ? 1 : -1\n }\n return mongoSort\n}\n\nconst buildKeysetFilterDelta = (\n spec: NormalizedPaginationSpec,\n cursorValues: Record<string, unknown>,\n): Record<string, unknown> => {\n const branches: Record<string, unknown>[] = []\n\n for (let i = 0; i < spec.sort.length; i++) {\n const current = spec.sort[i]\n if (!current) continue\n\n const and: Record<string, unknown>[] = []\n\n for (let j = 0; j < i; j++) {\n const prev = spec.sort[j]\n if (!prev) continue\n const eq = Object.create(null) as Record<string, unknown>\n eq[prev.field] = cursorValues[prev.field]\n and.push(eq)\n }\n\n const op = getKeysetOp(current.order, spec.direction)\n const cmpOp = Object.create(null) as Record<string, unknown>\n cmpOp[op] = cursorValues[current.field]\n const cmp = Object.create(null) as Record<string, unknown>\n cmp[current.field] = cmpOp\n and.push(cmp)\n\n branches.push(and.length === 1 ? and[0]! : { $and: and })\n }\n\n return { $or: branches }\n}\n\nconst getKeysetOp = (order: PaginationOrder, direction: NormalizedPaginationSpec[\"direction\"]): \"$gt\" | \"$lt\" => {\n if (direction === \"next\") return order === \"asc\" ? \"$gt\" : \"$lt\"\n return order === \"asc\" ? \"$lt\" : \"$gt\"\n}\n\nconst invertOrder = (order: PaginationOrder): PaginationOrder => {\n return order === \"asc\" ? \"desc\" : \"asc\"\n}\n","import type { PaginationResponse } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { encodePaginationCursor } from \"./cursor\"\nimport type { CompiledMongoPagination } from \"./compileMongoPagination\"\n\n\nexport type MaterializePaginationOptions = {\n cursor: PaginationCursorCodecOptions;\n includeCursors?: boolean;\n}\n\nexport const materializeMongoPagination = <TNode>(\n compiled: CompiledMongoPagination,\n fetchedNodes: TNode[],\n options: MaterializePaginationOptions,\n): PaginationResponse<TNode> => {\n const limit = compiled.spec.limit\n const hasMore = fetchedNodes.length > limit\n\n const trimmed = fetchedNodes.slice(0, limit)\n const nodes = compiled.spec.direction === \"prev\" ? trimmed.reverse() : trimmed\n\n const hasPrevPage = compiled.spec.direction === \"next\" ? Boolean(compiled.spec.cursor) : hasMore\n const hasNextPage = compiled.spec.direction === \"next\" ? hasMore : Boolean(compiled.spec.cursor)\n\n const pageInfo: PaginationResponse<TNode>[\"pageInfo\"] = {\n hasNextPage,\n hasPrevPage,\n }\n\n if (nodes.length === 0) {\n return { nodes, pageInfo }\n }\n\n if (options.includeCursors !== false && hasPrevPage) {\n pageInfo.prevCursor = encodePaginationCursor(compiled.spec, nodes[0], options.cursor)\n }\n\n if (options.includeCursors !== false && hasNextPage) {\n pageInfo.nextCursor = encodePaginationCursor(compiled.spec, nodes[nodes.length - 1], options.cursor)\n }\n\n return { nodes, pageInfo }\n}\n","import type { CompiledMongoPagination } from \"./compileMongoPagination\"\n\n\ntype MongoQueryLike = {\n where: (delta: Record<string, unknown>) => unknown;\n sort: (sort: Record<string, 1 | -1>) => unknown;\n limit: (limit: number) => unknown;\n}\n\nexport const MongoAdapter = {\n applyPagination: <TQuery extends MongoQueryLike>(query: TQuery, compiled: CompiledMongoPagination): TQuery => {\n query.where(compiled.mongoFilterDelta)\n query.sort(compiled.mongoSort)\n query.limit(compiled.mongoLimit)\n return query\n },\n}\n\n","import type { PaginationResponse, PaginationSpec } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { compileMongoPagination } from \"./compileMongoPagination\"\nimport { materializeMongoPagination } from \"./materializePagination\"\nimport { MongoAdapter } from \"./mongoAdapter\"\n\n\ntype MongoPaginateQueryLike<TNode> = {\n where: (delta: Record<string, unknown>) => unknown;\n sort: (sort: Record<string, 1 | -1>) => unknown;\n limit: (limit: number) => unknown;\n exec: () => Promise<TNode[]>;\n}\n\nexport type PaginateMongoQueryOptions = {\n cursor: PaginationCursorCodecOptions;\n includeCursors?: boolean;\n}\n\nexport const paginateMongoQuery = async <TNode>(\n query: MongoPaginateQueryLike<TNode>,\n pagination: PaginationSpec,\n options: PaginateMongoQueryOptions,\n): Promise<PaginationResponse<TNode>> => {\n const compiled = compileMongoPagination(pagination, { cursor: options.cursor })\n\n MongoAdapter.applyPagination(query, compiled)\n\n const fetchedNodes = await query.exec()\n if (!Array.isArray(fetchedNodes)) {\n throw new Error(\"paginateMongoQuery expects query.exec() to return an array\")\n }\n\n return materializeMongoPagination(compiled, fetchedNodes, {\n cursor: options.cursor,\n includeCursors: options.includeCursors,\n })\n}\n","import mongoose from \"mongoose\"\nimport type { PaginationResponse, PaginationSpec } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { paginateMongoQuery } from \"./paginateMongoQuery\"\n\n\ndeclare const mongoPaginationPluginBrand: unique symbol\n\n\ntype QueryOptionsLike = Record<string, unknown>\n\nconst getQueryOptions = (query: unknown): QueryOptionsLike | undefined => {\n if (!query || typeof query !== \"object\") return undefined\n if (!(\"getOptions\" in query) || typeof (query as { getOptions?: unknown }).getOptions !== \"function\") return undefined\n return (query as { getOptions: () => QueryOptionsLike }).getOptions()\n}\n\nconst getPaginationFromOptions = (query: unknown): PaginationSpec | undefined => {\n const options = getQueryOptions(query)\n return options?.pagination as PaginationSpec | undefined\n}\n\nconst getCursorFromOptions = (query: unknown): PaginationCursorCodecOptions | undefined => {\n const options = getQueryOptions(query)\n return options?.paginationCursor as PaginationCursorCodecOptions | undefined\n}\n\nexport type MongoPaginationPluginOptions = {\n cursor: PaginationCursorCodecOptions;\n includeCursors?: boolean;\n}\n\ntype QueryResultNode<TResult> = TResult extends Array<infer TNode> ? TNode : unknown\n\ndeclare module \"mongoose\" {\n interface Query<\n ResultType,\n DocType,\n THelpers = {},\n RawDocType = unknown,\n QueryOp = \"find\",\n TDocOverrides = Record<string, never>,\n > {\n [mongoPaginationPluginBrand]?: [DocType, THelpers, RawDocType, QueryOp, TDocOverrides];\n paginate: (\n pagination?: PaginationSpec,\n options?: MongoPaginationPluginOptions,\n ) => Promise<PaginationResponse<QueryResultNode<ResultType>>>;\n }\n}\n\nexport const mongoPaginationPlugin = (schema: mongoose.Schema, pluginOptions?: MongoPaginationPluginOptions): void => {\n ;(schema.query as Record<string, unknown>).paginate = async function(\n this: mongoose.Query<unknown[], unknown>,\n pagination?: PaginationSpec,\n options?: MongoPaginationPluginOptions,\n ): Promise<PaginationResponse<unknown>> {\n const spec = pagination ?? getPaginationFromOptions(this)\n if (!spec) throw new Error(\"Missing pagination spec\")\n\n const cursor = options?.cursor ?? getCursorFromOptions(this) ?? pluginOptions?.cursor\n if (!cursor?.signingSecret) throw new Error(\"Missing pagination cursor signingSecret\")\n\n return await paginateMongoQuery(this, spec, {\n cursor,\n includeCursors: options?.includeCursors ?? pluginOptions?.includeCursors,\n })\n }\n}\n","type MongoDbLike = {\n databaseName?: string\n command: (command: Record<string, unknown>) => Promise<unknown>\n}\n\nexport type SearchTextStageOptions = {\n index: string\n query: string\n path: string | string[]\n highlightPath?: string | string[]\n}\n\nexport type SearchTextStage = {\n $search: {\n index: string\n text: {\n query: string\n path: string | string[]\n }\n highlight?: {\n path: string | string[]\n }\n }\n}\n\nexport const buildSearchTextStage = (options: SearchTextStageOptions): SearchTextStage => {\n const index = options.index.trim()\n if (!index) throw new Error(\"Missing search index name\")\n\n const query = options.query.trim()\n if (!query) throw new Error(\"Missing search query\")\n\n const stage: SearchTextStage = {\n $search: {\n index,\n text: {\n query,\n path: options.path,\n },\n },\n }\n\n if (options.highlightPath) {\n stage.$search.highlight = { path: options.highlightPath }\n }\n\n return stage\n}\n\nexport const searchMetaProjection = () => {\n return {\n score: { $meta: \"searchScore\" },\n highlights: { $meta: \"searchHighlights\" },\n } as const\n}\n\nexport type EnsureSearchIndexParams = {\n db: MongoDbLike\n collection: string\n name: string\n definition: Record<string, unknown>\n}\n\nconst listResultHasIndex = (listResult: unknown, name: string): boolean => {\n if (!listResult || typeof listResult !== \"object\") return false\n if (!(\"cursor\" in listResult)) return false\n const cursor = (listResult as { cursor?: unknown }).cursor\n if (!cursor || typeof cursor !== \"object\") return false\n const firstBatch = (cursor as { firstBatch?: unknown }).firstBatch\n if (!Array.isArray(firstBatch)) return false\n return firstBatch.some((idx) => idx && typeof idx === \"object\" && \"name\" in idx && (idx as { name?: unknown }).name === name)\n}\n\nconst isIndexAlreadyExistsError = (error: unknown): boolean => {\n if (!error || typeof error !== \"object\") return false\n const codeName = \"codeName\" in error ? (error as { codeName?: unknown }).codeName : undefined\n if (codeName === \"IndexAlreadyExists\") return true\n const message = \"message\" in error ? String((error as { message?: unknown }).message ?? \"\") : \"\"\n return /already exists/i.test(message)\n}\n\nexport const ensureSearchIndex = async (params: EnsureSearchIndexParams): Promise<{ created: boolean }> => {\n const collection = params.collection.trim()\n if (!collection) throw new Error(\"Missing collection name\")\n\n const name = params.name.trim()\n if (!name) throw new Error(\"Missing search index name\")\n\n let listResult: unknown\n try {\n listResult = await params.db.command({ listSearchIndexes: collection })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n throw new Error(`listSearchIndexes failed for \"${collection}\": ${message}`)\n }\n\n if (listResultHasIndex(listResult, name)) {\n return { created: false }\n }\n\n try {\n await params.db.command({\n createSearchIndexes: collection,\n indexes: [{ name, definition: params.definition }],\n })\n } catch (error) {\n if (isIndexAlreadyExistsError(error)) {\n return { created: false }\n }\n const message = error instanceof Error ? error.message : String(error)\n throw new Error(`createSearchIndexes failed for \"${collection}\" (index \"${name}\"): ${message}`)\n }\n\n return { created: true }\n}\n","const getAppName = (env: NodeJS.ProcessEnv = process.env): string => {\n const appName = env.APP_NAME?.trim()\n if (!appName) {\n throw new Error(\"Missing APP_NAME\")\n }\n return appName\n}\n\nexport const GLOBAL_DB_SUFFIX = \"-global-db\"\n\nexport const getGlobalDbName = (env: NodeJS.ProcessEnv = process.env): string => {\n return `${getAppName(env)}${GLOBAL_DB_SUFFIX}`\n}\n\nexport const getTenantDbName = (tenantId: string, env: NodeJS.ProcessEnv = process.env): string => {\n return `${getAppName(env)}-${tenantId.trim()}-db`\n}\n","import type mongoose from \"mongoose\"\n\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value)\n\nexport const mergeMongoQuery = (\n left: unknown,\n right: Record<string, unknown>,\n): Record<string, unknown> => {\n if (left != null && !isRecord(left)) {\n throw new TypeError(\"ACL-protected MongoDB filters must be objects.\")\n }\n const leftQuery = left ?? {}\n if (Object.keys(leftQuery).length === 0) return right\n if (Object.keys(right).length === 0) return leftQuery\n return { $and: [leftQuery, right] }\n}\n\nexport const cloneMongoValue = <TValue>(value: TValue): TValue => {\n if (value instanceof Date) {\n return new Date(value.getTime()) as TValue\n }\n\n if (Buffer.isBuffer(value)) {\n return Buffer.from(value) as TValue\n }\n\n if (Array.isArray(value)) {\n return value.map((entry) => cloneMongoValue(entry)) as TValue\n }\n\n if (!isRecord(value)) {\n return value\n }\n\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) return value\n\n const copy = Object.create(prototype) as Record<string, unknown>\n for (const [key, entry] of Object.entries(value)) {\n copy[key] = cloneMongoValue(entry)\n }\n return copy as TValue\n}\n\nexport const castMongoQuery = (\n model: mongoose.Model<unknown>,\n query: Record<string, unknown>,\n): Record<string, unknown> => {\n const casted = model.find(cloneMongoValue(query)).cast(model)\n if (!isRecord(casted)) {\n throw new TypeError(`Mongoose returned an invalid casted query for model \"${model.modelName}\".`)\n }\n return casted\n}\n","import mongoose from \"mongoose\"\nimport { accessibleBy } from \"@casl/mongoose\"\n\nimport { hasRegisteredPolicy } from \"./registry\"\nimport { castMongoQuery, isRecord, mergeMongoQuery } from \"./mongooseAclUtils\"\nimport type { AclAction, AclSubjectType, AppAbility } from \"./types\"\n\n\ntype PipelineStageLike = Record<string, unknown>\n\nconst allowedAggregateStages = new Set([\n \"$addFields\",\n \"$bucket\",\n \"$bucketAuto\",\n \"$count\",\n \"$densify\",\n \"$facet\",\n \"$fill\",\n \"$geoNear\",\n \"$graphLookup\",\n \"$group\",\n \"$limit\",\n \"$lookup\",\n \"$match\",\n \"$project\",\n \"$redact\",\n \"$replaceRoot\",\n \"$replaceWith\",\n \"$sample\",\n \"$search\",\n \"$set\",\n \"$setWindowFields\",\n \"$skip\",\n \"$sort\",\n \"$sortByCount\",\n \"$unionWith\",\n \"$unset\",\n \"$unwind\",\n \"$vectorSearch\",\n])\n\nexport const injectAggregateMatch = (\n pipeline: PipelineStageLike[],\n match: Record<string, unknown>,\n): void => {\n if (Object.keys(match).length === 0) return\n if (pipeline.length === 0) {\n pipeline.unshift({ $match: match })\n return\n }\n\n const first = pipeline[0]\n if (!isRecord(first)) {\n pipeline.unshift({ $match: match })\n return\n }\n\n if (\"$geoNear\" in first) {\n const geoNear = first.$geoNear\n if (isRecord(geoNear)) {\n geoNear.query = mergeMongoQuery(geoNear.query, match)\n return\n }\n }\n\n if (\"$search\" in first || \"$vectorSearch\" in first) {\n pipeline.splice(1, 0, { $match: match })\n return\n }\n\n pipeline.unshift({ $match: match })\n}\n\nconst containsSearchMetadataReference = (value: unknown): boolean => {\n if (typeof value === \"string\") {\n return value === \"$$SEARCH_META\" || value.startsWith(\"$$SEARCH_META.\")\n }\n if (Array.isArray(value)) return value.some(containsSearchMetadataReference)\n if (!isRecord(value)) return false\n return Object.values(value).some(containsSearchMetadataReference)\n}\n\nconst getModelCollectionName = (model: mongoose.Model<unknown>): string | null => {\n const collection = model.collection as unknown as { collectionName?: unknown; name?: unknown }\n if (typeof collection.collectionName === \"string\") return collection.collectionName\n if (typeof collection.name === \"string\") return collection.name\n return null\n}\n\nexport const resolveAggregateModel = (\n sourceModel: mongoose.Model<unknown>,\n collectionName: string,\n): mongoose.Model<unknown> => {\n const candidates = new Map<string, mongoose.Model<unknown>>()\n const connectionModels = sourceModel.db?.models ?? {}\n\n for (const model of [...Object.values(connectionModels), ...Object.values(mongoose.models)]) {\n const typedModel = model as mongoose.Model<unknown>\n if (getModelCollectionName(typedModel) !== collectionName) continue\n candidates.set(typedModel.modelName, typedModel)\n }\n\n if (candidates.size === 0) {\n throw new Error(\n `ACL driver cannot access collection \"${collectionName}\" because no registered Mongoose model maps to it.`,\n )\n }\n\n if (candidates.size > 1) {\n throw new Error(\n `ACL driver cannot resolve collection \"${collectionName}\" unambiguously.`,\n )\n }\n\n return [...candidates.values()][0]\n}\n\nconst assertAllowedAggregateStage = (stage: PipelineStageLike): void => {\n const stageNames = Object.keys(stage)\n if (stageNames.length !== 1) {\n throw new Error(\"ACL-protected aggregates require exactly one operator per pipeline stage.\")\n }\n\n const stageName = stageNames[0]\n if (stageName === \"$merge\" || stageName === \"$out\") {\n throw new Error(\n `ACL-protected aggregates cannot use ${stageName}. Use models.getUnsafe(...) after explicit authorization.`,\n )\n }\n\n if (!allowedAggregateStages.has(stageName)) {\n throw new Error(\n `ACL-protected aggregates cannot use unreviewed stage ${stageName}. Use models.getUnsafe(...) explicitly.`,\n )\n }\n}\n\nconst secureTargetPipeline = (\n pipeline: PipelineStageLike[],\n targetModel: mongoose.Model<unknown>,\n ability?: AppAbility,\n): void => {\n secureAggregateStages(pipeline, targetModel, ability)\n if (!hasRegisteredPolicy(targetModel.modelName)) return\n if (!ability) {\n throw new Error(\n `ACL-protected aggregate target \"${targetModel.modelName}\" requires .acl(ability).`,\n )\n }\n\n const accessQuery = castMongoQuery(\n targetModel,\n accessibleBy(ability, \"read\").ofType(targetModel.modelName as AclSubjectType),\n )\n injectAggregateMatch(pipeline, accessQuery)\n}\n\nconst secureAggregateStages = (\n pipeline: PipelineStageLike[],\n sourceModel: mongoose.Model<unknown>,\n ability?: AppAbility,\n): void => {\n for (const stage of pipeline) {\n if (!isRecord(stage)) {\n throw new Error(\"ACL-protected aggregates require object pipeline stages.\")\n }\n if (containsSearchMetadataReference(stage)) {\n throw new Error(\n \"ACL-protected aggregates cannot expose $$SEARCH_META because it includes unauthorized search matches.\",\n )\n }\n assertAllowedAggregateStage(stage)\n\n if (isRecord(stage.$lookup)) {\n const lookup = stage.$lookup\n const nestedPipeline = Array.isArray(lookup.pipeline)\n ? lookup.pipeline as PipelineStageLike[]\n : []\n\n if (typeof lookup.from === \"string\") {\n const targetModel = resolveAggregateModel(sourceModel, lookup.from)\n lookup.pipeline = nestedPipeline\n secureTargetPipeline(nestedPipeline, targetModel, ability)\n } else if (lookup.from === undefined && Array.isArray(lookup.pipeline)) {\n secureAggregateStages(nestedPipeline, sourceModel, ability)\n } else {\n throw new Error(\"ACL-protected $lookup requires a registered collection name in `from`.\")\n }\n }\n\n if (typeof stage.$unionWith === \"string\") {\n const targetModel = resolveAggregateModel(sourceModel, stage.$unionWith)\n const nestedPipeline: PipelineStageLike[] = []\n stage.$unionWith = { coll: stage.$unionWith, pipeline: nestedPipeline }\n secureTargetPipeline(nestedPipeline, targetModel, ability)\n } else if (isRecord(stage.$unionWith)) {\n const unionWith = stage.$unionWith\n const nestedPipeline = Array.isArray(unionWith.pipeline)\n ? unionWith.pipeline as PipelineStageLike[]\n : []\n\n if (typeof unionWith.coll === \"string\") {\n const targetModel = resolveAggregateModel(sourceModel, unionWith.coll)\n unionWith.pipeline = nestedPipeline\n secureTargetPipeline(nestedPipeline, targetModel, ability)\n } else if (unionWith.coll === undefined && Array.isArray(unionWith.pipeline)) {\n secureAggregateStages(nestedPipeline, sourceModel, ability)\n } else {\n throw new Error(\"ACL-protected $unionWith requires a registered collection name in `coll`.\")\n }\n }\n\n if (isRecord(stage.$graphLookup)) {\n const graphLookup = stage.$graphLookup\n const collectionName = graphLookup.from\n if (typeof collectionName !== \"string\") {\n throw new Error(\"ACL-protected $graphLookup requires a registered collection name in `from`.\")\n }\n const targetModel = resolveAggregateModel(sourceModel, collectionName)\n if (hasRegisteredPolicy(targetModel.modelName)) {\n if (!ability) {\n throw new Error(\n `ACL-protected aggregate target \"${targetModel.modelName}\" requires .acl(ability).`,\n )\n }\n const targetAccessQuery = castMongoQuery(\n targetModel,\n accessibleBy(ability, \"read\").ofType(targetModel.modelName as AclSubjectType),\n )\n graphLookup.restrictSearchWithMatch = mergeMongoQuery(\n graphLookup.restrictSearchWithMatch,\n targetAccessQuery,\n )\n }\n }\n\n if (isRecord(stage.$facet)) {\n for (const nestedPipeline of Object.values(stage.$facet)) {\n if (!Array.isArray(nestedPipeline)) {\n throw new Error(\"ACL-protected $facet entries must be pipelines.\")\n }\n secureAggregateStages(nestedPipeline as PipelineStageLike[], sourceModel, ability)\n }\n }\n }\n}\n\nexport const secureAggregatePipeline = (\n pipeline: PipelineStageLike[],\n model: mongoose.Model<unknown>,\n ability: AppAbility | undefined,\n action: AclAction,\n): void => {\n secureAggregateStages(pipeline, model, ability)\n if (!hasRegisteredPolicy(model.modelName)) return\n if (!ability) {\n throw new Error(\n `ACL-protected model \"${model.modelName}\" requires .acl(ability).`,\n )\n }\n const accessQuery = castMongoQuery(\n model,\n accessibleBy(ability, action).ofType(model.modelName as AclSubjectType),\n )\n injectAggregateMatch(pipeline, accessQuery)\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\"\n\nimport type { AppAbility } from \"./types\"\n\n\nexport type MongooseAclDriverContext =\n | { mode: \"ability\"; ability: AppAbility }\n | { mode: \"unbound\" }\n | { mode: \"unsafe\" }\n\nconst contextStorage = new AsyncLocalStorage<MongooseAclDriverContext>()\nconst collectionContexts = new WeakMap<object, MongooseAclDriverContext>()\nconst rawConnections = new WeakMap<object, object>()\n\nexport const unsafeMongooseAclDriverContext: MongooseAclDriverContext = Object.freeze({\n mode: \"unsafe\",\n})\n\nexport const unboundMongooseAclDriverContext: MongooseAclDriverContext = Object.freeze({\n mode: \"unbound\",\n})\n\nexport const bindMongooseAclDriverContext = (\n value: object,\n context: MongooseAclDriverContext,\n): void => {\n collectionContexts.set(value, context)\n}\n\nexport const getMongooseAclDriverContext = (\n value?: object,\n): MongooseAclDriverContext | undefined => {\n return (value ? collectionContexts.get(value) : undefined) ?? contextStorage.getStore()\n}\n\nexport const bindMongooseAclRawConnection = (\n scopedConnection: object,\n rawConnection: object,\n): void => {\n rawConnections.set(scopedConnection, rawConnection)\n}\n\nexport const getMongooseAclRawConnection = <TConnection extends object>(\n connection: TConnection,\n): TConnection => (rawConnections.get(connection) ?? connection) as TConnection\n\nexport const runWithMongooseAclDriverContext = <TResult>(\n context: MongooseAclDriverContext,\n callback: () => TResult,\n): TResult => contextStorage.run(context, callback)\n","import mongoose from \"mongoose\"\nimport { ForbiddenError, subject } from \"@casl/ability\"\nimport { accessibleBy } from \"@casl/mongoose\"\n\nimport { secureAggregatePipeline } from \"./mongooseAclAggregate\"\nimport {\n getMongooseAclDriverContext,\n runWithMongooseAclDriverContext,\n unsafeMongooseAclDriverContext,\n type MongooseAclDriverContext,\n} from \"./mongooseAclDriverContext\"\nimport { castMongoQuery, cloneMongoValue, isRecord, mergeMongoQuery } from \"./mongooseAclUtils\"\nimport { hasRegisteredPolicy } from \"./registry\"\nimport type { AclAction, AclSubject, AclSubjectType, AppAbility } from \"./types\"\n\n\ntype NativeMongooseCollection = mongoose.Collection & {\n collection: unknown\n conn: mongoose.Connection\n modelName?: string\n}\n\ntype NativeMongooseCollectionConstructor = new (\n name: string,\n connection: mongoose.Connection,\n options?: Record<string, unknown>,\n) => NativeMongooseCollection\n\ntype MongooseDriver = {\n Collection: NativeMongooseCollectionConstructor\n Connection: new (base: mongoose.Mongoose) => mongoose.Connection\n [key: string]: unknown\n}\n\ntype NativeMethod = (...args: unknown[]) => unknown\n\ntype NativeDriverAccessor = typeof mongoose & {\n driver: {\n get: () => MongooseDriver\n }\n}\n\nconst nativeDriver = (mongoose as NativeDriverAccessor).driver.get()\nconst NativeCollection = nativeDriver.Collection\nconst rawCollections = new WeakMap<object, object | null>()\nconst rawCollectionProxies = new WeakMap<object, { raw: object; proxy: object }>()\nconst blockedNativeCollectionProperties = new Set<PropertyKey>([\n \"client\",\n \"db\",\n \"s\",\n])\nconst blockedCursorProperties = new Set<PropertyKey>([\n \"aggregateOptions\",\n \"client\",\n \"cursorClient\",\n \"cursorFilter\",\n \"cursorOptions\",\n \"cursorSession\",\n \"selectedServer\",\n \"server\",\n \"session\",\n])\nconst aggregateCursorMutationMethods = new Set<PropertyKey>([\n \"addStage\",\n \"geoNear\",\n \"group\",\n \"limit\",\n \"lookup\",\n \"match\",\n \"out\",\n \"project\",\n \"redact\",\n \"skip\",\n \"sort\",\n \"unwind\",\n])\n\nconst dataMethods = new Set([\n \"aggregate\",\n \"bulkWrite\",\n \"count\",\n \"countDocuments\",\n \"deleteMany\",\n \"deleteOne\",\n \"distinct\",\n \"estimatedDocumentCount\",\n \"find\",\n \"findOne\",\n \"findOneAndDelete\",\n \"findOneAndReplace\",\n \"findOneAndUpdate\",\n \"insertMany\",\n \"insertOne\",\n \"replaceOne\",\n \"updateMany\",\n \"updateOne\",\n])\n\nconst readFilterArgumentByMethod: Partial<Record<string, number>> = {\n count: 0,\n countDocuments: 0,\n distinct: 1,\n find: 0,\n findOne: 0,\n}\n\nconst writeFilterActionByMethod: Partial<Record<string, AclAction>> = {\n deleteMany: \"delete\",\n deleteOne: \"delete\",\n findOneAndDelete: \"delete\",\n findOneAndReplace: \"update\",\n findOneAndUpdate: \"update\",\n replaceOne: \"update\",\n updateMany: \"update\",\n updateOne: \"update\",\n}\n\nconst getCollectionName = (collection: NativeMongooseCollection): string => {\n const value = collection.collectionName ?? collection.name\n return typeof value === \"string\" ? value : \"\"\n}\n\nconst getModelCollectionName = (model: mongoose.Model<unknown>): string | null => {\n const collection = model.collection as unknown as { collectionName?: unknown; name?: unknown }\n if (typeof collection.collectionName === \"string\") return collection.collectionName\n if (typeof collection.name === \"string\") return collection.name\n return null\n}\n\nconst getCollectionModels = (\n collection: NativeMongooseCollection,\n): Map<string, mongoose.Model<unknown>> => {\n const collectionName = getCollectionName(collection)\n const candidates = new Map<string, mongoose.Model<unknown>>()\n for (const model of [\n ...Object.values(mongoose.models),\n ...Object.values(collection.conn.models ?? {}),\n ]) {\n const typedModel = model as mongoose.Model<unknown>\n if (getModelCollectionName(typedModel) === collectionName) {\n candidates.set(typedModel.modelName, typedModel)\n }\n }\n\n return candidates\n}\n\nconst getCollectionModelName = (collection: NativeMongooseCollection): string | null => {\n if (typeof collection.modelName === \"string\" && collection.modelName) {\n return collection.modelName\n }\n\n const candidates = getCollectionModels(collection)\n return candidates.size === 1 ? [...candidates.keys()][0] : null\n}\n\nconst getProtectedCollectionModelNames = (\n collection: NativeMongooseCollection,\n): string[] => [...getCollectionModels(collection).keys()].filter(hasRegisteredPolicy)\n\nconst hasSecuredCollectionBoundary = (\n collection: NativeMongooseCollection,\n): boolean => {\n const context = getMongooseAclDriverContext(collection)\n if (context) return context.mode !== \"unsafe\"\n\n if (typeof collection.modelName === \"string\" && collection.modelName) {\n if (hasRegisteredPolicy(collection.modelName)) return true\n }\n return [...getCollectionModels(collection).keys()].some(hasRegisteredPolicy)\n}\n\nconst getCollectionModel = (\n collection: NativeMongooseCollection,\n modelName: string,\n): mongoose.Model<unknown> => {\n const model = collection.conn.models?.[modelName] ?? mongoose.models[modelName]\n if (!model) {\n throw new Error(`ACL driver could not resolve Mongoose model \"${modelName}\".`)\n }\n return model as mongoose.Model<unknown>\n}\n\nconst getAccessQuery = (\n ability: AppAbility,\n action: AclAction,\n model: mongoose.Model<unknown>,\n): Record<string, unknown> => castMongoQuery(\n model,\n accessibleBy(ability, action).ofType(model.modelName as AclSubjectType),\n)\n\nconst assertCanCreate = (\n ability: AppAbility,\n modelName: string,\n value: unknown,\n): void => {\n const rawValue = value instanceof mongoose.Document ? value.toObject() : value\n const document = isRecord(rawValue) ? rawValue : {}\n ForbiddenError.from(ability).throwUnlessCan(\n \"create\",\n subject(modelName, document) as unknown as AclSubject,\n )\n}\n\nconst materializeBsonValue = (\n value: unknown,\n seen: WeakMap<object, unknown>,\n): unknown => {\n if (!value || typeof value !== \"object\") return value\n if (seen.has(value)) return seen.get(value)\n\n const toBSON = (value as { toBSON?: unknown }).toBSON\n if (typeof toBSON === \"function\") {\n const placeholder = Object.create(null) as Record<string, unknown>\n seen.set(value, placeholder)\n const materialized = Reflect.apply(toBSON, value, []) as unknown\n if (materialized !== value) {\n const result = materializeBsonValue(materialized, seen)\n seen.set(value, result)\n return result\n }\n\n for (const [key, entry] of Object.entries(value)) {\n if (key === \"toBSON\" && typeof entry === \"function\") continue\n placeholder[key] = materializeBsonValue(entry, seen)\n }\n return placeholder\n }\n\n if (value instanceof Date || Buffer.isBuffer(value)) return cloneMongoValue(value)\n if (\n value instanceof RegExp\n || ArrayBuffer.isView(value)\n || (isRecord(value) && typeof value._bsontype === \"string\")\n ) {\n return value\n }\n\n if (Array.isArray(value)) {\n const copy: unknown[] = []\n seen.set(value, copy)\n for (const entry of value) copy.push(materializeBsonValue(entry, seen))\n return copy\n }\n\n if (value instanceof Map) {\n const copy = new Map<unknown, unknown>()\n seen.set(value, copy)\n for (const [key, entry] of value) {\n copy.set(key, materializeBsonValue(entry, seen))\n }\n return copy\n }\n\n const copy = Object.create(null) as Record<string, unknown>\n seen.set(value, copy)\n for (const [key, entry] of Object.entries(value)) {\n copy[key] = materializeBsonValue(entry, seen)\n }\n return copy\n}\n\nconst materializeInsertDocument = (value: unknown): unknown =>\n materializeBsonValue(value, new WeakMap<object, unknown>())\n\nconst safeExplainVerbosities = new Set([\n \"queryPlanner\",\n \"queryPlannerExtended\",\n])\n\nconst isSafeExplainVerbosity = (value: unknown): boolean => {\n if (value === false) return true\n if (typeof value === \"string\") return safeExplainVerbosities.has(value)\n return isRecord(value) && isSafeExplainVerbosity(value.verbosity)\n}\n\nconst assertSafeExplainVerbosity = (value: unknown): void => {\n if (!isSafeExplainVerbosity(value)) {\n throw new Error(\n \"ACL-protected cursors cannot expose execution statistics. Use queryPlanner verbosity or models.getUnsafe(...) explicitly.\",\n )\n }\n}\n\nconst assertSafeExplainOptions = (options: unknown): void => {\n if (\n isRecord(options)\n && Object.hasOwn(options, \"explain\")\n && options.explain != null\n ) {\n assertSafeExplainVerbosity(options.explain)\n }\n}\n\nconst assertNoUpsert = (methodName: string, options: unknown): void => {\n if (isRecord(options) && options.upsert === true) {\n throw new Error(\n `ACL-protected ${methodName}() cannot use upsert. Use models.getUnsafe(...) after explicit create and update authorization.`,\n )\n }\n}\n\nconst secureBulkWriteOperations = (\n ability: AppAbility,\n model: mongoose.Model<unknown>,\n value: unknown,\n): Array<Record<string, unknown>> => {\n if (!Array.isArray(value)) {\n throw new TypeError(\"ACL-protected bulkWrite() expects an array of operations.\")\n }\n\n return value.map((operation) => {\n if (!isRecord(operation)) {\n throw new TypeError(\"ACL-protected bulkWrite() received an invalid operation.\")\n }\n\n const operationActions: Array<{ key: string; action: AclAction }> = [\n { key: \"updateOne\", action: \"update\" },\n { key: \"updateMany\", action: \"update\" },\n { key: \"replaceOne\", action: \"update\" },\n { key: \"deleteOne\", action: \"delete\" },\n { key: \"deleteMany\", action: \"delete\" },\n ]\n const supportedKeys = [\n \"insertOne\",\n ...operationActions.map(({ key }) => key),\n ].filter((key) => Object.hasOwn(operation, key))\n if (supportedKeys.length !== 1 || Object.keys(operation).length !== 1) {\n throw new Error(\n \"ACL-protected bulkWrite() requires exactly one supported operator per operation.\",\n )\n }\n\n if (supportedKeys[0] === \"insertOne\" && isRecord(operation.insertOne)) {\n const document = materializeInsertDocument(operation.insertOne.document)\n assertCanCreate(ability, model.modelName, document)\n return {\n ...cloneMongoValue(operation),\n insertOne: {\n ...cloneMongoValue(operation.insertOne),\n document,\n },\n }\n }\n\n for (const { key, action } of operationActions) {\n const details = operation[key]\n if (!isRecord(details)) continue\n assertNoUpsert(`bulkWrite ${key}`, details)\n return {\n ...cloneMongoValue(operation),\n [key]: {\n ...cloneMongoValue(details),\n filter: mergeMongoQuery(details.filter, getAccessQuery(ability, action, model)),\n },\n }\n }\n\n throw new Error(\"ACL-protected bulkWrite() received an unsupported operation.\")\n })\n}\n\nconst secureCollectionArguments = (\n collection: NativeMongooseCollection,\n ability: AppAbility,\n modelName: string,\n methodName: string,\n input: unknown[],\n): unknown[] => {\n const args = input.map((value) => cloneMongoValue(value))\n const model = getCollectionModel(collection, modelName)\n if (methodName === \"find\" || methodName === \"findOne\" || methodName === \"aggregate\") {\n assertSafeExplainOptions(args[1])\n }\n const readFilterIndex = readFilterArgumentByMethod[methodName]\n if (readFilterIndex !== undefined) {\n args[readFilterIndex] = mergeMongoQuery(\n args[readFilterIndex],\n getAccessQuery(ability, \"read\", model),\n )\n return args\n }\n\n const writeAction = writeFilterActionByMethod[methodName]\n if (writeAction) {\n if (writeAction === \"update\") {\n assertNoUpsert(methodName, args[2])\n }\n args[0] = mergeMongoQuery(args[0], getAccessQuery(ability, writeAction, model))\n return args\n }\n\n if (methodName === \"insertOne\") {\n args[0] = materializeInsertDocument(input[0])\n assertCanCreate(ability, modelName, args[0])\n return args\n }\n\n if (methodName === \"insertMany\") {\n if (!Array.isArray(input[0])) {\n throw new TypeError(\"ACL-protected insertMany() expects an array of documents.\")\n }\n const documents = input[0].map((document) => materializeInsertDocument(document))\n for (const document of documents) assertCanCreate(ability, modelName, document)\n args[0] = documents\n return args\n }\n\n if (methodName === \"bulkWrite\") {\n args[0] = secureBulkWriteOperations(ability, model, input[0])\n return args\n }\n\n if (methodName === \"aggregate\") {\n if (!Array.isArray(args[0])) {\n throw new TypeError(\"ACL-protected aggregate() expects a pipeline array.\")\n }\n const pipeline = args[0] as Array<Record<string, unknown>>\n secureAggregatePipeline(\n pipeline,\n model,\n ability,\n \"read\",\n )\n args[0] = pipeline\n return args\n }\n\n if (methodName === \"estimatedDocumentCount\") {\n throw new Error(\n \"ACL-protected estimatedDocumentCount() cannot be filtered. Use countDocuments() or models.getUnsafe(...).\",\n )\n }\n\n throw new Error(\n `ACL-protected collection method ${methodName}() is not supported. Use models.getUnsafe(...) explicitly.`,\n )\n}\n\nconst wrapFindCursor = (cursor: object): object => {\n const proxy: object = new Proxy(cursor, {\n get(target, prop) {\n if (blockedCursorProperties.has(prop)) {\n throw new Error(\n `ACL-protected cursor property .${String(prop)} is blocked.`,\n )\n }\n const value = Reflect.get(target, prop, target) as unknown\n if (prop === \"filter\") {\n return () => {\n throw new Error(\"ACL-protected cursors cannot replace their filter.\")\n }\n }\n if (prop === \"addQueryModifier\" && typeof value === \"function\") {\n return (...args: unknown[]) => {\n if (args[0] === \"$query\") {\n throw new Error(\"ACL-protected cursors cannot replace their filter.\")\n }\n if (args[0] === \"$explain\") assertSafeExplainVerbosity(args[1])\n const result = Reflect.apply(value, target, args) as unknown\n return result === target ? proxy : result\n }\n }\n if (prop === \"explain\" && typeof value === \"function\") {\n return (...args: unknown[]) => {\n assertSafeExplainVerbosity(args[0])\n return Reflect.apply(value, target, args) as unknown\n }\n }\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => {\n const result = Reflect.apply(value, target, args) as unknown\n if (prop === \"stream\" && result && typeof result === \"object\") {\n return wrapCursorStream(result)\n }\n if (prop === \"clone\" && result && typeof result === \"object\") {\n return wrapFindCursor(result)\n }\n return result === target ? proxy : result\n }\n },\n set() {\n throw new Error(\"ACL-protected cursors cannot be mutated directly.\")\n },\n })\n return proxy\n}\n\nconst wrapCursorStream = (stream: object): object => {\n const proxy: object = new Proxy(stream, {\n get(target, prop) {\n if (prop === \"_cursor\") {\n throw new Error(\"ACL-protected cursor streams do not expose their native cursor.\")\n }\n const value = Reflect.get(target, prop, target) as unknown\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => {\n const result = Reflect.apply(value, target, args) as unknown\n return result === target ? proxy : result\n }\n },\n set(target, prop, value) {\n if (prop === \"_cursor\") {\n throw new Error(\"ACL-protected cursor streams cannot replace their native cursor.\")\n }\n return Reflect.set(target, prop, value, target)\n },\n })\n return proxy\n}\n\nconst wrapAggregateCursor = (cursor: object): object => {\n const proxy: object = new Proxy(cursor, {\n get(target, prop) {\n if (blockedCursorProperties.has(prop)) {\n throw new Error(\n `ACL-protected aggregation cursor property .${String(prop)} is blocked.`,\n )\n }\n if (prop === \"pipeline\") {\n return cloneMongoValue(Reflect.get(target, prop, target))\n }\n const value = Reflect.get(target, prop, target) as unknown\n if (aggregateCursorMutationMethods.has(prop)) {\n return () => {\n throw new Error(\n \"ACL-protected aggregation cursors cannot mutate their pipeline after validation.\",\n )\n }\n }\n if (prop === \"explain\" && typeof value === \"function\") {\n return (...args: unknown[]) => {\n assertSafeExplainVerbosity(args[0])\n return Reflect.apply(value, target, args) as unknown\n }\n }\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => {\n const result = Reflect.apply(value, target, args) as unknown\n if (prop === \"stream\" && result && typeof result === \"object\") {\n return wrapCursorStream(result)\n }\n if (prop === \"clone\" && result && typeof result === \"object\") {\n return wrapAggregateCursor(result)\n }\n return result === target ? proxy : result\n }\n },\n set() {\n throw new Error(\"ACL-protected aggregation cursors cannot be mutated directly.\")\n },\n })\n return proxy\n}\n\nconst wrapCursorResult = (\n methodName: string,\n result: unknown,\n): unknown => {\n if (result && typeof result === \"object\" && \"then\" in result && typeof result.then === \"function\") {\n return Promise.resolve(result).then((resolved) => wrapCursorResult(methodName, resolved))\n }\n if (!result || typeof result !== \"object\") return result\n if (methodName === \"find\") return wrapFindCursor(result)\n if (methodName === \"aggregate\") return wrapAggregateCursor(result)\n return result\n}\n\nconst invokeSafeUnprotectedCollectionMethod = (\n collection: NativeMongooseCollection,\n rawCollection: object,\n modelName: string,\n context: Exclude<MongooseAclDriverContext, { mode: \"unsafe\" }>,\n methodName: string,\n method: NativeMethod,\n input: unknown[],\n): unknown => {\n if (!dataMethods.has(methodName)) {\n throw new Error(\n `Safe collection method ${methodName}() is not supported. Use models.getUnsafe(...) explicitly.`,\n )\n }\n\n const args = input.map((value) => cloneMongoValue(value))\n if (methodName === \"aggregate\") {\n if (!Array.isArray(args[0])) {\n throw new TypeError(\"Safe aggregate() expects a pipeline array.\")\n }\n secureAggregatePipeline(\n args[0] as Array<Record<string, unknown>>,\n getCollectionModel(collection, modelName),\n context.mode === \"ability\" ? context.ability : undefined,\n \"read\",\n )\n }\n\n const result = Reflect.apply(method, rawCollection, args)\n return wrapCursorResult(methodName, result)\n}\n\nconst invokeNativeCollectionMethod = (\n collection: NativeMongooseCollection,\n rawCollection: object,\n methodName: string,\n method: NativeMethod,\n input: unknown[],\n): unknown => {\n const context = getMongooseAclDriverContext(collection)\n const modelName = getCollectionModelName(collection)\n\n if (context?.mode === \"unsafe\") {\n return Reflect.apply(method, rawCollection, input)\n }\n\n if (modelName && !hasRegisteredPolicy(modelName)) {\n const protectedModelNames = getProtectedCollectionModelNames(collection)\n if (protectedModelNames.length > 0) {\n throw new Error(\n `Model \"${modelName}\" maps to ACL-protected collection \"${getCollectionName(collection)}\" without its own policy.`,\n )\n }\n if (!context) return Reflect.apply(method, rawCollection, input)\n return invokeSafeUnprotectedCollectionMethod(\n collection,\n rawCollection,\n modelName,\n context,\n methodName,\n method,\n input,\n )\n }\n\n if (!modelName) {\n const collectionModels = getCollectionModels(collection)\n const protectedModelNames = [...collectionModels.keys()].filter(hasRegisteredPolicy)\n if (collectionModels.size > 0 && protectedModelNames.length === 0) {\n if (!context) return Reflect.apply(method, rawCollection, input)\n return invokeSafeUnprotectedCollectionMethod(\n collection,\n rawCollection,\n [...collectionModels.keys()][0],\n context,\n methodName,\n method,\n input,\n )\n }\n if (protectedModelNames.length > 0) {\n throw new Error(\n `ACL driver cannot choose a policy for collection \"${getCollectionName(collection)}\" (${protectedModelNames.join(\", \")}). Use models.get(...).acl(ability).`,\n )\n }\n throw new Error(\n `ACL driver cannot authorize unregistered collection \"${getCollectionName(collection)}\". Use models.getUnsafe(...) explicitly.`,\n )\n }\n\n if (context?.mode !== \"ability\") {\n if (context?.mode === \"unbound\") {\n throw new Error(\n `Model \"${modelName}\" is ACL-protected. Call .acl(ability) before executing the operation.`,\n )\n }\n throw new Error(\n `Model \"${modelName}\" is ACL-protected. Use models.get(...).acl(ability) or models.getUnsafe(...) explicitly.`,\n )\n }\n\n if (!dataMethods.has(methodName)) {\n throw new Error(\n `ACL-protected collection method ${methodName}() is not filterable. Use models.getUnsafe(...) explicitly.`,\n )\n }\n\n const args = secureCollectionArguments(\n collection,\n context.ability,\n modelName,\n methodName,\n input,\n )\n const result = Reflect.apply(method, rawCollection, args)\n return wrapCursorResult(methodName, result)\n}\n\nconst getRawCollectionProxy = (\n collection: NativeMongooseCollection,\n rawCollection: object,\n): object => {\n const cached = rawCollectionProxies.get(collection)\n if (cached?.raw === rawCollection) return cached.proxy\n\n const proxy = new Proxy(rawCollection, {\n get(target, prop) {\n if (blockedNativeCollectionProperties.has(prop) && hasSecuredCollectionBoundary(collection)) {\n throw new Error(\n `ACL-protected native collection property .${String(prop)} is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n }\n const value = Reflect.get(target, prop, target) as unknown\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => invokeNativeCollectionMethod(\n collection,\n target,\n String(prop),\n value as NativeMethod,\n args,\n )\n },\n set(target, prop, value) {\n if (hasSecuredCollectionBoundary(collection)) {\n throw new Error(\n `ACL-protected native collection property .${String(prop)} cannot be changed. Use models.getUnsafe(...) explicitly.`,\n )\n }\n return Reflect.set(target, prop, value, target)\n },\n })\n rawCollectionProxies.set(collection, { raw: rawCollection, proxy })\n return proxy\n}\n\nconst installRawCollectionAccessor = (collection: NativeMongooseCollection): void => {\n const initialRawCollection = collection.collection\n Object.defineProperty(collection, \"collection\", {\n configurable: true,\n enumerable: true,\n get() {\n const rawCollection = rawCollections.get(collection)\n return rawCollection ? getRawCollectionProxy(collection, rawCollection) : rawCollection\n },\n set(value: unknown) {\n rawCollections.set(collection, value && typeof value === \"object\" ? value : null)\n rawCollectionProxies.delete(collection)\n },\n })\n collection.collection = initialRawCollection\n}\n\nexport class AclMongooseCollection extends NativeCollection {\n constructor(\n name: string,\n connection: mongoose.Connection,\n options: Record<string, unknown> = {},\n ) {\n super(name, connection, options)\n installRawCollectionAccessor(this)\n }\n}\n\nconst ACL_DRIVER_GLOBAL_KEY = Symbol.for(\"@rpcbase/db/acl/mongooseDriverInstalled\")\n\nexport const installMongooseAclDriver = (): void => {\n const globalState = globalThis as unknown as Record<symbol, unknown>\n const installedInstances = globalState[ACL_DRIVER_GLOBAL_KEY] instanceof WeakSet\n ? globalState[ACL_DRIVER_GLOBAL_KEY] as WeakSet<object>\n : new WeakSet<object>()\n if (installedInstances.has(mongoose)) return\n\n mongoose.setDriver({\n ...nativeDriver,\n Collection: AclMongooseCollection,\n })\n installedInstances.add(mongoose)\n globalState[ACL_DRIVER_GLOBAL_KEY] = installedInstances\n}\n\nexport const runWithUnsafeMongooseAclDriver = <TResult>(\n callback: () => TResult,\n): TResult => runWithMongooseAclDriverContext(unsafeMongooseAclDriverContext, callback)\n\nexport const _private = {\n getCollectionModels,\n getCollectionModelName,\n secureBulkWriteOperations,\n secureCollectionArguments,\n}\n","import mongoose from \"mongoose\"\n\nimport { installMongooseAclDriver } from \"./acl/mongooseAclDriver\"\nimport { getMongoDirectConnection, getMongoUrl } from \"./getMongoUrl\"\n\n\ninstallMongooseAclDriver()\n\nconst connections = new Map<string, mongoose.Connection>()\nlet rootConnection: mongoose.Connection | null = null\nconst CONNECTION_MAX_LISTENERS = 50\n\nconst waitForOpen = async (connection: mongoose.Connection): Promise<void> => {\n if (connection.readyState === 1) return\n if (connection.getMaxListeners() < CONNECTION_MAX_LISTENERS) {\n connection.setMaxListeners(CONNECTION_MAX_LISTENERS)\n }\n\n await new Promise<void>((resolve, reject) => {\n connection.once(\"open\", resolve)\n connection.once(\"error\", reject)\n })\n}\n\nexport const ensureMongooseConnection = async (dbName: string): Promise<mongoose.Connection> => {\n const normalizedDbName = dbName.trim()\n if (!normalizedDbName) {\n throw new Error(\"Missing dbName\")\n }\n\n const existing = connections.get(normalizedDbName)\n if (existing) {\n await waitForOpen(existing)\n return existing\n }\n\n if (!rootConnection) {\n const mongoUrl = getMongoUrl()\n const manageResourcesWithMigrations = process.env.NODE_ENV === \"production\"\n rootConnection = mongoose.createConnection(mongoUrl, {\n sanitizeFilter: true,\n dbName: normalizedDbName,\n directConnection: getMongoDirectConnection(),\n autoCreate: !manageResourcesWithMigrations,\n autoIndex: !manageResourcesWithMigrations,\n })\n }\n\n await waitForOpen(rootConnection)\n\n const connection = rootConnection.name === normalizedDbName\n ? rootConnection\n : rootConnection.useDb(normalizedDbName, { useCache: true })\n\n await waitForOpen(connection)\n\n connections.set(normalizedDbName, connection)\n return connection\n}\n","import type mongoose from \"mongoose\"\n\nimport { getMongooseAclRawConnection } from \"./acl/mongooseAclDriverContext\"\nimport { GLOBAL_DB_SUFFIX } from \"./dbNames\"\nimport { RBRtsChangeSchema, type IRBRtsChange } from \"./models/RBRtsChange\"\nimport { RBRtsCounterSchema, type IRBRtsCounter } from \"./models/RBRtsCounter\"\n\n\ntype RtsChangeOp = IRBRtsChange[\"op\"]\n\nconst RTS_COUNTER_ID = \"rts\"\nconst EXCLUDED_MODEL_NAMES = new Set([\"RBRtsChange\", \"RBRtsCounter\"])\n\nconst maxDeleteIdsRaw = process.env.RB_RTS_DELETE_LOG_MAX_IDS ?? \"\"\nconst maxDeleteIds = Number.isFinite(Number(maxDeleteIdsRaw)) ? Math.max(1, Math.floor(Number(maxDeleteIdsRaw))) : 5000\n\ntype DeleteMeta = {\n modelName: string\n ids: string[]\n reset: boolean\n session?: mongoose.ClientSession\n}\n\nconst deleteMetaByQuery = new WeakMap<object, DeleteMeta>()\n\nconst hasToString = (value: unknown): value is { toString: () => string } => {\n if (typeof value !== \"object\" || value === null) return false\n const maybe = value as { toString?: unknown }\n return typeof maybe.toString === \"function\"\n}\n\nconst normalizeId = (id: unknown): string | null => {\n if (!id) return null\n if (typeof id === \"string\") return id\n if (hasToString(id)) return id.toString()\n return null\n}\n\nconst getDbName = (db: unknown): string => {\n if (!db || typeof db !== \"object\") return \"\"\n const maybe = db as { name?: unknown; db?: { databaseName?: unknown } }\n const raw = maybe.name ?? maybe.db?.databaseName\n return typeof raw === \"string\" ? raw : \"\"\n}\n\nconst isGlobalDb = (db: unknown): boolean => getDbName(db).endsWith(GLOBAL_DB_SUFFIX)\n\ntype RtsCounterDoc = IRBRtsCounter\ntype RtsChangeDoc = IRBRtsChange\n\nconst getQuerySession = (query: MongooseQuery): mongoose.ClientSession | undefined => {\n const opts = typeof query.getOptions === \"function\" ? query.getOptions() : undefined\n if (!opts || typeof opts !== \"object\") return undefined\n const session = (opts as { session?: unknown }).session\n if (!session || typeof session !== \"object\") return undefined\n return session as mongoose.ClientSession\n}\n\nconst getRtsModels = (db: mongoose.Connection) => {\n const rawDb = getMongooseAclRawConnection(db)\n const RtsCounter = (rawDb.models.RBRtsCounter as mongoose.Model<RtsCounterDoc>)\n ?? rawDb.model<RtsCounterDoc>(\"RBRtsCounter\", RBRtsCounterSchema)\n const RtsChange = (rawDb.models.RBRtsChange as mongoose.Model<RtsChangeDoc>)\n ?? rawDb.model<RtsChangeDoc>(\"RBRtsChange\", RBRtsChangeSchema)\n return { RtsCounter, RtsChange }\n}\n\nconst allocateSeqRange = async (\n db: mongoose.Connection,\n count: number,\n session?: mongoose.ClientSession,\n): Promise<{ start: number; end: number }> => {\n const { RtsCounter } = getRtsModels(db)\n const updated = await RtsCounter.findOneAndUpdate(\n { _id: RTS_COUNTER_ID },\n { $inc: { seq: count } },\n { upsert: true, returnDocument: \"after\", setDefaultsOnInsert: true, projection: { seq: 1 }, session },\n ).lean()\n\n const end = Number(updated?.seq ?? 0)\n const start = end - count + 1\n return { start, end }\n}\n\nconst insertChanges = async (\n db: mongoose.Connection,\n changes: Array<{ seq: number; modelName: string; op: RtsChangeOp; docId?: string | null }>,\n session?: mongoose.ClientSession,\n): Promise<void> => {\n if (!changes.length) return\n const { RtsChange } = getRtsModels(db)\n const ts = new Date()\n const docs = changes.map((c) => ({\n seq: c.seq,\n modelName: c.modelName,\n op: c.op,\n docId: c.docId ?? undefined,\n ts,\n }))\n\n if (session) {\n await RtsChange.insertMany(docs, { session })\n return\n }\n\n await RtsChange.insertMany(docs)\n}\n\nconst recordDeleteChanges = async (\n db: mongoose.Connection,\n modelName: string,\n ids: string[],\n session?: mongoose.ClientSession,\n): Promise<void> => {\n const uniqueIds = Array.from(new Set(ids)).filter(Boolean)\n if (!uniqueIds.length) return\n const { start } = await allocateSeqRange(db, uniqueIds.length, session)\n await insertChanges(db, uniqueIds.map((docId, idx) => ({\n seq: start + idx,\n modelName,\n op: \"delete\",\n docId,\n })), session)\n}\n\nconst recordResetModel = async (db: mongoose.Connection, modelName: string, session?: mongoose.ClientSession): Promise<void> => {\n const { start } = await allocateSeqRange(db, 1, session)\n await insertChanges(db, [{ seq: start, modelName, op: \"reset_model\" }], session)\n}\n\ntype MongooseQuery = mongoose.Query<unknown, unknown> & {\n model?: {\n modelName?: string\n db?: unknown\n find: (filter: unknown, projection: unknown) => unknown\n }\n getFilter?: () => unknown\n getQuery?: () => unknown\n getOptions?: () => unknown\n}\n\nconst captureDeleteMeta = async (query: MongooseQuery, mode: \"one\" | \"many\") => {\n const modelName = String(query?.model?.modelName ?? \"\")\n if (!modelName || modelName.startsWith(\"RB\") || EXCLUDED_MODEL_NAMES.has(modelName)) return\n if (isGlobalDb(query?.model?.db)) return\n\n const filter = typeof query.getFilter === \"function\" ? query.getFilter() : query.getQuery?.() ?? {}\n const session = getQuerySession(query)\n const findQuery = query.model.find(filter, { _id: 1 }) as unknown as {\n session?: (s: mongoose.ClientSession) => unknown\n limit: (n: number) => unknown\n lean: () => unknown\n }\n if (session && typeof findQuery.session === \"function\") {\n findQuery.session(session)\n }\n\n findQuery.lean()\n\n if (mode === \"one\") {\n findQuery.limit(1)\n } else {\n findQuery.limit(maxDeleteIds + 1)\n }\n\n const docs = await findQuery\n const ids = Array.isArray(docs)\n ? docs\n .map((d) => normalizeId((d as { _id?: unknown })?._id))\n .filter((id): id is string => Boolean(id))\n : []\n const reset = mode === \"many\" && ids.length > maxDeleteIds\n const trimmedIds = reset ? [] : ids\n\n const meta: DeleteMeta = {\n modelName,\n ids: trimmedIds,\n reset,\n session,\n }\n\n deleteMetaByQuery.set(query, meta)\n}\n\nconst flushDeleteMeta = async (query: MongooseQuery) => {\n const meta = deleteMetaByQuery.get(query)\n deleteMetaByQuery.delete(query)\n if (!meta) return\n\n const db = query?.model?.db as mongoose.Connection | undefined\n if (!db) return\n\n try {\n if (meta.reset) {\n await recordResetModel(db, meta.modelName, meta.session)\n } else {\n await recordDeleteChanges(db, meta.modelName, meta.ids, meta.session)\n }\n } catch {\n return\n }\n}\n\nexport const rtsChangeLogPlugin = (schema: mongoose.Schema): void => {\n schema.pre(\"deleteOne\", { query: true, document: false }, async function(this: MongooseQuery) {\n await captureDeleteMeta(this, \"one\")\n })\n\n schema.pre(\"deleteMany\", { query: true, document: false }, async function(this: MongooseQuery) {\n await captureDeleteMeta(this, \"many\")\n })\n\n schema.post(\"deleteOne\", { query: true, document: false }, async function(this: MongooseQuery) {\n await flushDeleteMeta(this)\n })\n\n schema.post(\"deleteMany\", { query: true, document: false }, async function(this: MongooseQuery) {\n await flushDeleteMeta(this)\n })\n\n schema.post(\"findOneAndDelete\", { query: true, document: false }, async function(this: MongooseQuery, doc: unknown) {\n const modelName = String(this?.model?.modelName ?? \"\")\n if (!modelName || modelName.startsWith(\"RB\") || EXCLUDED_MODEL_NAMES.has(modelName)) return\n\n const db = this?.model?.db as mongoose.Connection | undefined\n if (!db) return\n if (isGlobalDb(db)) return\n\n const docId = normalizeId((doc as { _id?: unknown } | null | undefined)?._id)\n if (!docId) return\n\n try {\n const session = getQuerySession(this)\n await recordDeleteChanges(db, modelName, [docId], session)\n } catch {\n return\n }\n })\n}\n\nexport const _private = {\n getRtsModels,\n}\n","import mongoose from \"mongoose\"\nimport { accessibleRecordsPlugin } from \"@casl/mongoose\"\n\nimport * as frameworkSchemas from \"./models\"\nimport { rtsChangeLogPlugin } from \"./rtsChangeLogPlugin\"\nimport { registerPoliciesFromModules } from \"./acl\"\nimport {\n installMongooseAclDriver,\n runWithUnsafeMongooseAclDriver,\n} from \"./acl/mongooseAclDriver\"\nimport { mongoPaginationPlugin } from \"./pagination/mongoPaginationPlugin\"\n\n\ntype ModelModules = Record<string, unknown>\ntype ModelsScope = \"tenant\" | \"global\"\ntype RegisterModelsOptions = {\n allowReservedRbModelNames?: boolean;\n}\n\ntype RegisteredSchemas = Record<string, mongoose.Schema>\n\ntype RegisteredModels = {\n tenant: RegisteredSchemas\n global: RegisteredSchemas\n}\n\nlet cachedModels: RegisteredModels | null = null\n\nconst DEFAULT_GLOBAL_RB_MODEL_NAMES_SET = new Set<string>([\n \"RBUser\",\n \"RBTenant\",\n \"RBOAuthRequest\",\n])\n\nconst assertSchema = (exportName: string, value: unknown): mongoose.Schema => {\n if (value instanceof mongoose.Schema) return value\n\n throw new Error(\n [\n `Expected ${exportName} to be an instance of mongoose.Schema, but it was not.`,\n \"rpcbase supports mongoose 9+ only.\",\n \"Fix: ensure the project is using mongoose 9.x and that all packages resolve the same mongoose instance (try `npm ls mongoose`).\",\n ].join(\" \"),\n )\n}\n\nconst getFrameworkSchemaForModelName = (modelName: string): mongoose.Schema | null => {\n const exportName = `${modelName}Schema`\n const value = (frameworkSchemas as unknown as Record<string, unknown>)[exportName]\n if (!(value instanceof mongoose.Schema)) return null\n return value\n}\n\nconst applyTenantPlugins = (schema: mongoose.Schema): void => {\n schema.plugin(accessibleRecordsPlugin)\n schema.plugin(mongoPaginationPlugin)\n schema.plugin(rtsChangeLogPlugin)\n}\n\nconst registerSchema = (\n target: RegisteredSchemas,\n other: RegisteredSchemas,\n modelName: string,\n schema: mongoose.Schema,\n scope: ModelsScope,\n): void => {\n if (target[modelName] || other[modelName]) {\n throw new Error(`Duplicate model name \"${modelName}\" across tenant/global scopes`)\n }\n target[modelName] = schema\n}\n\nconst buildSchemasFromModules = (modules: ModelModules): Array<{ modelName: string; schema: mongoose.Schema }> =>\n Object.entries(modules)\n .filter(([key]) => key.endsWith(\"Schema\"))\n .map(([key, schemaValue]) => {\n const schema = assertSchema(key, schemaValue)\n const modelName = key.replace(/Schema$/, \"\")\n return { modelName, schema }\n })\n\nexport const getFrameworkModelSchemas = (): RegisteredModels => {\n const tenant: RegisteredSchemas = {}\n const global: RegisteredSchemas = {}\n\n for (const { modelName, schema } of buildSchemasFromModules(frameworkSchemas as unknown as ModelModules)) {\n const cloned = schema.clone()\n if (DEFAULT_GLOBAL_RB_MODEL_NAMES_SET.has(modelName)) {\n registerSchema(global, tenant, modelName, cloned, \"global\")\n } else {\n applyTenantPlugins(cloned)\n registerSchema(tenant, global, modelName, cloned, \"tenant\")\n }\n }\n\n return { tenant, global }\n}\n\nexport const registerModels = (\n { tenant, global }: { tenant: ModelModules; global?: ModelModules },\n options: RegisterModelsOptions = {},\n) => {\n installMongooseAclDriver()\n registerPoliciesFromModules(frameworkSchemas as unknown as Record<string, unknown>)\n registerPoliciesFromModules(tenant)\n\n const tenantSchemas: RegisteredSchemas = {}\n const globalSchemas: RegisteredSchemas = {}\n const allowReservedRbModelNames = options.allowReservedRbModelNames === true\n\n for (const { modelName, schema } of buildSchemasFromModules(frameworkSchemas as unknown as ModelModules)) {\n if (DEFAULT_GLOBAL_RB_MODEL_NAMES_SET.has(modelName)) {\n const cloned = schema.clone()\n registerSchema(globalSchemas, tenantSchemas, modelName, cloned, \"global\")\n } else {\n const cloned = schema.clone()\n applyTenantPlugins(cloned)\n registerSchema(tenantSchemas, globalSchemas, modelName, cloned, \"tenant\")\n }\n }\n\n for (const { modelName, schema } of buildSchemasFromModules(tenant)) {\n if (modelName === \"RBUser\" || modelName === \"RBTenant\") {\n throw new Error(`Invalid tenant model name \"${modelName}\". RBUser/RBTenant are global models.`)\n }\n if (modelName.startsWith(\"RB\")) {\n const frameworkSchema = getFrameworkSchemaForModelName(modelName)\n if (frameworkSchema && schema === frameworkSchema) continue\n if (!allowReservedRbModelNames) {\n throw new Error(`Invalid tenant model name \"${modelName}\". RB* models are reserved for rpcbase.`)\n }\n }\n const cloned = schema.clone()\n applyTenantPlugins(cloned)\n registerSchema(tenantSchemas, globalSchemas, modelName, cloned, \"tenant\")\n }\n\n for (const { modelName, schema } of buildSchemasFromModules(global ?? {})) {\n if (modelName.startsWith(\"RB\")) {\n const frameworkSchema = getFrameworkSchemaForModelName(modelName)\n if (frameworkSchema && schema === frameworkSchema) continue\n if (!allowReservedRbModelNames) {\n throw new Error(`Invalid global model name \"${modelName}\". RB* models are reserved for rpcbase.`)\n }\n }\n const cloned = schema.clone()\n registerSchema(globalSchemas, tenantSchemas, modelName, cloned, \"global\")\n }\n\n const allSchemas = { ...globalSchemas, ...tenantSchemas }\n\n for (const [modelName, schema] of Object.entries(allSchemas)) {\n if (!mongoose.models[modelName]) {\n runWithUnsafeMongooseAclDriver(() => mongoose.model(modelName, schema))\n }\n }\n\n cachedModels = {\n tenant: { ...(cachedModels?.tenant ?? {}), ...tenantSchemas },\n global: { ...(cachedModels?.global ?? {}), ...globalSchemas },\n }\n}\n\nexport const getRegisteredModels = (scope: ModelsScope) => {\n if (!cachedModels) {\n throw new Error(\"Models not registered. Call createModels(...) once at startup (or import your models module) before using models.get.\")\n }\n return cachedModels[scope]\n}\n\nexport type { ModelModules, ModelsScope, RegisteredSchemas, RegisterModelsOptions }\n","import mongoose from \"mongoose\"\n\nimport {\n AclMongooseCollection,\n installMongooseAclDriver,\n} from \"./mongooseAclDriver\"\nimport {\n bindMongooseAclRawConnection,\n bindMongooseAclDriverContext,\n unboundMongooseAclDriverContext,\n unsafeMongooseAclDriverContext,\n type MongooseAclDriverContext,\n} from \"./mongooseAclDriverContext\"\nimport { hasRegisteredPolicy } from \"./registry\"\nimport type { AppAbility } from \"./types\"\n\n\ndeclare const mongooseAclModelBrand: unique symbol\n\ndeclare module \"mongoose\" {\n interface Model<\n TRawDocType,\n TQueryHelpers,\n TInstanceMethods,\n TVirtuals,\n THydratedDocumentType,\n TSchema,\n TLeanResultType,\n > {\n [mongooseAclModelBrand]?: [\n TRawDocType,\n TQueryHelpers,\n TInstanceMethods,\n TVirtuals,\n THydratedDocumentType,\n TSchema,\n TLeanResultType,\n ]\n acl: (ability: AppAbility) => this\n }\n}\n\ntype SubclassableModel<TModel extends mongoose.Model<unknown>> = TModel & {\n __subclass: (\n connection: mongoose.Connection,\n schema: mongoose.Schema,\n collectionName: string,\n ) => TModel\n}\n\nconst scopedModelsByAbility = new WeakMap<object, WeakMap<object, mongoose.Model<unknown>>>()\nconst unboundModels = new WeakMap<object, mongoose.Model<unknown>>()\nconst unsafeModels = new WeakMap<object, mongoose.Model<unknown>>()\nconst collectionTargets = new WeakMap<object, AclMongooseCollection>()\nconst blockedModelMethods = new Set<PropertyKey>([\n \"$__updateConnection\",\n \"__subclass\",\n \"clientEncryption\",\n \"cleanIndexes\",\n \"compile\",\n \"createCollection\",\n \"createIndexes\",\n \"createSearchIndex\",\n \"createSearchIndexes\",\n \"diffIndexes\",\n \"dropSearchIndex\",\n \"ensureIndexes\",\n \"init\",\n \"listIndexes\",\n \"listSearchIndexes\",\n \"recompileSchema\",\n \"startSession\",\n \"syncIndexes\",\n \"updateSearchIndex\",\n \"useConnection\",\n \"watch\",\n])\nconst blockedCollectionProperties = new Set<PropertyKey>([\n \"_getCollection\",\n \"addQueue\",\n \"doQueue\",\n \"emitter\",\n \"onClose\",\n \"onOpen\",\n \"queue\",\n \"removeQueue\",\n])\nconst blockedConnectionMethods = new Set<PropertyKey>([\n \"aggregate\",\n \"bulkWrite\",\n \"close\",\n \"createClient\",\n \"createCollection\",\n \"createCollections\",\n \"deleteModel\",\n \"destroy\",\n \"doClose\",\n \"dropCollection\",\n \"dropDatabase\",\n \"listCollections\",\n \"listDatabases\",\n \"onClose\",\n \"onOpen\",\n \"openUri\",\n \"plugin\",\n \"set\",\n \"setClient\",\n \"startSession\",\n \"syncIndexes\",\n \"transaction\",\n \"useDb\",\n \"watch\",\n \"withSession\",\n])\nconst blockedConnectionProperties = new Set<PropertyKey>([\n \"$initialConnection\",\n \"_parent\",\n \"client\",\n \"otherDbs\",\n \"relatedDbs\",\n])\nconst blockedMongooseMethods = new Set<PropertyKey>([\n \"connect\",\n \"createConnection\",\n \"deleteModel\",\n \"disconnect\",\n \"model\",\n \"plugin\",\n \"set\",\n \"setDriver\",\n \"startSession\",\n \"syncIndexes\",\n])\nconst blockedMongooseProperties = new Set<PropertyKey>([\n \"connection\",\n \"connections\",\n \"models\",\n])\nconst allowedDbProperties = new Set<PropertyKey>([\n \"databaseName\",\n \"namespace\",\n \"readConcern\",\n \"readPreference\",\n \"writeConcern\",\n])\n\nconst getModelCollectionName = (model: mongoose.Model<unknown>): string => {\n const collection = model.collection as unknown as { collectionName?: unknown; name?: unknown }\n const value = collection.collectionName ?? collection.name\n return typeof value === \"string\" ? value : \"\"\n}\n\nconst resolveModelNameForCollection = (\n connection: mongoose.Connection,\n collectionName: string,\n): string | undefined => {\n const candidates = new Set<string>()\n for (const model of [\n ...Object.values(connection.models ?? {}),\n ...Object.values(mongoose.models),\n ]) {\n const typedModel = model as mongoose.Model<unknown>\n if (getModelCollectionName(typedModel) === collectionName) {\n candidates.add(typedModel.modelName)\n }\n }\n return candidates.size === 1 ? [...candidates][0] : undefined\n}\n\nconst detachMongooseSubclassRetention = (\n rawModel: mongoose.Model<unknown>,\n scopedModel: mongoose.Model<unknown>,\n): void => {\n const symbol = Object.getOwnPropertySymbols(rawModel)\n .find((entry) => entry.description === \"mongoose#Model#subclassed\")\n if (!symbol) return\n\n const subclasses = (rawModel as unknown as Record<symbol, unknown>)[symbol]\n if (!Array.isArray(subclasses)) return\n const index = subclasses.lastIndexOf(scopedModel)\n if (index >= 0) subclasses.splice(index, 1)\n}\n\nconst getCachedModel = <TModel extends mongoose.Model<unknown>>(\n model: TModel,\n context: MongooseAclDriverContext,\n): TModel | undefined => {\n if (context.mode === \"unsafe\") {\n return unsafeModels.get(model) as TModel | undefined\n }\n if (context.mode === \"unbound\") {\n return unboundModels.get(model) as TModel | undefined\n }\n return scopedModelsByAbility.get(context.ability)?.get(model) as TModel | undefined\n}\n\nconst cacheModel = <TModel extends mongoose.Model<unknown>>(\n rawModel: TModel,\n scopedModel: TModel,\n context: MongooseAclDriverContext,\n): void => {\n if (context.mode === \"unsafe\") {\n unsafeModels.set(rawModel, scopedModel)\n return\n }\n if (context.mode === \"unbound\") {\n unboundModels.set(rawModel, scopedModel)\n return\n }\n\n const models = scopedModelsByAbility.get(context.ability) ?? new WeakMap<object, mongoose.Model<unknown>>()\n models.set(rawModel, scopedModel)\n scopedModelsByAbility.set(context.ability, models)\n}\n\nconst lockModelCapability = (\n target: object,\n property: PropertyKey,\n value: unknown,\n): void => {\n const descriptor = Object.getOwnPropertyDescriptor(target, property)\n Object.defineProperty(target, property, {\n configurable: false,\n enumerable: descriptor?.enumerable ?? true,\n get: () => value,\n set: () => {\n throw new Error(\n `ACL-protected model property .${String(property)} cannot be changed. Use models.getUnsafe(...) explicitly.`,\n )\n },\n })\n}\n\nconst createAclModelWithContext = <TModel extends mongoose.Model<unknown>>(\n model: TModel,\n context: MongooseAclDriverContext,\n): TModel => {\n const cached = getCachedModel(model, context)\n if (cached) return cached\n\n const rawConnection = model.db\n const primaryCollectionName = getModelCollectionName(model)\n const collections = new Map<string, AclMongooseCollection>()\n\n let mongooseProxy: mongoose.Mongoose | undefined\n let collectionsProxy: Record<string, mongoose.Collection> | undefined\n let modelsProxy: Record<string, mongoose.Model<unknown>> | undefined\n let dbProxy: object | undefined\n\n const getMongooseProxy = (): mongoose.Mongoose => {\n const rawMongoose = rawConnection.base\n if (context.mode === \"unsafe\") return rawMongoose\n if (mongooseProxy) return mongooseProxy\n\n mongooseProxy = new Proxy(rawMongoose, {\n get(target, prop) {\n if (prop === \"default\" || prop === \"mongoose\") return mongooseProxy\n if (blockedMongooseProperties.has(prop)) {\n throw new Error(\n `ACL-protected Mongoose property .${String(prop)} is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n }\n if (blockedMongooseMethods.has(prop)) {\n return () => {\n throw new Error(\n `ACL-protected Mongoose method ${String(prop)}() is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n }\n }\n\n const value = Reflect.get(target, prop, target) as unknown\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => {\n const result = Reflect.apply(value, target, args) as unknown\n return result === target ? mongooseProxy : result\n }\n },\n set(_target, prop) {\n throw new Error(\n `ACL-protected Mongoose property .${String(prop)} cannot be changed. Use models.getUnsafe(...) explicitly.`,\n )\n },\n })\n return mongooseProxy\n }\n\n const createCollectionProxy = (\n collection: AclMongooseCollection,\n ): AclMongooseCollection => {\n if (context.mode === \"unsafe\") return collection\n\n const proxy: AclMongooseCollection = new Proxy(collection, {\n get(target, prop) {\n if (prop === \"conn\") return connectionProxy\n if (blockedCollectionProperties.has(prop)) {\n throw new Error(\n `ACL-protected collection property .${String(prop)} is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n }\n\n const value = Reflect.get(target, prop, target) as unknown\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => {\n const result = Reflect.apply(value, target, args) as unknown\n return result === target ? proxy : result\n }\n },\n set(_target, prop) {\n throw new Error(\n `ACL-protected collection property .${String(prop)} cannot be changed. Use models.getUnsafe(...) explicitly.`,\n )\n },\n })\n collectionTargets.set(proxy, collection)\n return proxy\n }\n\n const getCollection = (\n collectionName: string,\n options: Record<string, unknown> = {},\n ): AclMongooseCollection => {\n const existing = collections.get(collectionName)\n if (existing) return existing\n\n const modelName = collectionName === primaryCollectionName\n ? model.modelName\n : resolveModelNameForCollection(rawConnection, collectionName)\n if (\n context.mode !== \"unsafe\"\n && collectionName !== primaryCollectionName\n && (!modelName || !hasRegisteredPolicy(modelName))\n ) {\n throw new Error(\n `ACL-protected connections cannot access collection \"${collectionName}\" without a protected model. Load that model explicitly or use models.getUnsafe(...).`,\n )\n }\n const collection = new AclMongooseCollection(collectionName, rawConnection, {\n ...options,\n modelName,\n })\n bindMongooseAclDriverContext(collection, context)\n const exposedCollection = createCollectionProxy(collection)\n collections.set(collectionName, exposedCollection)\n return exposedCollection\n }\n\n const getRelatedModel = (modelName: string): mongoose.Model<unknown> => {\n const relatedModel = rawConnection.model(modelName) as mongoose.Model<unknown>\n return createAclModelWithContext(relatedModel, context)\n }\n\n const getModelsProxy = (): Record<string, mongoose.Model<unknown>> => {\n if (modelsProxy) return modelsProxy\n modelsProxy = new Proxy(rawConnection.models as Record<string, mongoose.Model<unknown>>, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver) as unknown\n return typeof prop === \"string\" && Object.hasOwn(target, prop) && value && typeof value === \"function\"\n ? getRelatedModel(prop)\n : value\n },\n set(target, prop, value, receiver) {\n if (context.mode === \"unsafe\") return Reflect.set(target, prop, value, receiver)\n throw new Error(`ACL-protected connection model .${String(prop)} cannot be changed.`)\n },\n deleteProperty(target, prop) {\n if (context.mode === \"unsafe\") return Reflect.deleteProperty(target, prop)\n throw new Error(`ACL-protected connection model .${String(prop)} cannot be deleted.`)\n },\n })\n return modelsProxy\n }\n\n const getCollectionsProxy = (): Record<string, mongoose.Collection> => {\n if (collectionsProxy) return collectionsProxy\n collectionsProxy = new Proxy(rawConnection.collections, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver) as unknown\n return typeof prop === \"string\" && Object.hasOwn(target, prop) && value\n ? getCollection(prop)\n : value\n },\n set(target, prop, value, receiver) {\n if (context.mode === \"unsafe\") return Reflect.set(target, prop, value, receiver)\n throw new Error(`ACL-protected connection collection .${String(prop)} cannot be changed.`)\n },\n deleteProperty(target, prop) {\n if (context.mode === \"unsafe\") return Reflect.deleteProperty(target, prop)\n throw new Error(`ACL-protected connection collection .${String(prop)} cannot be deleted.`)\n },\n })\n return collectionsProxy\n }\n\n const getDbProxy = (): object | null | undefined => {\n const rawDb = rawConnection.db\n if (!rawDb || context.mode === \"unsafe\") return rawDb\n if (dbProxy) return dbProxy\n\n dbProxy = new Proxy(rawDb, {\n get(target, prop) {\n if (prop === \"collection\") {\n return (collectionName: string) => getCollection(collectionName).collection\n }\n if (allowedDbProperties.has(prop)) {\n return Reflect.get(target, prop, target)\n }\n throw new Error(\n `ACL-protected database access .${String(prop)} is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n },\n set(_target, prop) {\n throw new Error(\n `ACL-protected database property .${String(prop)} cannot be changed. Use models.getUnsafe(...) explicitly.`,\n )\n },\n })\n return dbProxy\n }\n\n const connectionProxy: mongoose.Connection = new Proxy(rawConnection, {\n get(target, prop) {\n if (prop === \"collection\") return getCollection\n if (prop === \"collections\") return getCollectionsProxy()\n if (prop === \"models\") return getModelsProxy()\n if (prop === \"db\") return getDbProxy()\n if (prop === \"base\") return getMongooseProxy()\n if (context.mode !== \"unsafe\" && blockedConnectionProperties.has(prop)) {\n throw new Error(\n `ACL-protected connection property .${String(prop)} is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n }\n if (prop === \"getClient\") {\n if (context.mode === \"unsafe\") return target.getClient.bind(target)\n return () => {\n throw new Error(\"ACL-protected MongoClient access is blocked. Use models.getUnsafe(...) explicitly.\")\n }\n }\n if (prop === \"model\") {\n return (modelName: string, ...args: unknown[]) => {\n if (context.mode !== \"unsafe\" && args.length > 0) {\n throw new Error(\n \"ACL-protected connections cannot compile models. Use models.getUnsafe(...) explicitly.\",\n )\n }\n const relatedModel = Reflect.apply(target.model, target, [modelName, ...args]) as mongoose.Model<unknown>\n return createAclModelWithContext(relatedModel, context)\n }\n }\n if (context.mode !== \"unsafe\" && blockedConnectionMethods.has(prop)) {\n return () => {\n throw new Error(\n `ACL-protected connection method ${String(prop)}() is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n }\n }\n\n const value = Reflect.get(target, prop, target) as unknown\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => {\n const result = Reflect.apply(value, target, args) as unknown\n if (result === target) return connectionProxy\n if (result && typeof result === \"object\" && \"then\" in result) {\n const then = result.then\n if (typeof then === \"function\") {\n return Promise.resolve(result).then((resolved: unknown) => (\n resolved === (target as unknown) ? connectionProxy : resolved\n ))\n }\n }\n return result\n }\n },\n set(target, prop, value, receiver) {\n if (context.mode === \"unsafe\") return Reflect.set(target, prop, value, receiver)\n throw new Error(\n `ACL-protected connection property .${String(prop)} cannot be changed. Use models.getUnsafe(...) explicitly.`,\n )\n },\n })\n bindMongooseAclRawConnection(connectionProxy, rawConnection)\n\n const scopedModel = (model as SubclassableModel<TModel>).__subclass(\n connectionProxy,\n model.schema,\n primaryCollectionName,\n )\n detachMongooseSubclassRetention(model, scopedModel)\n cacheModel(model, scopedModel, context)\n\n Object.defineProperty(scopedModel, \"acl\", {\n configurable: false,\n value: (ability: AppAbility) => createAclModelWithContext(\n model,\n { mode: \"ability\", ability },\n ),\n })\n\n if (context.mode !== \"unsafe\") {\n const scopedCollection = scopedModel.collection\n lockModelCapability(scopedModel, \"base\", getMongooseProxy())\n lockModelCapability(scopedModel, \"db\", connectionProxy)\n lockModelCapability(scopedModel, \"collection\", scopedCollection)\n lockModelCapability(scopedModel, \"$__collection\", scopedCollection)\n lockModelCapability(scopedModel.prototype, \"db\", connectionProxy)\n lockModelCapability(scopedModel.prototype, \"collection\", scopedCollection)\n lockModelCapability(scopedModel.prototype, \"$collection\", scopedCollection)\n }\n\n const rawDiscriminators = model.discriminators\n if (rawDiscriminators) {\n const generatedDiscriminators = scopedModel.discriminators ?? {}\n const scopedDiscriminators: Record<string, mongoose.Model<unknown>> = {}\n for (const [name, discriminator] of Object.entries(rawDiscriminators)) {\n const generated = generatedDiscriminators[name]\n if (generated) detachMongooseSubclassRetention(discriminator, generated)\n scopedDiscriminators[name] = createAclModelWithContext(discriminator, context)\n }\n scopedModel.discriminators = scopedDiscriminators\n }\n\n if (context.mode !== \"unsafe\") {\n for (const methodName of blockedModelMethods) {\n Object.defineProperty(scopedModel, methodName, {\n configurable: false,\n value: () => {\n throw new Error(\n `ACL-protected model method ${String(methodName)}() is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n },\n })\n }\n Object.defineProperty(scopedModel, \"discriminator\", {\n configurable: false,\n value: () => {\n throw new Error(\n \"ACL-protected models cannot compile discriminators. Define them before models.get(...).\",\n )\n },\n })\n }\n return scopedModel\n}\n\ninstallMongooseAclDriver()\n\nexport const createAclMongooseModel = <TModel extends mongoose.Model<unknown>>(\n model: TModel,\n ability: AppAbility,\n): AclMongooseModel<TModel> => createAclModelWithContext(\n model,\n { mode: \"ability\", ability },\n) as AclMongooseModel<TModel>\n\nexport type AclMongooseModel<TModel extends mongoose.Model<unknown>> = TModel & {\n acl: (ability: AppAbility) => AclMongooseModel<TModel>\n}\n\nexport const createAclMongooseModelGateway = <TModel extends mongoose.Model<unknown>>(\n model: TModel,\n): AclMongooseModel<TModel> => createAclModelWithContext(\n model,\n unboundMongooseAclDriverContext,\n) as AclMongooseModel<TModel>\n\nexport const createUnsafeMongooseModel = <TModel extends mongoose.Model<unknown>>(\n model: TModel,\n): TModel => createAclModelWithContext(model, unsafeMongooseAclDriverContext)\n\nconst installMongooseAclModelFactory = (): void => {\n const modelConstructor = mongoose.Model as typeof mongoose.Model & {\n acl?: (ability: AppAbility) => mongoose.Model<unknown>\n }\n if (Object.hasOwn(modelConstructor, \"acl\")) return\n\n Object.defineProperty(modelConstructor, \"acl\", {\n configurable: false,\n value: function(\n this: mongoose.Model<unknown>,\n ability: AppAbility,\n ) {\n return createAclMongooseModel(this, ability)\n },\n })\n}\n\ninstallMongooseAclModelFactory()\n\nexport const _private = {\n createAclModelWithContext,\n resolveModelNameForCollection,\n setNativeCollection: (collection: object, nativeCollection: object): void => {\n const target = collectionTargets.get(collection) ?? collection as AclMongooseCollection\n target.collection = nativeCollection\n },\n}\n","import assert from \"assert\"\n\nimport { getGlobalDbName, getTenantDbName } from \"./dbNames\"\nimport { ensureMongooseConnection } from \"./ensureMongooseConnection\"\nimport { getRegisteredModels, registerModels, type ModelsScope } from \"./registerModels\"\nimport type { AppAbility } from \"./acl\"\nimport {\n createAclMongooseModel,\n createAclMongooseModelGateway,\n createUnsafeMongooseModel,\n} from \"./acl/mongooseAclModel\"\nimport { runWithUnsafeMongooseAclDriver } from \"./acl/mongooseAclDriver\"\n\n\nexport type LoadModelCtx = {\n tenantId?: string;\n req?: {\n session?: {\n user?: {\n currentTenantId?: string;\n }\n } | null;\n };\n ability?: AppAbility;\n};\n\nconst loadModelFromDb = async (\n modelName: string,\n dbName: string,\n scope: ModelsScope,\n) => {\n const schemas = getRegisteredModels(scope)\n const schema = schemas[modelName]\n assert(schema, `Model ${modelName} not registered. Available models: ${Object.keys(schemas).join(\", \")}`)\n\n const modelConnection = await ensureMongooseConnection(dbName)\n\n if (!modelConnection.models[modelName]) {\n await runWithUnsafeMongooseAclDriver(async() => {\n if (process.env.NODE_ENV === \"production\") {\n schema.set(\"autoCreate\", false)\n schema.set(\"autoIndex\", false)\n }\n const model = modelConnection.model(modelName, schema)\n if (process.env.NODE_ENV !== \"production\") await model.init()\n })\n }\n\n return modelConnection.models[modelName]\n}\n\nconst normalizeTenantId = (value: unknown): string | null => {\n if (typeof value !== \"string\") return null\n const tenantId = value.trim()\n return tenantId || null\n}\n\nexport const getTenantIdFromLoadModelCtx = (ctx: LoadModelCtx): string => {\n const tenantId =\n normalizeTenantId(ctx.tenantId)\n ?? normalizeTenantId(ctx.req?.session?.user?.currentTenantId)\n assert(tenantId, \"Tenant ID is missing from ctx (expected ctx.tenantId or ctx.req.session.user.currentTenantId)\")\n return tenantId\n}\n\nexport const models = {\n register: registerModels,\n\n getUnsafe: async (modelName: string, ctx: LoadModelCtx) => {\n const tenantId = getTenantIdFromLoadModelCtx(ctx)\n const dbName = getTenantDbName(tenantId)\n const model = await loadModelFromDb(modelName, dbName, \"tenant\")\n return createUnsafeMongooseModel(model)\n },\n\n get: async (modelName: string, ctx: LoadModelCtx) => {\n const tenantId = getTenantIdFromLoadModelCtx(ctx)\n const dbName = getTenantDbName(tenantId)\n const model = await loadModelFromDb(modelName, dbName, \"tenant\")\n return ctx.ability\n ? createAclMongooseModel(model, ctx.ability)\n : createAclMongooseModelGateway(model)\n },\n\n getGlobal: async (modelName: string, ctx: LoadModelCtx) => {\n const dbName = getGlobalDbName()\n return loadModelFromDb(modelName, dbName, \"global\")\n },\n} as const\n","import type { LoadModelCtx } from \"./modelsApi\"\nimport type { ModelModules, RegisterModelsOptions } from \"./registerModels\"\nimport type * as frameworkSchemas from \"./models\"\nimport { models } from \"./modelsApi\"\nimport { registerModels } from \"./registerModels\"\n\n\ntype ExtractModelNamesFromSchemas<TModules> = {\n [K in keyof TModules]-?: K extends `${infer Name}Schema` ? Name : never\n}[keyof TModules] & string\n\ntype FrameworkModelName = ExtractModelNamesFromSchemas<typeof frameworkSchemas>\n\ntype RpcbaseGlobalModelName = Extract<FrameworkModelName, \"RBUser\" | \"RBTenant\" | \"RBOAuthRequest\">\n\nexport type TenantModelName<TTenantModules extends ModelModules> =\n ExtractModelNamesFromSchemas<TTenantModules>\n\nexport type GlobalModelName<TGlobalModules extends ModelModules> =\n | RpcbaseGlobalModelName\n | ExtractModelNamesFromSchemas<TGlobalModules>\n\ntype LoadedTenantModel = Awaited<ReturnType<(typeof models)[\"get\"]>>\ntype LoadedGlobalModel = Awaited<ReturnType<(typeof models)[\"getGlobal\"]>>\n\ntype ModelsGetFn<TTenantModules extends ModelModules> = {\n (\n modelName: TenantModelName<TTenantModules>,\n ctx: LoadModelCtx,\n ): ReturnType<(typeof models)[\"get\"]>\n <const TNames extends readonly TenantModelName<TTenantModules>[]>(\n modelNames: TNames,\n ctx: LoadModelCtx,\n ): Promise<{ [K in keyof TNames]: LoadedTenantModel }>\n}\n\ntype ModelsGetUnsafeFn<TTenantModules extends ModelModules> = {\n (modelName: TenantModelName<TTenantModules>, ctx: LoadModelCtx): ReturnType<(typeof models)[\"getUnsafe\"]>\n <const TNames extends readonly TenantModelName<TTenantModules>[]>(\n modelNames: TNames,\n ctx: LoadModelCtx,\n ): Promise<{ [K in keyof TNames]: LoadedTenantModel }>\n}\n\ntype ModelsGetGlobalFn<TGlobalModules extends ModelModules> = {\n (modelName: GlobalModelName<TGlobalModules>, ctx: LoadModelCtx): ReturnType<(typeof models)[\"getGlobal\"]>\n <const TNames extends readonly GlobalModelName<TGlobalModules>[]>(\n modelNames: TNames,\n ctx: LoadModelCtx,\n ): Promise<{ [K in keyof TNames]: LoadedGlobalModel }>\n}\n\nexport type ModelsConfig<TTenantModules extends ModelModules, TGlobalModules extends ModelModules> = {\n tenant: TTenantModules\n global?: TGlobalModules\n}\n\nexport type ModelsClient<TTenantModules extends ModelModules, TGlobalModules extends ModelModules> = {\n register: (modules: ModelsConfig<TTenantModules, TGlobalModules>, options?: RegisterModelsOptions) => void\n get: ModelsGetFn<TTenantModules>\n getUnsafe: ModelsGetUnsafeFn<TTenantModules>\n getGlobal: ModelsGetGlobalFn<TGlobalModules>\n}\n\nexport const createModels = <\n TTenantModules extends ModelModules,\n TGlobalModules extends ModelModules = Record<string, never>,\n>(\n modules: ModelsConfig<TTenantModules, TGlobalModules>,\n options?: RegisterModelsOptions,\n ): ModelsClient<TTenantModules, TGlobalModules> => {\n registerModels(modules, options)\n\n const get = (async (\n modelNameOrNames: TenantModelName<TTenantModules> | readonly TenantModelName<TTenantModules>[],\n ctx: LoadModelCtx,\n ) => {\n if (Array.isArray(modelNameOrNames)) {\n return Promise.all(modelNameOrNames.map((modelName) => models.get(modelName as string, ctx)))\n }\n return models.get(modelNameOrNames as string, ctx)\n }) as ModelsClient<TTenantModules, TGlobalModules>[\"get\"]\n\n const getUnsafe = (async (\n modelNameOrNames: TenantModelName<TTenantModules> | readonly TenantModelName<TTenantModules>[],\n ctx: LoadModelCtx,\n ) => {\n if (Array.isArray(modelNameOrNames)) {\n return Promise.all(modelNameOrNames.map((modelName) => models.getUnsafe(modelName as string, ctx)))\n }\n return models.getUnsafe(modelNameOrNames as string, ctx)\n }) as ModelsClient<TTenantModules, TGlobalModules>[\"getUnsafe\"]\n\n const getGlobal = (async (\n modelNameOrNames: GlobalModelName<TGlobalModules> | readonly GlobalModelName<TGlobalModules>[],\n ctx: LoadModelCtx,\n ) => {\n if (Array.isArray(modelNameOrNames)) {\n return Promise.all(modelNameOrNames.map((modelName) => models.getGlobal(modelName as string, ctx)))\n }\n return models.getGlobal(modelNameOrNames as string, ctx)\n }) as ModelsClient<TTenantModules, TGlobalModules>[\"getGlobal\"]\n\n return {\n register: (nextModules, nextOptions) => registerModels(nextModules, nextOptions),\n get,\n getUnsafe,\n getGlobal,\n }\n}\n","import assert from \"assert\"\n\nimport type mongoose from \"mongoose\"\n\nimport { ensureMongooseConnection } from \"./ensureMongooseConnection\"\nimport { getTenantIdFromLoadModelCtx, type LoadModelCtx } from \"./modelsApi\"\n\n\nconst getAppName = (): string => {\n const appName = process.env.APP_NAME?.trim()\n assert(appName, \"Missing APP_NAME\")\n return appName\n}\n\nconst normalizeTenantId = (tenantId: string): string => {\n const normalized = tenantId.trim()\n assert(normalized, \"Tenant ID is missing\")\n return normalized\n}\n\nexport const getTenantFilesystemDbName = (tenantId: string): string =>\n `${getAppName()}-${normalizeTenantId(tenantId)}-filesystem-db`\n\nexport const getTenantFilesystemDb = async (tenantId: string): Promise<mongoose.Connection> =>\n ensureMongooseConnection(getTenantFilesystemDbName(tenantId))\n\nexport const getTenantFilesystemDbFromCtx = async (ctx: LoadModelCtx): Promise<mongoose.Connection> => {\n const tenantId = getTenantIdFromLoadModelCtx(ctx)\n return getTenantFilesystemDb(tenantId)\n}\n","import type mongoose from \"mongoose\"\nimport type { ClientSession } from \"mongoose\"\n\nimport { getGlobalDbName, getTenantDbName } from \"./dbNames\"\nimport { ensureMongooseConnection } from \"./ensureMongooseConnection\"\nimport { getTenantIdFromLoadModelCtx, type LoadModelCtx } from \"./modelsApi\"\nimport { getTenantFilesystemDbName } from \"./tenantFilesystemDb\"\n\n\ntype MongooseTransactionOptions = Parameters<ClientSession[\"withTransaction\"]>[1]\n\nexport type TenantGlobalFilesystemTransactionCtx = {\n tenantId: string\n session: ClientSession\n ctx: {\n tenant: LoadModelCtx\n global: LoadModelCtx\n }\n db: {\n tenant: mongoose.Connection\n global: mongoose.Connection\n filesystem: mongoose.Connection\n }\n}\n\ntype WithTransactionScope =\n | string\n | { tenantId: string }\n | { ctx: LoadModelCtx }\n\nconst buildTenantLoadModelCtx = (tenantId: string): LoadModelCtx => ({\n req: {\n session: {\n user: {\n currentTenantId: tenantId,\n },\n },\n },\n})\n\nexport function withTransaction<T>(\n tenantId: string,\n fn: (ctx: TenantGlobalFilesystemTransactionCtx) => Promise<T>,\n options?: MongooseTransactionOptions,\n): Promise<T>\nexport function withTransaction<T>(\n scope: { tenantId: string } | { ctx: LoadModelCtx },\n fn: (ctx: TenantGlobalFilesystemTransactionCtx) => Promise<T>,\n options?: MongooseTransactionOptions,\n): Promise<T>\nexport async function withTransaction<T>(\n scope: WithTransactionScope,\n fn: (ctx: TenantGlobalFilesystemTransactionCtx) => Promise<T>,\n options?: MongooseTransactionOptions,\n): Promise<T> {\n const normalizedTenantId = (() => {\n if (typeof scope === \"string\") return scope.trim()\n if (\"tenantId\" in scope) return scope.tenantId.trim()\n return getTenantIdFromLoadModelCtx(scope.ctx)\n })()\n\n if (!normalizedTenantId) throw new Error(\"Tenant ID is missing\")\n\n const tenantDbName = getTenantDbName(normalizedTenantId)\n const globalDbName = getGlobalDbName()\n const filesystemDbName = getTenantFilesystemDbName(normalizedTenantId)\n\n const tenantDb = await ensureMongooseConnection(tenantDbName)\n const globalDb = await ensureMongooseConnection(globalDbName)\n const filesystemDb = await ensureMongooseConnection(filesystemDbName)\n\n const session = await tenantDb.startSession()\n\n const tenantCtx: LoadModelCtx = typeof scope === \"object\" && \"ctx\" in scope\n ? scope.ctx\n : buildTenantLoadModelCtx(normalizedTenantId)\n\n const globalCtx: LoadModelCtx = { req: { session: null } }\n\n try {\n return await session.withTransaction(async () => fn({\n tenantId: normalizedTenantId,\n session,\n ctx: {\n tenant: tenantCtx,\n global: globalCtx,\n },\n db: {\n tenant: tenantDb,\n global: globalDb,\n filesystem: filesystemDb,\n },\n }), options)\n } finally {\n await session.endSession()\n }\n}\n","import type { ClientSession } from \"mongoose\"\nimport type {\n BillingStorage,\n BillingStorageTransaction,\n PersistedSubscriptionEvent,\n StoredSubscriptionProjection,\n SubscriptionEvent,\n} from \"@rpcbase/billing\"\n\nimport { ZRBTenantSubscriptionEvent } from \"./models/RBTenantSubscriptionEvent\"\nimport type { LoadModelCtx } from \"./modelsApi\"\nimport { models } from \"./modelsApi\"\nimport { withTransaction } from \"./transactions\"\n\n\ntype MongoBillingTransaction = {\n session: ClientSession\n}\n\ntype SubscriptionEventDocument = Record<string, unknown> & {\n _id?: unknown\n}\n\nconst getTransactionSession = (transaction?: BillingStorageTransaction): ClientSession | undefined => {\n if (!transaction || typeof transaction !== \"object\" || !(\"session\" in transaction)) return undefined\n return (transaction as MongoBillingTransaction).session\n}\n\nconst toSubscriptionEvent = (document: SubscriptionEventDocument): PersistedSubscriptionEvent => {\n const parsed = ZRBTenantSubscriptionEvent.parse(document)\n if (!document._id) throw new Error(\"Persisted subscription event is missing its id\")\n return {\n ...parsed,\n id: String(document._id),\n }\n}\n\nconst getExistingEventQuery = (event: SubscriptionEvent, tenantId: string): Record<string, unknown> => ({\n tenantId,\n idempotencyKey: event.idempotencyKey,\n})\n\nconst isDuplicateKeyError = (error: unknown): boolean =>\n Boolean(error && typeof error === \"object\" && \"code\" in error && error.code === 11000)\n\nconst toProjectionDocument = (projection: StoredSubscriptionProjection): Record<string, unknown> => ({\n tenantId: projection.tenantId,\n subscriptionId: projection.subscriptionId,\n type: projection.type,\n parentSubscriptionId: projection.parentSubscriptionId ?? undefined,\n scope: projection.scope,\n scopeId: projection.scopeId ?? undefined,\n planKey: projection.planKey,\n priceId: projection.priceId ?? undefined,\n status: projection.status,\n intervalUnit: projection.intervalUnit,\n intervalCount: projection.intervalCount,\n modules: projection.modules,\n billingAnchor: projection.billingAnchor,\n currentPeriodStart: projection.currentPeriodStart,\n currentPeriodEnd: projection.currentPeriodEnd,\n cancelAtPeriodEnd: projection.cancelAtPeriodEnd,\n cancelAt: projection.cancelAt ?? undefined,\n canceledAt: projection.canceledAt ?? undefined,\n scheduledPlanKey: projection.scheduledPlan?.planKey,\n scheduledPlanEffectiveAt: projection.scheduledPlan?.effectiveAt,\n provider: projection.provider ?? undefined,\n latestEventId: projection.latestEventId,\n latestEventAt: projection.latestEventAt,\n projectedAt: projection.projectedAt,\n})\n\nexport const createTenantBillingStorage = (params: {\n ctx: LoadModelCtx\n tenantId: string\n}): BillingStorage => {\n const findExistingEvent = async (\n query: Record<string, unknown>,\n transaction?: BillingStorageTransaction,\n ): Promise<PersistedSubscriptionEvent | null> => {\n const EventModel = await models.get(\"RBTenantSubscriptionEvent\", params.ctx)\n const request = EventModel.findOne(query)\n const session = getTransactionSession(transaction)\n if (session) request.session(session)\n const document = await request.lean() as SubscriptionEventDocument | null\n return document ? toSubscriptionEvent(document) : null\n }\n\n return {\n runInTransaction: (operation) => withTransaction(\n { ctx: params.ctx },\n ({ session }) => operation({ session } satisfies MongoBillingTransaction),\n ),\n createEvent: async (event, transaction) => {\n if (event.tenantId !== params.tenantId) {\n throw new Error(\"Billing event tenantId does not match the storage tenant\")\n }\n const existingQuery = getExistingEventQuery(event, params.tenantId)\n const existing = await findExistingEvent(existingQuery, transaction)\n if (existing) return existing\n\n const EventModel = await models.get(\"RBTenantSubscriptionEvent\", params.ctx)\n const eventDocument = ZRBTenantSubscriptionEvent.parse(event)\n const session = getTransactionSession(transaction)\n\n try {\n const documents = await EventModel.create([eventDocument], session ? { session } : undefined)\n const document = documents[0]?.toObject() as SubscriptionEventDocument | undefined\n if (!document) throw new Error(\"Subscription event was not persisted\")\n return toSubscriptionEvent(document)\n } catch (error) {\n if (!isDuplicateKeyError(error)) throw error\n const duplicate = await findExistingEvent(existingQuery, transaction)\n if (!duplicate) throw error\n return duplicate\n }\n },\n listEvents: async (tenantId, subscriptionId, transaction) => {\n if (tenantId !== params.tenantId) throw new Error(\"Billing storage tenant mismatch\")\n const EventModel = await models.get(\"RBTenantSubscriptionEvent\", params.ctx)\n const request = EventModel.find({ tenantId, subscriptionId })\n .sort({ effectiveAt: 1, occurredAt: 1, _id: 1 })\n const session = getTransactionSession(transaction)\n if (session) request.session(session)\n const documents = await request.lean() as SubscriptionEventDocument[]\n return documents.map(toSubscriptionEvent)\n },\n upsertProjection: async (projection, transaction) => {\n if (projection.tenantId !== params.tenantId) throw new Error(\"Billing projection tenant mismatch\")\n const ProjectionModel = await models.get(\"RBTenantSubscriptionProjection\", params.ctx)\n const session = getTransactionSession(transaction)\n await ProjectionModel.replaceOne(\n {\n tenantId: params.tenantId,\n subscriptionId: projection.subscriptionId,\n },\n toProjectionDocument(projection),\n {\n upsert: true,\n runValidators: true,\n ...(session ? { session } : {}),\n },\n )\n },\n }\n}\n","import mongoose from \"mongoose\"\nimport {\n defineMongoResources,\n type MigrationScope,\n type MongoIndexResource,\n type MongoResources,\n} from \"@rpcbase/migrations\"\n\n\nexport type ExtractMongoResourcesOptions = {\n scope: MigrationScope\n schemas: Readonly<Record<string, unknown>>\n}\n\nconst collectionNameForModel = (modelName: string, schema: mongoose.Schema): string => {\n const configured = schema.options.collection?.trim()\n if (configured) return configured\n const pluralize = mongoose.pluralize()\n return pluralize ? pluralize(modelName) : modelName\n}\n\nconst generatedIndexName = (key: Readonly<Record<string, unknown>>): string =>\n Object.entries(key).map(([path, direction]) => `${path}_${String(direction)}`).join(\"_\")\n\nconst observableIndexOptions = new Set([\n \"2dsphereIndexVersion\",\n \"bits\",\n \"bucketSize\",\n \"collation\",\n \"default_language\",\n \"expireAfterSeconds\",\n \"hidden\",\n \"language_override\",\n \"max\",\n \"min\",\n \"partialFilterExpression\",\n \"sparse\",\n \"storageEngine\",\n \"textIndexVersion\",\n \"unique\",\n \"weights\",\n \"wildcardProjection\",\n])\n\nexport const extractMongoResourcesFromSchemas = (\n options: ExtractMongoResourcesOptions,\n): MongoResources => {\n const schemas = Object.entries(options.schemas)\n .filter((entry): entry is [string, mongoose.Schema] => entry[1] instanceof mongoose.Schema)\n .map(([exportName, schema]) => [exportName.replace(/Schema$/, \"\"), schema] as const)\n const collections = schemas.map(([modelName, schema]) => ({\n scope: options.scope,\n name: collectionNameForModel(modelName, schema),\n }))\n const indexes: MongoIndexResource[] = []\n\n for (const [modelName, schema] of schemas) {\n const collection = collectionNameForModel(modelName, schema)\n for (const [key, indexOptions] of schema.indexes()) {\n const documentKey = key as Record<string, unknown>\n const name = typeof indexOptions.name === \"string\" && indexOptions.name.trim()\n ? indexOptions.name.trim()\n : generatedIndexName(documentKey)\n const normalizedOptions = Object.fromEntries(\n Object.entries(indexOptions).filter(([option, value]) => observableIndexOptions.has(option) && value !== undefined),\n )\n indexes.push({\n scope: options.scope,\n collection,\n name,\n key: documentKey,\n ...(Object.keys(normalizedOptions).length > 0 ? { options: normalizedOptions } : {}),\n })\n }\n }\n\n return defineMongoResources({ collections, indexes })\n}\n","type TenantProvisioner = (tenantId: string) => Promise<void>\n\ntype TenantModel = {\n create(document: Record<string, unknown>): Promise<unknown>\n updateOne(\n filter: Record<string, unknown>,\n update: Record<string, unknown>,\n ): Promise<{ matchedCount?: number }>\n}\n\n\nlet tenantProvisioner: TenantProvisioner | undefined\n\nexport const configureTenantMigrationProvisioner = (provisioner: TenantProvisioner) => {\n tenantProvisioner = provisioner\n return () => {\n if (tenantProvisioner === provisioner) tenantProvisioner = undefined\n }\n}\n\nconst errorMessage = (error: unknown): string => (\n error instanceof Error ? error.message : String(error)\n).slice(0, 8_000)\n\nexport const createProvisionedTenant = async (\n Tenant: TenantModel,\n tenant: { tenantId: string; name?: string; parentTenantId?: string },\n): Promise<void> => {\n await Tenant.create({\n ...tenant,\n provisioningStatus: \"initializing\",\n provisioningStartedAt: new Date(),\n })\n\n try {\n if (tenantProvisioner) {\n await tenantProvisioner(tenant.tenantId)\n } else if (process.env.NODE_ENV === \"production\") {\n throw new Error(\"No tenant migration provisioner is configured\")\n }\n const activation = await Tenant.updateOne(\n { tenantId: tenant.tenantId, provisioningStatus: \"initializing\" },\n {\n $set: { provisioningStatus: \"active\", provisionedAt: new Date() },\n $unset: { provisioningError: \"\" },\n },\n )\n if (activation.matchedCount !== undefined && activation.matchedCount !== 1) {\n throw new Error(`Tenant ${tenant.tenantId} provisioning state changed before activation`)\n }\n } catch (error) {\n await Tenant.updateOne(\n { tenantId: tenant.tenantId },\n {\n $set: {\n provisioningStatus: \"failed\",\n provisioningError: errorMessage(error),\n },\n },\n )\n throw error\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,IAAaE,UAAUD,IAAEE,OAAO;CAC9BC,OAAOH,IAAEI,OAAO,CAAC,CAACD,MAAM,CAAC,CAACE,SAAS;CACnCC,UAAUN,IAAEI,OAAO;CACnBG,MAAMP,IAAEI,OAAO,CAAC,CAACC,SAAS;CAC1BG,OAAOR,IAAEI,OAAO,CAAC,CAACC,SAAS;CAC3B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AChE;GACEO,MAAM;IAAEP,oBAAoB;IAAUQ,+BAAe,IAAIN,KAAK;GAAE;GAChEO,QAAQ,EAAEC,mBAAmB,GAAG;EAClC,CACF;EACA,IAAIJ,WAAWtB,iBAAiBI,KAAAA,KAAakB,WAAWtB,iBAAiB,GACvE,MAAM,IAAIO,MAAM,UAAUM,OAAOtB,SAAQ,8CAA+C;CAE5F,SAASe,OAAO;EACd,MAAMM,OAAOf,UACX,EAAEN,UAAUsB,OAAOtB,SAAS,GAC5B,EACEgC,MAAM;GACJP,oBAAoB;GACpBU,mBAAmBrB,aAAaC,KAAK;EACvC,EACF,CACF;EACA,MAAMA;CACR;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["Schema","z","ZRBUser","object","email","string","optional","password","name","phone","tenants","array","tenantRoles","record","oauthProviders","subject","accessToken","refreshToken","idToken","scope","tokenType","expiresAt","date","rawUserInfo","unknown","createdAt","updatedAt","emailVerificationCode","length","emailVerificationExpiresAt","passwordResetCode","passwordResetCodeExpiresAt","passwordResetToken","passwordResetTokenExpiresAt","IRBUser","infer","RBUserSchema","type","String","unique","sparse","required","index","Map","of","default","Date","Types","Mixed","_id","Schema","z","ZRBTenant","object","tenantId","string","parentTenantId","optional","name","provisioningStatus","enum","provisioningError","provisioningStartedAt","date","provisionedAt","IRBTenant","infer","RBTenantSchema","type","String","required","unique","index","Date","Schema","z","SUBSCRIPTION_CHANGE_DIRECTIONS","SUBSCRIPTION_EVENT_TYPES","SUBSCRIPTION_INTERVAL_UNITS","SUBSCRIPTION_SCOPES","SUBSCRIPTION_STATUSES","SUBSCRIPTION_TYPES","ZRBTenantSubscriptionStatus","enum","ZRBTenantSubscriptionIntervalUnit","ZRBTenantSubscriptionType","ZRBTenantSubscriptionScope","ZRBTenantSubscriptionEventType","ZRBTenantSubscriptionEventSource","ZRBTenantSubscriptionChangeDirection","subscriptionEventBaseSchema","object","tenantId","string","trim","min","subscriptionId","occurredAt","date","effectiveAt","subscriptionType","parentSubscriptionId","optional","scope","scopeId","fromPlanKey","toPlanKey","fromStatus","toStatus","fromModules","array","toModules","fromIntervalUnit","toIntervalUnit","fromIntervalCount","number","int","toIntervalCount","fromPriceId","toPriceId","billingAnchor","supersedesEventId","idempotencyKey","direction","actorUserId","source","reason","provider","providerEventId","providerPayload","unknown","metadata","record","subscriptionCreatedEventSchema","extend","type","literal","subscriptionPlanChangedEventSchema","subscriptionStatusChangedEventSchema","subscriptionResumedEventSchema","subscriptionCanceledEventSchema","subscriptionRenewedEventSchema","ZRBTenantSubscriptionEvent","discriminatedUnion","superRefine","event","ctx","addIssue","code","message","path","IRBTenantSubscriptionEvent","infer","SubscriptionEventDocument","requiredForEventTypes","types","Array","requiredForEventType","this","Boolean","includes","RBTenantSubscriptionEventSchema","String","required","index","options","Date","default","now","undefined","Number","Types","Mixed","unique","partialFilterExpression","$type","Schema","z","ZRBTenantSubscriptionIntervalUnit","ZRBTenantSubscriptionScope","ZRBTenantSubscriptionStatus","ZRBTenantSubscriptionType","ZRBTenantSubscriptionProjection","object","tenantId","string","subscriptionId","type","parentSubscriptionId","optional","scope","scopeId","planKey","priceId","status","intervalUnit","intervalCount","number","int","min","modules","array","billingAnchor","date","currentPeriodStart","currentPeriodEnd","cancelAtPeriodEnd","boolean","cancelAt","canceledAt","scheduledPlanKey","scheduledPlanEffectiveAt","provider","latestEventId","latestEventAt","projectedAt","IRBTenantSubscriptionProjection","infer","RBTenantSubscriptionProjectionSchema","String","required","index","enum","options","Number","default","Date","Boolean","unique","Schema","z","ZRBRtsCounter","object","_id","string","seq","number","int","min","IRBRtsCounter","infer","RBRtsCounterSchema","type","String","required","Number","default","versionKey","Schema","z","rtsChangesTtlSeconds","ZRBRtsChangeOp","enum","ZRBRtsChange","object","seq","number","int","min","modelName","string","op","docId","optional","ts","date","IRBRtsChange","infer","RBRtsChangeSchema","type","Number","required","String","index","options","Date","default","now","versionKey","unique","expireAfterSeconds","Schema","z","AclPolicy","ZRBUploadSessionStatus","enum","ZRBUploadAccessScope","ZRBUploadDeduplication","object","namespace","string","algorithm","literal","hash","key","pipelineVersion","number","int","min","ZRBUploadSession","_id","userId","optional","ownerKeyHash","filename","mimeType","totalSize","chunkSize","chunksTotal","status","createdAt","date","expiresAt","fileId","isPublic","boolean","accessScope","deduplication","deduplicated","error","IRBUploadSession","infer","RBUploadSessionSchema","type","String","required","index","Number","options","Date","default","now","Boolean","versionKey","expireAfterSeconds","RBUploadSessionPolicy","subject","define","builder","ctx","can","uploadKeyHash","claims","trim","Schema","z","ZRBUploadChunk","object","uploadId","string","index","number","int","min","data","unknown","size","sha256","optional","createdAt","date","expiresAt","IRBUploadChunk","infer","RBUploadChunkSchema","type","String","required","Number","Buffer","Date","default","now","versionKey","unique","expireAfterSeconds","Schema","z","AclPolicy","ZStringMap","record","string","ZRBNotificationPlatformPayload","object","webpush","unknown","optional","fcmOptions","android","apns","passthrough","IRBNotificationPlatformPayload","infer","ZRBNotification","userId","topic","tag","deliveryId","title","body","image","data","platform","drawerActive","boolean","createdAt","date","seenAt","readAt","archivedAt","IRBNotification","TTL_90_DAYS_S","RBNotificationSchema","type","String","required","index","Types","Mixed","Boolean","Date","default","now","versionKey","unique","partialFilterExpression","$exists","expireAfterSeconds","RBNotificationPolicy","subject","define","builder","ctx","can","Schema","z","AclPolicy","ZRBNotificationPlatformPayload","ZStringMap","record","string","ZRBNotificationDelivery","object","userId","notificationId","optional","deliveryId","topic","tag","title","body","image","data","platform","createdAt","date","IRBNotificationDelivery","infer","TTL_90_DAYS_S","RBNotificationDeliverySchema","type","String","required","index","unique","Types","Mixed","Date","default","now","versionKey","expireAfterSeconds","RBNotificationDeliveryPolicy","subject","define","builder","ctx","can","Schema","z","AclPolicy","ZRBNotificationDigestFrequency","enum","ZRBNotificationTopicPreference","object","topic","string","inApp","boolean","emailDigest","push","ZRBNotificationSettings","userId","digestFrequency","topicPreferences","array","optional","lastDigestSentAt","date","IRBNotificationSettings","infer","TopicPreferenceSchema","type","String","required","Boolean","default","_id","RBNotificationSettingsSchema","options","Date","versionKey","timestamps","index","unique","RBNotificationSettingsPolicy","subject","define","builder","ctx","can","Schema","z","ZRBOAuthRequest","object","_id","string","providerId","codeVerifier","returnTo","optional","createdAt","date","expiresAt","IRBOAuthRequest","infer","RBOAuthRequestSchema","type","String","required","index","Date","default","now","versionKey","expireAfterSeconds","Schema","MongooseSchemaExtension","Parameters","extendMongooseSchema","baseSchema","TSchema","extensions","schema","clone","forEach","extension","add","omitMongooseSchemaPaths","paths","path","remove","Schema","SchemaTypeOptions","LocalizedString","withLocalizedStringFallback","localizedStringField","options","Omit","userGet","get","type","Types","Mixed","value","PaginationErrorCode","PaginationValidationError","Error","code","statusCode","constructor","message","options","ErrorOptions","name","isPaginationValidationError","error","anyError","Partial","PaginationDirection","PaginationOrder","PaginationSpec","PaginationValidationError","DISALLOWED_MONGO_FIELD_SEGMENTS","Set","PAGINATION_LIMIT_MAX","NormalizedPaginationSpec","Omit","direction","limit","sort","Array","field","order","normalizePaginationSpec","spec","options","maxLimit","normalizeLimit","normalizeMaxLimit","isArray","length","map","assertSafeMongoFieldPath","normalizeOrder","seenFields","has","add","primaryOrder","push","undefined","Number","isSafeInteger","isFinite","isInteger","startsWith","parts","split","part","test","createHmac","timingSafeEqual","Types","PaginationSpec","PaginationValidationError","normalizePaginationSpec","CursorValue","$date","$oid","CursorPayloadV1","v","values","Record","PaginationCursorCodecOptions","signingSecret","Buffer","maxLimit","encodePaginationCursor","spec","node","options","normalized","Object","create","field","sort","value","readFieldValue","Error","encodeCursorValue","payload","payloadB64","from","JSON","stringify","toString","sigB64","signCursorPayloadB64","decodePaginationCursor","cursor","rest","split","length","verifyCursorSignature","payloadRaw","payloadUnknown","parse","Partial","decoded","prototype","hasOwnProperty","call","encodedValue","decodeCursorValue","secret","update","digest","expectedSigB64","a","b","unwrapCursorComparableValue","Date","ObjectId","current","depth","_id","comparableValue","toHexString","toISOString","d","Number","isNaN","getTime","isValid","undefined","get","path","reduce","acc","key","PaginationOrder","PaginationSpec","PaginationCursorCodecOptions","decodePaginationCursor","PaginationValidationError","NormalizedPaginationSpec","normalizePaginationSpec","CompiledMongoPagination","spec","mongoFilterDelta","Record","mongoSort","mongoLimit","CompileMongoPaginationOptions","cursor","compileMongoPagination","options","normalized","maxLimit","limit","toMongoSort","length","cursorValues","buildKeysetFilterDelta","Object","create","field","order","sort","forQueryOrder","direction","invertOrder","branches","i","current","and","j","prev","eq","push","op","getKeysetOp","cmpOp","cmp","$and","$or","PaginationResponse","PaginationCursorCodecOptions","encodePaginationCursor","CompiledMongoPagination","MaterializePaginationOptions","cursor","includeCursors","materializeMongoPagination","compiled","fetchedNodes","TNode","options","limit","spec","hasMore","length","trimmed","slice","nodes","direction","reverse","hasPrevPage","Boolean","hasNextPage","pageInfo","prevCursor","nextCursor","CompiledMongoPagination","MongoQueryLike","where","delta","Record","sort","limit","MongoAdapter","applyPagination","query","TQuery","compiled","mongoFilterDelta","mongoSort","mongoLimit","PaginationResponse","PaginationSpec","PaginationCursorCodecOptions","compileMongoPagination","materializeMongoPagination","MongoAdapter","MongoPaginateQueryLike","where","delta","Record","sort","limit","exec","Promise","TNode","PaginateMongoQueryOptions","cursor","includeCursors","paginateMongoQuery","query","pagination","options","compiled","applyPagination","fetchedNodes","Array","isArray","Error","mongoose","PaginationResponse","PaginationSpec","PaginationCursorCodecOptions","paginateMongoQuery","mongoPaginationPluginBrand","QueryOptionsLike","Record","getQueryOptions","query","undefined","getOptions","getPaginationFromOptions","options","pagination","getCursorFromOptions","paginationCursor","MongoPaginationPluginOptions","cursor","includeCursors","QueryResultNode","TResult","Array","TNode","Query","DocType","THelpers","RawDocType","QueryOp","TDocOverrides","paginate","Promise","ResultType","mongoPaginationPlugin","schema","Schema","pluginOptions","this","spec","Error","signingSecret","MongoDbLike","databaseName","command","Record","Promise","SearchTextStageOptions","index","query","path","highlightPath","SearchTextStage","$search","text","highlight","buildSearchTextStage","options","trim","Error","stage","searchMetaProjection","score","$meta","highlights","const","EnsureSearchIndexParams","db","collection","name","definition","listResultHasIndex","listResult","cursor","firstBatch","Array","isArray","some","idx","isIndexAlreadyExistsError","error","codeName","undefined","message","String","test","ensureSearchIndex","params","created","listSearchIndexes","createSearchIndexes","indexes","getAppName","env","NodeJS","ProcessEnv","process","appName","APP_NAME","trim","Error","GLOBAL_DB_SUFFIX","getGlobalDbName","getTenantDbName","tenantId","mongoose","isRecord","value","Record","Boolean","Array","isArray","mergeMongoQuery","left","right","TypeError","leftQuery","Object","keys","length","$and","cloneMongoValue","TValue","Date","getTime","Buffer","isBuffer","from","map","entry","prototype","getPrototypeOf","copy","create","key","entries","castMongoQuery","model","Model","query","casted","find","cast","modelName","mongoose","accessibleBy","hasRegisteredPolicy","castMongoQuery","isRecord","mergeMongoQuery","AclAction","AclSubjectType","AppAbility","PipelineStageLike","Record","allowedAggregateStages","Set","injectAggregateMatch","pipeline","match","Object","keys","length","unshift","$match","first","geoNear","$geoNear","query","splice","containsSearchMetadataReference","value","startsWith","Array","isArray","some","values","getModelCollectionName","model","Model","collection","collectionName","name","resolveAggregateModel","sourceModel","candidates","Map","connectionModels","db","models","typedModel","set","modelName","size","Error","assertAllowedAggregateStage","stage","stageNames","stageName","has","secureTargetPipeline","targetModel","ability","secureAggregateStages","accessQuery","ofType","$lookup","lookup","nestedPipeline","from","undefined","$unionWith","coll","unionWith","$graphLookup","graphLookup","targetAccessQuery","restrictSearchWithMatch","$facet","secureAggregatePipeline","action","AsyncLocalStorage","AppAbility","MongooseAclDriverContext","mode","ability","contextStorage","collectionContexts","WeakMap","rawConnections","unsafeMongooseAclDriverContext","Object","freeze","unboundMongooseAclDriverContext","bindMongooseAclDriverContext","value","context","set","getMongooseAclDriverContext","get","undefined","getStore","bindMongooseAclRawConnection","scopedConnection","rawConnection","getMongooseAclRawConnection","connection","TConnection","runWithMongooseAclDriverContext","callback","TResult","run","mongoose","ForbiddenError","subject","accessibleBy","secureAggregatePipeline","getMongooseAclDriverContext","runWithMongooseAclDriverContext","unsafeMongooseAclDriverContext","MongooseAclDriverContext","castMongoQuery","cloneMongoValue","isRecord","mergeMongoQuery","hasRegisteredPolicy","AclAction","AclSubject","AclSubjectType","AppAbility","NativeMongooseCollection","Collection","collection","conn","Connection","modelName","NativeMongooseCollectionConstructor","name","connection","options","Record","MongooseDriver","base","Mongoose","key","NativeMethod","args","NativeDriverAccessor","driver","get","nativeDriver","NativeCollection","rawCollections","WeakMap","rawCollectionProxies","raw","proxy","blockedNativeCollectionProperties","Set","PropertyKey","blockedCursorProperties","aggregateCursorMutationMethods","dataMethods","readFilterArgumentByMethod","Partial","count","countDocuments","distinct","find","findOne","writeFilterActionByMethod","deleteMany","deleteOne","findOneAndDelete","findOneAndReplace","findOneAndUpdate","replaceOne","updateMany","updateOne","getCollectionName","value","collectionName","getModelCollectionName","model","Model","getCollectionModels","Map","candidates","Object","values","models","typedModel","set","getCollectionModelName","size","keys","getProtectedCollectionModelNames","filter","hasSecuredCollectionBoundary","context","mode","some","getCollectionModel","Error","getAccessQuery","ability","action","ofType","assertCanCreate","rawValue","Document","toObject","document","from","throwUnlessCan","materializeBsonValue","seen","has","toBSON","placeholder","create","materialized","Reflect","apply","result","entry","entries","Date","Buffer","isBuffer","RegExp","ArrayBuffer","isView","_bsontype","Array","isArray","copy","push","materializeInsertDocument","safeExplainVerbosities","isSafeExplainVerbosity","verbosity","assertSafeExplainVerbosity","assertSafeExplainOptions","hasOwn","explain","assertNoUpsert","methodName","upsert","secureBulkWriteOperations","TypeError","map","operation","operationActions","supportedKeys","length","insertOne","details","secureCollectionArguments","input","readFilterIndex","undefined","writeAction","documents","pipeline","wrapFindCursor","cursor","Proxy","target","prop","String","wrapCursorStream","stream","wrapAggregateCursor","wrapCursorResult","then","Promise","resolve","resolved","invokeSafeUnprotectedCollectionMethod","rawCollection","Exclude","method","invokeNativeCollectionMethod","protectedModelNames","collectionModels","join","getRawCollectionProxy","cached","installRawCollectionAccessor","initialRawCollection","defineProperty","configurable","enumerable","delete","AclMongooseCollection","constructor","ACL_DRIVER_GLOBAL_KEY","Symbol","for","installMongooseAclDriver","globalState","globalThis","installedInstances","WeakSet","setDriver","add","runWithUnsafeMongooseAclDriver","callback","TResult","_private","mongoose","installMongooseAclDriver","getMongoDirectConnection","getMongoUrl","connections","Map","Connection","rootConnection","CONNECTION_MAX_LISTENERS","waitForOpen","connection","Promise","readyState","getMaxListeners","setMaxListeners","resolve","reject","once","ensureMongooseConnection","dbName","normalizedDbName","trim","Error","existing","get","mongoUrl","manageResourcesWithMigrations","process","env","NODE_ENV","createConnection","sanitizeFilter","directConnection","autoCreate","autoIndex","name","useDb","useCache","set","mongoose","getMongooseAclRawConnection","GLOBAL_DB_SUFFIX","RBRtsChangeSchema","IRBRtsChange","RBRtsCounterSchema","IRBRtsCounter","RtsChangeOp","RTS_COUNTER_ID","EXCLUDED_MODEL_NAMES","Set","maxDeleteIdsRaw","process","env","RB_RTS_DELETE_LOG_MAX_IDS","maxDeleteIds","Number","isFinite","Math","max","floor","DeleteMeta","modelName","ids","reset","session","ClientSession","deleteMetaByQuery","WeakMap","hasToString","value","toString","maybe","normalizeId","id","getDbName","db","name","databaseName","raw","isGlobalDb","endsWith","RtsCounterDoc","RtsChangeDoc","getQuerySession","query","MongooseQuery","opts","getOptions","undefined","getRtsModels","Connection","rawDb","RtsCounter","models","RBRtsCounter","Model","model","RtsChange","RBRtsChange","allocateSeqRange","count","Promise","start","end","updated","findOneAndUpdate","_id","$inc","seq","upsert","returnDocument","setDefaultsOnInsert","projection","lean","insertChanges","changes","Array","op","docId","length","ts","Date","docs","map","c","insertMany","recordDeleteChanges","uniqueIds","from","filter","Boolean","idx","recordResetModel","Query","find","getFilter","getQuery","captureDeleteMeta","mode","String","startsWith","has","findQuery","s","limit","n","isArray","d","trimmedIds","meta","set","flushDeleteMeta","get","delete","rtsChangeLogPlugin","schema","Schema","pre","document","this","post","doc","_private","mongoose","accessibleRecordsPlugin","frameworkSchemas","rtsChangeLogPlugin","registerPoliciesFromModules","installMongooseAclDriver","runWithUnsafeMongooseAclDriver","mongoPaginationPlugin","ModelModules","Record","ModelsScope","RegisterModelsOptions","allowReservedRbModelNames","RegisteredSchemas","Schema","RegisteredModels","tenant","global","cachedModels","DEFAULT_GLOBAL_RB_MODEL_NAMES_SET","Set","assertSchema","exportName","value","Error","join","getFrameworkSchemaForModelName","modelName","applyTenantPlugins","schema","plugin","registerSchema","target","other","scope","buildSchemasFromModules","modules","Array","Object","entries","filter","key","endsWith","map","schemaValue","replace","getFrameworkModelSchemas","cloned","clone","has","registerModels","options","tenantSchemas","globalSchemas","startsWith","frameworkSchema","allSchemas","models","model","getRegisteredModels","mongoose","AclMongooseCollection","installMongooseAclDriver","bindMongooseAclRawConnection","bindMongooseAclDriverContext","unboundMongooseAclDriverContext","unsafeMongooseAclDriverContext","MongooseAclDriverContext","hasRegisteredPolicy","AppAbility","mongooseAclModelBrand","Model","TRawDocType","TQueryHelpers","TInstanceMethods","TVirtuals","THydratedDocumentType","TSchema","TLeanResultType","acl","ability","SubclassableModel","TModel","__subclass","connection","Connection","schema","Schema","collectionName","scopedModelsByAbility","WeakMap","unboundModels","unsafeModels","collectionTargets","blockedModelMethods","Set","PropertyKey","blockedCollectionProperties","blockedConnectionMethods","blockedConnectionProperties","blockedMongooseMethods","blockedMongooseProperties","allowedDbProperties","getModelCollectionName","model","collection","name","value","resolveModelNameForCollection","candidates","Object","values","models","typedModel","add","modelName","size","undefined","detachMongooseSubclassRetention","rawModel","scopedModel","symbol","getOwnPropertySymbols","find","entry","description","subclasses","Record","Array","isArray","index","lastIndexOf","splice","getCachedModel","context","mode","get","cacheModel","set","lockModelCapability","target","property","descriptor","getOwnPropertyDescriptor","defineProperty","configurable","enumerable","Error","String","createAclModelWithContext","cached","rawConnection","db","primaryCollectionName","collections","Map","mongooseProxy","Mongoose","collectionsProxy","Collection","modelsProxy","dbProxy","getMongooseProxy","rawMongoose","base","Proxy","prop","has","Reflect","args","result","apply","_target","createCollectionProxy","proxy","connectionProxy","getCollection","options","existing","exposedCollection","getRelatedModel","relatedModel","getModelsProxy","receiver","hasOwn","deleteProperty","getCollectionsProxy","getDbProxy","rawDb","getClient","bind","length","then","Promise","resolve","resolved","scopedCollection","prototype","rawDiscriminators","discriminators","generatedDiscriminators","scopedDiscriminators","discriminator","entries","generated","methodName","createAclMongooseModel","AclMongooseModel","createAclMongooseModelGateway","createUnsafeMongooseModel","installMongooseAclModelFactory","modelConstructor","this","_private","setNativeCollection","nativeCollection","assert","getGlobalDbName","getTenantDbName","ensureMongooseConnection","getRegisteredModels","registerModels","ModelsScope","AppAbility","createAclMongooseModel","createAclMongooseModelGateway","createUnsafeMongooseModel","runWithUnsafeMongooseAclDriver","LoadModelCtx","tenantId","req","session","user","currentTenantId","ability","loadModelFromDb","modelName","dbName","scope","schemas","schema","Object","keys","join","modelConnection","models","process","env","NODE_ENV","set","model","init","normalizeTenantId","value","trim","getTenantIdFromLoadModelCtx","ctx","register","getUnsafe","get","getGlobal","const","LoadModelCtx","ModelModules","RegisterModelsOptions","frameworkSchemas","models","registerModels","ExtractModelNamesFromSchemas","TModules","K","Name","FrameworkModelName","RpcbaseGlobalModelName","Extract","TenantModelName","TTenantModules","GlobalModelName","TGlobalModules","LoadedTenantModel","Awaited","ReturnType","LoadedGlobalModel","ModelsGetFn","modelName","ctx","modelNames","TNames","Promise","ModelsGetUnsafeFn","ModelsGetGlobalFn","ModelsConfig","tenant","global","ModelsClient","register","modules","options","get","getUnsafe","getGlobal","createModels","Record","modelNameOrNames","Array","isArray","all","map","nextModules","nextOptions","assert","mongoose","ensureMongooseConnection","getTenantIdFromLoadModelCtx","LoadModelCtx","getAppName","appName","process","env","APP_NAME","trim","normalizeTenantId","tenantId","normalized","getTenantFilesystemDbName","getTenantFilesystemDb","Promise","Connection","getTenantFilesystemDbFromCtx","ctx","mongoose","ClientSession","getGlobalDbName","getTenantDbName","ensureMongooseConnection","getTenantIdFromLoadModelCtx","LoadModelCtx","getTenantFilesystemDbName","MongooseTransactionOptions","Parameters","TenantGlobalFilesystemTransactionCtx","tenantId","session","ctx","tenant","global","db","Connection","filesystem","WithTransactionScope","buildTenantLoadModelCtx","req","user","currentTenantId","withTransaction","fn","Promise","T","options","scope","normalizedTenantId","trim","Error","tenantDbName","globalDbName","filesystemDbName","tenantDb","globalDb","filesystemDb","startSession","tenantCtx","globalCtx","endSession","ClientSession","BillingStorage","BillingStorageTransaction","PersistedSubscriptionEvent","StoredSubscriptionProjection","SubscriptionEvent","ZRBTenantSubscriptionEvent","LoadModelCtx","models","withTransaction","MongoBillingTransaction","session","SubscriptionEventDocument","Record","_id","getTransactionSession","transaction","undefined","toSubscriptionEvent","document","parsed","parse","Error","id","String","getExistingEventQuery","event","tenantId","idempotencyKey","isDuplicateKeyError","error","Boolean","code","toProjectionDocument","projection","subscriptionId","type","parentSubscriptionId","scope","scopeId","planKey","priceId","status","intervalUnit","intervalCount","modules","billingAnchor","currentPeriodStart","currentPeriodEnd","cancelAtPeriodEnd","cancelAt","canceledAt","scheduledPlanKey","scheduledPlan","scheduledPlanEffectiveAt","effectiveAt","provider","latestEventId","latestEventAt","projectedAt","createTenantBillingStorage","params","ctx","findExistingEvent","query","Promise","EventModel","get","request","findOne","lean","runInTransaction","operation","createEvent","existingQuery","existing","eventDocument","documents","create","toObject","duplicate","listEvents","find","sort","occurredAt","map","upsertProjection","ProjectionModel","replaceOne","upsert","runValidators","mongoose","defineMongoResources","MigrationScope","MongoIndexResource","MongoResources","ExtractMongoResourcesOptions","scope","schemas","Readonly","Record","collectionNameForModel","modelName","schema","Schema","configured","options","collection","trim","pluralize","generatedIndexName","key","Object","entries","map","path","direction","String","join","observableIndexOptions","Set","extractMongoResourcesFromSchemas","filter","entry","exportName","replace","const","collections","name","indexes","indexOptions","documentKey","normalizedOptions","fromEntries","option","value","has","undefined","push","keys","length","TenantProvisioner","tenantId","Promise","TenantModel","create","document","Record","findOne","filter","PromiseLike","provisioningStatus","updateOne","update","matchedCount","tenantProvisioner","configureTenantMigrationProvisioner","provisioner","undefined","errorMessage","error","Error","message","String","slice","createProvisionedTenant","Tenant","tenant","name","parentTenantId","provisioningStartedAt","Date","process","env","NODE_ENV","activation","$set","provisionedAt","$unset","provisioningError","current"],"sources":["../src/models/RBUser.ts","../src/models/RBTenant.ts","../src/models/RBTenantSubscriptionEvent.ts","../src/models/RBTenantSubscriptionProjection.ts","../src/models/RBRtsCounter.ts","../src/models/RBRtsChange.ts","../src/models/RBUploadSession.ts","../src/models/RBUploadChunk.ts","../src/models/RBNotification.ts","../src/models/RBNotificationDelivery.ts","../src/models/RBNotificationSettings.ts","../src/models/RBOAuthRequest.ts","../src/models/index.ts","../src/mongoose/extendMongooseSchema.ts","../src/mongoose/localizedStringField.ts","../src/mongoose/index.ts","../src/pagination/errors.ts","../src/pagination/normalizeSpec.ts","../src/pagination/cursor.ts","../src/pagination/compileMongoPagination.ts","../src/pagination/materializePagination.ts","../src/pagination/mongoAdapter.ts","../src/pagination/paginateMongoQuery.ts","../src/pagination/mongoPaginationPlugin.ts","../src/search/index.ts","../src/dbNames.ts","../src/acl/mongooseAclUtils.ts","../src/acl/mongooseAclAggregate.ts","../src/acl/mongooseAclDriverContext.ts","../src/acl/mongooseAclDriver.ts","../src/ensureMongooseConnection.ts","../src/rtsChangeLogPlugin.ts","../src/registerModels.ts","../src/acl/mongooseAclModel.ts","../src/modelsApi.ts","../src/createModels.ts","../src/tenantFilesystemDb.ts","../src/transactions.ts","../src/billingStorage.ts","../src/mongoResources.ts","../src/tenantProvisioning.ts"],"sourcesContent":["import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBUser = z.object({\n email: z.string().email().optional(),\n password: z.string(),\n name: z.string().optional(),\n phone: z.string().optional(),\n tenants: z.array(z.string()),\n tenantRoles: z.record(z.string(), z.array(z.string())).optional(),\n oauthProviders: z.record(z.string(), z.object({\n subject: z.string(),\n email: z.string().email().optional(),\n name: z.string().optional(),\n accessToken: z.string().optional(),\n refreshToken: z.string().optional(),\n idToken: z.string().optional(),\n scope: z.string().optional(),\n tokenType: z.string().optional(),\n expiresAt: z.date().optional(),\n rawUserInfo: z.unknown().optional(),\n createdAt: z.date().optional(),\n updatedAt: z.date().optional(),\n })).optional(),\n emailVerificationCode: z.string().length(6).optional(),\n emailVerificationExpiresAt: z.date().optional(),\n passwordResetCode: z.string().length(6).optional(),\n passwordResetCodeExpiresAt: z.date().optional(),\n passwordResetToken: z.string().optional(),\n passwordResetTokenExpiresAt: z.date().optional(),\n})\n\nexport type IRBUser = z.infer<typeof ZRBUser>;\n\nexport const RBUserSchema: Schema = new Schema({\n email: { type: String, unique: true, sparse: true },\n phone: { type: String, unique: true, sparse: true },\n password: { type: String, required: true },\n name: String,\n tenants: { type: [String], index: true, required: true },\n tenantRoles: { type: Map, of: [String], required: false, default: {} },\n oauthProviders: {\n type: Map,\n of: new Schema({\n subject: { type: String, required: true },\n email: { type: String, required: false },\n name: { type: String, required: false },\n accessToken: { type: String, required: false },\n refreshToken: { type: String, required: false },\n idToken: { type: String, required: false },\n scope: { type: String, required: false },\n tokenType: { type: String, required: false },\n expiresAt: { type: Date, required: false },\n rawUserInfo: { type: Schema.Types.Mixed, required: false },\n createdAt: { type: Date, required: false },\n updatedAt: { type: Date, required: false },\n }, { _id: false }),\n default: {},\n required: false,\n },\n emailVerificationCode: { type: String, required: false },\n emailVerificationExpiresAt: { type: Date, required: false },\n passwordResetCode: { type: String, required: false },\n passwordResetCodeExpiresAt: { type: Date, required: false },\n passwordResetToken: { type: String, required: false },\n passwordResetTokenExpiresAt: { type: Date, required: false },\n})\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBTenant = z.object({\n tenantId: z.string(),\n parentTenantId: z.string().optional(),\n name: z.string().optional(),\n provisioningStatus: z.enum([\"initializing\", \"active\", \"failed\"]).optional(),\n provisioningError: z.string().optional(),\n provisioningStartedAt: z.date().optional(),\n provisionedAt: z.date().optional(),\n})\n\nexport type IRBTenant = z.infer<typeof ZRBTenant>;\n\nexport const RBTenantSchema: Schema = new Schema({\n tenantId: { type: String, required: true, unique: true, index: true },\n parentTenantId: { type: String },\n name: { type: String },\n provisioningStatus: { type: String, enum: [\"initializing\", \"active\", \"failed\"] },\n provisioningError: { type: String },\n provisioningStartedAt: { type: Date },\n provisionedAt: { type: Date },\n})\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\nimport {\n SUBSCRIPTION_CHANGE_DIRECTIONS,\n SUBSCRIPTION_EVENT_TYPES,\n SUBSCRIPTION_INTERVAL_UNITS,\n SUBSCRIPTION_SCOPES,\n SUBSCRIPTION_STATUSES,\n SUBSCRIPTION_TYPES,\n} from \"@rpcbase/billing\"\n\n\nexport const ZRBTenantSubscriptionStatus = z.enum(SUBSCRIPTION_STATUSES)\n\nexport const ZRBTenantSubscriptionIntervalUnit = z.enum(SUBSCRIPTION_INTERVAL_UNITS)\n\nexport const ZRBTenantSubscriptionType = z.enum(SUBSCRIPTION_TYPES)\n\nexport const ZRBTenantSubscriptionScope = z.enum(SUBSCRIPTION_SCOPES)\n\nexport const ZRBTenantSubscriptionEventType = z.enum(SUBSCRIPTION_EVENT_TYPES)\n\n\nexport const ZRBTenantSubscriptionEventSource = z.enum([\n \"admin\",\n \"system\",\n \"webhook\",\n \"user\",\n])\n\nexport const ZRBTenantSubscriptionChangeDirection = z.enum(SUBSCRIPTION_CHANGE_DIRECTIONS)\n\nconst subscriptionEventBaseSchema = z.object({\n tenantId: z.string().trim().min(1),\n subscriptionId: z.string().trim().min(1),\n occurredAt: z.date(),\n effectiveAt: z.date(),\n subscriptionType: ZRBTenantSubscriptionType,\n parentSubscriptionId: z.string().optional(),\n scope: ZRBTenantSubscriptionScope,\n scopeId: z.string().optional(),\n fromPlanKey: z.string().optional(),\n toPlanKey: z.string().optional(),\n fromStatus: ZRBTenantSubscriptionStatus.optional(),\n toStatus: ZRBTenantSubscriptionStatus.optional(),\n fromModules: z.array(z.string()).optional(),\n toModules: z.array(z.string()).optional(),\n fromIntervalUnit: ZRBTenantSubscriptionIntervalUnit.optional(),\n toIntervalUnit: ZRBTenantSubscriptionIntervalUnit.optional(),\n fromIntervalCount: z.number().int().min(1).optional(),\n toIntervalCount: z.number().int().min(1).optional(),\n fromPriceId: z.string().optional(),\n toPriceId: z.string().optional(),\n billingAnchor: z.date().optional(),\n supersedesEventId: z.string().optional(),\n idempotencyKey: z.string().trim().min(1),\n direction: ZRBTenantSubscriptionChangeDirection.optional(),\n actorUserId: z.string().optional(),\n source: ZRBTenantSubscriptionEventSource.optional(),\n reason: z.string().optional(),\n provider: z.string().optional(),\n providerEventId: z.string().optional(),\n providerPayload: z.unknown().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n\nconst subscriptionCreatedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"created\"),\n toPlanKey: z.string().trim().min(1),\n toStatus: ZRBTenantSubscriptionStatus,\n toModules: z.array(z.string()),\n toIntervalUnit: ZRBTenantSubscriptionIntervalUnit,\n toIntervalCount: z.number().int().min(1),\n billingAnchor: z.date(),\n})\n\nconst subscriptionPlanChangedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"plan_changed\"),\n fromPlanKey: z.string().trim().min(1),\n toPlanKey: z.string().trim().min(1),\n fromModules: z.array(z.string()),\n toModules: z.array(z.string()),\n fromIntervalUnit: ZRBTenantSubscriptionIntervalUnit,\n toIntervalUnit: ZRBTenantSubscriptionIntervalUnit,\n fromIntervalCount: z.number().int().min(1),\n toIntervalCount: z.number().int().min(1),\n})\n\nconst subscriptionStatusChangedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"status_changed\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: ZRBTenantSubscriptionStatus,\n})\n\nconst subscriptionResumedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"resumed\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: z.literal(\"active\"),\n})\n\nconst subscriptionCanceledEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"canceled\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: z.literal(\"canceled\"),\n})\n\nconst subscriptionRenewedEventSchema = subscriptionEventBaseSchema.extend({\n type: z.literal(\"renewed\"),\n fromStatus: ZRBTenantSubscriptionStatus,\n toStatus: ZRBTenantSubscriptionStatus,\n})\n\nexport const ZRBTenantSubscriptionEvent = z.discriminatedUnion(\"type\", [\n subscriptionCreatedEventSchema,\n subscriptionPlanChangedEventSchema,\n subscriptionStatusChangedEventSchema,\n subscriptionResumedEventSchema,\n subscriptionCanceledEventSchema,\n subscriptionRenewedEventSchema,\n]).superRefine((event, ctx) => {\n if (event.subscriptionType === \"addon\" && !event.parentSubscriptionId?.trim()) {\n ctx.addIssue({\n code: \"custom\",\n message: \"parentSubscriptionId is required for add-on subscriptions\",\n path: [\"parentSubscriptionId\"],\n })\n }\n if (event.scope !== \"tenant\" && !event.scopeId?.trim()) {\n ctx.addIssue({\n code: \"custom\",\n message: \"scopeId is required for non-tenant subscriptions\",\n path: [\"scopeId\"],\n })\n }\n})\n\nexport type IRBTenantSubscriptionEvent = z.infer<typeof ZRBTenantSubscriptionEvent>\n\ntype SubscriptionEventDocument = {\n type?: typeof SUBSCRIPTION_EVENT_TYPES[number]\n subscriptionType?: typeof SUBSCRIPTION_TYPES[number]\n scope?: typeof SUBSCRIPTION_SCOPES[number]\n}\n\nconst requiredForEventTypes = (...types: Array<typeof SUBSCRIPTION_EVENT_TYPES[number]>) =>\n function requiredForEventType(this: SubscriptionEventDocument): boolean {\n return Boolean(this.type && types.includes(this.type))\n }\n\nexport const RBTenantSubscriptionEventSchema: Schema = new Schema(\n {\n tenantId: { type: String, required: true, index: true },\n subscriptionId: { type: String, required: true, index: true },\n type: { type: String, required: true, enum: ZRBTenantSubscriptionEventType.options },\n occurredAt: { type: Date, required: true, default: Date.now },\n effectiveAt: { type: Date, required: true },\n subscriptionType: { type: String, required: true, enum: ZRBTenantSubscriptionType.options },\n parentSubscriptionId: {\n type: String,\n required(this: SubscriptionEventDocument) {\n return this.subscriptionType === \"addon\"\n },\n },\n scope: { type: String, required: true, enum: ZRBTenantSubscriptionScope.options },\n scopeId: {\n type: String,\n required(this: SubscriptionEventDocument) {\n return Boolean(this.scope && this.scope !== \"tenant\")\n },\n },\n fromPlanKey: { type: String, required: requiredForEventTypes(\"plan_changed\") },\n toPlanKey: { type: String, required: requiredForEventTypes(\"created\", \"plan_changed\") },\n fromStatus: {\n type: String,\n required: requiredForEventTypes(\"status_changed\", \"resumed\", \"canceled\", \"renewed\"),\n enum: ZRBTenantSubscriptionStatus.options,\n },\n toStatus: {\n type: String,\n required: requiredForEventTypes(\"created\", \"status_changed\", \"resumed\", \"canceled\", \"renewed\"),\n enum: ZRBTenantSubscriptionStatus.options,\n },\n fromModules: { type: [String], required: requiredForEventTypes(\"plan_changed\"), default: undefined },\n toModules: { type: [String], required: requiredForEventTypes(\"created\", \"plan_changed\"), default: undefined },\n fromIntervalUnit: {\n type: String,\n required: requiredForEventTypes(\"plan_changed\"),\n enum: ZRBTenantSubscriptionIntervalUnit.options,\n },\n toIntervalUnit: {\n type: String,\n required: requiredForEventTypes(\"created\", \"plan_changed\"),\n enum: ZRBTenantSubscriptionIntervalUnit.options,\n },\n fromIntervalCount: { type: Number, required: requiredForEventTypes(\"plan_changed\"), min: 1 },\n toIntervalCount: { type: Number, required: requiredForEventTypes(\"created\", \"plan_changed\"), min: 1 },\n fromPriceId: { type: String },\n toPriceId: { type: String },\n billingAnchor: { type: Date, required: requiredForEventTypes(\"created\") },\n supersedesEventId: { type: String },\n idempotencyKey: { type: String, required: true },\n direction: { type: String, enum: ZRBTenantSubscriptionChangeDirection.options },\n actorUserId: { type: String },\n source: { type: String, enum: ZRBTenantSubscriptionEventSource.options },\n reason: { type: String },\n provider: { type: String },\n providerEventId: { type: String },\n providerPayload: { type: Schema.Types.Mixed },\n metadata: { type: Schema.Types.Mixed },\n },\n)\n\nRBTenantSubscriptionEventSchema.index({ tenantId: 1, subscriptionId: 1, effectiveAt: 1, occurredAt: 1 })\nRBTenantSubscriptionEventSchema.index(\n { provider: 1, providerEventId: 1 },\n {\n unique: true,\n partialFilterExpression: {\n provider: { $type: \"string\" },\n providerEventId: { $type: \"string\" },\n },\n },\n)\nRBTenantSubscriptionEventSchema.index({ tenantId: 1, idempotencyKey: 1 }, { unique: true })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport {\n ZRBTenantSubscriptionIntervalUnit,\n ZRBTenantSubscriptionScope,\n ZRBTenantSubscriptionStatus,\n ZRBTenantSubscriptionType,\n} from \"./RBTenantSubscriptionEvent\"\n\n\nexport const ZRBTenantSubscriptionProjection = z.object({\n tenantId: z.string(),\n subscriptionId: z.string(),\n type: ZRBTenantSubscriptionType,\n parentSubscriptionId: z.string().optional(),\n scope: ZRBTenantSubscriptionScope,\n scopeId: z.string().optional(),\n planKey: z.string(),\n priceId: z.string().optional(),\n status: ZRBTenantSubscriptionStatus,\n intervalUnit: ZRBTenantSubscriptionIntervalUnit,\n intervalCount: z.number().int().min(1),\n modules: z.array(z.string()),\n billingAnchor: z.date(),\n currentPeriodStart: z.date(),\n currentPeriodEnd: z.date(),\n cancelAtPeriodEnd: z.boolean(),\n cancelAt: z.date().optional(),\n canceledAt: z.date().optional(),\n scheduledPlanKey: z.string().optional(),\n scheduledPlanEffectiveAt: z.date().optional(),\n provider: z.string().optional(),\n latestEventId: z.string(),\n latestEventAt: z.date(),\n projectedAt: z.date(),\n})\n\nexport type IRBTenantSubscriptionProjection = z.infer<typeof ZRBTenantSubscriptionProjection>\n\nexport const RBTenantSubscriptionProjectionSchema: Schema = new Schema({\n tenantId: { type: String, required: true, index: true },\n subscriptionId: { type: String, required: true },\n type: { type: String, required: true, enum: ZRBTenantSubscriptionType.options },\n parentSubscriptionId: { type: String },\n scope: { type: String, required: true, enum: ZRBTenantSubscriptionScope.options },\n scopeId: { type: String },\n planKey: { type: String, required: true },\n priceId: { type: String },\n status: { type: String, required: true, enum: ZRBTenantSubscriptionStatus.options },\n intervalUnit: { type: String, required: true, enum: ZRBTenantSubscriptionIntervalUnit.options },\n intervalCount: { type: Number, required: true, min: 1 },\n modules: { type: [String], required: true, default: [] },\n billingAnchor: { type: Date, required: true },\n currentPeriodStart: { type: Date, required: true },\n currentPeriodEnd: { type: Date, required: true },\n cancelAtPeriodEnd: { type: Boolean, required: true, default: false },\n cancelAt: { type: Date },\n canceledAt: { type: Date },\n scheduledPlanKey: { type: String },\n scheduledPlanEffectiveAt: { type: Date },\n provider: { type: String },\n latestEventId: { type: String, required: true },\n latestEventAt: { type: Date, required: true },\n projectedAt: { type: Date, required: true },\n})\n\nRBTenantSubscriptionProjectionSchema.index({ tenantId: 1, subscriptionId: 1 }, { unique: true })\nRBTenantSubscriptionProjectionSchema.index({ tenantId: 1, scope: 1, scopeId: 1 })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBRtsCounter = z.object({\n _id: z.string(),\n seq: z.number().int().min(0),\n})\n\nexport type IRBRtsCounter = z.infer<typeof ZRBRtsCounter>\n\nexport const RBRtsCounterSchema: Schema = new Schema(\n {\n _id: { type: String, required: true },\n seq: { type: Number, required: true, default: 0 },\n },\n {\n versionKey: false,\n },\n)\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport { rtsChangesTtlSeconds } from \"../migrations/rtsChanges\"\n\n\nexport const ZRBRtsChangeOp = z.enum([\"delete\", \"reset_model\"])\n\nexport const ZRBRtsChange = z.object({\n seq: z.number().int().min(0),\n modelName: z.string(),\n op: ZRBRtsChangeOp,\n docId: z.string().optional(),\n ts: z.date(),\n})\n\nexport type IRBRtsChange = z.infer<typeof ZRBRtsChange>\n\nexport const RBRtsChangeSchema: Schema = new Schema(\n {\n seq: { type: Number, required: true },\n modelName: { type: String, required: true, index: true },\n op: { type: String, required: true, enum: ZRBRtsChangeOp.options },\n docId: { type: String, required: false },\n ts: { type: Date, required: true, default: Date.now },\n },\n {\n versionKey: false,\n },\n)\n\nRBRtsChangeSchema.index({ seq: 1 }, { unique: true })\nRBRtsChangeSchema.index({ ts: 1 }, { expireAfterSeconds: rtsChangesTtlSeconds })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\n\n\nexport const ZRBUploadSessionStatus = z.enum([\"uploading\", \"assembling\", \"done\", \"error\"])\nexport const ZRBUploadAccessScope = z.enum([\"owner\", \"tenant\", \"public\"])\n\nexport const ZRBUploadDeduplication = z.object({\n namespace: z.string(),\n algorithm: z.literal(\"sha256\"),\n hash: z.string(),\n key: z.string(),\n pipelineVersion: z.number().int().min(1),\n})\n\nexport const ZRBUploadSession = z.object({\n _id: z.string(),\n userId: z.string().optional(),\n ownerKeyHash: z.string().optional(),\n filename: z.string(),\n mimeType: z.string(),\n totalSize: z.number().int().min(0),\n chunkSize: z.number().int().min(1),\n chunksTotal: z.number().int().min(1),\n status: ZRBUploadSessionStatus,\n createdAt: z.date(),\n expiresAt: z.date(),\n fileId: z.string().optional(),\n isPublic: z.boolean().optional(),\n accessScope: ZRBUploadAccessScope.optional(),\n deduplication: ZRBUploadDeduplication.optional(),\n deduplicated: z.boolean().optional(),\n error: z.string().optional(),\n})\n\nexport type IRBUploadSession = z.infer<typeof ZRBUploadSession>\n\nexport const RBUploadSessionSchema: Schema = new Schema(\n {\n _id: { type: String, required: true },\n userId: { type: String, required: false, index: true },\n ownerKeyHash: { type: String, required: false },\n filename: { type: String, required: true },\n mimeType: { type: String, required: true },\n totalSize: { type: Number, required: true },\n chunkSize: { type: Number, required: true },\n chunksTotal: { type: Number, required: true },\n status: { type: String, required: true, enum: ZRBUploadSessionStatus.options },\n createdAt: { type: Date, required: true, default: Date.now },\n expiresAt: { type: Date, required: true },\n fileId: { type: String, required: false },\n isPublic: { type: Boolean, required: false },\n accessScope: { type: String, required: false, enum: ZRBUploadAccessScope.options },\n deduplication: {\n type: new Schema(\n {\n namespace: { type: String, required: true },\n algorithm: { type: String, required: true, enum: [\"sha256\"] },\n hash: { type: String, required: true },\n key: { type: String, required: true },\n pipelineVersion: { type: Number, required: true },\n },\n { _id: false },\n ),\n required: false,\n },\n deduplicated: { type: Boolean, required: false },\n error: { type: String, required: false },\n },\n {\n versionKey: false,\n },\n)\n\nRBUploadSessionSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 })\n\nexport const RBUploadSessionPolicy: AclPolicy = {\n subject: \"RBUploadSession\",\n define: (builder, ctx) => {\n builder.can(\"create\", \"RBUploadSession\")\n\n if (ctx.userId) {\n builder.can(\"read\", \"RBUploadSession\", { userId: ctx.userId })\n builder.can(\"update\", \"RBUploadSession\", { userId: ctx.userId })\n builder.can(\"delete\", \"RBUploadSession\", { userId: ctx.userId })\n }\n\n const uploadKeyHash = typeof ctx.claims?.uploadKeyHash === \"string\" ? ctx.claims.uploadKeyHash.trim() : \"\"\n if (uploadKeyHash) {\n builder.can(\"read\", \"RBUploadSession\", { ownerKeyHash: uploadKeyHash })\n builder.can(\"update\", \"RBUploadSession\", { ownerKeyHash: uploadKeyHash })\n builder.can(\"delete\", \"RBUploadSession\", { ownerKeyHash: uploadKeyHash })\n }\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBUploadChunk = z.object({\n uploadId: z.string(),\n index: z.number().int().min(0),\n data: z.unknown(),\n size: z.number().int().min(0),\n sha256: z.string().optional(),\n createdAt: z.date(),\n expiresAt: z.date(),\n})\n\nexport type IRBUploadChunk = z.infer<typeof ZRBUploadChunk>\n\nexport const RBUploadChunkSchema: Schema = new Schema(\n {\n uploadId: { type: String, required: true, index: true },\n index: { type: Number, required: true },\n data: { type: Buffer, required: true },\n size: { type: Number, required: true },\n sha256: { type: String, required: false },\n createdAt: { type: Date, required: true, default: Date.now },\n expiresAt: { type: Date, required: true },\n },\n {\n versionKey: false,\n },\n)\n\nRBUploadChunkSchema.index({ uploadId: 1, index: 1 }, { unique: true })\nRBUploadChunkSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 })\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\n\n\nconst ZStringMap = z.record(z.string(), z.string())\n\nexport const ZRBNotificationPlatformPayload = z.object({\n webpush: z.record(z.string(), z.unknown()).optional(),\n fcmOptions: z.record(z.string(), z.unknown()).optional(),\n android: z.record(z.string(), z.unknown()).optional(),\n apns: z.record(z.string(), z.unknown()).optional(),\n}).passthrough()\n\nexport type IRBNotificationPlatformPayload = z.infer<typeof ZRBNotificationPlatformPayload>\n\nexport const ZRBNotification = z.object({\n userId: z.string(),\n topic: z.string().optional(),\n tag: z.string().optional(),\n deliveryId: z.string().optional(),\n title: z.string(),\n body: z.string().optional(),\n image: z.string().optional(),\n data: ZStringMap.optional(),\n platform: ZRBNotificationPlatformPayload.optional(),\n drawerActive: z.boolean().optional(),\n createdAt: z.date(),\n seenAt: z.date().optional(),\n readAt: z.date().optional(),\n archivedAt: z.date().optional(),\n})\n\nexport type IRBNotification = z.infer<typeof ZRBNotification>\n\nconst TTL_90_DAYS_S = 60 * 60 * 24 * 90\n\nexport const RBNotificationSchema: Schema = new Schema(\n {\n userId: { type: String, required: true, index: true },\n topic: { type: String, required: false, index: true },\n tag: { type: String, required: false },\n deliveryId: { type: String, required: false },\n title: { type: String, required: true },\n body: { type: String, required: false },\n image: { type: String, required: false },\n data: { type: Schema.Types.Mixed, required: false },\n platform: { type: Schema.Types.Mixed, required: false },\n drawerActive: { type: Boolean, required: false },\n createdAt: { type: Date, required: true, default: Date.now, index: true },\n seenAt: { type: Date, required: false, index: true },\n readAt: { type: Date, required: false, index: true },\n archivedAt: { type: Date, required: false },\n },\n {\n versionKey: false,\n },\n)\n\nRBNotificationSchema.index({ userId: 1, archivedAt: 1, createdAt: -1 })\nRBNotificationSchema.index({ userId: 1, seenAt: 1, archivedAt: 1, createdAt: -1 })\nRBNotificationSchema.index({ userId: 1, readAt: 1, archivedAt: 1, createdAt: -1 })\nRBNotificationSchema.index(\n { userId: 1, tag: 1 },\n { unique: true, partialFilterExpression: { tag: { $exists: true }, drawerActive: true } },\n)\nRBNotificationSchema.index({ archivedAt: 1 }, { expireAfterSeconds: TTL_90_DAYS_S })\n\nexport const RBNotificationPolicy: AclPolicy = {\n subject: \"RBNotification\",\n define: (builder, ctx) => {\n if (!ctx.userId) return\n builder.can(\"create\", \"RBNotification\")\n builder.can(\"read\", \"RBNotification\", { userId: ctx.userId })\n builder.can(\"update\", \"RBNotification\", { userId: ctx.userId })\n builder.can(\"delete\", \"RBNotification\", { userId: ctx.userId })\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\nimport { ZRBNotificationPlatformPayload } from \"./RBNotification\"\n\n\nconst ZStringMap = z.record(z.string(), z.string())\n\nexport const ZRBNotificationDelivery = z.object({\n userId: z.string(),\n notificationId: z.string().optional(),\n deliveryId: z.string(),\n topic: z.string().optional(),\n tag: z.string().optional(),\n title: z.string(),\n body: z.string().optional(),\n image: z.string().optional(),\n data: ZStringMap.optional(),\n platform: ZRBNotificationPlatformPayload.optional(),\n createdAt: z.date(),\n})\n\nexport type IRBNotificationDelivery = z.infer<typeof ZRBNotificationDelivery>\n\nconst TTL_90_DAYS_S = 60 * 60 * 24 * 90\n\nexport const RBNotificationDeliverySchema: Schema = new Schema(\n {\n userId: { type: String, required: true, index: true },\n notificationId: { type: String, required: false },\n deliveryId: { type: String, required: true, unique: true },\n topic: { type: String, required: false },\n tag: { type: String, required: false },\n title: { type: String, required: true },\n body: { type: String, required: false },\n image: { type: String, required: false },\n data: { type: Schema.Types.Mixed, required: false },\n platform: { type: Schema.Types.Mixed, required: false },\n createdAt: { type: Date, required: true, default: Date.now },\n },\n {\n versionKey: false,\n },\n)\n\nRBNotificationDeliverySchema.index({ userId: 1, createdAt: -1 })\nRBNotificationDeliverySchema.index({ createdAt: 1 }, { expireAfterSeconds: TTL_90_DAYS_S })\n\nexport const RBNotificationDeliveryPolicy: AclPolicy = {\n subject: \"RBNotificationDelivery\",\n define: (builder, ctx) => {\n if (!ctx.userId) return\n builder.can(\"create\", \"RBNotificationDelivery\")\n builder.can(\"read\", \"RBNotificationDelivery\", { userId: ctx.userId })\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\nimport type { AclPolicy } from \"../acl\"\n\n\nexport const ZRBNotificationDigestFrequency = z.enum([\"off\", \"daily\", \"weekly\"])\n\nexport const ZRBNotificationTopicPreference = z.object({\n topic: z.string(),\n inApp: z.boolean(),\n emailDigest: z.boolean(),\n push: z.boolean(),\n})\n\nexport const ZRBNotificationSettings = z.object({\n userId: z.string(),\n digestFrequency: ZRBNotificationDigestFrequency,\n topicPreferences: z.array(ZRBNotificationTopicPreference).optional(),\n lastDigestSentAt: z.date().optional(),\n})\n\nexport type IRBNotificationSettings = z.infer<typeof ZRBNotificationSettings>\n\nconst TopicPreferenceSchema = new Schema(\n {\n topic: { type: String, required: true },\n inApp: { type: Boolean, required: true, default: true },\n emailDigest: { type: Boolean, required: true, default: true },\n push: { type: Boolean, required: true, default: false },\n },\n { _id: false },\n)\n\nexport const RBNotificationSettingsSchema: Schema = new Schema(\n {\n userId: { type: String, required: true },\n digestFrequency: {\n type: String,\n required: true,\n enum: ZRBNotificationDigestFrequency.options,\n default: \"weekly\",\n },\n topicPreferences: {\n type: [TopicPreferenceSchema],\n default: [],\n },\n lastDigestSentAt: { type: Date, required: false },\n },\n {\n versionKey: false,\n timestamps: true,\n },\n)\n\nRBNotificationSettingsSchema.index({ userId: 1 }, { unique: true })\nRBNotificationSettingsSchema.index({ userId: 1, \"topicPreferences.topic\": 1 })\n\nexport const RBNotificationSettingsPolicy: AclPolicy = {\n subject: \"RBNotificationSettings\",\n define: (builder, ctx) => {\n if (!ctx.userId) return\n builder.can(\"create\", \"RBNotificationSettings\")\n builder.can(\"read\", \"RBNotificationSettings\", { userId: ctx.userId })\n builder.can(\"update\", \"RBNotificationSettings\", { userId: ctx.userId })\n },\n}\n","import { Schema } from \"mongoose\"\nimport { z } from \"zod\"\n\n\nexport const ZRBOAuthRequest = z.object({\n _id: z.string(),\n providerId: z.string(),\n codeVerifier: z.string(),\n returnTo: z.string().optional(),\n createdAt: z.date(),\n expiresAt: z.date(),\n})\n\nexport type IRBOAuthRequest = z.infer<typeof ZRBOAuthRequest>\n\nexport const RBOAuthRequestSchema: Schema = new Schema(\n {\n _id: { type: String, required: true },\n providerId: { type: String, required: true, index: true },\n codeVerifier: { type: String, required: true },\n returnTo: { type: String, required: false },\n createdAt: { type: Date, required: true, default: Date.now },\n expiresAt: { type: Date, required: true },\n },\n { versionKey: false },\n)\n\nRBOAuthRequestSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 })\n","export * from \"./RBUser\"\nexport * from \"./RBTenant\"\nexport * from \"./RBTenantSubscriptionEvent\"\nexport * from \"./RBTenantSubscriptionProjection\"\nexport * from \"./RBRtsCounter\"\nexport * from \"./RBRtsChange\"\nexport * from \"./RBUploadSession\"\nexport * from \"./RBUploadChunk\"\nexport * from \"./RBNotification\"\nexport * from \"./RBNotificationDelivery\"\nexport * from \"./RBNotificationSettings\"\nexport * from \"./RBOAuthRequest\"\n","import { Schema } from \"mongoose\"\n\n\ntype MongooseSchemaExtension = Parameters<Schema[\"add\"]>[0]\n\nexport function extendMongooseSchema<TSchema extends Schema>(\n baseSchema: TSchema,\n ...extensions: MongooseSchemaExtension[]\n): TSchema {\n const schema = baseSchema.clone() as TSchema\n\n extensions.forEach((extension) => schema.add(extension))\n\n return schema\n}\n\nexport function omitMongooseSchemaPaths<TSchema extends Schema>(\n schema: TSchema,\n paths: string[],\n): TSchema {\n const clone = schema.clone() as TSchema\n paths.forEach((path) => clone.remove(path))\n return clone\n}\n","import { Schema } from \"mongoose\"\nimport type { SchemaTypeOptions } from \"mongoose\"\n\nimport type { LocalizedString } from \"../zod/localizedString\"\nimport { withLocalizedStringFallback } from \"../zod/localizedString\"\n\n\nexport function localizedStringField(\n options?: Omit<SchemaTypeOptions<LocalizedString>, \"type\">\n): SchemaTypeOptions<LocalizedString> {\n const userGet = options?.get\n\n return {\n ...options,\n type: Schema.Types.Mixed,\n get: (value: unknown) => withLocalizedStringFallback(userGet ? userGet(value) : value),\n }\n}\n","import mongoose from \"mongoose\"\nimport type { InferSchemaType } from \"mongoose\"\n\n\nconst { Schema, model } = mongoose\n\nexport { Schema, model, mongoose, type InferSchemaType }\nexport * from \"./extendMongooseSchema\"\nexport * from \"./localizedStringField\"\n","export type PaginationErrorCode = \"invalid_pagination\"\n\nexport class PaginationValidationError extends Error {\n readonly code: PaginationErrorCode = \"invalid_pagination\"\n readonly statusCode = 400\n\n constructor(message: string, options?: ErrorOptions) {\n super(message, options)\n this.name = \"PaginationValidationError\"\n }\n}\n\nexport const isPaginationValidationError = (error: unknown): error is PaginationValidationError => {\n if (!error || typeof error !== \"object\") return false\n const anyError = error as Partial<PaginationValidationError>\n return (\n anyError.name === \"PaginationValidationError\" &&\n anyError.code === \"invalid_pagination\" &&\n anyError.statusCode === 400\n )\n}\n","import type { PaginationDirection, PaginationOrder, PaginationSpec } from \"@rpcbase/api\"\n\nimport { PaginationValidationError } from \"./errors\"\n\n\nconst DISALLOWED_MONGO_FIELD_SEGMENTS = new Set([\"__proto__\", \"constructor\", \"prototype\"])\nconst PAGINATION_LIMIT_MAX = 128\nexport type NormalizedPaginationSpec = Omit<PaginationSpec, \"direction\" | \"sort\" | \"limit\"> & {\n direction: PaginationDirection;\n limit: number;\n sort: Array<{\n field: string;\n order: PaginationOrder;\n }>;\n}\n\nexport const normalizePaginationSpec = (\n spec: PaginationSpec,\n options: { maxLimit?: number } = {},\n): NormalizedPaginationSpec => {\n if (!spec || typeof spec !== \"object\") throw new PaginationValidationError(\"Invalid PaginationSpec\")\n\n const limit = normalizeLimit(spec.limit, normalizeMaxLimit(options.maxLimit))\n const direction = spec.direction ?? \"next\"\n if (direction !== \"next\" && direction !== \"prev\") throw new PaginationValidationError(\"Invalid pagination direction\")\n\n if (!Array.isArray(spec.sort) || spec.sort.length === 0) throw new PaginationValidationError(\"Invalid pagination sort\")\n\n const sort: NormalizedPaginationSpec[\"sort\"] = spec.sort.map(({ field, order }) => ({\n field: assertSafeMongoFieldPath(field),\n order: normalizeOrder(order),\n }))\n\n const seenFields = new Set<string>()\n for (const { field } of sort) {\n if (seenFields.has(field)) throw new PaginationValidationError(`Duplicate pagination sort field: ${field}`)\n seenFields.add(field)\n }\n\n const primaryOrder = sort[0]?.order\n\n if (!seenFields.has(\"_id\")) {\n sort.push({ field: \"_id\", order: primaryOrder })\n }\n\n return {\n ...spec,\n limit,\n direction,\n sort,\n }\n}\n\nconst normalizeMaxLimit = (maxLimit: unknown): number => {\n if (maxLimit === undefined) return PAGINATION_LIMIT_MAX\n if (!Number.isSafeInteger(maxLimit) || (maxLimit as number) <= 0) {\n throw new PaginationValidationError(\"Invalid pagination max limit\")\n }\n return maxLimit as number\n}\n\nconst normalizeLimit = (limit: unknown, maxLimit: number): number => {\n if (typeof limit !== \"number\" || !Number.isFinite(limit) || !Number.isInteger(limit) || limit <= 0) {\n throw new PaginationValidationError(\"Invalid pagination limit\")\n }\n if (limit > maxLimit) {\n throw new PaginationValidationError(\"Invalid pagination limit\")\n }\n return limit\n}\n\nconst normalizeOrder = (order: unknown): PaginationOrder => {\n if (order !== \"asc\" && order !== \"desc\") throw new PaginationValidationError(\"Invalid pagination order\")\n return order\n}\n\nconst assertSafeMongoFieldPath = (field: unknown): string => {\n if (typeof field !== \"string\" || field.length === 0) throw new PaginationValidationError(\"Invalid pagination sort field\")\n if (field.startsWith(\"$\")) throw new PaginationValidationError(\"Invalid pagination sort field\")\n\n const parts = field.split(\".\")\n for (const part of parts) {\n if (part.length === 0) throw new PaginationValidationError(\"Invalid pagination sort field\")\n if (DISALLOWED_MONGO_FIELD_SEGMENTS.has(part)) throw new PaginationValidationError(\"Invalid pagination sort field\")\n if (!/^[a-zA-Z0-9_]+$/.test(part)) throw new PaginationValidationError(\"Invalid pagination sort field\")\n }\n\n return field\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\"\n\nimport { Types } from \"mongoose\"\nimport type { PaginationSpec } from \"@rpcbase/api\"\n\nimport { PaginationValidationError } from \"./errors\"\nimport { normalizePaginationSpec } from \"./normalizeSpec\"\n\n\ntype CursorValue =\n | null\n | string\n | number\n | boolean\n | { $date: string }\n | { $oid: string }\n\ntype CursorPayloadV1 = {\n v: 1;\n values: Record<string, CursorValue>;\n}\n\nexport type PaginationCursorCodecOptions = {\n signingSecret: string | Buffer;\n maxLimit?: number;\n}\n\nexport const encodePaginationCursor = (\n spec: PaginationSpec,\n node: unknown,\n options: PaginationCursorCodecOptions,\n): string => {\n const normalized = normalizePaginationSpec(spec, { maxLimit: options.maxLimit })\n\n const values = Object.create(null) as Record<string, CursorValue>\n for (const { field } of normalized.sort) {\n const value = readFieldValue(node, field)\n if (typeof value === \"undefined\") {\n throw new Error(`Pagination cursor encode failed (missing field: ${field})`)\n }\n values[field] = encodeCursorValue(field, value)\n }\n\n const payload: CursorPayloadV1 = { v: 1, values }\n const payloadB64 = Buffer.from(JSON.stringify(payload), \"utf8\").toString(\"base64url\")\n\n const sigB64 = signCursorPayloadB64(payloadB64, options.signingSecret)\n return `${payloadB64}.${sigB64}`\n}\n\nexport const decodePaginationCursor = (\n spec: PaginationSpec,\n cursor: string,\n options: PaginationCursorCodecOptions,\n): Record<string, unknown> => {\n const normalized = normalizePaginationSpec(spec, { maxLimit: options.maxLimit })\n\n const [payloadB64, sigB64, ...rest] = cursor.split(\".\")\n if (rest.length > 0) throw new PaginationValidationError(\"Invalid pagination cursor format\")\n if (!sigB64) throw new PaginationValidationError(\"Invalid pagination cursor format\")\n verifyCursorSignature(payloadB64, sigB64, options.signingSecret)\n\n const payloadRaw = Buffer.from(payloadB64, \"base64url\").toString(\"utf8\")\n\n let payloadUnknown: unknown\n try {\n payloadUnknown = JSON.parse(payloadRaw)\n } catch {\n throw new PaginationValidationError(\"Invalid pagination cursor payload\")\n }\n\n if (!payloadUnknown || typeof payloadUnknown !== \"object\") throw new PaginationValidationError(\"Invalid pagination cursor payload\")\n const payload = payloadUnknown as Partial<CursorPayloadV1>\n\n if (payload.v !== 1) throw new PaginationValidationError(\"Unsupported pagination cursor version\")\n if (!payload.values || typeof payload.values !== \"object\") throw new PaginationValidationError(\"Invalid pagination cursor payload\")\n\n const decoded = Object.create(null) as Record<string, unknown>\n for (const { field } of normalized.sort) {\n if (!Object.prototype.hasOwnProperty.call(payload.values, field)) {\n throw new PaginationValidationError(`Pagination cursor missing field: ${field}`)\n }\n const encodedValue = (payload.values as Record<string, CursorValue>)[field]\n decoded[field] = decodeCursorValue(field, encodedValue)\n }\n\n return decoded\n}\n\nconst signCursorPayloadB64 = (payloadB64: string, secret: string | Buffer): string => {\n return createHmac(\"sha256\", secret).update(payloadB64, \"utf8\").digest(\"base64url\")\n}\n\nconst verifyCursorSignature = (payloadB64: string, sigB64: string, secret: string | Buffer): void => {\n const expectedSigB64 = signCursorPayloadB64(payloadB64, secret)\n const a = Buffer.from(sigB64, \"utf8\")\n const b = Buffer.from(expectedSigB64, \"utf8\")\n if (a.length !== b.length || !timingSafeEqual(a, b)) {\n throw new PaginationValidationError(\"Invalid pagination cursor signature\")\n }\n}\n\nconst unwrapCursorComparableValue = (value: unknown): unknown => {\n if (value === null || typeof value !== \"object\") return value\n if (value instanceof Date || value instanceof Types.ObjectId) return value\n\n let current: unknown = value\n for (let depth = 0; depth < 4; depth += 1) {\n if (!current || typeof current !== \"object\") return current\n if (current instanceof Date || current instanceof Types.ObjectId) return current\n if (!(\"_id\" in current)) return current\n current = (current as { _id: unknown })._id\n }\n\n return current\n}\n\nconst encodeCursorValue = (field: string, value: unknown): CursorValue => {\n const comparableValue = unwrapCursorComparableValue(value)\n\n if (comparableValue === null) return null\n\n if (field === \"_id\") {\n if (comparableValue instanceof Types.ObjectId) return { $oid: comparableValue.toHexString() }\n if (typeof comparableValue === \"string\") return comparableValue\n throw new Error(\"Pagination cursor encode failed (_id must be an ObjectId or string)\")\n }\n\n if (comparableValue instanceof Date) return { $date: comparableValue.toISOString() }\n\n if (\n typeof comparableValue === \"string\" ||\n typeof comparableValue === \"number\" ||\n typeof comparableValue === \"boolean\"\n ) {\n return comparableValue\n }\n\n if (comparableValue instanceof Types.ObjectId) return { $oid: comparableValue.toHexString() }\n\n throw new Error(`Unsupported pagination cursor value type for field: ${field}`)\n}\n\nconst decodeCursorValue = (field: string, value: CursorValue): unknown => {\n if (value === null) return null\n\n if (typeof value === \"string\") {\n return value\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\") return value\n\n if (!value || typeof value !== \"object\") throw new PaginationValidationError(`Invalid pagination cursor value for field: ${field}`)\n\n if (\"$date\" in value) {\n if (typeof value.$date !== \"string\") throw new PaginationValidationError(`Invalid pagination cursor date for field: ${field}`)\n const d = new Date(value.$date)\n if (Number.isNaN(d.getTime())) throw new PaginationValidationError(`Invalid pagination cursor date for field: ${field}`)\n return d\n }\n\n if (\"$oid\" in value) {\n if (typeof value.$oid !== \"string\" || !Types.ObjectId.isValid(value.$oid)) {\n throw new PaginationValidationError(`Invalid pagination cursor ObjectId for field: ${field}`)\n }\n return new Types.ObjectId(value.$oid)\n }\n\n throw new PaginationValidationError(`Invalid pagination cursor value for field: ${field}`)\n}\n\nconst readFieldValue = (node: unknown, field: string): unknown => {\n if (!node || typeof node !== \"object\") return undefined\n\n if (\"get\" in node && typeof (node as { get?: unknown }).get === \"function\") {\n return (node as { get: (path: string) => unknown }).get(field)\n }\n\n return field.split(\".\").reduce((acc, key) => {\n if (!acc || typeof acc !== \"object\") return undefined\n return (acc as Record<string, unknown>)[key]\n }, node as unknown)\n}\n","import type { PaginationOrder, PaginationSpec } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { decodePaginationCursor } from \"./cursor\"\nimport { PaginationValidationError } from \"./errors\"\nimport type { NormalizedPaginationSpec } from \"./normalizeSpec\"\nimport { normalizePaginationSpec } from \"./normalizeSpec\"\n\n\nexport type CompiledMongoPagination = {\n spec: NormalizedPaginationSpec;\n mongoFilterDelta: Record<string, unknown>;\n mongoSort: Record<string, 1 | -1>;\n mongoLimit: number;\n}\n\nexport type CompileMongoPaginationOptions = {\n cursor: PaginationCursorCodecOptions;\n}\n\nexport const compileMongoPagination = (\n spec: PaginationSpec,\n options: CompileMongoPaginationOptions,\n): CompiledMongoPagination => {\n const normalized = normalizePaginationSpec(spec, { maxLimit: options.cursor.maxLimit })\n\n const mongoLimit = normalized.limit + 1\n const mongoSort = toMongoSort(normalized)\n\n if (normalized.cursor == null) {\n return {\n spec: normalized,\n mongoFilterDelta: {},\n mongoSort,\n mongoLimit,\n }\n }\n\n if (typeof normalized.cursor !== \"string\" || normalized.cursor.length === 0) {\n throw new PaginationValidationError(\"Invalid pagination cursor\")\n }\n\n const cursorValues = decodePaginationCursor(normalized, normalized.cursor, options.cursor)\n const mongoFilterDelta = buildKeysetFilterDelta(normalized, cursorValues)\n\n return {\n spec: normalized,\n mongoFilterDelta,\n mongoSort,\n mongoLimit,\n }\n}\n\nconst toMongoSort = (spec: NormalizedPaginationSpec): Record<string, 1 | -1> => {\n const mongoSort = Object.create(null) as Record<string, 1 | -1>\n for (const { field, order } of spec.sort) {\n const forQueryOrder = spec.direction === \"prev\" ? invertOrder(order) : order\n mongoSort[field] = forQueryOrder === \"asc\" ? 1 : -1\n }\n return mongoSort\n}\n\nconst buildKeysetFilterDelta = (\n spec: NormalizedPaginationSpec,\n cursorValues: Record<string, unknown>,\n): Record<string, unknown> => {\n const branches: Record<string, unknown>[] = []\n\n for (let i = 0; i < spec.sort.length; i++) {\n const current = spec.sort[i]\n if (!current) continue\n\n const and: Record<string, unknown>[] = []\n\n for (let j = 0; j < i; j++) {\n const prev = spec.sort[j]\n if (!prev) continue\n const eq = Object.create(null) as Record<string, unknown>\n eq[prev.field] = cursorValues[prev.field]\n and.push(eq)\n }\n\n const op = getKeysetOp(current.order, spec.direction)\n const cmpOp = Object.create(null) as Record<string, unknown>\n cmpOp[op] = cursorValues[current.field]\n const cmp = Object.create(null) as Record<string, unknown>\n cmp[current.field] = cmpOp\n and.push(cmp)\n\n branches.push(and.length === 1 ? and[0]! : { $and: and })\n }\n\n return { $or: branches }\n}\n\nconst getKeysetOp = (order: PaginationOrder, direction: NormalizedPaginationSpec[\"direction\"]): \"$gt\" | \"$lt\" => {\n if (direction === \"next\") return order === \"asc\" ? \"$gt\" : \"$lt\"\n return order === \"asc\" ? \"$lt\" : \"$gt\"\n}\n\nconst invertOrder = (order: PaginationOrder): PaginationOrder => {\n return order === \"asc\" ? \"desc\" : \"asc\"\n}\n","import type { PaginationResponse } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { encodePaginationCursor } from \"./cursor\"\nimport type { CompiledMongoPagination } from \"./compileMongoPagination\"\n\n\nexport type MaterializePaginationOptions = {\n cursor: PaginationCursorCodecOptions;\n includeCursors?: boolean;\n}\n\nexport const materializeMongoPagination = <TNode>(\n compiled: CompiledMongoPagination,\n fetchedNodes: TNode[],\n options: MaterializePaginationOptions,\n): PaginationResponse<TNode> => {\n const limit = compiled.spec.limit\n const hasMore = fetchedNodes.length > limit\n\n const trimmed = fetchedNodes.slice(0, limit)\n const nodes = compiled.spec.direction === \"prev\" ? trimmed.reverse() : trimmed\n\n const hasPrevPage = compiled.spec.direction === \"next\" ? Boolean(compiled.spec.cursor) : hasMore\n const hasNextPage = compiled.spec.direction === \"next\" ? hasMore : Boolean(compiled.spec.cursor)\n\n const pageInfo: PaginationResponse<TNode>[\"pageInfo\"] = {\n hasNextPage,\n hasPrevPage,\n }\n\n if (nodes.length === 0) {\n return { nodes, pageInfo }\n }\n\n if (options.includeCursors !== false && hasPrevPage) {\n pageInfo.prevCursor = encodePaginationCursor(compiled.spec, nodes[0], options.cursor)\n }\n\n if (options.includeCursors !== false && hasNextPage) {\n pageInfo.nextCursor = encodePaginationCursor(compiled.spec, nodes[nodes.length - 1], options.cursor)\n }\n\n return { nodes, pageInfo }\n}\n","import type { CompiledMongoPagination } from \"./compileMongoPagination\"\n\n\ntype MongoQueryLike = {\n where: (delta: Record<string, unknown>) => unknown;\n sort: (sort: Record<string, 1 | -1>) => unknown;\n limit: (limit: number) => unknown;\n}\n\nexport const MongoAdapter = {\n applyPagination: <TQuery extends MongoQueryLike>(query: TQuery, compiled: CompiledMongoPagination): TQuery => {\n query.where(compiled.mongoFilterDelta)\n query.sort(compiled.mongoSort)\n query.limit(compiled.mongoLimit)\n return query\n },\n}\n\n","import type { PaginationResponse, PaginationSpec } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { compileMongoPagination } from \"./compileMongoPagination\"\nimport { materializeMongoPagination } from \"./materializePagination\"\nimport { MongoAdapter } from \"./mongoAdapter\"\n\n\ntype MongoPaginateQueryLike<TNode> = {\n where: (delta: Record<string, unknown>) => unknown;\n sort: (sort: Record<string, 1 | -1>) => unknown;\n limit: (limit: number) => unknown;\n exec: () => Promise<TNode[]>;\n}\n\nexport type PaginateMongoQueryOptions = {\n cursor: PaginationCursorCodecOptions;\n includeCursors?: boolean;\n}\n\nexport const paginateMongoQuery = async <TNode>(\n query: MongoPaginateQueryLike<TNode>,\n pagination: PaginationSpec,\n options: PaginateMongoQueryOptions,\n): Promise<PaginationResponse<TNode>> => {\n const compiled = compileMongoPagination(pagination, { cursor: options.cursor })\n\n MongoAdapter.applyPagination(query, compiled)\n\n const fetchedNodes = await query.exec()\n if (!Array.isArray(fetchedNodes)) {\n throw new Error(\"paginateMongoQuery expects query.exec() to return an array\")\n }\n\n return materializeMongoPagination(compiled, fetchedNodes, {\n cursor: options.cursor,\n includeCursors: options.includeCursors,\n })\n}\n","import mongoose from \"mongoose\"\nimport type { PaginationResponse, PaginationSpec } from \"@rpcbase/api\"\n\nimport type { PaginationCursorCodecOptions } from \"./cursor\"\nimport { paginateMongoQuery } from \"./paginateMongoQuery\"\n\n\ndeclare const mongoPaginationPluginBrand: unique symbol\n\n\ntype QueryOptionsLike = Record<string, unknown>\n\nconst getQueryOptions = (query: unknown): QueryOptionsLike | undefined => {\n if (!query || typeof query !== \"object\") return undefined\n if (!(\"getOptions\" in query) || typeof (query as { getOptions?: unknown }).getOptions !== \"function\") return undefined\n return (query as { getOptions: () => QueryOptionsLike }).getOptions()\n}\n\nconst getPaginationFromOptions = (query: unknown): PaginationSpec | undefined => {\n const options = getQueryOptions(query)\n return options?.pagination as PaginationSpec | undefined\n}\n\nconst getCursorFromOptions = (query: unknown): PaginationCursorCodecOptions | undefined => {\n const options = getQueryOptions(query)\n return options?.paginationCursor as PaginationCursorCodecOptions | undefined\n}\n\nexport type MongoPaginationPluginOptions = {\n cursor: PaginationCursorCodecOptions;\n includeCursors?: boolean;\n}\n\ntype QueryResultNode<TResult> = TResult extends Array<infer TNode> ? TNode : unknown\n\ndeclare module \"mongoose\" {\n interface Query<\n ResultType,\n DocType,\n THelpers = {},\n RawDocType = unknown,\n QueryOp = \"find\",\n TDocOverrides = Record<string, never>,\n > {\n [mongoPaginationPluginBrand]?: [DocType, THelpers, RawDocType, QueryOp, TDocOverrides];\n paginate: (\n pagination?: PaginationSpec,\n options?: MongoPaginationPluginOptions,\n ) => Promise<PaginationResponse<QueryResultNode<ResultType>>>;\n }\n}\n\nexport const mongoPaginationPlugin = (schema: mongoose.Schema, pluginOptions?: MongoPaginationPluginOptions): void => {\n ;(schema.query as Record<string, unknown>).paginate = async function(\n this: mongoose.Query<unknown[], unknown>,\n pagination?: PaginationSpec,\n options?: MongoPaginationPluginOptions,\n ): Promise<PaginationResponse<unknown>> {\n const spec = pagination ?? getPaginationFromOptions(this)\n if (!spec) throw new Error(\"Missing pagination spec\")\n\n const cursor = options?.cursor ?? getCursorFromOptions(this) ?? pluginOptions?.cursor\n if (!cursor?.signingSecret) throw new Error(\"Missing pagination cursor signingSecret\")\n\n return await paginateMongoQuery(this, spec, {\n cursor,\n includeCursors: options?.includeCursors ?? pluginOptions?.includeCursors,\n })\n }\n}\n","type MongoDbLike = {\n databaseName?: string\n command: (command: Record<string, unknown>) => Promise<unknown>\n}\n\nexport type SearchTextStageOptions = {\n index: string\n query: string\n path: string | string[]\n highlightPath?: string | string[]\n}\n\nexport type SearchTextStage = {\n $search: {\n index: string\n text: {\n query: string\n path: string | string[]\n }\n highlight?: {\n path: string | string[]\n }\n }\n}\n\nexport const buildSearchTextStage = (options: SearchTextStageOptions): SearchTextStage => {\n const index = options.index.trim()\n if (!index) throw new Error(\"Missing search index name\")\n\n const query = options.query.trim()\n if (!query) throw new Error(\"Missing search query\")\n\n const stage: SearchTextStage = {\n $search: {\n index,\n text: {\n query,\n path: options.path,\n },\n },\n }\n\n if (options.highlightPath) {\n stage.$search.highlight = { path: options.highlightPath }\n }\n\n return stage\n}\n\nexport const searchMetaProjection = () => {\n return {\n score: { $meta: \"searchScore\" },\n highlights: { $meta: \"searchHighlights\" },\n } as const\n}\n\nexport type EnsureSearchIndexParams = {\n db: MongoDbLike\n collection: string\n name: string\n definition: Record<string, unknown>\n}\n\nconst listResultHasIndex = (listResult: unknown, name: string): boolean => {\n if (!listResult || typeof listResult !== \"object\") return false\n if (!(\"cursor\" in listResult)) return false\n const cursor = (listResult as { cursor?: unknown }).cursor\n if (!cursor || typeof cursor !== \"object\") return false\n const firstBatch = (cursor as { firstBatch?: unknown }).firstBatch\n if (!Array.isArray(firstBatch)) return false\n return firstBatch.some((idx) => idx && typeof idx === \"object\" && \"name\" in idx && (idx as { name?: unknown }).name === name)\n}\n\nconst isIndexAlreadyExistsError = (error: unknown): boolean => {\n if (!error || typeof error !== \"object\") return false\n const codeName = \"codeName\" in error ? (error as { codeName?: unknown }).codeName : undefined\n if (codeName === \"IndexAlreadyExists\") return true\n const message = \"message\" in error ? String((error as { message?: unknown }).message ?? \"\") : \"\"\n return /already exists/i.test(message)\n}\n\nexport const ensureSearchIndex = async (params: EnsureSearchIndexParams): Promise<{ created: boolean }> => {\n const collection = params.collection.trim()\n if (!collection) throw new Error(\"Missing collection name\")\n\n const name = params.name.trim()\n if (!name) throw new Error(\"Missing search index name\")\n\n let listResult: unknown\n try {\n listResult = await params.db.command({ listSearchIndexes: collection })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n throw new Error(`listSearchIndexes failed for \"${collection}\": ${message}`)\n }\n\n if (listResultHasIndex(listResult, name)) {\n return { created: false }\n }\n\n try {\n await params.db.command({\n createSearchIndexes: collection,\n indexes: [{ name, definition: params.definition }],\n })\n } catch (error) {\n if (isIndexAlreadyExistsError(error)) {\n return { created: false }\n }\n const message = error instanceof Error ? error.message : String(error)\n throw new Error(`createSearchIndexes failed for \"${collection}\" (index \"${name}\"): ${message}`)\n }\n\n return { created: true }\n}\n","const getAppName = (env: NodeJS.ProcessEnv = process.env): string => {\n const appName = env.APP_NAME?.trim()\n if (!appName) {\n throw new Error(\"Missing APP_NAME\")\n }\n return appName\n}\n\nexport const GLOBAL_DB_SUFFIX = \"-global-db\"\n\nexport const getGlobalDbName = (env: NodeJS.ProcessEnv = process.env): string => {\n return `${getAppName(env)}${GLOBAL_DB_SUFFIX}`\n}\n\nexport const getTenantDbName = (tenantId: string, env: NodeJS.ProcessEnv = process.env): string => {\n return `${getAppName(env)}-${tenantId.trim()}-db`\n}\n","import type mongoose from \"mongoose\"\n\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === \"object\" && !Array.isArray(value)\n\nexport const mergeMongoQuery = (\n left: unknown,\n right: Record<string, unknown>,\n): Record<string, unknown> => {\n if (left != null && !isRecord(left)) {\n throw new TypeError(\"ACL-protected MongoDB filters must be objects.\")\n }\n const leftQuery = left ?? {}\n if (Object.keys(leftQuery).length === 0) return right\n if (Object.keys(right).length === 0) return leftQuery\n return { $and: [leftQuery, right] }\n}\n\nexport const cloneMongoValue = <TValue>(value: TValue): TValue => {\n if (value instanceof Date) {\n return new Date(value.getTime()) as TValue\n }\n\n if (Buffer.isBuffer(value)) {\n return Buffer.from(value) as TValue\n }\n\n if (Array.isArray(value)) {\n return value.map((entry) => cloneMongoValue(entry)) as TValue\n }\n\n if (!isRecord(value)) {\n return value\n }\n\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) return value\n\n const copy = Object.create(prototype) as Record<string, unknown>\n for (const [key, entry] of Object.entries(value)) {\n copy[key] = cloneMongoValue(entry)\n }\n return copy as TValue\n}\n\nexport const castMongoQuery = (\n model: mongoose.Model<unknown>,\n query: Record<string, unknown>,\n): Record<string, unknown> => {\n const casted = model.find(cloneMongoValue(query)).cast(model)\n if (!isRecord(casted)) {\n throw new TypeError(`Mongoose returned an invalid casted query for model \"${model.modelName}\".`)\n }\n return casted\n}\n","import mongoose from \"mongoose\"\nimport { accessibleBy } from \"@casl/mongoose\"\n\nimport { hasRegisteredPolicy } from \"./registry\"\nimport { castMongoQuery, isRecord, mergeMongoQuery } from \"./mongooseAclUtils\"\nimport type { AclAction, AclSubjectType, AppAbility } from \"./types\"\n\n\ntype PipelineStageLike = Record<string, unknown>\n\nconst allowedAggregateStages = new Set([\n \"$addFields\",\n \"$bucket\",\n \"$bucketAuto\",\n \"$count\",\n \"$densify\",\n \"$facet\",\n \"$fill\",\n \"$geoNear\",\n \"$graphLookup\",\n \"$group\",\n \"$limit\",\n \"$lookup\",\n \"$match\",\n \"$project\",\n \"$redact\",\n \"$replaceRoot\",\n \"$replaceWith\",\n \"$sample\",\n \"$search\",\n \"$set\",\n \"$setWindowFields\",\n \"$skip\",\n \"$sort\",\n \"$sortByCount\",\n \"$unionWith\",\n \"$unset\",\n \"$unwind\",\n \"$vectorSearch\",\n])\n\nexport const injectAggregateMatch = (\n pipeline: PipelineStageLike[],\n match: Record<string, unknown>,\n): void => {\n if (Object.keys(match).length === 0) return\n if (pipeline.length === 0) {\n pipeline.unshift({ $match: match })\n return\n }\n\n const first = pipeline[0]\n if (!isRecord(first)) {\n pipeline.unshift({ $match: match })\n return\n }\n\n if (\"$geoNear\" in first) {\n const geoNear = first.$geoNear\n if (isRecord(geoNear)) {\n geoNear.query = mergeMongoQuery(geoNear.query, match)\n return\n }\n }\n\n if (\"$search\" in first || \"$vectorSearch\" in first) {\n pipeline.splice(1, 0, { $match: match })\n return\n }\n\n pipeline.unshift({ $match: match })\n}\n\nconst containsSearchMetadataReference = (value: unknown): boolean => {\n if (typeof value === \"string\") {\n return value === \"$$SEARCH_META\" || value.startsWith(\"$$SEARCH_META.\")\n }\n if (Array.isArray(value)) return value.some(containsSearchMetadataReference)\n if (!isRecord(value)) return false\n return Object.values(value).some(containsSearchMetadataReference)\n}\n\nconst getModelCollectionName = (model: mongoose.Model<unknown>): string | null => {\n const collection = model.collection as unknown as { collectionName?: unknown; name?: unknown }\n if (typeof collection.collectionName === \"string\") return collection.collectionName\n if (typeof collection.name === \"string\") return collection.name\n return null\n}\n\nexport const resolveAggregateModel = (\n sourceModel: mongoose.Model<unknown>,\n collectionName: string,\n): mongoose.Model<unknown> => {\n const candidates = new Map<string, mongoose.Model<unknown>>()\n const connectionModels = sourceModel.db?.models ?? {}\n\n for (const model of [...Object.values(connectionModels), ...Object.values(mongoose.models)]) {\n const typedModel = model as mongoose.Model<unknown>\n if (getModelCollectionName(typedModel) !== collectionName) continue\n candidates.set(typedModel.modelName, typedModel)\n }\n\n if (candidates.size === 0) {\n throw new Error(\n `ACL driver cannot access collection \"${collectionName}\" because no registered Mongoose model maps to it.`,\n )\n }\n\n if (candidates.size > 1) {\n throw new Error(\n `ACL driver cannot resolve collection \"${collectionName}\" unambiguously.`,\n )\n }\n\n return [...candidates.values()][0]\n}\n\nconst assertAllowedAggregateStage = (stage: PipelineStageLike): void => {\n const stageNames = Object.keys(stage)\n if (stageNames.length !== 1) {\n throw new Error(\"ACL-protected aggregates require exactly one operator per pipeline stage.\")\n }\n\n const stageName = stageNames[0]\n if (stageName === \"$merge\" || stageName === \"$out\") {\n throw new Error(\n `ACL-protected aggregates cannot use ${stageName}. Use models.getUnsafe(...) after explicit authorization.`,\n )\n }\n\n if (!allowedAggregateStages.has(stageName)) {\n throw new Error(\n `ACL-protected aggregates cannot use unreviewed stage ${stageName}. Use models.getUnsafe(...) explicitly.`,\n )\n }\n}\n\nconst secureTargetPipeline = (\n pipeline: PipelineStageLike[],\n targetModel: mongoose.Model<unknown>,\n ability?: AppAbility,\n): void => {\n secureAggregateStages(pipeline, targetModel, ability)\n if (!hasRegisteredPolicy(targetModel.modelName)) return\n if (!ability) {\n throw new Error(\n `ACL-protected aggregate target \"${targetModel.modelName}\" requires .acl(ability).`,\n )\n }\n\n const accessQuery = castMongoQuery(\n targetModel,\n accessibleBy(ability, \"read\").ofType(targetModel.modelName as AclSubjectType),\n )\n injectAggregateMatch(pipeline, accessQuery)\n}\n\nconst secureAggregateStages = (\n pipeline: PipelineStageLike[],\n sourceModel: mongoose.Model<unknown>,\n ability?: AppAbility,\n): void => {\n for (const stage of pipeline) {\n if (!isRecord(stage)) {\n throw new Error(\"ACL-protected aggregates require object pipeline stages.\")\n }\n if (containsSearchMetadataReference(stage)) {\n throw new Error(\n \"ACL-protected aggregates cannot expose $$SEARCH_META because it includes unauthorized search matches.\",\n )\n }\n assertAllowedAggregateStage(stage)\n\n if (isRecord(stage.$lookup)) {\n const lookup = stage.$lookup\n const nestedPipeline = Array.isArray(lookup.pipeline)\n ? lookup.pipeline as PipelineStageLike[]\n : []\n\n if (typeof lookup.from === \"string\") {\n const targetModel = resolveAggregateModel(sourceModel, lookup.from)\n lookup.pipeline = nestedPipeline\n secureTargetPipeline(nestedPipeline, targetModel, ability)\n } else if (lookup.from === undefined && Array.isArray(lookup.pipeline)) {\n secureAggregateStages(nestedPipeline, sourceModel, ability)\n } else {\n throw new Error(\"ACL-protected $lookup requires a registered collection name in `from`.\")\n }\n }\n\n if (typeof stage.$unionWith === \"string\") {\n const targetModel = resolveAggregateModel(sourceModel, stage.$unionWith)\n const nestedPipeline: PipelineStageLike[] = []\n stage.$unionWith = { coll: stage.$unionWith, pipeline: nestedPipeline }\n secureTargetPipeline(nestedPipeline, targetModel, ability)\n } else if (isRecord(stage.$unionWith)) {\n const unionWith = stage.$unionWith\n const nestedPipeline = Array.isArray(unionWith.pipeline)\n ? unionWith.pipeline as PipelineStageLike[]\n : []\n\n if (typeof unionWith.coll === \"string\") {\n const targetModel = resolveAggregateModel(sourceModel, unionWith.coll)\n unionWith.pipeline = nestedPipeline\n secureTargetPipeline(nestedPipeline, targetModel, ability)\n } else if (unionWith.coll === undefined && Array.isArray(unionWith.pipeline)) {\n secureAggregateStages(nestedPipeline, sourceModel, ability)\n } else {\n throw new Error(\"ACL-protected $unionWith requires a registered collection name in `coll`.\")\n }\n }\n\n if (isRecord(stage.$graphLookup)) {\n const graphLookup = stage.$graphLookup\n const collectionName = graphLookup.from\n if (typeof collectionName !== \"string\") {\n throw new Error(\"ACL-protected $graphLookup requires a registered collection name in `from`.\")\n }\n const targetModel = resolveAggregateModel(sourceModel, collectionName)\n if (hasRegisteredPolicy(targetModel.modelName)) {\n if (!ability) {\n throw new Error(\n `ACL-protected aggregate target \"${targetModel.modelName}\" requires .acl(ability).`,\n )\n }\n const targetAccessQuery = castMongoQuery(\n targetModel,\n accessibleBy(ability, \"read\").ofType(targetModel.modelName as AclSubjectType),\n )\n graphLookup.restrictSearchWithMatch = mergeMongoQuery(\n graphLookup.restrictSearchWithMatch,\n targetAccessQuery,\n )\n }\n }\n\n if (isRecord(stage.$facet)) {\n for (const nestedPipeline of Object.values(stage.$facet)) {\n if (!Array.isArray(nestedPipeline)) {\n throw new Error(\"ACL-protected $facet entries must be pipelines.\")\n }\n secureAggregateStages(nestedPipeline as PipelineStageLike[], sourceModel, ability)\n }\n }\n }\n}\n\nexport const secureAggregatePipeline = (\n pipeline: PipelineStageLike[],\n model: mongoose.Model<unknown>,\n ability: AppAbility | undefined,\n action: AclAction,\n): void => {\n secureAggregateStages(pipeline, model, ability)\n if (!hasRegisteredPolicy(model.modelName)) return\n if (!ability) {\n throw new Error(\n `ACL-protected model \"${model.modelName}\" requires .acl(ability).`,\n )\n }\n const accessQuery = castMongoQuery(\n model,\n accessibleBy(ability, action).ofType(model.modelName as AclSubjectType),\n )\n injectAggregateMatch(pipeline, accessQuery)\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\"\n\nimport type { AppAbility } from \"./types\"\n\n\nexport type MongooseAclDriverContext =\n | { mode: \"ability\"; ability: AppAbility }\n | { mode: \"unbound\" }\n | { mode: \"unsafe\" }\n\nconst contextStorage = new AsyncLocalStorage<MongooseAclDriverContext>()\nconst collectionContexts = new WeakMap<object, MongooseAclDriverContext>()\nconst rawConnections = new WeakMap<object, object>()\n\nexport const unsafeMongooseAclDriverContext: MongooseAclDriverContext = Object.freeze({\n mode: \"unsafe\",\n})\n\nexport const unboundMongooseAclDriverContext: MongooseAclDriverContext = Object.freeze({\n mode: \"unbound\",\n})\n\nexport const bindMongooseAclDriverContext = (\n value: object,\n context: MongooseAclDriverContext,\n): void => {\n collectionContexts.set(value, context)\n}\n\nexport const getMongooseAclDriverContext = (\n value?: object,\n): MongooseAclDriverContext | undefined => {\n return (value ? collectionContexts.get(value) : undefined) ?? contextStorage.getStore()\n}\n\nexport const bindMongooseAclRawConnection = (\n scopedConnection: object,\n rawConnection: object,\n): void => {\n rawConnections.set(scopedConnection, rawConnection)\n}\n\nexport const getMongooseAclRawConnection = <TConnection extends object>(\n connection: TConnection,\n): TConnection => (rawConnections.get(connection) ?? connection) as TConnection\n\nexport const runWithMongooseAclDriverContext = <TResult>(\n context: MongooseAclDriverContext,\n callback: () => TResult,\n): TResult => contextStorage.run(context, callback)\n","import mongoose from \"mongoose\"\nimport { ForbiddenError, subject } from \"@casl/ability\"\nimport { accessibleBy } from \"@casl/mongoose\"\n\nimport { secureAggregatePipeline } from \"./mongooseAclAggregate\"\nimport {\n getMongooseAclDriverContext,\n runWithMongooseAclDriverContext,\n unsafeMongooseAclDriverContext,\n type MongooseAclDriverContext,\n} from \"./mongooseAclDriverContext\"\nimport { castMongoQuery, cloneMongoValue, isRecord, mergeMongoQuery } from \"./mongooseAclUtils\"\nimport { hasRegisteredPolicy } from \"./registry\"\nimport type { AclAction, AclSubject, AclSubjectType, AppAbility } from \"./types\"\n\n\ntype NativeMongooseCollection = mongoose.Collection & {\n collection: unknown\n conn: mongoose.Connection\n modelName?: string\n}\n\ntype NativeMongooseCollectionConstructor = new (\n name: string,\n connection: mongoose.Connection,\n options?: Record<string, unknown>,\n) => NativeMongooseCollection\n\ntype MongooseDriver = {\n Collection: NativeMongooseCollectionConstructor\n Connection: new (base: mongoose.Mongoose) => mongoose.Connection\n [key: string]: unknown\n}\n\ntype NativeMethod = (...args: unknown[]) => unknown\n\ntype NativeDriverAccessor = typeof mongoose & {\n driver: {\n get: () => MongooseDriver\n }\n}\n\nconst nativeDriver = (mongoose as NativeDriverAccessor).driver.get()\nconst NativeCollection = nativeDriver.Collection\nconst rawCollections = new WeakMap<object, object | null>()\nconst rawCollectionProxies = new WeakMap<object, { raw: object; proxy: object }>()\nconst blockedNativeCollectionProperties = new Set<PropertyKey>([\n \"client\",\n \"db\",\n \"s\",\n])\nconst blockedCursorProperties = new Set<PropertyKey>([\n \"aggregateOptions\",\n \"client\",\n \"cursorClient\",\n \"cursorFilter\",\n \"cursorOptions\",\n \"cursorSession\",\n \"selectedServer\",\n \"server\",\n \"session\",\n])\nconst aggregateCursorMutationMethods = new Set<PropertyKey>([\n \"addStage\",\n \"geoNear\",\n \"group\",\n \"limit\",\n \"lookup\",\n \"match\",\n \"out\",\n \"project\",\n \"redact\",\n \"skip\",\n \"sort\",\n \"unwind\",\n])\n\nconst dataMethods = new Set([\n \"aggregate\",\n \"bulkWrite\",\n \"count\",\n \"countDocuments\",\n \"deleteMany\",\n \"deleteOne\",\n \"distinct\",\n \"estimatedDocumentCount\",\n \"find\",\n \"findOne\",\n \"findOneAndDelete\",\n \"findOneAndReplace\",\n \"findOneAndUpdate\",\n \"insertMany\",\n \"insertOne\",\n \"replaceOne\",\n \"updateMany\",\n \"updateOne\",\n])\n\nconst readFilterArgumentByMethod: Partial<Record<string, number>> = {\n count: 0,\n countDocuments: 0,\n distinct: 1,\n find: 0,\n findOne: 0,\n}\n\nconst writeFilterActionByMethod: Partial<Record<string, AclAction>> = {\n deleteMany: \"delete\",\n deleteOne: \"delete\",\n findOneAndDelete: \"delete\",\n findOneAndReplace: \"update\",\n findOneAndUpdate: \"update\",\n replaceOne: \"update\",\n updateMany: \"update\",\n updateOne: \"update\",\n}\n\nconst getCollectionName = (collection: NativeMongooseCollection): string => {\n const value = collection.collectionName ?? collection.name\n return typeof value === \"string\" ? value : \"\"\n}\n\nconst getModelCollectionName = (model: mongoose.Model<unknown>): string | null => {\n const collection = model.collection as unknown as { collectionName?: unknown; name?: unknown }\n if (typeof collection.collectionName === \"string\") return collection.collectionName\n if (typeof collection.name === \"string\") return collection.name\n return null\n}\n\nconst getCollectionModels = (\n collection: NativeMongooseCollection,\n): Map<string, mongoose.Model<unknown>> => {\n const collectionName = getCollectionName(collection)\n const candidates = new Map<string, mongoose.Model<unknown>>()\n for (const model of [\n ...Object.values(mongoose.models),\n ...Object.values(collection.conn.models ?? {}),\n ]) {\n const typedModel = model as mongoose.Model<unknown>\n if (getModelCollectionName(typedModel) === collectionName) {\n candidates.set(typedModel.modelName, typedModel)\n }\n }\n\n return candidates\n}\n\nconst getCollectionModelName = (collection: NativeMongooseCollection): string | null => {\n if (typeof collection.modelName === \"string\" && collection.modelName) {\n return collection.modelName\n }\n\n const candidates = getCollectionModels(collection)\n return candidates.size === 1 ? [...candidates.keys()][0] : null\n}\n\nconst getProtectedCollectionModelNames = (\n collection: NativeMongooseCollection,\n): string[] => [...getCollectionModels(collection).keys()].filter(hasRegisteredPolicy)\n\nconst hasSecuredCollectionBoundary = (\n collection: NativeMongooseCollection,\n): boolean => {\n const context = getMongooseAclDriverContext(collection)\n if (context) return context.mode !== \"unsafe\"\n\n if (typeof collection.modelName === \"string\" && collection.modelName) {\n if (hasRegisteredPolicy(collection.modelName)) return true\n }\n return [...getCollectionModels(collection).keys()].some(hasRegisteredPolicy)\n}\n\nconst getCollectionModel = (\n collection: NativeMongooseCollection,\n modelName: string,\n): mongoose.Model<unknown> => {\n const model = collection.conn.models?.[modelName] ?? mongoose.models[modelName]\n if (!model) {\n throw new Error(`ACL driver could not resolve Mongoose model \"${modelName}\".`)\n }\n return model as mongoose.Model<unknown>\n}\n\nconst getAccessQuery = (\n ability: AppAbility,\n action: AclAction,\n model: mongoose.Model<unknown>,\n): Record<string, unknown> => castMongoQuery(\n model,\n accessibleBy(ability, action).ofType(model.modelName as AclSubjectType),\n)\n\nconst assertCanCreate = (\n ability: AppAbility,\n modelName: string,\n value: unknown,\n): void => {\n const rawValue = value instanceof mongoose.Document ? value.toObject() : value\n const document = isRecord(rawValue) ? rawValue : {}\n ForbiddenError.from(ability).throwUnlessCan(\n \"create\",\n subject(modelName, document) as unknown as AclSubject,\n )\n}\n\nconst materializeBsonValue = (\n value: unknown,\n seen: WeakMap<object, unknown>,\n): unknown => {\n if (!value || typeof value !== \"object\") return value\n if (seen.has(value)) return seen.get(value)\n\n const toBSON = (value as { toBSON?: unknown }).toBSON\n if (typeof toBSON === \"function\") {\n const placeholder = Object.create(null) as Record<string, unknown>\n seen.set(value, placeholder)\n const materialized = Reflect.apply(toBSON, value, []) as unknown\n if (materialized !== value) {\n const result = materializeBsonValue(materialized, seen)\n seen.set(value, result)\n return result\n }\n\n for (const [key, entry] of Object.entries(value)) {\n if (key === \"toBSON\" && typeof entry === \"function\") continue\n placeholder[key] = materializeBsonValue(entry, seen)\n }\n return placeholder\n }\n\n if (value instanceof Date || Buffer.isBuffer(value)) return cloneMongoValue(value)\n if (\n value instanceof RegExp\n || ArrayBuffer.isView(value)\n || (isRecord(value) && typeof value._bsontype === \"string\")\n ) {\n return value\n }\n\n if (Array.isArray(value)) {\n const copy: unknown[] = []\n seen.set(value, copy)\n for (const entry of value) copy.push(materializeBsonValue(entry, seen))\n return copy\n }\n\n if (value instanceof Map) {\n const copy = new Map<unknown, unknown>()\n seen.set(value, copy)\n for (const [key, entry] of value) {\n copy.set(key, materializeBsonValue(entry, seen))\n }\n return copy\n }\n\n const copy = Object.create(null) as Record<string, unknown>\n seen.set(value, copy)\n for (const [key, entry] of Object.entries(value)) {\n copy[key] = materializeBsonValue(entry, seen)\n }\n return copy\n}\n\nconst materializeInsertDocument = (value: unknown): unknown =>\n materializeBsonValue(value, new WeakMap<object, unknown>())\n\nconst safeExplainVerbosities = new Set([\n \"queryPlanner\",\n \"queryPlannerExtended\",\n])\n\nconst isSafeExplainVerbosity = (value: unknown): boolean => {\n if (value === false) return true\n if (typeof value === \"string\") return safeExplainVerbosities.has(value)\n return isRecord(value) && isSafeExplainVerbosity(value.verbosity)\n}\n\nconst assertSafeExplainVerbosity = (value: unknown): void => {\n if (!isSafeExplainVerbosity(value)) {\n throw new Error(\n \"ACL-protected cursors cannot expose execution statistics. Use queryPlanner verbosity or models.getUnsafe(...) explicitly.\",\n )\n }\n}\n\nconst assertSafeExplainOptions = (options: unknown): void => {\n if (\n isRecord(options)\n && Object.hasOwn(options, \"explain\")\n && options.explain != null\n ) {\n assertSafeExplainVerbosity(options.explain)\n }\n}\n\nconst assertNoUpsert = (methodName: string, options: unknown): void => {\n if (isRecord(options) && options.upsert === true) {\n throw new Error(\n `ACL-protected ${methodName}() cannot use upsert. Use models.getUnsafe(...) after explicit create and update authorization.`,\n )\n }\n}\n\nconst secureBulkWriteOperations = (\n ability: AppAbility,\n model: mongoose.Model<unknown>,\n value: unknown,\n): Array<Record<string, unknown>> => {\n if (!Array.isArray(value)) {\n throw new TypeError(\"ACL-protected bulkWrite() expects an array of operations.\")\n }\n\n return value.map((operation) => {\n if (!isRecord(operation)) {\n throw new TypeError(\"ACL-protected bulkWrite() received an invalid operation.\")\n }\n\n const operationActions: Array<{ key: string; action: AclAction }> = [\n { key: \"updateOne\", action: \"update\" },\n { key: \"updateMany\", action: \"update\" },\n { key: \"replaceOne\", action: \"update\" },\n { key: \"deleteOne\", action: \"delete\" },\n { key: \"deleteMany\", action: \"delete\" },\n ]\n const supportedKeys = [\n \"insertOne\",\n ...operationActions.map(({ key }) => key),\n ].filter((key) => Object.hasOwn(operation, key))\n if (supportedKeys.length !== 1 || Object.keys(operation).length !== 1) {\n throw new Error(\n \"ACL-protected bulkWrite() requires exactly one supported operator per operation.\",\n )\n }\n\n if (supportedKeys[0] === \"insertOne\" && isRecord(operation.insertOne)) {\n const document = materializeInsertDocument(operation.insertOne.document)\n assertCanCreate(ability, model.modelName, document)\n return {\n ...cloneMongoValue(operation),\n insertOne: {\n ...cloneMongoValue(operation.insertOne),\n document,\n },\n }\n }\n\n for (const { key, action } of operationActions) {\n const details = operation[key]\n if (!isRecord(details)) continue\n assertNoUpsert(`bulkWrite ${key}`, details)\n return {\n ...cloneMongoValue(operation),\n [key]: {\n ...cloneMongoValue(details),\n filter: mergeMongoQuery(details.filter, getAccessQuery(ability, action, model)),\n },\n }\n }\n\n throw new Error(\"ACL-protected bulkWrite() received an unsupported operation.\")\n })\n}\n\nconst secureCollectionArguments = (\n collection: NativeMongooseCollection,\n ability: AppAbility,\n modelName: string,\n methodName: string,\n input: unknown[],\n): unknown[] => {\n const args = input.map((value) => cloneMongoValue(value))\n const model = getCollectionModel(collection, modelName)\n if (methodName === \"find\" || methodName === \"findOne\" || methodName === \"aggregate\") {\n assertSafeExplainOptions(args[1])\n }\n const readFilterIndex = readFilterArgumentByMethod[methodName]\n if (readFilterIndex !== undefined) {\n args[readFilterIndex] = mergeMongoQuery(\n args[readFilterIndex],\n getAccessQuery(ability, \"read\", model),\n )\n return args\n }\n\n const writeAction = writeFilterActionByMethod[methodName]\n if (writeAction) {\n if (writeAction === \"update\") {\n assertNoUpsert(methodName, args[2])\n }\n args[0] = mergeMongoQuery(args[0], getAccessQuery(ability, writeAction, model))\n return args\n }\n\n if (methodName === \"insertOne\") {\n args[0] = materializeInsertDocument(input[0])\n assertCanCreate(ability, modelName, args[0])\n return args\n }\n\n if (methodName === \"insertMany\") {\n if (!Array.isArray(input[0])) {\n throw new TypeError(\"ACL-protected insertMany() expects an array of documents.\")\n }\n const documents = input[0].map((document) => materializeInsertDocument(document))\n for (const document of documents) assertCanCreate(ability, modelName, document)\n args[0] = documents\n return args\n }\n\n if (methodName === \"bulkWrite\") {\n args[0] = secureBulkWriteOperations(ability, model, input[0])\n return args\n }\n\n if (methodName === \"aggregate\") {\n if (!Array.isArray(args[0])) {\n throw new TypeError(\"ACL-protected aggregate() expects a pipeline array.\")\n }\n const pipeline = args[0] as Array<Record<string, unknown>>\n secureAggregatePipeline(\n pipeline,\n model,\n ability,\n \"read\",\n )\n args[0] = pipeline\n return args\n }\n\n if (methodName === \"estimatedDocumentCount\") {\n throw new Error(\n \"ACL-protected estimatedDocumentCount() cannot be filtered. Use countDocuments() or models.getUnsafe(...).\",\n )\n }\n\n throw new Error(\n `ACL-protected collection method ${methodName}() is not supported. Use models.getUnsafe(...) explicitly.`,\n )\n}\n\nconst wrapFindCursor = (cursor: object): object => {\n const proxy: object = new Proxy(cursor, {\n get(target, prop) {\n if (blockedCursorProperties.has(prop)) {\n throw new Error(\n `ACL-protected cursor property .${String(prop)} is blocked.`,\n )\n }\n const value = Reflect.get(target, prop, target) as unknown\n if (prop === \"filter\") {\n return () => {\n throw new Error(\"ACL-protected cursors cannot replace their filter.\")\n }\n }\n if (prop === \"addQueryModifier\" && typeof value === \"function\") {\n return (...args: unknown[]) => {\n if (args[0] === \"$query\") {\n throw new Error(\"ACL-protected cursors cannot replace their filter.\")\n }\n if (args[0] === \"$explain\") assertSafeExplainVerbosity(args[1])\n const result = Reflect.apply(value, target, args) as unknown\n return result === target ? proxy : result\n }\n }\n if (prop === \"explain\" && typeof value === \"function\") {\n return (...args: unknown[]) => {\n assertSafeExplainVerbosity(args[0])\n return Reflect.apply(value, target, args) as unknown\n }\n }\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => {\n const result = Reflect.apply(value, target, args) as unknown\n if (prop === \"stream\" && result && typeof result === \"object\") {\n return wrapCursorStream(result)\n }\n if (prop === \"clone\" && result && typeof result === \"object\") {\n return wrapFindCursor(result)\n }\n return result === target ? proxy : result\n }\n },\n set() {\n throw new Error(\"ACL-protected cursors cannot be mutated directly.\")\n },\n })\n return proxy\n}\n\nconst wrapCursorStream = (stream: object): object => {\n const proxy: object = new Proxy(stream, {\n get(target, prop) {\n if (prop === \"_cursor\") {\n throw new Error(\"ACL-protected cursor streams do not expose their native cursor.\")\n }\n const value = Reflect.get(target, prop, target) as unknown\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => {\n const result = Reflect.apply(value, target, args) as unknown\n return result === target ? proxy : result\n }\n },\n set(target, prop, value) {\n if (prop === \"_cursor\") {\n throw new Error(\"ACL-protected cursor streams cannot replace their native cursor.\")\n }\n return Reflect.set(target, prop, value, target)\n },\n })\n return proxy\n}\n\nconst wrapAggregateCursor = (cursor: object): object => {\n const proxy: object = new Proxy(cursor, {\n get(target, prop) {\n if (blockedCursorProperties.has(prop)) {\n throw new Error(\n `ACL-protected aggregation cursor property .${String(prop)} is blocked.`,\n )\n }\n if (prop === \"pipeline\") {\n return cloneMongoValue(Reflect.get(target, prop, target))\n }\n const value = Reflect.get(target, prop, target) as unknown\n if (aggregateCursorMutationMethods.has(prop)) {\n return () => {\n throw new Error(\n \"ACL-protected aggregation cursors cannot mutate their pipeline after validation.\",\n )\n }\n }\n if (prop === \"explain\" && typeof value === \"function\") {\n return (...args: unknown[]) => {\n assertSafeExplainVerbosity(args[0])\n return Reflect.apply(value, target, args) as unknown\n }\n }\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => {\n const result = Reflect.apply(value, target, args) as unknown\n if (prop === \"stream\" && result && typeof result === \"object\") {\n return wrapCursorStream(result)\n }\n if (prop === \"clone\" && result && typeof result === \"object\") {\n return wrapAggregateCursor(result)\n }\n return result === target ? proxy : result\n }\n },\n set() {\n throw new Error(\"ACL-protected aggregation cursors cannot be mutated directly.\")\n },\n })\n return proxy\n}\n\nconst wrapCursorResult = (\n methodName: string,\n result: unknown,\n): unknown => {\n if (result && typeof result === \"object\" && \"then\" in result && typeof result.then === \"function\") {\n return Promise.resolve(result).then((resolved) => wrapCursorResult(methodName, resolved))\n }\n if (!result || typeof result !== \"object\") return result\n if (methodName === \"find\") return wrapFindCursor(result)\n if (methodName === \"aggregate\") return wrapAggregateCursor(result)\n return result\n}\n\nconst invokeSafeUnprotectedCollectionMethod = (\n collection: NativeMongooseCollection,\n rawCollection: object,\n modelName: string,\n context: Exclude<MongooseAclDriverContext, { mode: \"unsafe\" }>,\n methodName: string,\n method: NativeMethod,\n input: unknown[],\n): unknown => {\n if (!dataMethods.has(methodName)) {\n throw new Error(\n `Safe collection method ${methodName}() is not supported. Use models.getUnsafe(...) explicitly.`,\n )\n }\n\n const args = input.map((value) => cloneMongoValue(value))\n if (methodName === \"aggregate\") {\n if (!Array.isArray(args[0])) {\n throw new TypeError(\"Safe aggregate() expects a pipeline array.\")\n }\n secureAggregatePipeline(\n args[0] as Array<Record<string, unknown>>,\n getCollectionModel(collection, modelName),\n context.mode === \"ability\" ? context.ability : undefined,\n \"read\",\n )\n }\n\n const result = Reflect.apply(method, rawCollection, args)\n return wrapCursorResult(methodName, result)\n}\n\nconst invokeNativeCollectionMethod = (\n collection: NativeMongooseCollection,\n rawCollection: object,\n methodName: string,\n method: NativeMethod,\n input: unknown[],\n): unknown => {\n const context = getMongooseAclDriverContext(collection)\n const modelName = getCollectionModelName(collection)\n\n if (context?.mode === \"unsafe\") {\n return Reflect.apply(method, rawCollection, input)\n }\n\n if (modelName && !hasRegisteredPolicy(modelName)) {\n const protectedModelNames = getProtectedCollectionModelNames(collection)\n if (protectedModelNames.length > 0) {\n throw new Error(\n `Model \"${modelName}\" maps to ACL-protected collection \"${getCollectionName(collection)}\" without its own policy.`,\n )\n }\n if (!context) return Reflect.apply(method, rawCollection, input)\n return invokeSafeUnprotectedCollectionMethod(\n collection,\n rawCollection,\n modelName,\n context,\n methodName,\n method,\n input,\n )\n }\n\n if (!modelName) {\n const collectionModels = getCollectionModels(collection)\n const protectedModelNames = [...collectionModels.keys()].filter(hasRegisteredPolicy)\n if (collectionModels.size > 0 && protectedModelNames.length === 0) {\n if (!context) return Reflect.apply(method, rawCollection, input)\n return invokeSafeUnprotectedCollectionMethod(\n collection,\n rawCollection,\n [...collectionModels.keys()][0],\n context,\n methodName,\n method,\n input,\n )\n }\n if (protectedModelNames.length > 0) {\n throw new Error(\n `ACL driver cannot choose a policy for collection \"${getCollectionName(collection)}\" (${protectedModelNames.join(\", \")}). Use models.get(...).acl(ability).`,\n )\n }\n throw new Error(\n `ACL driver cannot authorize unregistered collection \"${getCollectionName(collection)}\". Use models.getUnsafe(...) explicitly.`,\n )\n }\n\n if (context?.mode !== \"ability\") {\n if (context?.mode === \"unbound\") {\n throw new Error(\n `Model \"${modelName}\" is ACL-protected. Call .acl(ability) before executing the operation.`,\n )\n }\n throw new Error(\n `Model \"${modelName}\" is ACL-protected. Use models.get(...).acl(ability) or models.getUnsafe(...) explicitly.`,\n )\n }\n\n if (!dataMethods.has(methodName)) {\n throw new Error(\n `ACL-protected collection method ${methodName}() is not filterable. Use models.getUnsafe(...) explicitly.`,\n )\n }\n\n const args = secureCollectionArguments(\n collection,\n context.ability,\n modelName,\n methodName,\n input,\n )\n const result = Reflect.apply(method, rawCollection, args)\n return wrapCursorResult(methodName, result)\n}\n\nconst getRawCollectionProxy = (\n collection: NativeMongooseCollection,\n rawCollection: object,\n): object => {\n const cached = rawCollectionProxies.get(collection)\n if (cached?.raw === rawCollection) return cached.proxy\n\n const proxy = new Proxy(rawCollection, {\n get(target, prop) {\n if (blockedNativeCollectionProperties.has(prop) && hasSecuredCollectionBoundary(collection)) {\n throw new Error(\n `ACL-protected native collection property .${String(prop)} is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n }\n const value = Reflect.get(target, prop, target) as unknown\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => invokeNativeCollectionMethod(\n collection,\n target,\n String(prop),\n value as NativeMethod,\n args,\n )\n },\n set(target, prop, value) {\n if (hasSecuredCollectionBoundary(collection)) {\n throw new Error(\n `ACL-protected native collection property .${String(prop)} cannot be changed. Use models.getUnsafe(...) explicitly.`,\n )\n }\n return Reflect.set(target, prop, value, target)\n },\n })\n rawCollectionProxies.set(collection, { raw: rawCollection, proxy })\n return proxy\n}\n\nconst installRawCollectionAccessor = (collection: NativeMongooseCollection): void => {\n const initialRawCollection = collection.collection\n Object.defineProperty(collection, \"collection\", {\n configurable: true,\n enumerable: true,\n get() {\n const rawCollection = rawCollections.get(collection)\n return rawCollection ? getRawCollectionProxy(collection, rawCollection) : rawCollection\n },\n set(value: unknown) {\n rawCollections.set(collection, value && typeof value === \"object\" ? value : null)\n rawCollectionProxies.delete(collection)\n },\n })\n collection.collection = initialRawCollection\n}\n\nexport class AclMongooseCollection extends NativeCollection {\n constructor(\n name: string,\n connection: mongoose.Connection,\n options: Record<string, unknown> = {},\n ) {\n super(name, connection, options)\n installRawCollectionAccessor(this)\n }\n}\n\nconst ACL_DRIVER_GLOBAL_KEY = Symbol.for(\"@rpcbase/db/acl/mongooseDriverInstalled\")\n\nexport const installMongooseAclDriver = (): void => {\n const globalState = globalThis as unknown as Record<symbol, unknown>\n const installedInstances = globalState[ACL_DRIVER_GLOBAL_KEY] instanceof WeakSet\n ? globalState[ACL_DRIVER_GLOBAL_KEY] as WeakSet<object>\n : new WeakSet<object>()\n if (installedInstances.has(mongoose)) return\n\n mongoose.setDriver({\n ...nativeDriver,\n Collection: AclMongooseCollection,\n })\n installedInstances.add(mongoose)\n globalState[ACL_DRIVER_GLOBAL_KEY] = installedInstances\n}\n\nexport const runWithUnsafeMongooseAclDriver = <TResult>(\n callback: () => TResult,\n): TResult => runWithMongooseAclDriverContext(unsafeMongooseAclDriverContext, callback)\n\nexport const _private = {\n getCollectionModels,\n getCollectionModelName,\n secureBulkWriteOperations,\n secureCollectionArguments,\n}\n","import mongoose from \"mongoose\"\n\nimport { installMongooseAclDriver } from \"./acl/mongooseAclDriver\"\nimport { getMongoDirectConnection, getMongoUrl } from \"./getMongoUrl\"\n\n\ninstallMongooseAclDriver()\n\nconst connections = new Map<string, mongoose.Connection>()\nlet rootConnection: mongoose.Connection | null = null\nconst CONNECTION_MAX_LISTENERS = 50\n\nconst waitForOpen = async (connection: mongoose.Connection): Promise<void> => {\n if (connection.readyState === 1) return\n if (connection.getMaxListeners() < CONNECTION_MAX_LISTENERS) {\n connection.setMaxListeners(CONNECTION_MAX_LISTENERS)\n }\n\n await new Promise<void>((resolve, reject) => {\n connection.once(\"open\", resolve)\n connection.once(\"error\", reject)\n })\n}\n\nexport const ensureMongooseConnection = async (dbName: string): Promise<mongoose.Connection> => {\n const normalizedDbName = dbName.trim()\n if (!normalizedDbName) {\n throw new Error(\"Missing dbName\")\n }\n\n const existing = connections.get(normalizedDbName)\n if (existing) {\n await waitForOpen(existing)\n return existing\n }\n\n if (!rootConnection) {\n const mongoUrl = getMongoUrl()\n const manageResourcesWithMigrations = process.env.NODE_ENV === \"production\"\n rootConnection = mongoose.createConnection(mongoUrl, {\n sanitizeFilter: true,\n dbName: normalizedDbName,\n directConnection: getMongoDirectConnection(),\n autoCreate: !manageResourcesWithMigrations,\n autoIndex: !manageResourcesWithMigrations,\n })\n }\n\n await waitForOpen(rootConnection)\n\n const connection = rootConnection.name === normalizedDbName\n ? rootConnection\n : rootConnection.useDb(normalizedDbName, { useCache: true })\n\n await waitForOpen(connection)\n\n connections.set(normalizedDbName, connection)\n return connection\n}\n","import type mongoose from \"mongoose\"\n\nimport { getMongooseAclRawConnection } from \"./acl/mongooseAclDriverContext\"\nimport { GLOBAL_DB_SUFFIX } from \"./dbNames\"\nimport { RBRtsChangeSchema, type IRBRtsChange } from \"./models/RBRtsChange\"\nimport { RBRtsCounterSchema, type IRBRtsCounter } from \"./models/RBRtsCounter\"\n\n\ntype RtsChangeOp = IRBRtsChange[\"op\"]\n\nconst RTS_COUNTER_ID = \"rts\"\nconst EXCLUDED_MODEL_NAMES = new Set([\"RBRtsChange\", \"RBRtsCounter\"])\n\nconst maxDeleteIdsRaw = process.env.RB_RTS_DELETE_LOG_MAX_IDS ?? \"\"\nconst maxDeleteIds = Number.isFinite(Number(maxDeleteIdsRaw)) ? Math.max(1, Math.floor(Number(maxDeleteIdsRaw))) : 5000\n\ntype DeleteMeta = {\n modelName: string\n ids: string[]\n reset: boolean\n session?: mongoose.ClientSession\n}\n\nconst deleteMetaByQuery = new WeakMap<object, DeleteMeta>()\n\nconst hasToString = (value: unknown): value is { toString: () => string } => {\n if (typeof value !== \"object\" || value === null) return false\n const maybe = value as { toString?: unknown }\n return typeof maybe.toString === \"function\"\n}\n\nconst normalizeId = (id: unknown): string | null => {\n if (!id) return null\n if (typeof id === \"string\") return id\n if (hasToString(id)) return id.toString()\n return null\n}\n\nconst getDbName = (db: unknown): string => {\n if (!db || typeof db !== \"object\") return \"\"\n const maybe = db as { name?: unknown; db?: { databaseName?: unknown } }\n const raw = maybe.name ?? maybe.db?.databaseName\n return typeof raw === \"string\" ? raw : \"\"\n}\n\nconst isGlobalDb = (db: unknown): boolean => getDbName(db).endsWith(GLOBAL_DB_SUFFIX)\n\ntype RtsCounterDoc = IRBRtsCounter\ntype RtsChangeDoc = IRBRtsChange\n\nconst getQuerySession = (query: MongooseQuery): mongoose.ClientSession | undefined => {\n const opts = typeof query.getOptions === \"function\" ? query.getOptions() : undefined\n if (!opts || typeof opts !== \"object\") return undefined\n const session = (opts as { session?: unknown }).session\n if (!session || typeof session !== \"object\") return undefined\n return session as mongoose.ClientSession\n}\n\nconst getRtsModels = (db: mongoose.Connection) => {\n const rawDb = getMongooseAclRawConnection(db)\n const RtsCounter = (rawDb.models.RBRtsCounter as mongoose.Model<RtsCounterDoc>)\n ?? rawDb.model<RtsCounterDoc>(\"RBRtsCounter\", RBRtsCounterSchema)\n const RtsChange = (rawDb.models.RBRtsChange as mongoose.Model<RtsChangeDoc>)\n ?? rawDb.model<RtsChangeDoc>(\"RBRtsChange\", RBRtsChangeSchema)\n return { RtsCounter, RtsChange }\n}\n\nconst allocateSeqRange = async (\n db: mongoose.Connection,\n count: number,\n session?: mongoose.ClientSession,\n): Promise<{ start: number; end: number }> => {\n const { RtsCounter } = getRtsModels(db)\n const updated = await RtsCounter.findOneAndUpdate(\n { _id: RTS_COUNTER_ID },\n { $inc: { seq: count } },\n { upsert: true, returnDocument: \"after\", setDefaultsOnInsert: true, projection: { seq: 1 }, session },\n ).lean()\n\n const end = Number(updated?.seq ?? 0)\n const start = end - count + 1\n return { start, end }\n}\n\nconst insertChanges = async (\n db: mongoose.Connection,\n changes: Array<{ seq: number; modelName: string; op: RtsChangeOp; docId?: string | null }>,\n session?: mongoose.ClientSession,\n): Promise<void> => {\n if (!changes.length) return\n const { RtsChange } = getRtsModels(db)\n const ts = new Date()\n const docs = changes.map((c) => ({\n seq: c.seq,\n modelName: c.modelName,\n op: c.op,\n docId: c.docId ?? undefined,\n ts,\n }))\n\n if (session) {\n await RtsChange.insertMany(docs, { session })\n return\n }\n\n await RtsChange.insertMany(docs)\n}\n\nconst recordDeleteChanges = async (\n db: mongoose.Connection,\n modelName: string,\n ids: string[],\n session?: mongoose.ClientSession,\n): Promise<void> => {\n const uniqueIds = Array.from(new Set(ids)).filter(Boolean)\n if (!uniqueIds.length) return\n const { start } = await allocateSeqRange(db, uniqueIds.length, session)\n await insertChanges(db, uniqueIds.map((docId, idx) => ({\n seq: start + idx,\n modelName,\n op: \"delete\",\n docId,\n })), session)\n}\n\nconst recordResetModel = async (db: mongoose.Connection, modelName: string, session?: mongoose.ClientSession): Promise<void> => {\n const { start } = await allocateSeqRange(db, 1, session)\n await insertChanges(db, [{ seq: start, modelName, op: \"reset_model\" }], session)\n}\n\ntype MongooseQuery = mongoose.Query<unknown, unknown> & {\n model?: {\n modelName?: string\n db?: unknown\n find: (filter: unknown, projection: unknown) => unknown\n }\n getFilter?: () => unknown\n getQuery?: () => unknown\n getOptions?: () => unknown\n}\n\nconst captureDeleteMeta = async (query: MongooseQuery, mode: \"one\" | \"many\") => {\n const modelName = String(query?.model?.modelName ?? \"\")\n if (!modelName || modelName.startsWith(\"RB\") || EXCLUDED_MODEL_NAMES.has(modelName)) return\n if (isGlobalDb(query?.model?.db)) return\n\n const filter = typeof query.getFilter === \"function\" ? query.getFilter() : query.getQuery?.() ?? {}\n const session = getQuerySession(query)\n const findQuery = query.model.find(filter, { _id: 1 }) as unknown as {\n session?: (s: mongoose.ClientSession) => unknown\n limit: (n: number) => unknown\n lean: () => unknown\n }\n if (session && typeof findQuery.session === \"function\") {\n findQuery.session(session)\n }\n\n findQuery.lean()\n\n if (mode === \"one\") {\n findQuery.limit(1)\n } else {\n findQuery.limit(maxDeleteIds + 1)\n }\n\n const docs = await findQuery\n const ids = Array.isArray(docs)\n ? docs\n .map((d) => normalizeId((d as { _id?: unknown })?._id))\n .filter((id): id is string => Boolean(id))\n : []\n const reset = mode === \"many\" && ids.length > maxDeleteIds\n const trimmedIds = reset ? [] : ids\n\n const meta: DeleteMeta = {\n modelName,\n ids: trimmedIds,\n reset,\n session,\n }\n\n deleteMetaByQuery.set(query, meta)\n}\n\nconst flushDeleteMeta = async (query: MongooseQuery) => {\n const meta = deleteMetaByQuery.get(query)\n deleteMetaByQuery.delete(query)\n if (!meta) return\n\n const db = query?.model?.db as mongoose.Connection | undefined\n if (!db) return\n\n try {\n if (meta.reset) {\n await recordResetModel(db, meta.modelName, meta.session)\n } else {\n await recordDeleteChanges(db, meta.modelName, meta.ids, meta.session)\n }\n } catch {\n return\n }\n}\n\nexport const rtsChangeLogPlugin = (schema: mongoose.Schema): void => {\n schema.pre(\"deleteOne\", { query: true, document: false }, async function(this: MongooseQuery) {\n await captureDeleteMeta(this, \"one\")\n })\n\n schema.pre(\"deleteMany\", { query: true, document: false }, async function(this: MongooseQuery) {\n await captureDeleteMeta(this, \"many\")\n })\n\n schema.post(\"deleteOne\", { query: true, document: false }, async function(this: MongooseQuery) {\n await flushDeleteMeta(this)\n })\n\n schema.post(\"deleteMany\", { query: true, document: false }, async function(this: MongooseQuery) {\n await flushDeleteMeta(this)\n })\n\n schema.post(\"findOneAndDelete\", { query: true, document: false }, async function(this: MongooseQuery, doc: unknown) {\n const modelName = String(this?.model?.modelName ?? \"\")\n if (!modelName || modelName.startsWith(\"RB\") || EXCLUDED_MODEL_NAMES.has(modelName)) return\n\n const db = this?.model?.db as mongoose.Connection | undefined\n if (!db) return\n if (isGlobalDb(db)) return\n\n const docId = normalizeId((doc as { _id?: unknown } | null | undefined)?._id)\n if (!docId) return\n\n try {\n const session = getQuerySession(this)\n await recordDeleteChanges(db, modelName, [docId], session)\n } catch {\n return\n }\n })\n}\n\nexport const _private = {\n getRtsModels,\n}\n","import mongoose from \"mongoose\"\nimport { accessibleRecordsPlugin } from \"@casl/mongoose\"\n\nimport * as frameworkSchemas from \"./models\"\nimport { rtsChangeLogPlugin } from \"./rtsChangeLogPlugin\"\nimport { registerPoliciesFromModules } from \"./acl\"\nimport {\n installMongooseAclDriver,\n runWithUnsafeMongooseAclDriver,\n} from \"./acl/mongooseAclDriver\"\nimport { mongoPaginationPlugin } from \"./pagination/mongoPaginationPlugin\"\n\n\ntype ModelModules = Record<string, unknown>\ntype ModelsScope = \"tenant\" | \"global\"\ntype RegisterModelsOptions = {\n allowReservedRbModelNames?: boolean;\n}\n\ntype RegisteredSchemas = Record<string, mongoose.Schema>\n\ntype RegisteredModels = {\n tenant: RegisteredSchemas\n global: RegisteredSchemas\n}\n\nlet cachedModels: RegisteredModels | null = null\n\nconst DEFAULT_GLOBAL_RB_MODEL_NAMES_SET = new Set<string>([\n \"RBUser\",\n \"RBTenant\",\n \"RBOAuthRequest\",\n])\n\nconst assertSchema = (exportName: string, value: unknown): mongoose.Schema => {\n if (value instanceof mongoose.Schema) return value\n\n throw new Error(\n [\n `Expected ${exportName} to be an instance of mongoose.Schema, but it was not.`,\n \"rpcbase supports mongoose 9+ only.\",\n \"Fix: ensure the project is using mongoose 9.x and that all packages resolve the same mongoose instance (try `npm ls mongoose`).\",\n ].join(\" \"),\n )\n}\n\nconst getFrameworkSchemaForModelName = (modelName: string): mongoose.Schema | null => {\n const exportName = `${modelName}Schema`\n const value = (frameworkSchemas as unknown as Record<string, unknown>)[exportName]\n if (!(value instanceof mongoose.Schema)) return null\n return value\n}\n\nconst applyTenantPlugins = (schema: mongoose.Schema): void => {\n schema.plugin(accessibleRecordsPlugin)\n schema.plugin(mongoPaginationPlugin)\n schema.plugin(rtsChangeLogPlugin)\n}\n\nconst registerSchema = (\n target: RegisteredSchemas,\n other: RegisteredSchemas,\n modelName: string,\n schema: mongoose.Schema,\n scope: ModelsScope,\n): void => {\n if (target[modelName] || other[modelName]) {\n throw new Error(`Duplicate model name \"${modelName}\" across tenant/global scopes`)\n }\n target[modelName] = schema\n}\n\nconst buildSchemasFromModules = (modules: ModelModules): Array<{ modelName: string; schema: mongoose.Schema }> =>\n Object.entries(modules)\n .filter(([key]) => key.endsWith(\"Schema\"))\n .map(([key, schemaValue]) => {\n const schema = assertSchema(key, schemaValue)\n const modelName = key.replace(/Schema$/, \"\")\n return { modelName, schema }\n })\n\nexport const getFrameworkModelSchemas = (): RegisteredModels => {\n const tenant: RegisteredSchemas = {}\n const global: RegisteredSchemas = {}\n\n for (const { modelName, schema } of buildSchemasFromModules(frameworkSchemas as unknown as ModelModules)) {\n const cloned = schema.clone()\n if (DEFAULT_GLOBAL_RB_MODEL_NAMES_SET.has(modelName)) {\n registerSchema(global, tenant, modelName, cloned, \"global\")\n } else {\n applyTenantPlugins(cloned)\n registerSchema(tenant, global, modelName, cloned, \"tenant\")\n }\n }\n\n return { tenant, global }\n}\n\nexport const registerModels = (\n { tenant, global }: { tenant: ModelModules; global?: ModelModules },\n options: RegisterModelsOptions = {},\n) => {\n installMongooseAclDriver()\n registerPoliciesFromModules(frameworkSchemas as unknown as Record<string, unknown>)\n registerPoliciesFromModules(tenant)\n\n const tenantSchemas: RegisteredSchemas = {}\n const globalSchemas: RegisteredSchemas = {}\n const allowReservedRbModelNames = options.allowReservedRbModelNames === true\n\n for (const { modelName, schema } of buildSchemasFromModules(frameworkSchemas as unknown as ModelModules)) {\n if (DEFAULT_GLOBAL_RB_MODEL_NAMES_SET.has(modelName)) {\n const cloned = schema.clone()\n registerSchema(globalSchemas, tenantSchemas, modelName, cloned, \"global\")\n } else {\n const cloned = schema.clone()\n applyTenantPlugins(cloned)\n registerSchema(tenantSchemas, globalSchemas, modelName, cloned, \"tenant\")\n }\n }\n\n for (const { modelName, schema } of buildSchemasFromModules(tenant)) {\n if (modelName === \"RBUser\" || modelName === \"RBTenant\") {\n throw new Error(`Invalid tenant model name \"${modelName}\". RBUser/RBTenant are global models.`)\n }\n if (modelName.startsWith(\"RB\")) {\n const frameworkSchema = getFrameworkSchemaForModelName(modelName)\n if (frameworkSchema && schema === frameworkSchema) continue\n if (!allowReservedRbModelNames) {\n throw new Error(`Invalid tenant model name \"${modelName}\". RB* models are reserved for rpcbase.`)\n }\n }\n const cloned = schema.clone()\n applyTenantPlugins(cloned)\n registerSchema(tenantSchemas, globalSchemas, modelName, cloned, \"tenant\")\n }\n\n for (const { modelName, schema } of buildSchemasFromModules(global ?? {})) {\n if (modelName.startsWith(\"RB\")) {\n const frameworkSchema = getFrameworkSchemaForModelName(modelName)\n if (frameworkSchema && schema === frameworkSchema) continue\n if (!allowReservedRbModelNames) {\n throw new Error(`Invalid global model name \"${modelName}\". RB* models are reserved for rpcbase.`)\n }\n }\n const cloned = schema.clone()\n registerSchema(globalSchemas, tenantSchemas, modelName, cloned, \"global\")\n }\n\n const allSchemas = { ...globalSchemas, ...tenantSchemas }\n\n for (const [modelName, schema] of Object.entries(allSchemas)) {\n if (!mongoose.models[modelName]) {\n runWithUnsafeMongooseAclDriver(() => mongoose.model(modelName, schema))\n }\n }\n\n cachedModels = {\n tenant: { ...(cachedModels?.tenant ?? {}), ...tenantSchemas },\n global: { ...(cachedModels?.global ?? {}), ...globalSchemas },\n }\n}\n\nexport const getRegisteredModels = (scope: ModelsScope) => {\n if (!cachedModels) {\n throw new Error(\"Models not registered. Call createModels(...) once at startup (or import your models module) before using models.get.\")\n }\n return cachedModels[scope]\n}\n\nexport type { ModelModules, ModelsScope, RegisteredSchemas, RegisterModelsOptions }\n","import mongoose from \"mongoose\"\n\nimport {\n AclMongooseCollection,\n installMongooseAclDriver,\n} from \"./mongooseAclDriver\"\nimport {\n bindMongooseAclRawConnection,\n bindMongooseAclDriverContext,\n unboundMongooseAclDriverContext,\n unsafeMongooseAclDriverContext,\n type MongooseAclDriverContext,\n} from \"./mongooseAclDriverContext\"\nimport { hasRegisteredPolicy } from \"./registry\"\nimport type { AppAbility } from \"./types\"\n\n\ndeclare const mongooseAclModelBrand: unique symbol\n\ndeclare module \"mongoose\" {\n interface Model<\n TRawDocType,\n TQueryHelpers,\n TInstanceMethods,\n TVirtuals,\n THydratedDocumentType,\n TSchema,\n TLeanResultType,\n > {\n [mongooseAclModelBrand]?: [\n TRawDocType,\n TQueryHelpers,\n TInstanceMethods,\n TVirtuals,\n THydratedDocumentType,\n TSchema,\n TLeanResultType,\n ]\n acl: (ability: AppAbility) => this\n }\n}\n\ntype SubclassableModel<TModel extends mongoose.Model<unknown>> = TModel & {\n __subclass: (\n connection: mongoose.Connection,\n schema: mongoose.Schema,\n collectionName: string,\n ) => TModel\n}\n\nconst scopedModelsByAbility = new WeakMap<object, WeakMap<object, mongoose.Model<unknown>>>()\nconst unboundModels = new WeakMap<object, mongoose.Model<unknown>>()\nconst unsafeModels = new WeakMap<object, mongoose.Model<unknown>>()\nconst collectionTargets = new WeakMap<object, AclMongooseCollection>()\nconst blockedModelMethods = new Set<PropertyKey>([\n \"$__updateConnection\",\n \"__subclass\",\n \"clientEncryption\",\n \"cleanIndexes\",\n \"compile\",\n \"createCollection\",\n \"createIndexes\",\n \"createSearchIndex\",\n \"createSearchIndexes\",\n \"diffIndexes\",\n \"dropSearchIndex\",\n \"ensureIndexes\",\n \"init\",\n \"listIndexes\",\n \"listSearchIndexes\",\n \"recompileSchema\",\n \"startSession\",\n \"syncIndexes\",\n \"updateSearchIndex\",\n \"useConnection\",\n \"watch\",\n])\nconst blockedCollectionProperties = new Set<PropertyKey>([\n \"_getCollection\",\n \"addQueue\",\n \"doQueue\",\n \"emitter\",\n \"onClose\",\n \"onOpen\",\n \"queue\",\n \"removeQueue\",\n])\nconst blockedConnectionMethods = new Set<PropertyKey>([\n \"aggregate\",\n \"bulkWrite\",\n \"close\",\n \"createClient\",\n \"createCollection\",\n \"createCollections\",\n \"deleteModel\",\n \"destroy\",\n \"doClose\",\n \"dropCollection\",\n \"dropDatabase\",\n \"listCollections\",\n \"listDatabases\",\n \"onClose\",\n \"onOpen\",\n \"openUri\",\n \"plugin\",\n \"set\",\n \"setClient\",\n \"startSession\",\n \"syncIndexes\",\n \"transaction\",\n \"useDb\",\n \"watch\",\n \"withSession\",\n])\nconst blockedConnectionProperties = new Set<PropertyKey>([\n \"$initialConnection\",\n \"_parent\",\n \"client\",\n \"otherDbs\",\n \"relatedDbs\",\n])\nconst blockedMongooseMethods = new Set<PropertyKey>([\n \"connect\",\n \"createConnection\",\n \"deleteModel\",\n \"disconnect\",\n \"model\",\n \"plugin\",\n \"set\",\n \"setDriver\",\n \"startSession\",\n \"syncIndexes\",\n])\nconst blockedMongooseProperties = new Set<PropertyKey>([\n \"connection\",\n \"connections\",\n \"models\",\n])\nconst allowedDbProperties = new Set<PropertyKey>([\n \"databaseName\",\n \"namespace\",\n \"readConcern\",\n \"readPreference\",\n \"writeConcern\",\n])\n\nconst getModelCollectionName = (model: mongoose.Model<unknown>): string => {\n const collection = model.collection as unknown as { collectionName?: unknown; name?: unknown }\n const value = collection.collectionName ?? collection.name\n return typeof value === \"string\" ? value : \"\"\n}\n\nconst resolveModelNameForCollection = (\n connection: mongoose.Connection,\n collectionName: string,\n): string | undefined => {\n const candidates = new Set<string>()\n for (const model of [\n ...Object.values(connection.models ?? {}),\n ...Object.values(mongoose.models),\n ]) {\n const typedModel = model as mongoose.Model<unknown>\n if (getModelCollectionName(typedModel) === collectionName) {\n candidates.add(typedModel.modelName)\n }\n }\n return candidates.size === 1 ? [...candidates][0] : undefined\n}\n\nconst detachMongooseSubclassRetention = (\n rawModel: mongoose.Model<unknown>,\n scopedModel: mongoose.Model<unknown>,\n): void => {\n const symbol = Object.getOwnPropertySymbols(rawModel)\n .find((entry) => entry.description === \"mongoose#Model#subclassed\")\n if (!symbol) return\n\n const subclasses = (rawModel as unknown as Record<symbol, unknown>)[symbol]\n if (!Array.isArray(subclasses)) return\n const index = subclasses.lastIndexOf(scopedModel)\n if (index >= 0) subclasses.splice(index, 1)\n}\n\nconst getCachedModel = <TModel extends mongoose.Model<unknown>>(\n model: TModel,\n context: MongooseAclDriverContext,\n): TModel | undefined => {\n if (context.mode === \"unsafe\") {\n return unsafeModels.get(model) as TModel | undefined\n }\n if (context.mode === \"unbound\") {\n return unboundModels.get(model) as TModel | undefined\n }\n return scopedModelsByAbility.get(context.ability)?.get(model) as TModel | undefined\n}\n\nconst cacheModel = <TModel extends mongoose.Model<unknown>>(\n rawModel: TModel,\n scopedModel: TModel,\n context: MongooseAclDriverContext,\n): void => {\n if (context.mode === \"unsafe\") {\n unsafeModels.set(rawModel, scopedModel)\n return\n }\n if (context.mode === \"unbound\") {\n unboundModels.set(rawModel, scopedModel)\n return\n }\n\n const models = scopedModelsByAbility.get(context.ability) ?? new WeakMap<object, mongoose.Model<unknown>>()\n models.set(rawModel, scopedModel)\n scopedModelsByAbility.set(context.ability, models)\n}\n\nconst lockModelCapability = (\n target: object,\n property: PropertyKey,\n value: unknown,\n): void => {\n const descriptor = Object.getOwnPropertyDescriptor(target, property)\n Object.defineProperty(target, property, {\n configurable: false,\n enumerable: descriptor?.enumerable ?? true,\n get: () => value,\n set: () => {\n throw new Error(\n `ACL-protected model property .${String(property)} cannot be changed. Use models.getUnsafe(...) explicitly.`,\n )\n },\n })\n}\n\nconst createAclModelWithContext = <TModel extends mongoose.Model<unknown>>(\n model: TModel,\n context: MongooseAclDriverContext,\n): TModel => {\n const cached = getCachedModel(model, context)\n if (cached) return cached\n\n const rawConnection = model.db\n const primaryCollectionName = getModelCollectionName(model)\n const collections = new Map<string, AclMongooseCollection>()\n\n let mongooseProxy: mongoose.Mongoose | undefined\n let collectionsProxy: Record<string, mongoose.Collection> | undefined\n let modelsProxy: Record<string, mongoose.Model<unknown>> | undefined\n let dbProxy: object | undefined\n\n const getMongooseProxy = (): mongoose.Mongoose => {\n const rawMongoose = rawConnection.base\n if (context.mode === \"unsafe\") return rawMongoose\n if (mongooseProxy) return mongooseProxy\n\n mongooseProxy = new Proxy(rawMongoose, {\n get(target, prop) {\n if (prop === \"default\" || prop === \"mongoose\") return mongooseProxy\n if (blockedMongooseProperties.has(prop)) {\n throw new Error(\n `ACL-protected Mongoose property .${String(prop)} is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n }\n if (blockedMongooseMethods.has(prop)) {\n return () => {\n throw new Error(\n `ACL-protected Mongoose method ${String(prop)}() is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n }\n }\n\n const value = Reflect.get(target, prop, target) as unknown\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => {\n const result = Reflect.apply(value, target, args) as unknown\n return result === target ? mongooseProxy : result\n }\n },\n set(_target, prop) {\n throw new Error(\n `ACL-protected Mongoose property .${String(prop)} cannot be changed. Use models.getUnsafe(...) explicitly.`,\n )\n },\n })\n return mongooseProxy\n }\n\n const createCollectionProxy = (\n collection: AclMongooseCollection,\n ): AclMongooseCollection => {\n if (context.mode === \"unsafe\") return collection\n\n const proxy: AclMongooseCollection = new Proxy(collection, {\n get(target, prop) {\n if (prop === \"conn\") return connectionProxy\n if (blockedCollectionProperties.has(prop)) {\n throw new Error(\n `ACL-protected collection property .${String(prop)} is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n }\n\n const value = Reflect.get(target, prop, target) as unknown\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => {\n const result = Reflect.apply(value, target, args) as unknown\n return result === target ? proxy : result\n }\n },\n set(_target, prop) {\n throw new Error(\n `ACL-protected collection property .${String(prop)} cannot be changed. Use models.getUnsafe(...) explicitly.`,\n )\n },\n })\n collectionTargets.set(proxy, collection)\n return proxy\n }\n\n const getCollection = (\n collectionName: string,\n options: Record<string, unknown> = {},\n ): AclMongooseCollection => {\n const existing = collections.get(collectionName)\n if (existing) return existing\n\n const modelName = collectionName === primaryCollectionName\n ? model.modelName\n : resolveModelNameForCollection(rawConnection, collectionName)\n if (\n context.mode !== \"unsafe\"\n && collectionName !== primaryCollectionName\n && (!modelName || !hasRegisteredPolicy(modelName))\n ) {\n throw new Error(\n `ACL-protected connections cannot access collection \"${collectionName}\" without a protected model. Load that model explicitly or use models.getUnsafe(...).`,\n )\n }\n const collection = new AclMongooseCollection(collectionName, rawConnection, {\n ...options,\n modelName,\n })\n bindMongooseAclDriverContext(collection, context)\n const exposedCollection = createCollectionProxy(collection)\n collections.set(collectionName, exposedCollection)\n return exposedCollection\n }\n\n const getRelatedModel = (modelName: string): mongoose.Model<unknown> => {\n const relatedModel = rawConnection.model(modelName) as mongoose.Model<unknown>\n return createAclModelWithContext(relatedModel, context)\n }\n\n const getModelsProxy = (): Record<string, mongoose.Model<unknown>> => {\n if (modelsProxy) return modelsProxy\n modelsProxy = new Proxy(rawConnection.models as Record<string, mongoose.Model<unknown>>, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver) as unknown\n return typeof prop === \"string\" && Object.hasOwn(target, prop) && value && typeof value === \"function\"\n ? getRelatedModel(prop)\n : value\n },\n set(target, prop, value, receiver) {\n if (context.mode === \"unsafe\") return Reflect.set(target, prop, value, receiver)\n throw new Error(`ACL-protected connection model .${String(prop)} cannot be changed.`)\n },\n deleteProperty(target, prop) {\n if (context.mode === \"unsafe\") return Reflect.deleteProperty(target, prop)\n throw new Error(`ACL-protected connection model .${String(prop)} cannot be deleted.`)\n },\n })\n return modelsProxy\n }\n\n const getCollectionsProxy = (): Record<string, mongoose.Collection> => {\n if (collectionsProxy) return collectionsProxy\n collectionsProxy = new Proxy(rawConnection.collections, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver) as unknown\n return typeof prop === \"string\" && Object.hasOwn(target, prop) && value\n ? getCollection(prop)\n : value\n },\n set(target, prop, value, receiver) {\n if (context.mode === \"unsafe\") return Reflect.set(target, prop, value, receiver)\n throw new Error(`ACL-protected connection collection .${String(prop)} cannot be changed.`)\n },\n deleteProperty(target, prop) {\n if (context.mode === \"unsafe\") return Reflect.deleteProperty(target, prop)\n throw new Error(`ACL-protected connection collection .${String(prop)} cannot be deleted.`)\n },\n })\n return collectionsProxy\n }\n\n const getDbProxy = (): object | null | undefined => {\n const rawDb = rawConnection.db\n if (!rawDb || context.mode === \"unsafe\") return rawDb\n if (dbProxy) return dbProxy\n\n dbProxy = new Proxy(rawDb, {\n get(target, prop) {\n if (prop === \"collection\") {\n return (collectionName: string) => getCollection(collectionName).collection\n }\n if (allowedDbProperties.has(prop)) {\n return Reflect.get(target, prop, target)\n }\n throw new Error(\n `ACL-protected database access .${String(prop)} is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n },\n set(_target, prop) {\n throw new Error(\n `ACL-protected database property .${String(prop)} cannot be changed. Use models.getUnsafe(...) explicitly.`,\n )\n },\n })\n return dbProxy\n }\n\n const connectionProxy: mongoose.Connection = new Proxy(rawConnection, {\n get(target, prop) {\n if (prop === \"collection\") return getCollection\n if (prop === \"collections\") return getCollectionsProxy()\n if (prop === \"models\") return getModelsProxy()\n if (prop === \"db\") return getDbProxy()\n if (prop === \"base\") return getMongooseProxy()\n if (context.mode !== \"unsafe\" && blockedConnectionProperties.has(prop)) {\n throw new Error(\n `ACL-protected connection property .${String(prop)} is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n }\n if (prop === \"getClient\") {\n if (context.mode === \"unsafe\") return target.getClient.bind(target)\n return () => {\n throw new Error(\"ACL-protected MongoClient access is blocked. Use models.getUnsafe(...) explicitly.\")\n }\n }\n if (prop === \"model\") {\n return (modelName: string, ...args: unknown[]) => {\n if (context.mode !== \"unsafe\" && args.length > 0) {\n throw new Error(\n \"ACL-protected connections cannot compile models. Use models.getUnsafe(...) explicitly.\",\n )\n }\n const relatedModel = Reflect.apply(target.model, target, [modelName, ...args]) as mongoose.Model<unknown>\n return createAclModelWithContext(relatedModel, context)\n }\n }\n if (context.mode !== \"unsafe\" && blockedConnectionMethods.has(prop)) {\n return () => {\n throw new Error(\n `ACL-protected connection method ${String(prop)}() is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n }\n }\n\n const value = Reflect.get(target, prop, target) as unknown\n if (typeof value !== \"function\") return value\n return (...args: unknown[]) => {\n const result = Reflect.apply(value, target, args) as unknown\n if (result === target) return connectionProxy\n if (result && typeof result === \"object\" && \"then\" in result) {\n const then = result.then\n if (typeof then === \"function\") {\n return Promise.resolve(result).then((resolved: unknown) => (\n resolved === (target as unknown) ? connectionProxy : resolved\n ))\n }\n }\n return result\n }\n },\n set(target, prop, value, receiver) {\n if (context.mode === \"unsafe\") return Reflect.set(target, prop, value, receiver)\n throw new Error(\n `ACL-protected connection property .${String(prop)} cannot be changed. Use models.getUnsafe(...) explicitly.`,\n )\n },\n })\n bindMongooseAclRawConnection(connectionProxy, rawConnection)\n\n const scopedModel = (model as SubclassableModel<TModel>).__subclass(\n connectionProxy,\n model.schema,\n primaryCollectionName,\n )\n detachMongooseSubclassRetention(model, scopedModel)\n cacheModel(model, scopedModel, context)\n\n Object.defineProperty(scopedModel, \"acl\", {\n configurable: false,\n value: (ability: AppAbility) => createAclModelWithContext(\n model,\n { mode: \"ability\", ability },\n ),\n })\n\n if (context.mode !== \"unsafe\") {\n const scopedCollection = scopedModel.collection\n lockModelCapability(scopedModel, \"base\", getMongooseProxy())\n lockModelCapability(scopedModel, \"db\", connectionProxy)\n lockModelCapability(scopedModel, \"collection\", scopedCollection)\n lockModelCapability(scopedModel, \"$__collection\", scopedCollection)\n lockModelCapability(scopedModel.prototype, \"db\", connectionProxy)\n lockModelCapability(scopedModel.prototype, \"collection\", scopedCollection)\n lockModelCapability(scopedModel.prototype, \"$collection\", scopedCollection)\n }\n\n const rawDiscriminators = model.discriminators\n if (rawDiscriminators) {\n const generatedDiscriminators = scopedModel.discriminators ?? {}\n const scopedDiscriminators: Record<string, mongoose.Model<unknown>> = {}\n for (const [name, discriminator] of Object.entries(rawDiscriminators)) {\n const generated = generatedDiscriminators[name]\n if (generated) detachMongooseSubclassRetention(discriminator, generated)\n scopedDiscriminators[name] = createAclModelWithContext(discriminator, context)\n }\n scopedModel.discriminators = scopedDiscriminators\n }\n\n if (context.mode !== \"unsafe\") {\n for (const methodName of blockedModelMethods) {\n Object.defineProperty(scopedModel, methodName, {\n configurable: false,\n value: () => {\n throw new Error(\n `ACL-protected model method ${String(methodName)}() is blocked. Use models.getUnsafe(...) explicitly.`,\n )\n },\n })\n }\n Object.defineProperty(scopedModel, \"discriminator\", {\n configurable: false,\n value: () => {\n throw new Error(\n \"ACL-protected models cannot compile discriminators. Define them before models.get(...).\",\n )\n },\n })\n }\n return scopedModel\n}\n\ninstallMongooseAclDriver()\n\nexport const createAclMongooseModel = <TModel extends mongoose.Model<unknown>>(\n model: TModel,\n ability: AppAbility,\n): AclMongooseModel<TModel> => createAclModelWithContext(\n model,\n { mode: \"ability\", ability },\n) as AclMongooseModel<TModel>\n\nexport type AclMongooseModel<TModel extends mongoose.Model<unknown>> = TModel & {\n acl: (ability: AppAbility) => AclMongooseModel<TModel>\n}\n\nexport const createAclMongooseModelGateway = <TModel extends mongoose.Model<unknown>>(\n model: TModel,\n): AclMongooseModel<TModel> => createAclModelWithContext(\n model,\n unboundMongooseAclDriverContext,\n) as AclMongooseModel<TModel>\n\nexport const createUnsafeMongooseModel = <TModel extends mongoose.Model<unknown>>(\n model: TModel,\n): TModel => createAclModelWithContext(model, unsafeMongooseAclDriverContext)\n\nconst installMongooseAclModelFactory = (): void => {\n const modelConstructor = mongoose.Model as typeof mongoose.Model & {\n acl?: (ability: AppAbility) => mongoose.Model<unknown>\n }\n if (Object.hasOwn(modelConstructor, \"acl\")) return\n\n Object.defineProperty(modelConstructor, \"acl\", {\n configurable: false,\n value: function(\n this: mongoose.Model<unknown>,\n ability: AppAbility,\n ) {\n return createAclMongooseModel(this, ability)\n },\n })\n}\n\ninstallMongooseAclModelFactory()\n\nexport const _private = {\n createAclModelWithContext,\n resolveModelNameForCollection,\n setNativeCollection: (collection: object, nativeCollection: object): void => {\n const target = collectionTargets.get(collection) ?? collection as AclMongooseCollection\n target.collection = nativeCollection\n },\n}\n","import assert from \"assert\"\n\nimport { getGlobalDbName, getTenantDbName } from \"./dbNames\"\nimport { ensureMongooseConnection } from \"./ensureMongooseConnection\"\nimport { getRegisteredModels, registerModels, type ModelsScope } from \"./registerModels\"\nimport type { AppAbility } from \"./acl\"\nimport {\n createAclMongooseModel,\n createAclMongooseModelGateway,\n createUnsafeMongooseModel,\n} from \"./acl/mongooseAclModel\"\nimport { runWithUnsafeMongooseAclDriver } from \"./acl/mongooseAclDriver\"\n\n\nexport type LoadModelCtx = {\n tenantId?: string;\n req?: {\n session?: {\n user?: {\n currentTenantId?: string;\n }\n } | null;\n };\n ability?: AppAbility;\n};\n\nconst loadModelFromDb = async (\n modelName: string,\n dbName: string,\n scope: ModelsScope,\n) => {\n const schemas = getRegisteredModels(scope)\n const schema = schemas[modelName]\n assert(schema, `Model ${modelName} not registered. Available models: ${Object.keys(schemas).join(\", \")}`)\n\n const modelConnection = await ensureMongooseConnection(dbName)\n\n if (!modelConnection.models[modelName]) {\n await runWithUnsafeMongooseAclDriver(async() => {\n if (process.env.NODE_ENV === \"production\") {\n schema.set(\"autoCreate\", false)\n schema.set(\"autoIndex\", false)\n }\n const model = modelConnection.model(modelName, schema)\n if (process.env.NODE_ENV !== \"production\") await model.init()\n })\n }\n\n return modelConnection.models[modelName]\n}\n\nconst normalizeTenantId = (value: unknown): string | null => {\n if (typeof value !== \"string\") return null\n const tenantId = value.trim()\n return tenantId || null\n}\n\nexport const getTenantIdFromLoadModelCtx = (ctx: LoadModelCtx): string => {\n const tenantId =\n normalizeTenantId(ctx.tenantId)\n ?? normalizeTenantId(ctx.req?.session?.user?.currentTenantId)\n assert(tenantId, \"Tenant ID is missing from ctx (expected ctx.tenantId or ctx.req.session.user.currentTenantId)\")\n return tenantId\n}\n\nexport const models = {\n register: registerModels,\n\n getUnsafe: async (modelName: string, ctx: LoadModelCtx) => {\n const tenantId = getTenantIdFromLoadModelCtx(ctx)\n const dbName = getTenantDbName(tenantId)\n const model = await loadModelFromDb(modelName, dbName, \"tenant\")\n return createUnsafeMongooseModel(model)\n },\n\n get: async (modelName: string, ctx: LoadModelCtx) => {\n const tenantId = getTenantIdFromLoadModelCtx(ctx)\n const dbName = getTenantDbName(tenantId)\n const model = await loadModelFromDb(modelName, dbName, \"tenant\")\n return ctx.ability\n ? createAclMongooseModel(model, ctx.ability)\n : createAclMongooseModelGateway(model)\n },\n\n getGlobal: async (modelName: string, ctx: LoadModelCtx) => {\n const dbName = getGlobalDbName()\n return loadModelFromDb(modelName, dbName, \"global\")\n },\n} as const\n","import type { LoadModelCtx } from \"./modelsApi\"\nimport type { ModelModules, RegisterModelsOptions } from \"./registerModels\"\nimport type * as frameworkSchemas from \"./models\"\nimport { models } from \"./modelsApi\"\nimport { registerModels } from \"./registerModels\"\n\n\ntype ExtractModelNamesFromSchemas<TModules> = {\n [K in keyof TModules]-?: K extends `${infer Name}Schema` ? Name : never\n}[keyof TModules] & string\n\ntype FrameworkModelName = ExtractModelNamesFromSchemas<typeof frameworkSchemas>\n\ntype RpcbaseGlobalModelName = Extract<FrameworkModelName, \"RBUser\" | \"RBTenant\" | \"RBOAuthRequest\">\n\nexport type TenantModelName<TTenantModules extends ModelModules> =\n ExtractModelNamesFromSchemas<TTenantModules>\n\nexport type GlobalModelName<TGlobalModules extends ModelModules> =\n | RpcbaseGlobalModelName\n | ExtractModelNamesFromSchemas<TGlobalModules>\n\ntype LoadedTenantModel = Awaited<ReturnType<(typeof models)[\"get\"]>>\ntype LoadedGlobalModel = Awaited<ReturnType<(typeof models)[\"getGlobal\"]>>\n\ntype ModelsGetFn<TTenantModules extends ModelModules> = {\n (\n modelName: TenantModelName<TTenantModules>,\n ctx: LoadModelCtx,\n ): ReturnType<(typeof models)[\"get\"]>\n <const TNames extends readonly TenantModelName<TTenantModules>[]>(\n modelNames: TNames,\n ctx: LoadModelCtx,\n ): Promise<{ [K in keyof TNames]: LoadedTenantModel }>\n}\n\ntype ModelsGetUnsafeFn<TTenantModules extends ModelModules> = {\n (modelName: TenantModelName<TTenantModules>, ctx: LoadModelCtx): ReturnType<(typeof models)[\"getUnsafe\"]>\n <const TNames extends readonly TenantModelName<TTenantModules>[]>(\n modelNames: TNames,\n ctx: LoadModelCtx,\n ): Promise<{ [K in keyof TNames]: LoadedTenantModel }>\n}\n\ntype ModelsGetGlobalFn<TGlobalModules extends ModelModules> = {\n (modelName: GlobalModelName<TGlobalModules>, ctx: LoadModelCtx): ReturnType<(typeof models)[\"getGlobal\"]>\n <const TNames extends readonly GlobalModelName<TGlobalModules>[]>(\n modelNames: TNames,\n ctx: LoadModelCtx,\n ): Promise<{ [K in keyof TNames]: LoadedGlobalModel }>\n}\n\nexport type ModelsConfig<TTenantModules extends ModelModules, TGlobalModules extends ModelModules> = {\n tenant: TTenantModules\n global?: TGlobalModules\n}\n\nexport type ModelsClient<TTenantModules extends ModelModules, TGlobalModules extends ModelModules> = {\n register: (modules: ModelsConfig<TTenantModules, TGlobalModules>, options?: RegisterModelsOptions) => void\n get: ModelsGetFn<TTenantModules>\n getUnsafe: ModelsGetUnsafeFn<TTenantModules>\n getGlobal: ModelsGetGlobalFn<TGlobalModules>\n}\n\nexport const createModels = <\n TTenantModules extends ModelModules,\n TGlobalModules extends ModelModules = Record<string, never>,\n>(\n modules: ModelsConfig<TTenantModules, TGlobalModules>,\n options?: RegisterModelsOptions,\n ): ModelsClient<TTenantModules, TGlobalModules> => {\n registerModels(modules, options)\n\n const get = (async (\n modelNameOrNames: TenantModelName<TTenantModules> | readonly TenantModelName<TTenantModules>[],\n ctx: LoadModelCtx,\n ) => {\n if (Array.isArray(modelNameOrNames)) {\n return Promise.all(modelNameOrNames.map((modelName) => models.get(modelName as string, ctx)))\n }\n return models.get(modelNameOrNames as string, ctx)\n }) as ModelsClient<TTenantModules, TGlobalModules>[\"get\"]\n\n const getUnsafe = (async (\n modelNameOrNames: TenantModelName<TTenantModules> | readonly TenantModelName<TTenantModules>[],\n ctx: LoadModelCtx,\n ) => {\n if (Array.isArray(modelNameOrNames)) {\n return Promise.all(modelNameOrNames.map((modelName) => models.getUnsafe(modelName as string, ctx)))\n }\n return models.getUnsafe(modelNameOrNames as string, ctx)\n }) as ModelsClient<TTenantModules, TGlobalModules>[\"getUnsafe\"]\n\n const getGlobal = (async (\n modelNameOrNames: GlobalModelName<TGlobalModules> | readonly GlobalModelName<TGlobalModules>[],\n ctx: LoadModelCtx,\n ) => {\n if (Array.isArray(modelNameOrNames)) {\n return Promise.all(modelNameOrNames.map((modelName) => models.getGlobal(modelName as string, ctx)))\n }\n return models.getGlobal(modelNameOrNames as string, ctx)\n }) as ModelsClient<TTenantModules, TGlobalModules>[\"getGlobal\"]\n\n return {\n register: (nextModules, nextOptions) => registerModels(nextModules, nextOptions),\n get,\n getUnsafe,\n getGlobal,\n }\n}\n","import assert from \"assert\"\n\nimport type mongoose from \"mongoose\"\n\nimport { ensureMongooseConnection } from \"./ensureMongooseConnection\"\nimport { getTenantIdFromLoadModelCtx, type LoadModelCtx } from \"./modelsApi\"\n\n\nconst getAppName = (): string => {\n const appName = process.env.APP_NAME?.trim()\n assert(appName, \"Missing APP_NAME\")\n return appName\n}\n\nconst normalizeTenantId = (tenantId: string): string => {\n const normalized = tenantId.trim()\n assert(normalized, \"Tenant ID is missing\")\n return normalized\n}\n\nexport const getTenantFilesystemDbName = (tenantId: string): string =>\n `${getAppName()}-${normalizeTenantId(tenantId)}-filesystem-db`\n\nexport const getTenantFilesystemDb = async (tenantId: string): Promise<mongoose.Connection> =>\n ensureMongooseConnection(getTenantFilesystemDbName(tenantId))\n\nexport const getTenantFilesystemDbFromCtx = async (ctx: LoadModelCtx): Promise<mongoose.Connection> => {\n const tenantId = getTenantIdFromLoadModelCtx(ctx)\n return getTenantFilesystemDb(tenantId)\n}\n","import type mongoose from \"mongoose\"\nimport type { ClientSession } from \"mongoose\"\n\nimport { getGlobalDbName, getTenantDbName } from \"./dbNames\"\nimport { ensureMongooseConnection } from \"./ensureMongooseConnection\"\nimport { getTenantIdFromLoadModelCtx, type LoadModelCtx } from \"./modelsApi\"\nimport { getTenantFilesystemDbName } from \"./tenantFilesystemDb\"\n\n\ntype MongooseTransactionOptions = Parameters<ClientSession[\"withTransaction\"]>[1]\n\nexport type TenantGlobalFilesystemTransactionCtx = {\n tenantId: string\n session: ClientSession\n ctx: {\n tenant: LoadModelCtx\n global: LoadModelCtx\n }\n db: {\n tenant: mongoose.Connection\n global: mongoose.Connection\n filesystem: mongoose.Connection\n }\n}\n\ntype WithTransactionScope =\n | string\n | { tenantId: string }\n | { ctx: LoadModelCtx }\n\nconst buildTenantLoadModelCtx = (tenantId: string): LoadModelCtx => ({\n req: {\n session: {\n user: {\n currentTenantId: tenantId,\n },\n },\n },\n})\n\nexport function withTransaction<T>(\n tenantId: string,\n fn: (ctx: TenantGlobalFilesystemTransactionCtx) => Promise<T>,\n options?: MongooseTransactionOptions,\n): Promise<T>\nexport function withTransaction<T>(\n scope: { tenantId: string } | { ctx: LoadModelCtx },\n fn: (ctx: TenantGlobalFilesystemTransactionCtx) => Promise<T>,\n options?: MongooseTransactionOptions,\n): Promise<T>\nexport async function withTransaction<T>(\n scope: WithTransactionScope,\n fn: (ctx: TenantGlobalFilesystemTransactionCtx) => Promise<T>,\n options?: MongooseTransactionOptions,\n): Promise<T> {\n const normalizedTenantId = (() => {\n if (typeof scope === \"string\") return scope.trim()\n if (\"tenantId\" in scope) return scope.tenantId.trim()\n return getTenantIdFromLoadModelCtx(scope.ctx)\n })()\n\n if (!normalizedTenantId) throw new Error(\"Tenant ID is missing\")\n\n const tenantDbName = getTenantDbName(normalizedTenantId)\n const globalDbName = getGlobalDbName()\n const filesystemDbName = getTenantFilesystemDbName(normalizedTenantId)\n\n const tenantDb = await ensureMongooseConnection(tenantDbName)\n const globalDb = await ensureMongooseConnection(globalDbName)\n const filesystemDb = await ensureMongooseConnection(filesystemDbName)\n\n const session = await tenantDb.startSession()\n\n const tenantCtx: LoadModelCtx = typeof scope === \"object\" && \"ctx\" in scope\n ? scope.ctx\n : buildTenantLoadModelCtx(normalizedTenantId)\n\n const globalCtx: LoadModelCtx = { req: { session: null } }\n\n try {\n return await session.withTransaction(async () => fn({\n tenantId: normalizedTenantId,\n session,\n ctx: {\n tenant: tenantCtx,\n global: globalCtx,\n },\n db: {\n tenant: tenantDb,\n global: globalDb,\n filesystem: filesystemDb,\n },\n }), options)\n } finally {\n await session.endSession()\n }\n}\n","import type { ClientSession } from \"mongoose\"\nimport type {\n BillingStorage,\n BillingStorageTransaction,\n PersistedSubscriptionEvent,\n StoredSubscriptionProjection,\n SubscriptionEvent,\n} from \"@rpcbase/billing\"\n\nimport { ZRBTenantSubscriptionEvent } from \"./models/RBTenantSubscriptionEvent\"\nimport type { LoadModelCtx } from \"./modelsApi\"\nimport { models } from \"./modelsApi\"\nimport { withTransaction } from \"./transactions\"\n\n\ntype MongoBillingTransaction = {\n session: ClientSession\n}\n\ntype SubscriptionEventDocument = Record<string, unknown> & {\n _id?: unknown\n}\n\nconst getTransactionSession = (transaction?: BillingStorageTransaction): ClientSession | undefined => {\n if (!transaction || typeof transaction !== \"object\" || !(\"session\" in transaction)) return undefined\n return (transaction as MongoBillingTransaction).session\n}\n\nconst toSubscriptionEvent = (document: SubscriptionEventDocument): PersistedSubscriptionEvent => {\n const parsed = ZRBTenantSubscriptionEvent.parse(document)\n if (!document._id) throw new Error(\"Persisted subscription event is missing its id\")\n return {\n ...parsed,\n id: String(document._id),\n }\n}\n\nconst getExistingEventQuery = (event: SubscriptionEvent, tenantId: string): Record<string, unknown> => ({\n tenantId,\n idempotencyKey: event.idempotencyKey,\n})\n\nconst isDuplicateKeyError = (error: unknown): boolean =>\n Boolean(error && typeof error === \"object\" && \"code\" in error && error.code === 11000)\n\nconst toProjectionDocument = (projection: StoredSubscriptionProjection): Record<string, unknown> => ({\n tenantId: projection.tenantId,\n subscriptionId: projection.subscriptionId,\n type: projection.type,\n parentSubscriptionId: projection.parentSubscriptionId ?? undefined,\n scope: projection.scope,\n scopeId: projection.scopeId ?? undefined,\n planKey: projection.planKey,\n priceId: projection.priceId ?? undefined,\n status: projection.status,\n intervalUnit: projection.intervalUnit,\n intervalCount: projection.intervalCount,\n modules: projection.modules,\n billingAnchor: projection.billingAnchor,\n currentPeriodStart: projection.currentPeriodStart,\n currentPeriodEnd: projection.currentPeriodEnd,\n cancelAtPeriodEnd: projection.cancelAtPeriodEnd,\n cancelAt: projection.cancelAt ?? undefined,\n canceledAt: projection.canceledAt ?? undefined,\n scheduledPlanKey: projection.scheduledPlan?.planKey,\n scheduledPlanEffectiveAt: projection.scheduledPlan?.effectiveAt,\n provider: projection.provider ?? undefined,\n latestEventId: projection.latestEventId,\n latestEventAt: projection.latestEventAt,\n projectedAt: projection.projectedAt,\n})\n\nexport const createTenantBillingStorage = (params: {\n ctx: LoadModelCtx\n tenantId: string\n}): BillingStorage => {\n const findExistingEvent = async (\n query: Record<string, unknown>,\n transaction?: BillingStorageTransaction,\n ): Promise<PersistedSubscriptionEvent | null> => {\n const EventModel = await models.get(\"RBTenantSubscriptionEvent\", params.ctx)\n const request = EventModel.findOne(query)\n const session = getTransactionSession(transaction)\n if (session) request.session(session)\n const document = await request.lean() as SubscriptionEventDocument | null\n return document ? toSubscriptionEvent(document) : null\n }\n\n return {\n runInTransaction: (operation) => withTransaction(\n { ctx: params.ctx },\n ({ session }) => operation({ session } satisfies MongoBillingTransaction),\n ),\n createEvent: async (event, transaction) => {\n if (event.tenantId !== params.tenantId) {\n throw new Error(\"Billing event tenantId does not match the storage tenant\")\n }\n const existingQuery = getExistingEventQuery(event, params.tenantId)\n const existing = await findExistingEvent(existingQuery, transaction)\n if (existing) return existing\n\n const EventModel = await models.get(\"RBTenantSubscriptionEvent\", params.ctx)\n const eventDocument = ZRBTenantSubscriptionEvent.parse(event)\n const session = getTransactionSession(transaction)\n\n try {\n const documents = await EventModel.create([eventDocument], session ? { session } : undefined)\n const document = documents[0]?.toObject() as SubscriptionEventDocument | undefined\n if (!document) throw new Error(\"Subscription event was not persisted\")\n return toSubscriptionEvent(document)\n } catch (error) {\n if (!isDuplicateKeyError(error)) throw error\n const duplicate = await findExistingEvent(existingQuery, transaction)\n if (!duplicate) throw error\n return duplicate\n }\n },\n listEvents: async (tenantId, subscriptionId, transaction) => {\n if (tenantId !== params.tenantId) throw new Error(\"Billing storage tenant mismatch\")\n const EventModel = await models.get(\"RBTenantSubscriptionEvent\", params.ctx)\n const request = EventModel.find({ tenantId, subscriptionId })\n .sort({ effectiveAt: 1, occurredAt: 1, _id: 1 })\n const session = getTransactionSession(transaction)\n if (session) request.session(session)\n const documents = await request.lean() as SubscriptionEventDocument[]\n return documents.map(toSubscriptionEvent)\n },\n upsertProjection: async (projection, transaction) => {\n if (projection.tenantId !== params.tenantId) throw new Error(\"Billing projection tenant mismatch\")\n const ProjectionModel = await models.get(\"RBTenantSubscriptionProjection\", params.ctx)\n const session = getTransactionSession(transaction)\n await ProjectionModel.replaceOne(\n {\n tenantId: params.tenantId,\n subscriptionId: projection.subscriptionId,\n },\n toProjectionDocument(projection),\n {\n upsert: true,\n runValidators: true,\n ...(session ? { session } : {}),\n },\n )\n },\n }\n}\n","import mongoose from \"mongoose\"\nimport {\n defineMongoResources,\n type MigrationScope,\n type MongoIndexResource,\n type MongoResources,\n} from \"@rpcbase/migrations\"\n\n\nexport type ExtractMongoResourcesOptions = {\n scope: MigrationScope\n schemas: Readonly<Record<string, unknown>>\n}\n\nconst collectionNameForModel = (modelName: string, schema: mongoose.Schema): string => {\n const configured = schema.options.collection?.trim()\n if (configured) return configured\n const pluralize = mongoose.pluralize()\n return pluralize ? pluralize(modelName) : modelName\n}\n\nconst generatedIndexName = (key: Readonly<Record<string, unknown>>): string =>\n Object.entries(key).map(([path, direction]) => `${path}_${String(direction)}`).join(\"_\")\n\nconst observableIndexOptions = new Set([\n \"2dsphereIndexVersion\",\n \"bits\",\n \"bucketSize\",\n \"collation\",\n \"default_language\",\n \"expireAfterSeconds\",\n \"hidden\",\n \"language_override\",\n \"max\",\n \"min\",\n \"partialFilterExpression\",\n \"sparse\",\n \"storageEngine\",\n \"textIndexVersion\",\n \"unique\",\n \"weights\",\n \"wildcardProjection\",\n])\n\nexport const extractMongoResourcesFromSchemas = (\n options: ExtractMongoResourcesOptions,\n): MongoResources => {\n const schemas = Object.entries(options.schemas)\n .filter((entry): entry is [string, mongoose.Schema] => entry[1] instanceof mongoose.Schema)\n .map(([exportName, schema]) => [exportName.replace(/Schema$/, \"\"), schema] as const)\n const collections = schemas.map(([modelName, schema]) => ({\n scope: options.scope,\n name: collectionNameForModel(modelName, schema),\n }))\n const indexes: MongoIndexResource[] = []\n\n for (const [modelName, schema] of schemas) {\n const collection = collectionNameForModel(modelName, schema)\n for (const [key, indexOptions] of schema.indexes()) {\n const documentKey = key as Record<string, unknown>\n const name = typeof indexOptions.name === \"string\" && indexOptions.name.trim()\n ? indexOptions.name.trim()\n : generatedIndexName(documentKey)\n const normalizedOptions = Object.fromEntries(\n Object.entries(indexOptions).filter(([option, value]) => observableIndexOptions.has(option) && value !== undefined),\n )\n indexes.push({\n scope: options.scope,\n collection,\n name,\n key: documentKey,\n ...(Object.keys(normalizedOptions).length > 0 ? { options: normalizedOptions } : {}),\n })\n }\n }\n\n return defineMongoResources({ collections, indexes })\n}\n","type TenantProvisioner = (tenantId: string) => Promise<void>\n\ntype TenantModel = {\n create(document: Record<string, unknown>): Promise<unknown>\n findOne?(filter: Record<string, unknown>): PromiseLike<{ provisioningStatus?: string } | null>\n updateOne(\n filter: Record<string, unknown>,\n update: Record<string, unknown>,\n ): Promise<{ matchedCount?: number }>\n}\n\n\nlet tenantProvisioner: TenantProvisioner | undefined\n\nexport const configureTenantMigrationProvisioner = (provisioner: TenantProvisioner) => {\n tenantProvisioner = provisioner\n return () => {\n if (tenantProvisioner === provisioner) tenantProvisioner = undefined\n }\n}\n\nconst errorMessage = (error: unknown): string => (\n error instanceof Error ? error.message : String(error)\n).slice(0, 8_000)\n\nexport const createProvisionedTenant = async (\n Tenant: TenantModel,\n tenant: { tenantId: string; name?: string; parentTenantId?: string },\n): Promise<void> => {\n await Tenant.create({\n ...tenant,\n provisioningStatus: \"initializing\",\n provisioningStartedAt: new Date(),\n })\n\n try {\n if (tenantProvisioner) {\n await tenantProvisioner(tenant.tenantId)\n } else if (process.env.NODE_ENV === \"production\") {\n throw new Error(\"No tenant migration provisioner is configured\")\n }\n const activation = await Tenant.updateOne(\n { tenantId: tenant.tenantId, provisioningStatus: \"initializing\" },\n {\n $set: { provisioningStatus: \"active\", provisionedAt: new Date() },\n $unset: { provisioningError: \"\" },\n },\n )\n if (activation.matchedCount !== undefined && activation.matchedCount !== 1) {\n const current = await Tenant.findOne?.({ tenantId: tenant.tenantId })\n if (current?.provisioningStatus !== \"active\") {\n throw new Error(`Tenant ${tenant.tenantId} provisioning state changed before activation`)\n }\n }\n } catch (error) {\n await Tenant.updateOne(\n { tenantId: tenant.tenantId },\n {\n $set: {\n provisioningStatus: \"failed\",\n provisioningError: errorMessage(error),\n },\n },\n )\n throw error\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,IAAaE,UAAUD,IAAEE,OAAO;CAC9BC,OAAOH,IAAEI,OAAO,CAAC,CAACD,MAAM,CAAC,CAACE,SAAS;CACnCC,UAAUN,IAAEI,OAAO;CACnBG,MAAMP,IAAEI,OAAO,CAAC,CAACC,SAAS;CAC1BG,OAAOR,IAAEI,OAAO,CAAC,CAACC,SAAS;CAC3BI,SAAST,IAAEU,MAAMV,IAAEI,OAAO,CAAC;CAC3BO,aAAaX,IAAEY,OAAOZ,IAAEI,OAAO,GAAG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