@ambiten/core 1.0.0 → 1.0.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index-browser.js","mappings":"CAAA,SAAAA,EAAAC,GACA,iBAAAC,SAAA,iBAAAC,OACAA,OAAAD,QAAAD,EAAAG,QAAA,MAAAA,QAAA,QAAAA,QAAA,UACA,mBAAAC,QAAAA,OAAAC,IACAD,OAAA,4CAAAJ,GACA,iBAAAC,QACAA,QAAA,uBAAAD,EAAAG,QAAA,MAAAA,QAAA,QAAAA,QAAA,UAEAJ,EAAA,uBAAAC,EAAAD,EAAA,GAAAA,EAAA,KAAAA,EAAA,MACC,CATD,CASCO,KAAA,CAAAC,EAAAC,EAAAC,qCCRDC,OAAAC,eAAAV,EAAA,cAA+CW,OAAA,IAC/CX,EAAAY,qBACA,SAAAC,GACA,UAAAF,KAAAE,EACA,QAAAC,IAAAH,EACA,OAAAA,CAGA,yBCRAF,OAAAC,eAAAV,EAAA,cAA+CW,OAAA,6BCA/CF,OAAAC,eAAAV,EAAA,cAA+CW,OAAA,IAC/CX,EAAAe,qBAA4BA,EAC5Bf,EAAAgB,kBAsBA,SAAAC,EAAAC,GACA,OAAAD,GACA,WACA,wBAAAC,GAAAC,KAAA,MACA,WACA,wBAAAD,GAAAC,KAAA,MAEA,QACA,2BAAAD,GAAAC,KAAA,MAEA,EA/BAnB,EAAAoB,gBAgCAC,eAAAH,EAAA,GAAAI,EAAAC,QAAAD,OACA,MAAAL,EAAAF,EAAAO,GACAE,EAAA,IAAAN,EAAAO,OACA,YACA,QAAAR,EACA,cAAAC,GACA,UAAAA,SACA,IAAAQ,QAAA,CAAAC,EAAAC,KACA,MAAAC,GAAA,EAAAC,EAAAC,OAAAd,EAAAO,EAAA,CACAF,MACAU,MAAA,UACAC,MAAA,UAAAV,QAAAW,WAEAL,EAAAM,GAAA,QAAAP,GACAC,EAAAM,GAAA,QAAAC,IACA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AAcvC,KCH3CgoC,EAAA,GAGA,SAAAzlC,EAAA0lC,GAEA,IAAAC,EAAAF,EAAAC,GACA,QAAAnnC,IAAAonC,EACA,OAAAA,EAAAloC,QAGA,IAAAC,EAAA+nC,EAAAC,GAAA,CAGAjoC,QAAA,IAOA,OAHAmoC,EAAAF,GAAAhoC,EAAAA,EAAAD,QAAAuC,GAGAtC,EAAAD,OACA,QCtBAuC,EAAA6lC,EAAA,CAAAC,EAAAC,IAAA7nC,OAAAmyB,UAAAE,eAAAC,KAAAsV,EAAAC,GCGA/lC,EAAA","sources":["webpack://ambitencore-browser/webpack/universalModuleDefinition","webpack://ambitencore-browser/./src/utils/resolveAmbitenOption.ts","webpack://ambitencore-browser/./src/types/db.provider.ts","webpack://ambitencore-browser/./src/utils/detect-package-manager.ts","webpack://ambitencore-browser/./src/utils/symbols.ts","webpack://ambitencore-browser/./src/types/GCConfig.ts","webpack://ambitencore-browser/external commonjs \"jsonwebtoken\"","webpack://ambitencore-browser/./src/tanancy/index.ts","webpack://ambitencore-browser/./src/utils/index.ts","webpack://ambitencore-browser/./src/types/graphql.type.ts","webpack://ambitencore-browser/./src/utils/ lazy referencedExports: default, default namespace object","webpack://ambitencore-browser/./src/types/result.utils.types.ts","webpack://ambitencore-browser/external commonjs \"buffer\"","webpack://ambitencore-browser/./src/utils/logger.ts","webpack://ambitencore-browser/./src/templates/generateDefaultConfigContent.ts","webpack://ambitencore-browser/./src/utils/builders/createModel.ts","webpack://ambitencore-browser/./src/config/index.ts","webpack://ambitencore-browser/./src/templates/index.ts","webpack://ambitencore-browser/./src/lib-core/ambitenClient.ts","webpack://ambitencore-browser/external commonjs \"graphql-tag\"","webpack://ambitencore-browser/./src/plugins/index.ts","webpack://ambitencore-browser/./src/utils/events.ts","webpack://ambitencore-browser/./src/debug/debugLog.ts","webpack://ambitencore-browser/./src/utils/ensureRedis.ts","webpack://ambitencore-browser/./src/types/document.ts","webpack://ambitencore-browser/./src/tanancy/TenantModelResolver.ts","webpack://ambitencore-browser/external commonjs \"mongodb\"","webpack://ambitencore-browser/./src/utils/resolveRuntimeConfig.ts","webpack://ambitencore-browser/./src/middleware/rbac/rbacMiddleware.ts","webpack://ambitencore-browser/./src/config/loadAmbitenConfig.ts","webpack://ambitencore-browser/external commonjs \"node-cron\"","webpack://ambitencore-browser/./src/utils/time.ts","webpack://ambitencore-browser/external umd \"fs\"","webpack://ambitencore-browser/./src/utils/error/ambitenError-handler.ts","webpack://ambitencore-browser/./src/lib-core/bootstrap/ambitenBootstrap.ts","webpack://ambitencore-browser/./src/context/ambitenContext.ts","webpack://ambitencore-browser/./src/ambiten-cache/index.ts","webpack://ambitencore-browser/./src/types/index.ts","webpack://ambitencore-browser/./src/types/middleware/types.ts","webpack://ambitencore-browser/./src/instrumentation/measureQuery.browser.ts","webpack://ambitencore-browser/./src/types/bootstrapClient.type.ts","webpack://ambitencore-browser/./src/utils/builders/getTenantDb.ts","webpack://ambitencore-browser/./src/redis-manager/index.ts","webpack://ambitencore-browser/./src/gc/gcManager.ts","webpack://ambitencore-browser/./src/instrumentation/index.ts","webpack://ambitencore-browser/external umd \"path\"","webpack://ambitencore-browser/external commonjs \"graphql-subscriptions\"","webpack://ambitencore-browser/./src/utils/cacheWithRedis.ts","webpack://ambitencore-browser/./src/init-cli/generate.project.ts","webpack://ambitencore-browser/./src/utils/scaffoldLoger.ts","webpack://ambitencore-browser/./src/types/schema.type.ts","webpack://ambitencore-browser/external commonjs \"dotenv/config\"","webpack://ambitencore-browser/external commonjs \"fs-extra\"","webpack://ambitencore-browser/./src/plugins/softDelete/applySoftDelete.ts","webpack://ambitencore-browser/./src/context/helpers/runManualTransaction.ts","webpack://ambitencore-browser/./src/utils/color-palatte.ts","webpack://ambitencore-browser/./src/tanancy/MultiTenantManager.ts","webpack://ambitencore-browser/./src/types/ambiten.client.type.ts","webpack://ambitencore-browser/external commonjs \"tslib\"","webpack://ambitencore-browser/./src/templates/generateMainEntry.ts","webpack://ambitencore-browser/./src/utils/configureAmbitenContext.ts","webpack://ambitencore-browser/./src/ambiten-cache/ambitenCache.ts","webpack://ambitencore-browser/external commonjs \"ajv\"","webpack://ambitencore-browser/external commonjs \"@graphql-tools/schema\"","webpack://ambitencore-browser/./src/gc/gcCron.node.ts","webpack://ambitencore-browser/./src/lib-core/index.ts","webpack://ambitencore-browser/./src/utils/builders/schema.ts","webpack://ambitencore-browser/./src/index.ts","webpack://ambitencore-browser/./src/tanancy/TenantContext.ts","webpack://ambitencore-browser/./src/redis-manager/redisClient.ts","webpack://ambitencore-browser/./src/templates/generateGCRunnerFile.ts","webpack://ambitencore-browser/./src/utils/eventOptions.ts","webpack://ambitencore-browser/./src/lib-core/ambitenSchema.ts","webpack://ambitencore-browser/./src/templates/scaffold/structureGenerator.ts","webpack://ambitencore-browser/./src/middleware/rbac/rbacTypes.ts","webpack://ambitencore-browser/./src/templates/generateGCManagerFile.ts","webpack://ambitencore-browser/./src/context/helpers/transactionSession.ts","webpack://ambitencore-browser/./src/types/logger.types.ts","webpack://ambitencore-browser/./src/tanancy/init/initMultiTenancy.ts","webpack://ambitencore-browser/./src/graphql/ambitenGraphQL.ts","webpack://ambitencore-browser/./src/utils/error/errorTypes.ts","webpack://ambitencore-browser/./src/utils/AuthUtils.ts","webpack://ambitencore-browser/./src/plugins/softDelete/types.ts","webpack://ambitencore-browser/./src/utils/castId.ts","webpack://ambitencore-browser/./src/lib-core/bootstrap/index.ts","webpack://ambitencore-browser/./src/middleware/index.ts","webpack://ambitencore-browser/./src/utils/ensureModelNameSafe.ts","webpack://ambitencore-browser/./src/utils/modelLoader.ts","webpack://ambitencore-browser/./src/graphql/index.ts","webpack://ambitencore-browser/./src/gc/index.ts","webpack://ambitencore-browser/./src/middleware/authorization/auth.ts","webpack://ambitencore-browser/external umd \"false\"","webpack://ambitencore-browser/./src/utils/ModelRegistry.ts","webpack://ambitencore-browser/./src/context/index.ts","webpack://ambitencore-browser/./src/gc/ambitenGC.ts","webpack://ambitencore-browser/./src/utils/invalidateTenantCache.ts","webpack://ambitencore-browser/./src/types/event.type.ts","webpack://ambitencore-browser/./src/gc/gcCron.browser.ts","webpack://ambitencore-browser/./src/instrumentation/measureQueryWithErrors.ts","webpack://ambitencore-browser/external commonjs \"@ambiten/logger\"","webpack://ambitencore-browser/./src/debug/index.ts","webpack://ambitencore-browser/./src/lib-core/ambitenModelFactory.ts","webpack://ambitencore-browser/./src/types/ambitenConfig.ts","webpack://ambitencore-browser/./src/browser.ts","webpack://ambitencore-browser/./src/types/user.type.ts","webpack://ambitencore-browser/./src/utils/builders/index.ts","webpack://ambitencore-browser/./src/types/ambiten.model.type.ts","webpack://ambitencore-browser/./src/utils/error/index.ts","webpack://ambitencore-browser/webpack/bootstrap","webpack://ambitencore-browser/webpack/runtime/hasOwnProperty shorthand","webpack://ambitencore-browser/webpack/startup"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"fs\"), require(\"path\"), require(\"false\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"ambitencore-browser\", [\"fs\", \"path\", \"false\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"ambitencore-browser\"] = factory(require(\"fs\"), require(\"path\"), require(\"false\"));\n\telse\n\t\troot[\"ambitencore-browser\"] = factory(root[\"fs\"], root[\"path\"], root[\"false\"]);\n})(self, (__WEBPACK_EXTERNAL_MODULE__2947__, __WEBPACK_EXTERNAL_MODULE__3911__, __WEBPACK_EXTERNAL_MODULE__8535__) => {\nreturn ","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.resolveAmbitenOption = resolveAmbitenOption;\nfunction resolveAmbitenOption(values) {\n for (const value of values) {\n if (value !== undefined)\n return value;\n }\n return undefined;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.detectPackageManager = detectPackageManager;\nexports.getInstallCommand = getInstallCommand;\nexports.installPackages = installPackages;\nconst tslib_1 = require(\"tslib\");\nconst fs_1 = tslib_1.__importDefault(require(\"fs\"));\nconst path_1 = tslib_1.__importDefault(require(\"path\"));\nconst child_process_1 = require(\"child_process\");\nfunction detectPackageManager(cwd = process.cwd()) {\n if (fs_1.default.existsSync(path_1.default.join(cwd, 'pnpm-lock.yaml')))\n return 'pnpm';\n if (fs_1.default.existsSync(path_1.default.join(cwd, 'yarn.lock')))\n return 'yarn';\n if (fs_1.default.existsSync(path_1.default.join(cwd, 'package-lock.json')))\n return 'npm';\n const userAgent = process.env.npm_config_user_agent ?? '';\n if (userAgent.includes('pnpm'))\n return 'pnpm';\n if (userAgent.includes('yarn'))\n return 'yarn';\n if (userAgent.includes('npm'))\n return 'npm';\n return 'npm';\n}\nfunction getInstallCommand(manager, packages) {\n switch (manager) {\n case 'pnpm':\n return ['pnpm', ['add', ...packages].join(' ')];\n case 'yarn':\n return ['yarn', ['add', ...packages].join(' ')];\n case 'npm':\n default:\n return ['npm', ['install', ...packages].join(' ')];\n }\n}\nasync function installPackages(packages = [], cwd = process.cwd()) {\n const manager = detectPackageManager(cwd);\n const args = packages.length === 0\n ? ['install']\n : manager === 'npm'\n ? ['install', ...packages]\n : ['add', ...packages];\n await new Promise((resolve, reject) => {\n const child = (0, child_process_1.spawn)(manager, args, {\n cwd,\n stdio: 'inherit',\n shell: process.platform === 'win32',\n });\n child.on('error', reject);\n child.on('close', (code) => {\n if (code === 0) {\n resolve();\n return;\n }\n reject(new Error(`${manager} ${args.join(' ')} failed with exit code ${code}`));\n });\n });\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.objectIdSymbol = exports.schemaTypeSymbol = exports.AmbitenSymbol = void 0;\nexports.AmbitenSymbol = Symbol('Ambiten');\nexports.schemaTypeSymbol = Symbol('AmbitenSchemaType');\nexports.objectIdSymbol = Symbol.for('AmbitenObjectId');\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","module.exports = require(\"jsonwebtoken\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./MultiTenantManager\"), exports);\ntslib_1.__exportStar(require(\"./TenantContext\"), exports);\ntslib_1.__exportStar(require(\"./TenantModelResolver\"), exports);\ntslib_1.__exportStar(require(\"./init/initMultiTenancy\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./builders/createModel\"), exports);\ntslib_1.__exportStar(require(\"./builders/schema\"), exports);\ntslib_1.__exportStar(require(\"./ensureModelNameSafe\"), exports);\ntslib_1.__exportStar(require(\"./ModelRegistry\"), exports);\ntslib_1.__exportStar(require(\"./castId\"), exports);\ntslib_1.__exportStar(require(\"./symbols\"), exports);\ntslib_1.__exportStar(require(\"./error/ambitenError-handler\"), exports);\ntslib_1.__exportStar(require(\"./error\"), exports);\ntslib_1.__exportStar(require(\"./AuthUtils\"), exports);\ntslib_1.__exportStar(require(\"./events\"), exports);\ntslib_1.__exportStar(require(\"./cacheWithRedis\"), exports);\ntslib_1.__exportStar(require(\"./logger\"), exports);\ntslib_1.__exportStar(require(\"./eventOptions\"), exports);\ntslib_1.__exportStar(require(\"./time\"), exports);\ntslib_1.__exportStar(require(\"./modelLoader\"), exports);\ntslib_1.__exportStar(require(\"./scaffoldLoger\"), exports);\ntslib_1.__exportStar(require(\"./ensureRedis\"), exports);\ntslib_1.__exportStar(require(\"./resolveAmbitenOption\"), exports);\ntslib_1.__exportStar(require(\"./resolveRuntimeConfig\"), exports);\ntslib_1.__exportStar(require(\"./configureAmbitenContext\"), exports);\ntslib_1.__exportStar(require(\"./color-palatte\"), exports);\ntslib_1.__exportStar(require(\"./detect-package-manager\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","function webpackEmptyAsyncContext(req) {\n\t// Here Promise.resolve().then() is used instead of new Promise() to prevent\n\t// uncaught exception popping up in devtools\n\treturn Promise.resolve().then(() => {\n\t\tvar e = new Error(\"Cannot find module '\" + req + \"'\");\n\t\te.code = 'MODULE_NOT_FOUND';\n\t\tthrow e;\n\t});\n}\nwebpackEmptyAsyncContext.keys = () => ([]);\nwebpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;\nwebpackEmptyAsyncContext.id = 1077;\nmodule.exports = webpackEmptyAsyncContext;","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","module.exports = require(\"buffer\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createBootstrapLogger = createBootstrapLogger;\nconst logger_1 = require(\"@ambiten/logger\");\nfunction createBootstrapLogger(config = {\n transportConfigs: []\n}) {\n if (!config?.enabled) {\n return (0, logger_1.setupLogger)({\n level: 'warn',\n colorize: false,\n });\n }\n const loggerConfig = {\n level: config.level ?? 'info',\n colorize: config.colorize ?? true,\n json: config.json ?? false,\n transports: config.transports ?? [],\n formatOptions: config.formatOptions,\n hooks: config.hooks,\n contextProvider: config.contextProvider,\n enableMetrics: config.enableMetrics ?? { enabled: false },\n circuitBreaker: config.circuitBreaker,\n compress: config.compress ?? { enabled: false },\n };\n return (0, logger_1.setupLogger)(loggerConfig);\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DEFAULT_CONFIG_CONTENT = DEFAULT_CONFIG_CONTENT;\nfunction DEFAULT_CONFIG_CONTENT(options) {\n const config = {\n configVersion: '1.0.0',\n projectName: options.projectName ?? 'my-ambiten-app',\n connection: {\n uri: options.connection?.uri ?? 'mongodb://localhost:27017/my-ambiten-app',\n options: {\n dbName: options.connection?.options?.dbName ??\n options.projectName ??\n 'my-ambiten-app',\n },\n },\n ...(options.multiTenant?.enabled\n ? {\n multiTenant: {\n enabled: true,\n headerKey: options.multiTenant.headerKey ?? 'x-tenant-id',\n tenants: options.multiTenant.tenants ?? {},\n initOptions: {\n lazy: options.multiTenant.initOptions?.lazy ?? false,\n retryAttempts: options.multiTenant.initOptions?.retryAttempts ?? 3,\n },\n },\n }\n : {}),\n ...(options.logger?.enabled\n ? {\n logger: {\n enabled: true,\n level: options.logger.level ?? 'info',\n colorize: options.logger.colorize ?? true,\n json: options.logger.json ?? false,\n transportConfigs: [\n {\n \"type\": \"console\",\n \"options\": {}\n },\n {\n \"type\": \"rotating-file\",\n \"options\": {\n \"filename\": \"./logs/ambiten.log\",\n \"frequency\": \"hourly\",\n \"maxSize\": 200,\n \"compress\": false,\n \"flushInterval\": 1000\n }\n }\n ],\n enableMetrics: typeof options.logger.enableMetrics === 'boolean'\n ? {\n enabled: options.logger.enableMetrics,\n logInterval: 60000,\n }\n : options.logger.enableMetrics ?? {\n enabled: false,\n logInterval: 60000,\n },\n compress: typeof options.logger.compress === 'boolean'\n ? {\n enabled: options.logger.compress,\n }\n : options.logger.compress ?? {\n enabled: false,\n },\n }\n }\n : {}),\n ...(options.graphql?.enabled\n ? {\n graphql: {\n enabled: true,\n subscriptions: options.graphql.subscriptions ?? false,\n playground: options.graphql.playground ?? true,\n schemaOutputPath: options.graphql.schemaOutputPath ?? './src/graphql/schema.gql',\n },\n }\n : {}),\n features: {\n models: options.features?.models ?? './src/models',\n schemas: options.features?.schemas ?? './src/schemas',\n ...(options.graphql?.enabled\n ? {\n typeDefs: options.features?.typeDefs ?? './src/graphql/typeDefs',\n resolvers: options.features?.resolvers ?? './src/graphql/resolvers',\n }\n : {}),\n useRedisCache: options.features?.useRedisCache ?? false,\n redisUri: options.features?.redisUri ?? '',\n },\n advanced: {\n autoInstall: options.advanced?.autoInstall ?? false,\n circuitBreaker: {\n enabled: options.advanced?.circuitBreaker?.enabled ?? true,\n retryAttempts: options.advanced?.circuitBreaker?.retryAttempts ?? 5,\n },\n garbageCollector: {\n enabled: options.advanced?.garbageCollector?.enabled ?? false,\n retentionPeriod: options.advanced?.garbageCollector?.retentionPeriod ?? 30,\n logResults: options.advanced?.garbageCollector?.logResults ?? true,\n },\n gcCron: options.advanced?.gcCron ?? '* * * * *',\n },\n };\n return JSON.stringify(config, null, 2);\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Model = void 0;\nconst lib_core_1 = require(\"../../lib-core\");\n/**\n * Creates a new model for a MongoDB collection.\n * In Multi-Tenancy mode, the model will be created for the specified tenant.\n * If no tenant ID is provided, the model will be created for the default tenant.\n * Note: Once a the applyMultiTenancy() middleware is applied to a connection to register tenant/s, the tenantId will be automatically set for all models created after that.\n * This allows you to create models for different tenants without having to specify the tenantId each time. Then a tenantId or db instance or client instance is required to create a model.\n * @template T - The type of the document in the collection.\n * @param {CreateModelParams<T>} params - The parameters for creating the model.\n * @returns {AmbitenModel<T>} The created model.\n *\n * @example\n * const userSchema = createSchema({\n * name: { type: String, required: true },\n * age: { type: Number, required: true },\n * email: { type: String, required: true },\n * });\n *\n * const userModel = Model({\n * name: 'users',\n * schema: userSchema,\n * provider: (client/db - whichever you naming is)/new MyCustomDbProvider(), // Your custom database provider instance\n * ctx: {\n * tenantId: 'tenant-a', // Optional: specify tenant ID if using multi-tenancy\n * dbName: 'myDatabase', // Optional: specify database name if needed\n * } read docs for more details on what context options you can provide\n * });\n */\nconst Model = (options) => {\n return new lib_core_1.AmbitenModel({\n ...options,\n provider: options.provider ?? lib_core_1.AmbitenClient.init()\n });\n};\nexports.Model = Model;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./loadAmbitenConfig\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./generateDefaultConfigContent\"), exports);\ntslib_1.__exportStar(require(\"./generateMainEntry\"), exports);\ntslib_1.__exportStar(require(\"./scaffold/structureGenerator\"), exports);\ntslib_1.__exportStar(require(\"./generateGCManagerFile\"), exports);\ntslib_1.__exportStar(require(\"./generateGCRunnerFile\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenClient = void 0;\nexports.createAmbitenClientModule = createAmbitenClientModule;\n/* eslint-disable @typescript-eslint/no-require-imports */\nconst mongodb_1 = require(\"mongodb\");\nrequire(\"dotenv/config\");\nconst utils_1 = require(\"../utils\");\nconst tanancy_1 = require(\"../tanancy\");\nconst context_1 = require(\"../context\");\nconst AmbitenSymbol = Symbol.for('Ambiten:default');\n/**\n * AmbitenClient is a MongoDB client wrapper that provides a simplified interface\n * for connecting to and interacting with MongoDB databases.\n */\nclass AmbitenClient {\n _opts;\n _uri;\n _client;\n _db;\n collectionRef;\n _connected = false;\n _defaultDbName;\n _overrideDbName;\n static instances = new Map();\n static defaultUri = 'mongodb://127.0.0.1:27017';\n constructor(_opts) {\n this._opts = _opts;\n this._uri = _opts.uri || process.env.MONGO_URI || AmbitenClient.defaultUri;\n this._defaultDbName =\n _opts?.options?.dbName ||\n process.env.DB_NAME ||\n 'Ambiten_default_db';\n this._client = new mongodb_1.MongoClient(this._uri, {\n directConnection: true,\n minPoolSize: 5,\n maxPoolSize: 50,\n serverSelectionTimeoutMS: 5000\n });\n this._db = this._client.db(this._opts.options?.dbName);\n this.ensureMongoDependency();\n }\n static init(opts) {\n const key = String(AmbitenSymbol);\n const existing = this.instances.get(key);\n if (existing) {\n return existing;\n }\n const client = createAmbitenClientModule({\n uri: opts?.uri ?? this.defaultUri ?? process.env.MONGO_URI,\n options: { dbName: opts?.options?.dbName },\n tenantResolver: opts?.tenantResolver\n });\n this.instances.set(key, client);\n return client;\n }\n ensureMongoDependency() {\n try {\n const { MongoClient } = require('mongodb');\n void MongoClient;\n }\n catch {\n console.error('\\n❌ Missing peer dependency: \"mongodb\".\\n' +\n 'Please install it in your project before continuing:\\n\\n' +\n ' npm i mongodb\\n');\n process.exit(1);\n }\n }\n /**\n * Resolution order:\n * 1. explicit ctx.db\n * 2. tenant-aware db resolution\n * 3. explicit ctx.dbName on base client\n * 4. mutable override dbName\n * 5. default dbName\n */\n async db(ctx) {\n if (ctx?.db) {\n return ctx.db;\n }\n if (ctx?.tenantId) {\n const resolver = this._opts.tenantResolver;\n if (!resolver) {\n throw new Error('Multi-tenancy not enabled. Provide tenantResolver to AmbitenClient or avoid passing tenantId.');\n }\n const tenantClient = await resolver.getClient(ctx.tenantId);\n if (!tenantClient) {\n throw new Error(`Tenant \"${ctx.tenantId}\" is not registered.`);\n }\n const resolvedTenantDbName = ctx.dbName ??\n tanancy_1.MultiTenantManager.getTenantDbName(ctx.tenantId) ??\n this._defaultDbName;\n return tenantClient.db(resolvedTenantDbName);\n }\n if (!this._client || !this._connected) {\n const message = 'AmbitenClient not connected. call connect() first.';\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.CONNECTION_ERROR, message, {\n details: {\n operation: 'db'\n }\n });\n }\n if (ctx?.dbName) {\n return this._client.db(ctx.dbName);\n }\n if (this._overrideDbName) {\n return this._client.db(this._overrideDbName);\n }\n return this._client.db(this._defaultDbName);\n }\n static async db(ctx) {\n return this.init().db(ctx);\n }\n validateUri(uri) {\n if (!uri || typeof uri !== 'string') {\n const message = 'Missing MongoDB URI. Set MONGODB_URI (or pass uri explicitly).';\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.VALIDATION_ERROR, message, {\n details: {\n operation: 'validateUri',\n providedUri: uri,\n }\n });\n }\n if (!/^mongodb(\\+srv)?:\\/\\//.test(uri)) {\n const message = `Invalid MongoDB URI \"${uri}\". It must start with \"mongodb://\" or \"mongodb+srv://\".`;\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.VALIDATION_ERROR, message, {\n details: {\n operation: 'validateUri',\n providedUri: uri,\n }\n });\n }\n }\n async connect() {\n this.validateUri(this._opts.uri);\n if (!this._client) {\n this._client = new mongodb_1.MongoClient(this._opts.uri);\n }\n if (!this._connected) {\n await this._client.connect();\n this._connected = true;\n }\n return this;\n }\n async client(ctx) {\n if (ctx?.tenantId) {\n const resolver = this._opts.tenantResolver;\n if (!resolver) {\n throw new Error('Multi-tenancy not enabled. Provide tenantResolver to AmbitenClient or avoid passing tenantId.');\n }\n const tenantClient = await resolver.getClient(ctx.tenantId);\n if (!tenantClient) {\n throw new Error(`Tenant \"${ctx.tenantId}\" is not registered.`);\n }\n return tenantClient;\n }\n if (!this._client) {\n throw new Error('Client not initialized. Call `connect()` first.');\n }\n return this._client;\n }\n async useCollection(collectionName) {\n if (!collectionName || typeof collectionName !== 'string' || !collectionName.trim()) {\n throw new Error('Collection name is required.');\n }\n if (!this._client) {\n throw new Error('Client not initialized. Call `connect()` first.');\n }\n const scope = this.resolveClientScope({ collectionName });\n const db = this._client.db(scope.dbName);\n if (!db || typeof db.collection !== 'function') {\n throw new Error('Database name is required in client options.');\n }\n const collection = db.collection(scope.collectionName);\n this.collectionRef = collection;\n return collection;\n }\n async collection(collectionName, ctx) {\n const db = await this.db(ctx);\n return db.collection(collectionName);\n }\n async getCollection(collectionName, ctx) {\n if (!this._client || typeof this._client.db !== 'function') {\n return {\n toString: () => collectionName\n };\n }\n return this.collection(collectionName, ctx);\n }\n async getClusterInfo() {\n if (!this._client) {\n throw new Error('Client not initialized. Call `connect()` first.');\n }\n const dbName = this._opts?.options?.dbName;\n if (!dbName) {\n throw new Error('Database name is required in client options.');\n }\n const helloResult = await this._client\n .db(dbName)\n .admin()\n .command({ hello: 1 });\n if (helloResult?.msg === 'isdbgrid') {\n console.log('MongoDB is running in a sharded cluster.');\n return { type: 'sharded' };\n }\n if (helloResult?.setName || helloResult?.hosts) {\n console.log('MongoDB is running as a replica set.');\n return {\n type: 'replicaSet',\n setName: helloResult.setName,\n hosts: helloResult.hosts\n };\n }\n console.log('MongoDB is running as a standalone instance.');\n return { type: 'standalone' };\n }\n /**\n * Resolves database + session + runtime binding\n */\n static async resolveRuntime() {\n const ctx = context_1.AmbitenContext.get();\n if (!ctx?.tenantId) {\n throw new Error(\"Tenant not resolved in context.\");\n }\n const tenant = tanancy_1.MultiTenantManager.getTenant(ctx.tenantId);\n if (!tenant) {\n throw new Error(`Tenant not found: ${ctx.tenantId}`);\n }\n const db = this.resolveDbFromTenant(tenant, ctx);\n return {\n db,\n session: ctx?.session,\n };\n }\n /**\n * Mutable legacy helper. Prefer withDatabase() or withScope() in request-safe flows.\n */\n async useDatabase(dbName) {\n if (!dbName) {\n throw new Error('Database name is required.');\n }\n const client = await this.client();\n this._overrideDbName = dbName;\n return {\n db: client.db(dbName),\n client\n };\n }\n withDatabase(dbName) {\n return {\n db: async (ctx) => {\n const merged = { ...ctx, dbName: ctx?.dbName ?? dbName };\n return this.db(merged);\n },\n connect: async () => {\n await this.connect();\n return this;\n },\n client: async (ctx) => {\n const merged = { ...ctx, dbName: ctx?.dbName ?? dbName };\n return this.client(merged);\n },\n collection: async (collectionName, ctx) => {\n const merged = { ...ctx, dbName: ctx?.dbName ?? dbName };\n return this.collection(collectionName, merged);\n },\n startSession: async (ctx) => {\n const merged = {\n ...ctx, dbName: ctx?.dbName ?? dbName, session: ctx?.session\n };\n return this.startSession(merged);\n },\n close: async () => {\n await this.close();\n }\n };\n }\n /**\n * Resolves the active database name.\n *\n * @param overrideDbName - Optional database override.\n * @returns The resolved database name.\n * @throws {Error} When no database name can be resolved.\n */\n resolveDbName(overrideDbName) {\n return this.resolveClientScope({ dbName: overrideDbName }).dbName;\n }\n /**\n * Resolves the active client execution scope by combining explicit method\n * arguments, active Ambiten runtime context, and client-level defaults.\n *\n * Resolution priority:\n * 1. Explicit method arguments\n * 2. Active Ambiten runtime context\n * 3. Client configuration\n * 4. Client defaults\n *\n * This method does not mutate runtime context or client configuration.\n *\n * @param input - Optional scope overrides for database, collection, and session.\n * @returns The resolved execution scope for client-level operations.\n * @throws {Error} When no database name can be resolved.\n */\n resolveClientScope(input = {}) {\n const ctx = context_1.AmbitenContext.get();\n const dbName = input.dbName ??\n ctx.dbName ??\n this._opts?.options?.dbName ??\n this._defaultDbName;\n if (!dbName) {\n throw new Error('Database name is required in client options.');\n }\n const collectionName = input.collectionName ??\n ctx.collectionName;\n return {\n tenantId: ctx.tenantId,\n requestId: ctx.requestId,\n dbName,\n collectionName: collectionName?.trim() || undefined,\n session: input.session ?? ctx.session\n };\n }\n static resolveDbFromTenant(tenant, ctx) {\n if (!tenant?.client) {\n throw new Error(`Tenant \"${ctx?.tenantId}\" has no MongoDB client.`);\n }\n const dbName = ctx?.dbName ?? tenant.dbName;\n if (!dbName) {\n throw new Error(`Database name not resolved for tenant \"${ctx?.tenantId}\".`);\n }\n return tenant.client.db(dbName);\n }\n ;\n async withContext(context, callback) {\n return context_1.AmbitenContext.run({\n tenantId: context.tenantId,\n requestId: context.requestId,\n dbName: context.dbName,\n collectionName: context.collectionName,\n session: context.session\n }, callback);\n }\n logWithContext(level, message, meta = {}) {\n const ctx = context_1.AmbitenContext.get();\n const enrichedMeta = {\n requestId: ctx.requestId,\n tenantId: ctx.tenantId,\n ...ctx.loggerMeta,\n ...meta\n };\n this._opts.options?.config?.logger?.[level]?.(message, enrichedMeta);\n }\n withTenant(tenantId) {\n return {\n db: async (ctx) => {\n const merged = { ...ctx, tenantId: ctx?.tenantId ?? tenantId };\n return this.db(merged);\n },\n connect: async () => {\n await this.connect();\n return this;\n },\n client: async (ctx) => {\n const merged = { ...ctx, tenantId: ctx?.tenantId ?? tenantId };\n return this.client(merged);\n },\n collection: async (collectionName, ctx) => {\n const merged = { ...ctx, tenantId: ctx?.tenantId ?? tenantId };\n return this.collection(collectionName, merged);\n },\n startSession: async (ctx) => {\n const merged = { ...ctx, tenantId: ctx.tenantId ?? tenantId };\n return this.startSession(merged);\n },\n close: async () => {\n await this.close();\n }\n };\n }\n withScope(scope) {\n return {\n db: async (ctx) => {\n const merged = {\n ...ctx,\n tenantId: ctx?.tenantId ?? scope.tenantId,\n dbName: ctx?.dbName ?? scope.dbName\n };\n return this.db(merged);\n },\n connect: async () => {\n await this.connect();\n return this;\n },\n client: async (ctx) => {\n const merged = {\n ...ctx,\n tenantId: ctx?.tenantId ?? scope.tenantId,\n dbName: ctx?.dbName ?? scope.dbName\n };\n return this.client(merged);\n },\n collection: async (collectionName, ctx) => {\n const merged = {\n ...ctx,\n tenantId: ctx?.tenantId ?? scope.tenantId,\n dbName: ctx?.dbName ?? scope.dbName\n };\n return this.collection(collectionName, merged);\n },\n startSession: async (ctx) => {\n const merged = {\n ...ctx,\n tenantId: ctx?.tenantId ?? scope.tenantId,\n dbName: ctx?.dbName ?? scope.dbName\n };\n return this.startSession(merged);\n },\n close: async () => {\n await this.close();\n }\n };\n }\n resetDatabase() {\n this._overrideDbName = undefined;\n }\n async startSession(ctx) {\n const client = await this.client(ctx);\n return client.startSession();\n }\n async dropCollection(collectionName, ctx) {\n if (!this._client && !ctx?.db) {\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.CONNECTION_ERROR, 'Client not initialized. Call `connect()` first.', {\n details: {\n operation: 'dropCollection',\n providedCollectionName: collectionName\n }\n });\n }\n const resolvedCollectionName = collectionName?.trim() ||\n this.collectionRef?.collectionName;\n if (!resolvedCollectionName) {\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.VALIDATION_ERROR, 'Collection name is required.', {\n details: {\n operation: 'dropCollection',\n providedCollectionName: collectionName\n }\n });\n }\n const db = ctx?.db ?? this._client.db(this.resolveDbName(ctx?.dbName));\n await db.collection(resolvedCollectionName).drop();\n }\n async dropDatabase(ctx) {\n if (!this._client && !ctx?.db) {\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.CONNECTION_ERROR, 'Client not initialized. Call `connect()` first.', {\n details: {\n operation: 'dropDatabase'\n }\n });\n }\n const db = ctx?.db ??\n this._client.db(this.resolveDbName(ctx?.dbName));\n const result = await db.dropDatabase();\n return result === undefined ? true : result;\n }\n async close() {\n if (this._client) {\n await this._client.close?.();\n }\n this._client = null;\n this._db = null;\n this._connected = false;\n console.log('[info]: Disconnected from MongoDB');\n }\n async disconnect() {\n await this.close();\n }\n isConnected() {\n return this._connected;\n }\n static handleTopologyEvent(event) {\n if (event instanceof mongodb_1.TopologyOpeningEvent) {\n console.log(`Topology opened: ${event.topologyId}`);\n }\n else if (event instanceof mongodb_1.TopologyClosedEvent) {\n console.log(`Topology closed: ${event.topologyId}`);\n }\n else {\n console.warn(`[warning]: Unknown topology event: ${event}`);\n }\n }\n ;\n static async handleLogBatch(batch, transporter) {\n if (!Array.isArray(batch) || batch.length === 0) {\n console.warn('[warning]: Received an empty log batch or invalid format.');\n return;\n }\n const ctx = context_1.AmbitenContext.get();\n this.handleTopologyEvent(batch[0]);\n const remaining = batch.slice(1);\n if (remaining.length === 0)\n return;\n if (!transporter) {\n console.warn(`[warning]: No transporter provided; ${remaining.length} topology event(s) will not be processed.`);\n return;\n }\n const writes = remaining.map((event) => {\n const eventName = event.constructor?.name ?? 'TopologyEvent';\n const eventType = eventName.toLowerCase().includes('opening')\n ? 'opening'\n : eventName.toLowerCase().includes('closed')\n ? 'closed'\n : 'unknown';\n const message = `Topology event: ${eventName}`;\n return transporter.write({\n level: 'info',\n timestamp: new Date().toISOString(),\n message,\n source: 'AmbitenTopology',\n context: {\n requestId: ctx?.requestId,\n tenantId: ctx?.tenantId,\n collectionName: ctx?.collectionName,\n dbName: ctx?.dbName,\n },\n meta: {\n eventType,\n topologyId: event.topologyId,\n },\n }, message);\n });\n await Promise.all(writes);\n }\n}\nexports.AmbitenClient = AmbitenClient;\nfunction createAmbitenClientModule(opts) {\n return new AmbitenClient(opts);\n}\n","module.exports = require(\"graphql-tag\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./softDelete/applySoftDelete\"), exports);\ntslib_1.__exportStar(require(\"./softDelete/types\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DB_CHANGE_EVENT = exports.DOCUMENT_DELETED_EVENT = exports.DOCUMENT_UPDATED_EVENT = exports.DOCUMENT_INSERTED_EVENT = void 0;\nexports.DOCUMENT_INSERTED_EVENT = 'DOCUMENT_INSERTED';\nexports.DOCUMENT_UPDATED_EVENT = 'DOCUMENT_UPDATED';\nexports.DOCUMENT_DELETED_EVENT = 'DOCUMENT_DELETED';\nexports.DB_CHANGE_EVENT = 'DB_CHANGE_EVENT';\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.debugLog = debugLog;\nconst context_1 = require(\"../context\");\nfunction debugLog(message, meta = {}) {\n if (!context_1.AmbitenContext.isDebug())\n return;\n const logger = context_1.AmbitenContext.getLogger();\n const loggerMeta = context_1.AmbitenContext.getLoggerMeta() ?? {};\n const payload = {\n tenantId: context_1.AmbitenContext.getTenantId(),\n requestId: context_1.AmbitenContext.getRequestId(),\n dbName: context_1.AmbitenContext.getDbName(),\n collectionName: context_1.AmbitenContext.getCollectionName(),\n ...loggerMeta,\n ...meta\n };\n if (logger?.debug) {\n logger.debug(message, payload);\n return;\n }\n console.debug(`[AMBITEN_DEBUG] ${message}`, payload);\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ensureRedis = ensureRedis;\nconst redis_manager_1 = require(\"../redis-manager\");\nasync function ensureRedis() {\n let publisher = this.publisher;\n let subscriber = this.subscriber;\n try {\n const client = await redis_manager_1.redis.get();\n if (!client) {\n console.log('⚠️ Redis client not available from redis manager; skipping Redis initialization');\n return this;\n }\n if (!client.isOpen && typeof client.connect === 'function') {\n await client.connect();\n }\n if (!publisher) {\n publisher = typeof client.duplicate === 'function' ? client.duplicate() : client;\n if (publisher && typeof publisher.connect === 'function') {\n await publisher.connect();\n }\n this.publisher = publisher;\n }\n if (!subscriber) {\n subscriber = typeof client.duplicate === 'function' ? client.duplicate() : client;\n if (subscriber && typeof subscriber.connect === 'function') {\n await subscriber.connect();\n }\n this.subscriber = subscriber;\n }\n console.log('[info] Ensuring Redis connection...');\n console.log('[info] Redis connection established');\n return this;\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.log('[info] ⚠️ Redis connection skipped or failed:', message);\n return this;\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getTenantModel = void 0;\nconst builders_1 = require(\"../utils/builders\");\nconst MultiTenantManager_1 = require(\"./MultiTenantManager\");\nconst context_1 = require(\"../context\");\nconst tenantModelsCache = new Map();\nfunction createTenantProvider(tenantId, dbName) {\n return {\n async db(ctx) {\n const client = await MultiTenantManager_1.MultiTenantManager.getClient(tenantId);\n if (!client) {\n throw new Error(`Tenant \"${tenantId}\" not registered.`);\n }\n const resolvedDbName = ctx?.dbName ?? dbName;\n return resolvedDbName ? client.db(resolvedDbName) : client.db();\n },\n };\n}\nconst getTenantModel = async (params) => {\n const collectionName = params?.collectionName?.trim();\n const tenantId = params?.tenantId ?? context_1.AmbitenContext.getTenantId();\n if (!collectionName) {\n throw new Error(\"collectionName is required.\");\n }\n if (!tenantId) {\n throw new Error(\"tenantId is required to run tenant context\");\n }\n if (!tenantModelsCache.has(tenantId)) {\n tenantModelsCache.set(tenantId, new Map());\n }\n const tenantCache = tenantModelsCache.get(tenantId);\n const cacheKey = params.dbName\n ? `${collectionName}::${params.dbName}`\n : collectionName;\n if (tenantCache.has(cacheKey)) {\n return tenantCache.get(cacheKey);\n }\n const provider = createTenantProvider(tenantId, params.dbName);\n const model = (0, builders_1.Model)({\n collectionName,\n schema: params.schema,\n provider,\n });\n tenantCache.set(cacheKey, model);\n return model;\n};\nexports.getTenantModel = getTenantModel;\n// import { AmbitenSchema } from '../lib-core';\n// import { MultiTenantManager } from './MultiTenantManager';\n// import { TenantContext } from './TenantContext';\n// import { Model } from '../utils/builders/createModel';\n// import { ensureModelNameSafe } from '../utils/ensureModelNameSafe'; // <- wherever you put it\n// import { Document } from '../types';\n// import { Db } from 'mongodb';\n// type DbProvider = { db(ctx?: { dbName?: string }): Promise<Db> };\n// /**\n// * Parameters required to resolve a tenant-specific model.\n// * @template T - The type of the document in the model.\n// */\n// export type GetTanantModelParams<T extends Document> = {\n// collectionName: string;\n// tenantId: string;\n// schema?: AmbitenSchema<T>;\n// };\n// const tenantModelsCache: Map<string, Map<string, ReturnType<typeof Model>>> = new Map();\n// /**\n// * Resolves a tenant-specific model by creating or retrieving it from the cache.\n// * Ensures that each tenant has its own isolated model instance.\n// *\n// * @template T - The type of the document in the model.\n// * @param {GetTanantModelParams<T>} param - The parameters required to resolve the model.\n// * @param {string} param.modelName - The name of the model to resolve.\n// * @param {AmbitenSchema<T>} [param.schema] - The schema definition for the model (optional).\n// * @param {string} param.tenantId - The ID of the tenant for which the model is being resolved.\n// * @returns {Promise<any>} A promise that resolves to the tenant-specific model instance.\n// * @throws {Error} If no tenant context is found or the tenant is not registered.\n// * @example\n// * const userModel = await getTenantModel({\n// * modelName: 'User',\n// * schema: UserSchema,\n// * tenantId: 'tenant123'\n// * });\n// * // userModel is now a tenant-specific model for the 'User' collection in 'tenant123'\n// * @example\n// * const productModel = await getTenantModel({\n// * modelName: 'Product',\n// * schema: ProductSchema,\n// * tenantId: 'tenant456'\n// * });\n// */\n// export const getTenantModel = async <T extends Document>\n// (param: GetTanantModelParams<T>): Promise<any> => {\n// const safeCollectionName = ensureModelNameSafe(param.collectionName);\n// const schema = param.schema;\n// // const client = await MultiTenantManager.getClient(param.tenantId);\n// const tenantId = param.tenantId ?? TenantContext.getTenantId();\n// if (!tenantId) throw new Error('No tenant context found');\n// if (!tenantModelsCache.has(tenantId)) {\n// tenantModelsCache.set(tenantId, new Map());\n// }\n// const clientCache = tenantModelsCache.get(tenantId)!;\n// if (clientCache.has(safeCollectionName)) {\n// return clientCache.get(safeCollectionName);\n// }\n// const provider = tenantDbProvider(tenantId);\n// const model = Model({\n// collectionName: safeCollectionName,\n// schema,\n// provider: provider\n// });\n// clientCache.set(safeCollectionName, model as unknown as ReturnType<typeof Model>);\n// return model;\n// };\n","module.exports = require(\"mongodb\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.resolveRuntimeConfig = resolveRuntimeConfig;\nconst context_1 = require(\"../context\");\nconst resolveAmbitenOption_1 = require(\"./resolveAmbitenOption\");\nfunction resolveRuntimeConfig(input) {\n const ctx = context_1.AmbitenContext.get();\n return {\n tenantId: (0, resolveAmbitenOption_1.resolveAmbitenOption)([\n input.methodTenantId,\n ctx?.tenantId,\n input.modelTenantId\n ]),\n dbName: (0, resolveAmbitenOption_1.resolveAmbitenOption)([\n input.methodDbName,\n ctx?.dbName,\n input.modelDbName,\n input.clientDbName\n ]),\n collectionName: (0, resolveAmbitenOption_1.resolveAmbitenOption)([\n input.methodCollectionName,\n ctx?.collectionName,\n input.modelCollectionName\n ]),\n session: (0, resolveAmbitenOption_1.resolveAmbitenOption)([\n input.methodSession,\n ctx?.session,\n input.modelSession\n ]),\n requestId: ctx?.requestId,\n loggerMeta: ctx?.loggerMeta\n };\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.checkPermission = checkPermission;\nexports.getCachedData = getCachedData;\nexports.setCachedData = setCachedData;\nexports.invalidateTenantCache = invalidateTenantCache;\nexports.enforceRBAC = enforceRBAC;\nexports.getRBACAction = getRBACAction;\nexports.getOriginalResolver = getOriginalResolver;\nconst redis_manager_1 = require(\"../../redis-manager\");\nconst rbacTypes_1 = require(\"./rbacTypes\");\nfunction buildCacheKey(role, key) {\n if (Array.isArray(role)) {\n return `${role.join(',')}:${key}`;\n }\n if (role && typeof role === 'object') {\n if ('tenantId' in role)\n return `${role.tenantId}:${key}`;\n // If role is actually a role object or other shape, fallback to JSON-safe string\n try {\n const convertCredentials = JSON.parse(JSON.stringify(role));\n return `${convertCredentials}:${key}`;\n }\n catch (err) {\n return `${String(role)}:${key}`;\n }\n }\n return `${role}:${key}`;\n}\n;\n// const tenantCache: Map<string, any> = new Map();\n/**\n * Check if a user has a specific permission\n * @param role The role of the user\n * @param permission The permission to check\n * @returns A promise that resolves to true if the user has the permission, false otherwise\n * @example\n * const hasPermission = await checkPermission('admin', 'createUser');\n * if (hasPermission) {\n * // User has permission to create a user\n * } else {\n * // User does not have permission to create a user\n * }\n */\nasync function checkPermission(role, permission) {\n const cacheKey = buildCacheKey(role, 'permissions');\n let allowedActions = await getCachedData(role, 'permissions');\n if (!allowedActions) {\n console.info(`Cache miss for role \"${role}\". Fetching permissions...`);\n // Fetch permissions from the rolePermissions object\n allowedActions = rbacTypes_1.rolePermissions[role] || [];\n if (allowedActions.length > 0) {\n console.info(`Permissions found for role \"${role}\": ${allowedActions.join(', ')}`);\n }\n else {\n console.warn(`No permissions found for role \"${role}\"`);\n }\n }\n ;\n const cacheExists = await redis_manager_1.redis.exists(cacheKey);\n if (cacheExists) {\n console.info(`Cache hit for role \"${role}\"`);\n }\n // If allowedActions is not already cached, set it\n if (allowedActions) {\n allowedActions = Promise.resolve(rbacTypes_1.rolePermissions[role] || []);\n await setCachedData(role, 'permissions', await allowedActions, 500); // Cache for 500s\n }\n return Promise.resolve(rbacTypes_1.rolePermissions[role] || []).then(permissions => {\n if (permissions.includes(permission)) {\n console.info(`Permission granted for role \"${role}\" to perform action \"${permission}\"`);\n return true;\n }\n else {\n console.warn(`Permission denied for role \"${role}\" to perform action \"${permission}\"`);\n return false;\n }\n });\n}\n/**\n * Get cached data for a specific role and key\n * @param role The role or tenant object\n * @param key The key to retrieve from the cache\n * @return {Promise<any>} A promise that resolves to the cached data or null if not found\n * This function retrieves cached data from Redis based on the provided role and key.\n * It constructs a unique cache key using the role and key, checks if the data exists in the cache,\n * and returns the parsed data if found. If the data is not found, it logs a cache miss and returns null.\n * @throws {Error} If there is an issue with the Redis operation\n * @example\n * // Get cached permissions for role 'admin'\n * const cachedPermissions = await getCachedData('admin', 'permissions');\n * if (cachedPermissions) {\n * console.log('Cached permissions:', cachedPermissions);\n * } else {\n * console.log('No cached permissions found');\n * }\n */\nasync function getCachedData(role, key) {\n const cacheKey = buildCacheKey(role, key);\n const cachedData = await redis_manager_1.redis.get(cacheKey);\n if (cachedData) {\n console.info(`Cache hit for key \"${cacheKey}\"`);\n }\n else {\n console.warn(`Cache miss for key \"${cacheKey}\"`);\n }\n try {\n return cachedData ? JSON.parse(JSON.stringify(cachedData)) : null;\n }\n catch (err) {\n console.warn(`Failed to parse cached data for key ${cacheKey}:`, err);\n // If parsing fails, return raw value to avoid crashing\n return cachedData;\n }\n}\n;\nasync function setCachedData(role, key, data, ttl) {\n // Build a consistent cache key and store JSON-stringified data with TTL\n const cacheKey = buildCacheKey(role, key);\n try {\n await redis_manager_1.redis?.set(cacheKey, JSON.stringify(data), { EX: ttl });\n console.info(`Cache set for ${cacheKey}:`, data);\n }\n catch (err) {\n console.error(`Failed to set cache for ${cacheKey}:`, err);\n }\n // Only log permissions if role is a string or array with values\n let roleKey;\n if (typeof role === 'string') {\n roleKey = role;\n }\n else if (Array.isArray(role) && role.length > 0) {\n roleKey = role[0];\n }\n else if (role && typeof role === 'object' && 'tenantId' in role) {\n roleKey = role.tenantId;\n }\n if (roleKey) {\n const permissions = rbacTypes_1.rolePermissions[roleKey] || [];\n if (permissions.length > 0) {\n console.info(`Permissions cached for role \"${roleKey}\": ${permissions.join(', ')}`);\n }\n else {\n console.warn(`No permissions found for role \"${roleKey}\" to cache`);\n }\n }\n else {\n console.warn(`Role key is not a string, cannot cache permissions`);\n }\n return;\n}\n/**\n * Invalidate the cache for a specific tenant and role\n * @param tenantId The ID of the tenant\n * @param role The role to invalidate cache for\n * @return {Promise<void>}\n * This function removes the cached permissions for the specified tenant and role.\n * It is useful when permissions change and you want to ensure the cache reflects the latest state.\n * It logs the invalidation action and deletes the cache entry from Redis.\n * This is particularly important in multi-tenant applications where each tenant may have different permissions.\n * @throws {Error} If there is an issue with the Redis operation\n * @example\n * // Invalidate cache for tenant 'tenant123' with role 'admin'\n * await invalidateTenantCache('tenant123', 'admin');\n */\nasync function invalidateTenantCache(tenantId, role) {\n try {\n const cacheKey = `${tenantId}:permissions:${role}`;\n const cacheExists = await redis_manager_1.redis.exists(cacheKey);\n if (cacheExists) {\n await redis_manager_1.redis.del(cacheKey);\n console.info(`Cache invalidated for tenant ${tenantId} and role ${role}`);\n }\n else {\n console.warn(`No cache found for tenant ${tenantId} and role ${role}`);\n }\n }\n catch (error) {\n console.error(`Error invalidating cache for tenant ${tenantId} and role ${role}:`, error);\n throw new Error(`Failed to invalidate cache for tenant ${tenantId} and role ${role}`);\n }\n return;\n}\n/**\n * Middleware to enforce RBAC (Role-Based Access Control) on GraphQL resolvers\n * @param resolver The original resolver function\n * @param permission The required permission for the action\n * @returns A wrapped resolver function that checks permissions\n * @throws {Error} If the user does not have the required permission\n * @example\n * // Wrap a resolver with RBAC enforcement\n * const securedResolver = enforceRBAC(originalResolver, 'createUser');\n *\n * // Use the secured resolver in your GraphQL schema\n * const resolvers = {\n * Mutation: {\n * createUser: securedResolver,\n * \t}, };\n *\n * In this example, the `enforceRBAC` function wraps the `originalResolver` and checks if the user has the 'createUser' permission before allowing access to the resolver. If the user lacks the required permission, an error is thrown, preventing unauthorized access.\n * * This middleware is essential for implementing fine-grained access control in GraphQL APIs, ensuring that only authorized users can perform specific actions based on their roles and permissions.\n * @remarks This function is designed to be used in GraphQL resolvers to enforce role-based access control (RBAC). It checks if the user has the necessary permissions before allowing access to the resolver function. If the user lacks the required permission, an error is thrown, preventing unauthorized access.\n * * @see {@link checkPermission} for checking user permissions\n * * @see {@link Role} and {@link Permission} for role and permission types\n * * @see {@link rolePermissions} for the mapping of roles to permissions\n * * @see {@link getCachedData} and {@link setCachedData} for caching permissions\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nfunction enforceRBAC(resolver, permission) {\n const wrapped = async (parent, args, context, info) => {\n const { user } = context;\n // Ensure we pass the user's role (string) and await the async permission check\n if (!user || !(await checkPermission(user.role, permission))) {\n throw new Error('Unauthorized: You do not have permission to perform this action.');\n }\n return await resolver(parent, args, context, info);\n };\n // Preserve function name (useful for logging, debugging)\n Object.defineProperty(wrapped, 'name', {\n value: resolver.name || 'anonymous',\n writable: false,\n configurable: true,\n });\n // Attach metadata\n wrapped.__originalResolver = resolver;\n wrapped.__rbacAction = permission;\n return wrapped;\n}\n/**\n * Get the RBAC action from a wrapped resolver\n * @param resolver The wrapped resolver function\n * @returns The RBAC action\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nfunction getRBACAction(resolver) {\n return resolver.__rbacAction || null;\n}\n/**\n * Get the original resolver function from a wrapped resolver\n * @param resolver The wrapped resolver function\n * @returns The original resolver function\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nfunction getOriginalResolver(resolver) {\n return resolver.__originalResolver || resolver;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.loadAmbitenConfig = loadAmbitenConfig;\nconst tslib_1 = require(\"tslib\");\nconst fs_extra_1 = tslib_1.__importDefault(require(\"fs-extra\"));\nconst path_1 = tslib_1.__importDefault(require(\"path\"));\nconst ajv_1 = tslib_1.__importDefault(require(\"ajv\"));\nconst ambiten_config_schema_json_1 = tslib_1.__importDefault(require(\"./ambiten.config.schema.json\"));\nconst ajv = new ajv_1.default({\n allErrors: true,\n useDefaults: true,\n strict: false,\n coerceTypes: true,\n});\nlet validate = null;\nconst DEFAULT_CONFIG_FILENAME = 'ambiten.config.json';\nfunction normalizeAmbitenConfig(rawConfig) {\n const cfg = { ...rawConfig };\n if (typeof cfg.logger === 'boolean') {\n cfg.logger = { enabled: cfg.logger };\n }\n if (cfg.logger && typeof cfg.logger === 'object') {\n if (typeof cfg.logger.enableMetrics === 'boolean') {\n cfg.logger.enableMetrics = {\n enabled: cfg.logger.enableMetrics,\n logInterval: 60000,\n };\n }\n if (!cfg.logger.enableMetrics) {\n cfg.logger.enableMetrics = {\n enabled: false,\n logInterval: 60000,\n };\n }\n if (typeof cfg.logger.compressLogFiles === 'boolean') {\n cfg.logger.compressLogFiles = {\n enabled: cfg.logger.compressLogFiles,\n };\n }\n if (!cfg.logger.compressLogFiles) {\n cfg.logger.compressLogFiles = {\n enabled: false,\n };\n }\n }\n if (typeof cfg.graphql === 'boolean') {\n cfg.graphql = { enabled: cfg.graphql };\n }\n if (typeof cfg.advanced === 'boolean') {\n cfg.advanced = {\n garbageCollector: { enabled: cfg.advanced },\n };\n }\n if (cfg.advanced && typeof cfg.advanced.garbageCollector === 'boolean') {\n cfg.advanced.garbageCollector = {\n enabled: cfg.advanced.garbageCollector,\n };\n }\n if (!cfg.features) {\n cfg.features = {};\n }\n if (typeof cfg.features.useRedisCache === 'undefined') {\n cfg.features.useRedisCache = false;\n }\n return cfg;\n}\nfunction assertValidAmbitenConfig(config) {\n if (!config.connection?.uri) {\n throw new Error('Invalid config: \"connection.uri\" is required.');\n }\n if (config.multiTenant?.enabled &&\n config.multiTenant.tenants &&\n typeof config.multiTenant.tenants !== 'object') {\n throw new Error('Invalid config: \"multiTenant.tenants\" must be a tenant-to-URI map.');\n }\n}\nasync function loadAmbitenConfig(configPath) {\n const candidates = configPath\n ? [path_1.default.resolve(configPath)]\n : [\n path_1.default.resolve(process.cwd(), DEFAULT_CONFIG_FILENAME),\n path_1.default.resolve(process.cwd(), 'config', DEFAULT_CONFIG_FILENAME),\n path_1.default.resolve(process.cwd(), 'src', 'config', DEFAULT_CONFIG_FILENAME),\n path_1.default.resolve(__dirname, DEFAULT_CONFIG_FILENAME),\n path_1.default.resolve(__dirname, '..', DEFAULT_CONFIG_FILENAME),\n ];\n let finalPath;\n for (const candidate of candidates) {\n if (await fs_extra_1.default.pathExists(candidate)) {\n finalPath = candidate;\n break;\n }\n }\n if (!finalPath) {\n throw new Error(`Config file not found at any of: ${candidates.join(', ')}`);\n }\n let parsed;\n try {\n const raw = await fs_extra_1.default.readFile(finalPath, 'utf-8');\n parsed = normalizeAmbitenConfig(JSON.parse(raw));\n }\n catch (err) {\n throw new Error(`[Ambiten] Failed to parse config file: ${err}`);\n }\n if (!validate) {\n validate = ajv.compile(ambiten_config_schema_json_1.default);\n }\n const isValid = validate(parsed);\n if (!isValid) {\n console.error(JSON.stringify(validate.errors, null, 2));\n const errors = validate.errors\n ?.map((e) => {\n const location = e.instancePath || '(root)';\n const extra = e.keyword === 'additionalProperties'\n ? `: ${e.params.additionalProperty}`\n : '';\n return `${location} ${e.message}${extra}`;\n })\n .join('; ');\n throw new Error(`[Ambiten] Invalid configuration: ${errors}`);\n }\n assertValidAmbitenConfig(parsed);\n parsed.graphql ??= { enabled: false };\n parsed.features ??= { useRedisCache: false };\n parsed.advanced ??= {\n circuitBreaker: { enabled: false },\n garbageCollector: { enabled: false },\n };\n return parsed;\n}\n;\n","module.exports = require(\"node-cron\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.now = exports.isValidDuration = exports.formatDuration = exports.parseDuration = void 0;\nconst parseDuration = (duration) => {\n const match = duration.match(/^(\\d+)([smhd])$/);\n const isValid = (0, exports.isValidDuration)(duration);\n if (!match || !isValid) {\n throw new Error(`Invalid duration format: ${duration}. Expected format is <number><unit> where unit is one of 's', 'm', 'h', or 'd'.`);\n }\n const value = parseInt(match[1], 10);\n const unit = match[2];\n switch (unit) {\n case 's': return value * 1000; // seconds to milliseconds\n case 'm': return value * 60 * 1000; // minutes to milliseconds\n case 'h': return value * 60 * 60 * 1000; // hours to milliseconds\n case 'd': return value * 24 * 60 * 60 * 1000; // days to milliseconds\n default: throw new Error(`Unknown time unit: ${unit}`);\n }\n};\nexports.parseDuration = parseDuration;\nconst formatDuration = (ms) => {\n const seconds = Math.floor(ms / 1000);\n const minutes = Math.floor(seconds / 60);\n const hours = Math.floor(minutes / 60);\n const days = Math.floor(hours / 24);\n if (days > 0)\n return `${days}d`;\n if (hours > 0)\n return `${hours}h`;\n if (minutes > 0)\n return `${minutes}m`;\n return `${seconds}s`;\n};\nexports.formatDuration = formatDuration;\nconst isValidDuration = (duration) => {\n return /^(\\d+)([smhd])$/.test(duration);\n};\nexports.isValidDuration = isValidDuration;\nexports.now = new Date();\n","module.exports = __WEBPACK_EXTERNAL_MODULE__2947__;","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenError = void 0;\nexports.createAmbitenError = createAmbitenError;\nclass AmbitenError extends Error {\n type;\n details;\n constructor(options) {\n super(options.message, { cause: options.cause });\n this.name = options.type;\n this.type = options.type;\n this.details = options.details;\n Error.captureStackTrace?.(this, AmbitenError);\n }\n toJSON() {\n return {\n name: this.name,\n type: this.type,\n message: this.message,\n details: this.details,\n cause: this.cause instanceof Error\n ? {\n name: this.cause.name,\n message: this.cause.message\n }\n : this.cause\n };\n }\n}\nexports.AmbitenError = AmbitenError;\nfunction createAmbitenError(type, message, options = {}) {\n return new AmbitenError({\n type,\n message,\n cause: options.cause,\n details: options.details\n });\n}\n;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenBootstrapFactory = void 0;\nconst config_1 = require(\"../../config\");\nconst logger_1 = require(\"@ambiten/logger\");\nconst index_1 = require(\"../index\");\nconst __1 = require(\"../..\");\nconst redis_manager_1 = require(\"../../redis-manager\");\nconst utils_1 = require(\"../../utils\");\nconst tanancy_1 = require(\"../../tanancy\");\nconst gc_1 = require(\"../../gc\");\nconst invalidateTenantCache_1 = require(\"../../utils/invalidateTenantCache\");\n/**\n * AmbitenBootstrap is the main entry point for initializing\n * and managing the Ambiten application stack when you opt for the CLI.\n * It handles MongoDB, Redis, and GraphQL setup,\n * along with custom hooks for post-connection logic.\n * @example\n *\n * ```bash\n * npx Ambiten-core my-project\n * cd my-project\n * ```\n *\n * This will create a new Ambiten project in the 'my-project' directory.\n * You can then customize the configuration file and start using Ambiten in your application.\n *\n * ---\n *\n * Add flags as needed:\n *\n * ```bash\n * npx Ambiten init my-app --with-graphql --multi-tenant --with-redis\n * cd my-app\n * ```\n * This will create a new Ambiten project with Redis caching, GraphQL support, and multi-tenancy enabled.\n * enabling them in the configuration file.\n *\n * ---\n *\n * You can also use AmbitenBootstrap programmatically in your application:\n * ```ts\n * @example\n * import { AmbitenBootstrapFactory } from '@Ambiten/core';\n * async function start() {\n * const Ambiten = await AmbitenBootstrapFactory.create();\n * const db = Ambiten.getMongoClient();\n * await db.connect();\n * const graphql = await Ambiten.getGraphQL();\n * // You can now use the GraphQL instance to generate schema or start a server\n * // or perform other GraphQL related operations\n * graphql.generateSchema();\n * Ambiten.getRedisClient();\n * }\n * start();\n * ```\n *\n *\n * @param {string} [configFilePathOrObject] - Optional path to a custom configuration file or a config object.\n * If not provided, it defaults to 'Ambiten.config.json'.\n * @returns {Promise<void>} - A promise that resolves when the initialization is complete.\n *\n * // Now you can use Ambiten.getMongoClient(), Ambiten.getRedisClient(), etc.\n */\nclass AmbitenBootstrap {\n config;\n provider;\n model;\n schema;\n graphql;\n gc;\n logger;\n adapter;\n onConnectHooks = [];\n connectCallbacks = [];\n isConnected;\n constructor(adapter) {\n this.adapter = adapter;\n }\n onConnect(callback) {\n if (!this.isConnected) {\n callback();\n return;\n }\n this.connectCallbacks.push(callback);\n }\n /**\n * Initializes the Ambiten application stack.\n */\n async initialize(configFilePathOrObject) {\n this.config =\n configFilePathOrObject && typeof configFilePathOrObject === 'object'\n ? configFilePathOrObject\n : await (0, config_1.loadAmbitenConfig)(configFilePathOrObject);\n this.initializeLogger();\n await this.initializeRedis();\n await this.initializeMongoProvider();\n this.initializeSchema();\n await this.initializeModel();\n await this.initializeMultiTenancy();\n await this.initializeGraphQL();\n await this.runOnConnectHooks();\n await this.initializeGarbageCollector();\n }\n initializeLogger() {\n const loggerConfig = this.config.logger;\n const defaultTransportConfigs = [\n { type: 'console', options: {} },\n {\n type: 'rotating-file',\n options: {\n filename: './logs/ambiten.log',\n frequency: 'daily',\n compress: false,\n flushInterval: 1000,\n },\n },\n ];\n this.logger = (0, logger_1.setupLogger)({\n ...loggerConfig,\n transports: undefined,\n transportConfigs: loggerConfig?.transportConfigs?.length\n ? loggerConfig.transportConfigs\n : defaultTransportConfigs,\n });\n this.logger.info('Logger initialized', {\n source: 'AmbitenBootstrap',\n });\n }\n async initializeRedis() {\n if (!this.config.features?.useRedisCache || !this.config.features.redisUri) {\n return;\n }\n await redis_manager_1.redis.get(this.config.features.redisUri);\n this.getLogger().info('Redis connected', {\n source: 'AmbitenBootstrap'\n });\n }\n async initializeMongoProvider() {\n const resolvedDbName = this.config.connection?.options?.dbName ||\n this.config.projectName ||\n undefined;\n this.provider =\n this.config.mongoClient ??\n this.config.provider ??\n (0, index_1.createAmbitenClientModule)({\n uri: this.config.connection?.uri || 'mongodb://localhost:27017',\n options: {\n dbName: resolvedDbName,\n ...this.config.connection?.options,\n },\n });\n await this.provider.connect();\n (0, utils_1.configureAmbitenContext)(this.provider);\n if (this.logger) {\n this.getLogger().info('MongoDB connected via AmbitenClientModule', {\n source: 'AmbitenBootstrap'\n });\n }\n else {\n console.log((0, utils_1.colorize)('MongoDB connected via AmbitenClientModule', 'blue'));\n }\n }\n initializeSchema() {\n this.schema = new index_1.Schema(typeof this.config.schema === 'object'\n ? this.config.schema\n : {});\n if (this.config.schema) {\n this.schema.registerSchema(this.config.schema);\n this.getLogger().info('Schema registered', { source: 'AmbitenBootstrap' });\n }\n else {\n this.getLogger().warn('No schema provided, using default schema', { source: 'AmbitenBootstrap' });\n }\n }\n async initializeModel() {\n const collectionName = this.config.model?.collectionName || 'default';\n this.model = (0, utils_1.Model)({\n collectionName,\n schema: this.schema,\n provider: this.provider,\n ctx: this.config.model?.ctx,\n collection: this.config.model?.collection,\n gcConfig: this.config.model?.gcConfig,\n });\n if (this.config.model) {\n await this.model.registerModel({\n ...this.config.model,\n collectionName,\n schema: this.schema,\n provider: this.provider,\n });\n if (this.logger) {\n this.getLogger().info(`Model registered: ${collectionName}`, {\n source: 'AmbitenBootstrap'\n });\n }\n else {\n console.log((0, utils_1.colorize)(`Model registered: ${collectionName}`, 'blue'));\n }\n }\n }\n async initializeMultiTenancy() {\n if (!this.config.multiTenant?.enabled)\n return;\n const tenants = this.config.multiTenant.tenants || {};\n const initOptions = this.config.multiTenant.initOptions || {};\n await (0, tanancy_1.initMultiTenancy)(tenants, initOptions);\n this.getLogger().info('Multi-tenancy initialized', {\n source: 'AmbitenBootstrap',\n tenantCount: Object.keys(tenants).length,\n lazy: initOptions.lazy ?? false,\n });\n }\n async initializeGraphQL() {\n if (!this.config.graphql?.enabled) {\n return;\n }\n this.graphql = new __1.AmbitenGraphQL({\n useRedis: this.config.features?.useRedisCache ?? false,\n customTypeDefs: this.config.features?.typeDefs\n ? Array.isArray(this.config.features.typeDefs)\n ? this.config.features.typeDefs\n : [this.config.features.typeDefs]\n : [],\n customResolvers: this.config.features?.resolvers\n ? Array.isArray(this.config.features.resolvers)\n ? this.config.features.resolvers\n : [this.config.features.resolvers]\n : [],\n provider: this.provider\n });\n await this.graphql.generateSchema();\n if (this.logger) {\n this.getLogger().info('GraphQL schema generated');\n this.getLogger().info('GraphQL initialized');\n }\n else {\n console.log((0, utils_1.colorize)('GraphQL schema generated', 'blue'));\n console.log((0, utils_1.colorize)('GraphQL initialized', 'blue'));\n }\n }\n async runOnConnectHooks() {\n for (const hook of this.onConnectHooks) {\n await hook();\n }\n }\n async initializeGarbageCollector() {\n if (!this.config.advanced?.garbageCollector?.enabled)\n return;\n this.gc = new gc_1.AmbitenGC({\n enabled: this.config.advanced.garbageCollector.enabled ?? true,\n cron: this.config.advanced.gcCron || '0 0 * * *',\n logResults: this.config.advanced.garbageCollector.logResults ?? true,\n continueOnError: true\n });\n console.log('✅ Garbage Collector initialized');\n }\n async registerMultiTenancy(options) {\n const multiTenantConfig = this.config.multiTenant;\n const logger = this.config.logger?.logger;\n if (!multiTenantConfig?.enabled) {\n logger?.warn('Multi-tenancy is not enabled.', {\n source: 'AmbitenBootstrap',\n });\n return;\n }\n const tenants = options?.tenants ?? multiTenantConfig.tenants;\n if (!tenants || Object.keys(tenants).length === 0) {\n logger?.warn('Multi-tenancy is enabled but no tenants were provided.', {\n source: 'AmbitenBootstrap',\n });\n return;\n }\n await (0, tanancy_1.initMultiTenancy)(tenants, {\n lazy: options?.lazy ?? multiTenantConfig.initOptions?.lazy ?? true,\n config: this.config.logger,\n });\n logger?.info('Multi-tenancy registered successfully.', {\n source: 'AmbitenBootstrap',\n tenantCount: Object.keys(tenants).length,\n });\n }\n async cache(key, fetcher, options = {}) {\n if (!redis_manager_1.redis) {\n throw new Error('Redis is not initialized');\n }\n return (0, utils_1.cacheWithRedis)(redis_manager_1.redis, key, fetcher, options);\n }\n async invalidateCache(tenantId, namespace) {\n if (!redis_manager_1.redis) {\n throw new Error('No Redis client available');\n }\n const logger = this.config.logger?.logger;\n if (!tenantId) {\n throw new Error('Tenant ID is required to invalidate cache');\n }\n logger?.info('Invalidating cache for tenant:', {\n source: 'AmbitenBootstrap',\n tenantId,\n namespace: namespace\n });\n await (0, invalidateTenantCache_1.invalidateTenantCache)(redis_manager_1.redis, tenantId, namespace);\n }\n /**\n * Returns the Redis client if Redis is enabled in the configuration.\n */\n async getRedisClient() {\n if (this.config.features?.useRedisCache && this.config.features.redisUri) {\n await redis_manager_1.redis.get(this.config.features.redisUri);\n }\n return redis_manager_1.redis;\n }\n getMongoClient() {\n return this.provider;\n }\n getModel() {\n return this.model;\n }\n getSchema() {\n return this.schema;\n }\n getGraphQL() {\n if (!this.graphql) {\n throw new Error('GraphQL is not initialized.');\n }\n return this.graphql;\n }\n getGCRunner() {\n if (!this.gc) {\n throw new Error('Garbage Collector is not initialized.');\n }\n return this.gc;\n }\n getLogger() {\n return this.logger;\n }\n async shutdown() {\n const logger = this.config.logger?.logger;\n if (redis_manager_1.redis.isOpen) {\n await redis_manager_1.redis.disconnect();\n logger?.info('🧹 Redis connection closed', {\n source: 'AmbitenBootstrap'\n });\n }\n if (this.provider) {\n await this.provider.close();\n logger?.log?.('info', 'MongoDB connection closed');\n }\n logger?.log?.('info', 'Shutdown complete');\n }\n}\n;\n/**\n * Factory class to create an instance of AmbitenBootstrap.\n * This class encapsulates the logic for initializing the Ambiten application stack,\n * including MongoDB, Multi-Tenancy, Redis, GraphQL logger etc. setup.\n * It can be used to create a fully configured Ambiten instance\n * with optional configuration parameters.\n * @example\n * const Ambiten = await AmbitenBootstrapFactory.create();\n * const db = Ambiten.getMongoClient();\n * await db.connect();\n * const graphql = await Ambiten.getGraphQL();\n * // You can now use the GraphQL instance to generate schema or start a server\n * // or perform other GraphQL related operations\n * graphql.generateSchema();\n * Ambiten.getRedisClient();\n * // or with custom config\n * const Ambiten = await AmbitenBootstrapFactory.create(customConfig);\n * @param {AmbitenConfig} [config] - Optional configuration object for Ambiten.\n * @returns {Promise<AmbitenBootstrap>} - A promise that resolves to an instance of AmbitenBootstrap.\n */\nclass AmbitenBootstrapFactory {\n static async create(options = {}) {\n const bootstrap = new AmbitenBootstrap(options.adapter);\n await bootstrap.initialize(options.config);\n return bootstrap;\n }\n}\nexports.AmbitenBootstrapFactory = AmbitenBootstrapFactory;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenContext = void 0;\nconst node_async_hooks_1 = require(\"node:async_hooks\");\nconst runManualTransaction_1 = require(\"./helpers/runManualTransaction\");\nconst DEFAULT_AMBITEN_BUDGET = {\n maxQueries: Infinity,\n queriesExecuted: 0,\n totalTimeMs: 0\n};\nclass AmbitenContextManager {\n storage = new node_async_hooks_1.AsyncLocalStorage();\n transactionResolver;\n run(context, callback) {\n const parent = this.storage.getStore() ?? {};\n const merged = {\n ...parent,\n ...context,\n budget: context.budget\n ? this.normalizeBudget(context.budget)\n : parent.budget\n ? this.normalizeBudget(parent.budget)\n : undefined\n };\n return this.storage.run(merged, callback);\n }\n get() {\n return this.storage.getStore() ?? {};\n }\n hasActiveContext() {\n return this.storage.getStore() !== undefined;\n }\n set(patch) {\n const current = this.storage.getStore();\n if (!current)\n return;\n Object.assign(current, patch);\n }\n clear() {\n const current = this.storage.getStore();\n if (!current)\n return;\n for (const key of Object.keys(current)) {\n delete current[key];\n }\n }\n configureTransactionResolver(resolver) {\n this.transactionResolver = resolver;\n }\n getTenantId() {\n return this.get().tenantId;\n }\n getRequestId() {\n return this.get().requestId;\n }\n getDbName() {\n return this.get().dbName;\n }\n getCollectionName() {\n return this.get().collectionName;\n }\n getSession() {\n return this.get().session;\n }\n getLogger() {\n return this.get().logger;\n }\n getLoggerMeta() {\n return this.get().loggerMeta;\n }\n getObserver() {\n return this.get().observer;\n }\n normalizeBudget(budget) {\n return {\n maxQueries: budget?.maxQueries ?? DEFAULT_AMBITEN_BUDGET.maxQueries,\n queriesExecuted: budget?.queriesExecuted ?? DEFAULT_AMBITEN_BUDGET.queriesExecuted,\n totalTimeMs: budget?.totalTimeMs ?? DEFAULT_AMBITEN_BUDGET.totalTimeMs\n };\n }\n getBudget() {\n const state = this.get();\n const normalized = this.normalizeBudget(state.budget);\n state.budget = normalized;\n return normalized;\n }\n setBudget(budget) {\n const state = this.get();\n state.budget = this.normalizeBudget(budget);\n }\n assertQueryBudget() {\n const state = this.get();\n const budget = this.getBudget();\n if (budget.queriesExecuted >= budget.maxQueries) {\n throw new Error(`[Ambiten] Tenant ${state.tenantId ?? 'unknown'} exceeded query budget for this request.`);\n }\n }\n incrementQueries() {\n this.assertQueryBudget();\n const budget = this.getBudget();\n budget.queriesExecuted += 1;\n return budget;\n }\n addQueryTime(durationMs) {\n const budget = this.getBudget();\n budget.totalTimeMs += durationMs;\n return budget;\n }\n isDebug() {\n const ctx = this.get();\n return Boolean(ctx.debug ||\n process.env.AMBITEN_DEBUG === 'true' ||\n process.env.AMBITEN_DEBUG === '1');\n }\n async withTransaction(callback) {\n const current = this.get();\n if (current.session) {\n return callback(current.session);\n }\n if (!this.transactionResolver) {\n throw new Error('AmbitenContext transaction resolver is not configured.');\n }\n const client = await this.transactionResolver.resolveClient(current.tenantId, current.dbName);\n if (!client) {\n throw new Error(`No MongoClient available for${current.tenantId ? ` tenant \"${current.tenantId}\"` : ' current context'}.`);\n }\n const session = client.startSession();\n if (typeof session.withTransaction === 'function') {\n try {\n let result;\n await session.withTransaction(async () => {\n result = await this.run({ session }, () => callback(session));\n return result;\n });\n return result;\n }\n finally {\n await session.endSession();\n }\n }\n return this.run({ session }, () => (0, runManualTransaction_1.runManualTransaction)(session, callback));\n }\n hasTransactionResolver() {\n return Boolean(this.transactionResolver);\n }\n}\nexports.AmbitenContext = new AmbitenContextManager();\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenCache\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenConfig\"), exports);\ntslib_1.__exportStar(require(\"./schema.type\"), exports);\ntslib_1.__exportStar(require(\"./ambiten.model.type\"), exports);\ntslib_1.__exportStar(require(\"./user.type\"), exports);\ntslib_1.__exportStar(require(\"./ambiten.client.type\"), exports);\ntslib_1.__exportStar(require(\"./document\"), exports);\ntslib_1.__exportStar(require(\"./event.type\"), exports);\ntslib_1.__exportStar(require(\"./graphql.type\"), exports);\ntslib_1.__exportStar(require(\"./GCConfig\"), exports);\ntslib_1.__exportStar(require(\"./logger.types\"), exports);\ntslib_1.__exportStar(require(\"./db.provider\"), exports);\ntslib_1.__exportStar(require(\"./result.utils.types\"), exports);\ntslib_1.__exportStar(require(\"./bootstrapClient.type\"), exports);\ntslib_1.__exportStar(require(\"./middleware/types\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.measureQueryForBrowser = measureQueryForBrowser;\nasync function measureQueryForBrowser(_meta, executor) {\n return executor();\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getTenantDB = void 0;\nconst lib_core_1 = require(\"../../lib-core\");\nconst dbCache = new Map();\n/**\n * Retrieves the database instance for a specific tenant.\n * If the database is already cached, it returns the cached instance.\n * Otherwise, it initializes a new database connection for the tenant, caches it, and returns it.\n *\n * @param {string} tenantId - The ID of the tenant whose database is to be retrieved.\n * @returns {Promise<Db>} A promise that resolves to the MongoDB database instance for the tenant.\n * @throws {Error} If the database for the specified tenant is not found.\n */\nconst getTenantDB = async (tenantId) => {\n if (dbCache.has(tenantId)) {\n return dbCache.get(tenantId);\n }\n const db = lib_core_1.AmbitenClient.init().withDatabase(tenantId);\n if (!db)\n throw new Error(`Database not found for tenant: ${tenantId}`);\n dbCache.set(tenantId, await db.db());\n return await db.db();\n};\nexports.getTenantDB = getTenantDB;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./redisClient\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.runGarbageCollectorOnAllModels = runGarbageCollectorOnAllModels;\nexports.runGarbageCollector = runGarbageCollector;\nconst ModelRegistry_1 = require(\"../utils/ModelRegistry\");\nconst utils_1 = require(\"../utils\");\n/**\n * Runs garbage collection on all registered Ambiten model instances.\n *\n * This delegates cleanup to each model's `runGC()` method so the operation\n * remains context-aware and preserves middleware, schema hooks, query\n * instrumentation, cache invalidation, and event publishing.\n *\n * @param options - Optional garbage collection execution options.\n * @returns Summary of the garbage collection run.\n */\nasync function runGarbageCollectorOnAllModels(options = {}) {\n const models = ModelRegistry_1.AmbitenModelRegistry.getAllModels();\n const result = {\n scanned: models.length,\n succeeded: 0,\n failed: 0,\n models: []\n };\n for (const model of models) {\n const modelContext = model.getContext?.();\n const collectionName = modelContext?.ctx?.collectionName;\n try {\n if (typeof model.runGC !== 'function') {\n throw new Error('Registered model does not implement runGC().');\n }\n await model.runGC(options.ctx);\n result.succeeded += 1;\n result.models.push({\n collectionName,\n success: true\n });\n }\n catch (error) {\n result.failed += 1;\n result.models.push({\n collectionName,\n success: false,\n error\n });\n console.error((0, utils_1.colorize)(`[GC] Failed on collection \"${collectionName ?? 'unknown'}\"`, 'red'), error);\n if (!options.continueOnError) {\n throw error;\n }\n }\n }\n return result;\n}\n/**\n * Runs garbage collection on a single Ambiten model instance.\n *\n * @param model - Registered Ambiten model instance.\n * @param ctx - Optional model execution context.\n */\nasync function runGarbageCollector(model, ctx) {\n await model.runGC(ctx);\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./measureQueryWithErrors\"), exports);\ntslib_1.__exportStar(require(\"./measureQuery.browser\"), exports);\n","module.exports = __WEBPACK_EXTERNAL_MODULE__3911__;","module.exports = require(\"graphql-subscriptions\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.cacheWithRedis = cacheWithRedis;\nconst ambiten_cache_1 = require(\"../ambiten-cache\");\n/**\n * Caches a value in Redis with optional tenant and namespace scoping.\n * If the value is not found in cache, it runs the provided fetcher function\n * to get the value, caches it, and then returns it.\n *\n * @param {string} key - The cache key to use.\n * @param {() => Promise<T>} fetcher - A function that fetches the value if not cached.\n * @param {AmbitenCacheOptions} options - Options for caching behavior.\n * @returns {Promise<T>} - The cached or fetched value.\n * @example\n * const value = await cacheWithRedis(redisClient, 'myKey', async () => {\n * // Fetch from database or external API\n * return await fetchDataFromSource();\n */\nasync function cacheWithRedis(client, key, fetcher, options = {}) {\n const cache = new ambiten_cache_1.AmbitenCache(client);\n return await cache.wrap(key, fetcher, options);\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.generateProject = generateProject;\nexports.generateProjectWithConfig = generateProjectWithConfig;\nconst tslib_1 = require(\"tslib\");\nconst fs_extra_1 = tslib_1.__importDefault(require(\"fs-extra\"));\nconst path_1 = tslib_1.__importDefault(require(\"path\"));\nconst templates_1 = require(\"../templates\");\nconst utils_1 = require(\"../utils\");\nasync function generateProject(options) {\n const startedAt = Date.now();\n const projectName = options.projectName?.trim() || 'Ambiten-app';\n const projectRoot = path_1.default.resolve(process.cwd(), projectName);\n const configPath = path_1.default.join(projectRoot, 'Ambiten.config.json');\n const entryFilePath = path_1.default.join(projectRoot, 'src', 'main.ts');\n console.log((0, utils_1.colorize)(`\\n🚀 Creating project \"${projectName}\"`, 'green'));\n console.log((0, utils_1.colorize)(`📁 Location: ${projectRoot}\\n`, 'blue'));\n await fs_extra_1.default.ensureDir(projectRoot);\n const logger = (0, utils_1.createScaffoldLogger)(projectRoot);\n const resolvedOptions = {\n ...options,\n projectName,\n };\n await (0, templates_1.generateAppStructure)(projectRoot, resolvedOptions, logger);\n const durationMs = Date.now() - startedAt;\n logger.printSummary(projectName, resolvedOptions, durationMs);\n return {\n projectRoot,\n configPath,\n entryFilePath,\n };\n}\nasync function generateProjectWithConfig(config) {\n return generateProject({\n ...config,\n projectName: config.projectName || 'Ambiten-app',\n });\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createScaffoldLogger = createScaffoldLogger;\nconst tslib_1 = require(\"tslib\");\nconst path_1 = tslib_1.__importDefault(require(\"path\"));\nconst color_palatte_1 = require(\"./color-palatte\");\nfunction createScaffoldLogger(projectRoot) {\n const log = {\n files: [],\n dirs: [],\n };\n const normalize = (p) => path_1.default.relative(projectRoot, p).replace(/\\\\/g, '/');\n return {\n addFile(filePath) {\n log.files.push(normalize(filePath));\n },\n addDir(dirPath) {\n log.dirs.push(normalize(dirPath) + '/');\n },\n printSummary(projectName, options, durationMs) {\n const enabledFeatures = [\n options.multiTenant?.enabled ? 'Multi-tenancy' : null,\n options.graphql?.enabled ? 'GraphQL' : null,\n options.logger?.enabled ? 'Logger' : null,\n options.features?.useRedisCache ? 'Redis Cache' : null,\n options.advanced?.garbageCollector?.enabled ? 'Garbage Collector' : null,\n ].filter(Boolean);\n const disabledFeatures = [\n !options.multiTenant?.enabled ? 'Multi-tenancy' : null,\n !options.graphql?.enabled ? 'GraphQL' : null,\n !options.logger?.enabled ? 'Logger' : null,\n !options.features?.useRedisCache ? 'Redis Cache' : null,\n !options.advanced?.garbageCollector?.enabled ? 'Garbage Collector' : null,\n ].filter(Boolean);\n const seconds = (durationMs / 1000).toFixed(2);\n console.log('');\n console.log((0, color_palatte_1.colorize)(`✔ Project scaffold completed in ${seconds}s`, 'green'));\n console.log('');\n if (log.dirs.length) {\n console.log((0, color_palatte_1.colorize)('Directories:', 'blue'));\n log.dirs.forEach((d) => {\n console.log((0, color_palatte_1.colorize)(` + ${d}`, 'green'));\n });\n console.log('');\n }\n if (log.files.length) {\n console.log((0, color_palatte_1.colorize)('Files:', 'blue'));\n log.files.forEach((f) => {\n console.log((0, color_palatte_1.colorize)(` + ${f}`, 'green'));\n });\n console.log('');\n }\n console.log((0, color_palatte_1.colorize)('Feature summary:', 'blue'));\n enabledFeatures.forEach((feature) => {\n console.log((0, color_palatte_1.colorize)(` ✓ ${feature}`, 'green'));\n });\n disabledFeatures.forEach((feature) => {\n console.log((0, color_palatte_1.colorize)(` ✗ ${feature}`, 'yellow'));\n });\n console.log('');\n console.log((0, color_palatte_1.colorize)('Next steps:', 'blue'));\n console.log((0, color_palatte_1.colorize)(` cd ${projectName}`, 'green'));\n console.log((0, color_palatte_1.colorize)(` pnpm install`, 'green'));\n console.log((0, color_palatte_1.colorize)(` pnpm dev`, 'green'));\n console.log('');\n },\n };\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SchemaType = void 0;\nconst mongodb_1 = require(\"mongodb\");\n/**\n * MongoDB schema types.\n */\nexports.SchemaType = {\n Types: { ObjectId: mongodb_1.ObjectId },\n};\n","module.exports = require(\"dotenv/config\");","module.exports = require(\"fs-extra\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.applySoftDelete = applySoftDelete;\nconst DEFAULTS = {\n field: 'deletedAt',\n deletedAtField: 'deletedAt',\n deletedByField: 'deletedBy',\n isDeletedField: 'isDeleted',\n enabled: true,\n excludeDeletedByDefault: true\n};\nfunction buildNotDeletedFilter(options) {\n return {\n $and: [\n {\n $or: [\n { [options.deletedAtField]: { $exists: false } },\n { [options.deletedAtField]: null }\n ]\n },\n {\n $or: [\n { [options.isDeletedField]: { $exists: false } },\n { [options.isDeletedField]: false }\n ]\n }\n ]\n };\n}\nfunction buildOnlyDeletedFilter(options) {\n return {\n $or: [\n { [options.deletedAtField]: { $ne: null } },\n { [options.isDeletedField]: true }\n ]\n };\n}\nfunction mergeFilter(original, extra) {\n if (!original || Object.keys(original).length === 0) {\n return extra;\n }\n return {\n $and: [original, extra]\n };\n}\nfunction buildSoftDeleteUpdate(options) {\n return {\n $set: {\n [options.deletedAtField]: new Date(),\n [options.isDeletedField]: true\n }\n };\n}\nfunction applySoftDelete(model, opts = {}) {\n const options = { ...DEFAULTS, ...opts };\n if (!options.enabled) {\n return model;\n }\n const applyReadFilter = (ctx) => {\n if (ctx.withDeleted === true) {\n return;\n }\n if (ctx.onlyDeleted === true) {\n ctx.filter = mergeFilter(ctx.filter, buildOnlyDeletedFilter(options));\n return;\n }\n if (options.excludeDeletedByDefault) {\n ctx.filter = mergeFilter(ctx.filter, buildNotDeletedFilter(options));\n }\n };\n model.beforeFind((ctx) => {\n applyReadFilter(ctx);\n });\n model.beforeFindOne((ctx) => {\n applyReadFilter(ctx);\n });\n model.beforeFindOneAndUpdate((ctx) => {\n applyReadFilter(ctx);\n });\n model.beforeFindOneAndReplace((ctx) => {\n applyReadFilter(ctx);\n });\n model.beforeFindOneAndUpsert((ctx) => {\n applyReadFilter(ctx);\n });\n model.beforeAggregate((ctx) => {\n if (ctx.withDeleted === true) {\n return;\n }\n const stage = ctx.onlyDeleted === true\n ? { $match: buildOnlyDeletedFilter(options) }\n : options.excludeDeletedByDefault\n ? { $match: buildNotDeletedFilter(options) }\n : null;\n if (!stage) {\n return;\n }\n ctx.pipeline = [stage, ...(ctx.pipeline ?? [])];\n });\n model.beforeDeleteOne((ctx) => {\n if (ctx.hardDelete === true) {\n return;\n }\n ctx.filter = mergeFilter(ctx.filter, buildNotDeletedFilter(options));\n ctx.update = buildSoftDeleteUpdate(options);\n ctx.meta = {\n ...(ctx.meta ?? {}),\n softDelete: true\n };\n });\n model.beforeDeleteMany((ctx) => {\n if (ctx.hardDelete === true) {\n return;\n }\n ctx.filter = mergeFilter(ctx.filter, buildNotDeletedFilter(options));\n ctx.update = buildSoftDeleteUpdate(options);\n ctx.meta = {\n ...(ctx.meta ?? {}),\n softDelete: true\n };\n });\n model.beforeFindOneAndDelete((ctx) => {\n ctx.filter = mergeFilter(ctx.filter, buildNotDeletedFilter(options));\n if (ctx.hardDelete === true) {\n return;\n }\n ctx.update = buildSoftDeleteUpdate(options);\n ctx.meta = {\n ...(ctx.meta ?? {}),\n softDelete: true\n };\n });\n model.setSoftDeleteConfig({\n deletedAtField: options.deletedAtField,\n isDeletedField: options.isDeletedField\n });\n return model;\n}\n;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.runManualTransaction = runManualTransaction;\nconst transactionSession_1 = require(\"./transactionSession\");\nasync function runManualTransaction(session, operation) {\n if (!(0, transactionSession_1.hasManualTransactionMethods)(session)) {\n throw new Error('Session does not implement manual transaction methods.');\n }\n session.startTransaction();\n try {\n const result = await operation(session);\n await session.commitTransaction();\n return result;\n }\n catch (error) {\n await session.abortTransaction();\n throw error;\n }\n finally {\n await session.endSession();\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.colorize = void 0;\n;\nconst colorize = (text, platform) => {\n switch (platform) {\n case 'red':\n return `\\x1b[31m${text}\\x1b[0m`; // Red color\n case 'green':\n return `\\x1b[32m${text}\\x1b[0m`; // Green color\n case 'magenta':\n return `\\x1b[35m${text}\\x1b[0m`; // Magenta color\n case 'cyan':\n return `\\x1b[36m${text}\\x1b[0m`; // Cyan color\n case 'yellow':\n return `\\x1b[33m${text}\\x1b[0m`; // Yellow color\n case 'blue':\n return `\\x1b[34m${text}\\x1b[0m`; // Blue color\n default:\n break;\n }\n return `\\x1b[36m${text}\\x1b[0m`;\n};\nexports.colorize = colorize;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MultiTenantManager = void 0;\nconst mongodb_1 = require(\"mongodb\");\n/**\n * MultiTenantManager is responsible for managing tenant configurations and MongoDB client connections in a multi-tenant application.\n * It supports both lazy and immediate tenant registration, allowing for flexible connection management based on application needs.\n */\nclass MultiTenantManager {\n static tenants = new Map();\n constructor() { }\n /**\n * Checks if a tenant is already registered.\n * @param {string} tenantId - The ID of the tenant to check.\n * @returns {boolean} `true` if the tenant is registered, `false` otherwise.\n */\n static hasTenant(tenantId) {\n return this.tenants.has(tenantId);\n }\n /**\n * Registers a tenant for lazy connection.\n * Connection is established only when the tenant is accessed for the first time.\n *\n * @param {string} tenantId - The tenant ID.\n * @param {string} uri - The MongoDB URI.\n * @param {RegisterTenantOptions} [options] - Optional tenant registration settings.\n */\n static registerLazyTenant(tenantId, uri, options = {}) {\n this.validateTenantId(tenantId);\n this.validateUri(uri);\n const normalizedTenantId = tenantId.trim();\n const tenantConfig = {\n tenantId: normalizedTenantId,\n uri: uri.trim(),\n dbName: options.dbName?.trim() || this.extractDbNameFromUri(uri) || normalizedTenantId,\n client: undefined,\n lazy: true,\n metadata: options.metadata\n };\n this.tenants.set(normalizedTenantId, tenantConfig);\n return tenantConfig;\n }\n /**\n * Registers a tenant and establishes a connection immediately.\n *\n * @param {string} tenantId - The tenant ID.\n * @param {string} uri - The MongoDB URI.\n * @param {RegisterTenantOptions} [options] - Optional tenant registration settings.\n * @returns {Promise<MongoClient>} The connected MongoClient instance.\n */\n static async registerTenant(tenantId, uri, options = {}) {\n this.validateTenantId(tenantId);\n this.validateUri(uri);\n const normalizedTenantId = tenantId.trim();\n const existing = this.tenants.get(normalizedTenantId);\n if (existing?.client) {\n return existing.client;\n }\n const client = options.client ?? new mongodb_1.MongoClient(uri);\n if (!options.client) {\n await client.connect();\n }\n const tenantConfig = {\n tenantId: normalizedTenantId,\n uri: uri.trim(),\n dbName: options.dbName?.trim() || this.extractDbNameFromUri(uri) || normalizedTenantId,\n client,\n lazy: false,\n metadata: options.metadata\n };\n this.tenants.set(normalizedTenantId, tenantConfig);\n return client;\n }\n /**\n * Retrieves the MongoClient instance for a specific tenant.\n * If the tenant was registered lazily, connection is established on first access.\n *\n * @param {string} tenantId - The tenant ID.\n * @returns {Promise<MongoClient | null>} The MongoClient or null if not registered.\n */\n static async getClient(tenantId) {\n this.validateTenantId(tenantId);\n const normalizedTenantId = tenantId.trim();\n const tenant = this.tenants.get(normalizedTenantId);\n if (!tenant)\n return null;\n if (tenant.client) {\n return tenant.client;\n }\n if (tenant.lazy) {\n const client = new mongodb_1.MongoClient(tenant.uri);\n await client.connect();\n this.tenants.set(normalizedTenantId, {\n ...tenant,\n client,\n lazy: false\n });\n return client;\n }\n return null;\n }\n /**\n * Retrieves the full tenant configuration.\n *\n * @param {string} tenantId - The tenant ID.\n * @returns {TenantConfig | undefined} The tenant configuration if found.\n */\n static getTenant(tenantId) {\n this.validateTenantId(tenantId);\n return this.tenants.get(tenantId.trim());\n }\n /**\n * Retrieves the configured database name for a tenant.\n *\n * @param {string} tenantId - The tenant ID.\n * @returns {string | undefined} The database name if found.\n */\n static getTenantDbName(tenantId) {\n return this.getTenant(tenantId)?.dbName;\n }\n /**\n * Returns the first connected tenant ID.\n * Useful for backward compatibility, though not ideal in multi-tenant flows.\n */\n static getConnectedTenant() {\n const connected = Array.from(this.tenants.values()).find(tenant => !!tenant.client);\n return connected?.tenantId || '';\n }\n /**\n * Returns all currently connected tenant IDs.\n */\n static getAllConnectedTenants() {\n return Array.from(this.tenants.values())\n .filter(tenant => !!tenant.client)\n .map(tenant => tenant.tenantId);\n }\n /**\n * Returns all registered tenant configs.\n */\n static getAllTenants() {\n return Array.from(this.tenants.values());\n }\n /**\n * Returns true if at least one tenant is registered.\n */\n static isEnabled() {\n return this.tenants.size > 0;\n }\n /**\n * Removes a tenant from the registry.\n */\n static removeTenant(tenantId) {\n this.validateTenantId(tenantId);\n return this.tenants.delete(tenantId.trim());\n }\n /**\n * Clears all tenants from the registry.\n */\n static clearTenants() {\n this.tenants.clear();\n }\n static validateTenantId(tenantId) {\n if (!tenantId || typeof tenantId !== 'string' || !tenantId.trim()) {\n throw new Error('Tenant ID is required.');\n }\n }\n static validateUri(uri) {\n if (!uri || typeof uri !== 'string' || !uri.trim()) {\n throw new Error('MongoDB URI is required.');\n }\n if (!uri.startsWith('mongodb://') && !uri.startsWith('mongodb+srv://')) {\n throw new Error(`Invalid MongoDB URI: ${uri}`);\n }\n }\n static extractDbNameFromUri(uri) {\n try {\n const withoutQuery = uri.split('?')[0];\n const parts = withoutQuery.split('/');\n const lastPart = parts[parts.length - 1];\n if (!lastPart || lastPart.includes(':')) {\n return undefined;\n }\n return lastPart.trim() || undefined;\n }\n catch {\n return undefined;\n }\n }\n}\nexports.MultiTenantManager = MultiTenantManager;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n;\n","module.exports = require(\"tslib\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.generateMainTS = generateMainTS;\nfunction generateMainTS(options) {\n return `import { run } from './core/initAmbiten';\n\nasync function main() {\n const app = await run();\n\n if (typeof app?.onConnect === 'function') {\n app.onConnect(() => {\n console.log('✅ Ambiten application initialized successfully.');\n });\n }\n\n return app;\n}\n\nmain().catch((error) => {\n console.error('❌ Failed to start application:', error);\n process.exit(1);\n});\n`;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.configureAmbitenContext = configureAmbitenContext;\nconst context_1 = require(\"../context\");\nconst tanancy_1 = require(\"../tanancy\");\n/**\n * Configures the Ambiten runtime context with a transaction client resolver.\n *\n * The resolver is used by {@link AmbitenContext.withTransaction} to obtain the\n * correct MongoDB client for the current runtime scope. Tenant-specific clients\n * are resolved first when a tenant identifier is available; otherwise the\n * configured provider client factory is used.\n *\n * @param provider - Bootstrap client/provider used to resolve MongoDB clients.\n */\nfunction configureAmbitenContext(provider) {\n context_1.AmbitenContext.configureTransactionResolver({\n resolveClient: async (tenantId, dbName) => {\n if (tenantId) {\n const tenantClient = await tanancy_1.MultiTenantManager.getClient(tenantId);\n if (tenantClient) {\n return tenantClient;\n }\n }\n if (typeof provider.client === 'function') {\n const ctx = {\n tenantId,\n dbName\n };\n return provider.client(ctx);\n }\n return undefined;\n }\n });\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenCache = void 0;\nexports.createAmbitenCache = createAmbitenCache;\nconst redis_manager_1 = require(\"../redis-manager\");\nconst context_1 = require(\"../context\");\nclass AmbitenCache {\n client;\n constructor(client = redis_manager_1.redis) {\n this.client = client;\n }\n /**\n * Builds a tenant-aware cache key.\n * Key format: {prefix}:{tenantId}:{namespace}:{key}\n * - prefix: Optional string to namespace cache keys (default: \"Ambiten\")\n * - tenantId: Resolved tenant ID for multi-tenancy (explicit > context > \"default\")\n * - namespace: Optional string to further namespace keys (default: \"cache\")\n * - key: The original cache key provided by the caller\n *\n * Resolution priority:\n * 1. Explicit tenantId from options\n * 2. Active Ambiten runtime tenantId\n * 3. \"default\"\n */\n buildKey(key, options = {}) {\n const ctx = context_1.AmbitenContext.get();\n const prefix = options.prefix ?? 'Ambiten';\n const tenantId = options.tenantId ?? ctx.tenantId ?? 'default';\n const namespace = options.namespace ?? 'cache';\n return [prefix, tenantId, namespace, key]\n .filter(Boolean)\n .join(':');\n }\n /**\n * Reads and deserializes a cached value.\n */\n async get(key, options) {\n const namespacedKey = this.buildKey(key, options);\n const cached = await this.client.get(namespacedKey);\n if (cached === null || cached === undefined) {\n this.emit('miss', namespacedKey);\n return null;\n }\n try {\n this.emit('hit', namespacedKey);\n return JSON.parse(cached);\n }\n catch {\n await this.client.del(namespacedKey);\n this.emit('corrupt', namespacedKey);\n return null;\n }\n }\n /**\n * Serializes and writes a cached value.\n */\n async set(key, value, options = {}) {\n const namespacedKey = this.buildKey(key, options);\n await this.client.set(namespacedKey, JSON.stringify(value), { EX: options.ttlSeconds ?? 60 });\n this.emit('set', namespacedKey);\n }\n /**\n * Returns cached value if available, otherwise computes, stores, and returns it.\n */\n async wrap(key, fetcher, options = {}) {\n const existing = await this.get(key, options);\n if (existing !== null) {\n return existing;\n }\n const result = await fetcher();\n await this.set(key, result, options);\n return result;\n }\n /**\n * Invalidates one cache key.\n */\n async invalidate(key, options) {\n const namespacedKey = this.buildKey(key, options);\n await this.client.del(namespacedKey);\n this.emit('invalidate', namespacedKey);\n }\n /**\n * Invalidates cache keys by pattern using SCAN.\n */\n async invalidatePattern(pattern) {\n if (!pattern || typeof pattern !== 'string') {\n throw new Error('Pattern must be a non-empty string.');\n }\n if (!this.client.scan) {\n throw new Error('Cache client does not support scan().');\n }\n let cursor = 0;\n let deletedCount = 0;\n do {\n const result = await this.client.scan(cursor, {\n MATCH: pattern,\n COUNT: 100\n });\n const nextCursor = Array.isArray(result)\n ? Number(result[0])\n : result.cursor;\n const keys = Array.isArray(result)\n ? result[1]\n : result.keys;\n if (keys.length > 0) {\n await this.client.del(keys);\n deletedCount += keys.length;\n }\n cursor = nextCursor;\n } while (cursor !== 0);\n if (deletedCount > 0) {\n this.emit('invalidatePattern', pattern);\n }\n return deletedCount;\n }\n /**\n * Internal event hook point for future observability and policy integrations.\n */\n emit(event, key) {\n void event;\n void key;\n }\n}\nexports.AmbitenCache = AmbitenCache;\nfunction createAmbitenCache(client = redis_manager_1.redis) {\n return new AmbitenCache(client);\n}\n","module.exports = require(\"ajv\");","module.exports = require(\"@graphql-tools/schema\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.scheduleGarbageCollector = scheduleGarbageCollector;\nconst tslib_1 = require(\"tslib\");\nconst cron = tslib_1.__importStar(require(\"node-cron\"));\nconst gcManager_1 = require(\"./gcManager\");\nconst ModelRegistry_1 = require(\"../utils/ModelRegistry\");\nconst utils_1 = require(\"../utils\");\n/**\n * Schedules registry-driven garbage collection.\n *\n * The cron task uses registered model instances and delegates cleanup to\n * `model.runGC()` so Ambiten's runtime context, middleware, schema hooks,\n * instrumentation, cache invalidation, and events remain centralized.\n *\n * @param options - Cron expression or scheduler options.\n * @returns The scheduled cron task.\n */\nfunction scheduleGarbageCollector(options = '0 * * * *') {\n const cronExpr = typeof options === 'string'\n ? options\n : options.cronExpr ?? '0 * * * *';\n const ctx = typeof options === 'string'\n ? undefined\n : options.ctx;\n const continueOnError = typeof options === 'string'\n ? true\n : options.continueOnError ?? true;\n return cron.schedule(cronExpr, async () => {\n try {\n const models = ModelRegistry_1.AmbitenModelRegistry.getAllModels();\n if (models.length === 0) {\n console.warn((0, utils_1.colorize)('[GC] Skipping GC: no registered models found.', 'yellow'));\n return;\n }\n console.log((0, utils_1.colorize)(`[GC] Running garbage collector at ${new Date().toISOString()}`, 'blue'));\n const result = await (0, gcManager_1.runGarbageCollectorOnAllModels)({\n ctx,\n continueOnError\n });\n console.log((0, utils_1.colorize)(`[GC] Completed. scanned=${result.scanned}, succeeded=${result.succeeded}, failed=${result.failed}`, result.failed > 0 ? 'yellow' : 'blue'));\n }\n catch (error) {\n console.error((0, utils_1.colorize)('[GC] Error running garbage collector', 'red'), error);\n }\n });\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenClient\"), exports);\ntslib_1.__exportStar(require(\"./ambitenModelFactory\"), exports);\ntslib_1.__exportStar(require(\"./ambitenSchema\"), exports);\ntslib_1.__exportStar(require(\"./bootstrap\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createSchema = void 0;\nconst lib_core_1 = require(\"../../lib-core\");\n/**\n * Creates a new AmbitenSchema instance with the provided schema definition.\n * @param {SchemaDefinition<T> | Record<keyof T, any>} schema - The schema definition for the document.\n * @returns {AmbitenSchema<T>} The created AmbitenSchema instance.\n *\n * @template T - The type of the document.\n * @example\n * const userSchema = createSchema({\n * name: { type: String, required: true },\n * age: { type: Number, required: true },\n * email: { type: String, required: true },\n * });\n * const userModel = new AmbitenModel(userSchema, 'users', db);\n *\n * const user = await userModel.create({ name: 'John Doe', age: 30, email: 'example.com' });\n * console.log(user); // { _id: '...', name: 'John Doe', age: 30, email: 'example.com' }\n *\n */\nconst createSchema = (schema) => {\n return new lib_core_1.AmbitenSchema(schema);\n};\nexports.createSchema = createSchema;\n","\"use strict\";\n/**\n * @author Emmanuel Nodolomwanyi - Ambiten Team\n * @package - @Ambiten/core\n * @version 1.0.0\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.initializeRedis = void 0;\nconst tslib_1 = require(\"tslib\");\nconst redis_manager_1 = require(\"./redis-manager\");\n/**\n * Ambiten Core Library\n * This library provides core functionalities for Ambiten, ORM/ODM solution\n * for MongoDB in Node.js and Browser environments.\n * @module Ambiten Core Library\n * @version 1.0.0\n */\nconsole.log('Ambiten Core Library Loaded. \\n (Node.js environment detected.)');\nconst initializeRedis = async ({ useRedis = false } = {}) => {\n if (useRedis) {\n const redisClient = redis_manager_1.RedisService.getInstance();\n const client = await redisClient.getClient();\n if (!client.isOpen) {\n await client.connect();\n }\n }\n};\nexports.initializeRedis = initializeRedis;\ntslib_1.__exportStar(require(\"./lib-core\"), exports);\ntslib_1.__exportStar(require(\"./lib-core/bootstrap\"), exports);\ntslib_1.__exportStar(require(\"./config\"), exports);\ntslib_1.__exportStar(require(\"./redis-manager\"), exports);\ntslib_1.__exportStar(require(\"./tanancy\"), exports);\ntslib_1.__exportStar(require(\"./context\"), exports);\ntslib_1.__exportStar(require(\"./plugins\"), exports);\ntslib_1.__exportStar(require(\"./instrumentation\"), exports);\ntslib_1.__exportStar(require(\"./debug\"), exports);\ntslib_1.__exportStar(require(\"./ambiten-cache\"), exports);\ntslib_1.__exportStar(require(\"./init-cli/generate.project\"), exports);\ntslib_1.__exportStar(require(\"./middleware\"), exports);\ntslib_1.__exportStar(require(\"./graphql\"), exports);\ntslib_1.__exportStar(require(\"./utils\"), exports);\ntslib_1.__exportStar(require(\"./utils/builders\"), exports);\ntslib_1.__exportStar(require(\"./gc\"), exports);\ntslib_1.__exportStar(require(\"./types\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TenantContext = void 0;\n/**\n * This is legacy code and is not intended for public use. It may be removed in future versions without warning.\n * @deprecated\n * @internal\n * TenantContext provides a thread-safe way to manage tenant-specific data using AsyncLocalStorage.\n * This is particularly useful in multi-tenant applications where you need to track the current tenant across asynchronous operations.\n */\nconst node_async_hooks_1 = require(\"node:async_hooks\");\nconst tenantStorage = new node_async_hooks_1.AsyncLocalStorage();\n/**\n * @deprecated\n * @internal\n *\n * This is legacy code and is not intended for public use. It may be removed in future versions without warning.\n * Provides a thread-safe context for managing tenant-specific data using `AsyncLocalStorage`.\n * This is useful for multi-tenant applications where the current tenant needs to be tracked across asynchronous operations.\n */\nclass TenantContext {\n /**\n * Runs a callback function within a specific tenant context.\n * @param {string} tenantId - The ID of the tenant to set in the context.\n * @param {() => void} callback - The callback function to execute within the tenant context.\n */\n static run(tenantId, callback) {\n if (!tenantId) {\n throw new Error('tenantId is required to run tenant context');\n }\n tenantStorage.run({ tenantId: tenantId }, callback);\n }\n /**\n * Sets the tenant ID in the current context.\n * @param {string} tenantId - The ID of the tenant to set.\n */\n static setTenantId(tenantId) {\n const store = tenantStorage.getStore();\n if (store)\n store.tenantId = tenantId;\n }\n /**\n * Retrieves the tenant ID from the current context.\n * @returns {string | undefined} The tenant ID, or `undefined` if no tenant ID is set.\n */\n static getTenantId() {\n return tenantStorage.getStore()?.tenantId;\n }\n /**\n * Clears the tenant ID from the current context.\n */\n static clear() {\n const store = tenantStorage.getStore();\n if (store)\n store.tenantId = undefined;\n }\n}\nexports.TenantContext = TenantContext;\n;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.RedisService = exports.redis = void 0;\nexports.connectRedis = connectRedis;\nrequire(\"dotenv/config\");\nconst redis_1 = require(\"redis\");\nconst DEFAULT_RECONNECT = (retries) => Math.min(retries * 50, 1000);\nconst redisUrl = process.env.REDIS_URI;\nlet currentClient = null;\nconst createStub = () => ({\n isOpen: false,\n connect: async () => null,\n disconnect: async () => null,\n publish: async () => 0,\n subscribe: async () => null,\n duplicate: () => createStub(),\n get: async () => null,\n set: async () => 'OK',\n del: async () => 0,\n exists: async () => 0,\n scan: async () => ({\n cursor: 0,\n keys: [],\n }),\n multi: () => ({\n incr() {\n return this;\n },\n expire() {\n return this;\n },\n exec: async () => [],\n }),\n});\nexports.redis = {\n async getClient(uri) {\n if (currentClient && currentClient.isOpen) {\n return currentClient;\n }\n const url = uri || redisUrl;\n if (!url) {\n return createStub();\n }\n try {\n const client = (0, redis_1.createClient)({\n url,\n socket: {\n reconnectStrategy: DEFAULT_RECONNECT,\n },\n });\n await client.connect();\n currentClient = client;\n return client;\n }\n catch {\n return createStub();\n }\n },\n async disconnect() {\n if (currentClient) {\n try {\n if (currentClient.isOpen &&\n typeof currentClient.disconnect === 'function') {\n await currentClient.disconnect();\n }\n else if (currentClient.isOpen &&\n typeof currentClient.quit === 'function') {\n await currentClient.quit();\n }\n }\n catch {\n // swallow disconnect errors\n }\n }\n currentClient = null;\n },\n get isOpen() {\n return !!currentClient?.isOpen;\n },\n async get(key) {\n const client = await this.getClient();\n return client.get?.(key);\n },\n async set(key, value, options) {\n const client = await this.getClient();\n return client.set?.(key, value, options);\n },\n async del(...keys) {\n const client = await this.getClient();\n return client.del?.(keys);\n },\n async exists(key) {\n const client = await this.getClient();\n return client.exists?.(key);\n },\n async scan(cursor = 0, options) {\n const client = await this.getClient();\n if (typeof client.scan !== 'function') {\n return {\n cursor: 0,\n keys: [],\n };\n }\n return client.scan(cursor, options);\n },\n async publish(channel, message) {\n const client = await this.getClient();\n return client.publish?.(channel, message);\n },\n async subscribe(channel, listener) {\n const client = await this.getClient();\n return client.subscribe?.(channel, listener);\n },\n duplicate() {\n if (currentClient?.duplicate) {\n return currentClient.duplicate();\n }\n return createStub();\n },\n multi() {\n if (currentClient?.multi) {\n return currentClient.multi();\n }\n return createStub().multi?.();\n },\n};\nclass RedisService {\n static getInstance() {\n return new RedisService();\n }\n async connect(url) {\n await exports.redis.getClient(url);\n }\n getClient() {\n return exports.redis.getClient();\n }\n async close() {\n await exports.redis.disconnect();\n }\n}\nexports.RedisService = RedisService;\nasync function connectRedis() {\n return {\n connect: async (url) => exports.redis.getClient(url),\n };\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.generateGCRunner = generateGCRunner;\nfunction generateGCRunner() {\n return `/**\n * Garbage collector runner\n *\n * Replace the imports below with your actual bootstrap/model entry points.\n */\n\nimport { runGarbageCollector } from './gcManager';\n// import { UserModel } from '../models/UserModel';\n\nasync function main() {\n // Example:\n // await runGarbageCollector(UserModel, { retentionPeriod: 7 });\n console.log('⚠️ Update gcRunner.ts with your model imports before using it.');\n}\n\nmain().catch((error) => {\n console.error('❌ Garbage collector failed:', error);\n process.exit(1);\n});\n`;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getEventOptions = getEventOptions;\nexports.getEventType = getEventType;\nexports.describeEvent = describeEvent;\nexports.logEvent = logEvent;\nexports.logDefaultEvent = logDefaultEvent;\nconst logger_1 = require(\"@ambiten/logger\");\n/**\n * Mapping from event type to option key.\n */\nconst eventOptionMap = {\n \"pre-save\": \"save\",\n \"post-save\": \"save\",\n \"pre-update\": \"update\",\n \"post-update\": \"update\",\n \"pre-delete\": \"delete\",\n \"post-delete\": \"delete\",\n \"aggregate\": \"aggregate\",\n \"disconnect\": \"disconnect\",\n \"connect\": \"connect\",\n \"dropDatabase\": \"dropDatabase\",\n \"createIndex\": \"index\",\n \"dropIndex\": \"index\",\n \"create\": \"create\",\n \"find\": \"find\",\n \"findOne\": \"find\",\n \"insertOne\": \"insertOne\",\n \"insertMany\": \"insertMany\",\n \"updateOne\": \"updateOne\",\n \"updateMany\": \"updateMany\",\n \"deleteOne\": \"deleteOne\",\n \"deleteMany\": \"deleteMany\",\n \"pre-bulkWrite\": \"bulkWrite\",\n \"post-bulkWrite\": \"bulkWrite\",\n \"pre-insertMany\": \"insertMany\",\n \"post-insertMany\": \"insertMany\",\n \"pre-updateMany\": \"updateMany\",\n \"post-updateMany\": \"updateMany\",\n \"pre-deleteMany\": \"deleteMany\",\n \"post-deleteMany\": \"deleteMany\",\n \"transaction\": \"transaction\"\n};\n/**\n * Returns the options object for the given event type.\n * @param eventType - The type of the event.\n * @returns The options for the event.\n */\nfunction getEventOptions(eventType) {\n const key = eventOptionMap[eventType] || eventType;\n return { [key]: true };\n}\n/**\n * Returns the event type based on the options provided.\n * @param options - The options for the event.\n * @returns The event type, or null if not found.\n */\nfunction getEventType(options) {\n const key = Object.keys(options).find((k) => Object.values(eventOptionMap).includes(k));\n if (!key)\n return null;\n // Find the first eventType that maps to this key\n const eventType = Object.keys(eventOptionMap).find((et) => eventOptionMap[et] === key);\n return eventType || null;\n}\n/**\n * Returns a human-readable description for the given event type.\n * @param eventType - The type of the event.\n * @returns The event description.\n */\nfunction describeEvent(eventType) {\n const descriptions = {\n \"pre-save\": \"Before Save\",\n \"post-save\": \"After Save\",\n \"pre-update\": \"Before Update\",\n \"post-update\": \"After Update\",\n \"pre-delete\": \"Before Delete\",\n \"post-delete\": \"After Delete\",\n aggregate: \"Aggregation\",\n disconnect: \"Disconnect\",\n connect: \"Connect\",\n dropDatabase: \"Drop Database\",\n createIndex: \"Create Index\",\n dropIndex: \"Drop Index\",\n create: \"Create\",\n find: \"Find\",\n findOne: \"Find One\",\n insertOne: \"Insert One\",\n insertMany: \"Insert Many\",\n updateOne: \"Update One\",\n updateMany: \"Update Many\",\n deleteOne: \"Delete One\",\n deleteMany: \"Delete Many\",\n };\n return descriptions[eventType] || eventType;\n}\n;\n/**\n * Logs the event action using a provided logger.\n * @param logger - The logger instance (must have a log method).\n * @param eventType - The type of the event.\n * @param message - Optional custom message.\n * @param level - Log level (default: 'info').\n * @param context - Optional context or payload to log.\n */\nfunction logEvent(logger, eventType, message, level = 'info', context) {\n const eventDesc = describeEvent(eventType);\n const logMsg = message\n ? `[Ambiten EVENT]: ${eventDesc}: ${message}`\n : `[Ambiten] Event: ${eventDesc}`;\n const log = {\n level,\n message: logMsg,\n context\n };\n logger.info(`${log.level}${log.message} ${log.context ? JSON.stringify(log.context) : ''}`);\n}\n;\n/**\n * Logs an event with a default logger.\n * @param eventType - The type of the event.\n * @param message - Optional custom message.\n * @param context - Optional context or payload to log.\n * @param level - Log level (default: 'info').\n */\nfunction logDefaultEvent(eventType, message, level, context) {\n const logger = (0, logger_1.setupLogger)(); // Get the default logger instance\n logEvent(logger, eventType, message, level, context);\n return eventType;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Schema = exports.AmbitenSchema = void 0;\n/**\n * The AmbitenSchema class allows you to define a schema for MongoDB documents.\n * It supports:\n * - schema definition\n * - custom validation\n * - indexes\n * - relationships\n * - virtual fields\n * - context-aware middleware\n * - garbage collection metadata\n */\nclass AmbitenSchema {\n schemaDefinition;\n indexes = [];\n virtuals = {};\n validators = {};\n relationships = [];\n gcConfig;\n middleware = {\n pre: {},\n post: {},\n };\n /**\n * Creates an instance of AmbitenSchema.\n * @param schemaDefinition - The schema definition for the document.\n */\n constructor(schemaDefinition) {\n this.schemaDefinition = schemaDefinition;\n }\n /**\n * Retrieves the schema definition.\n */\n getSchema() {\n return this.schemaDefinition;\n }\n /**\n * Re-registers the schema definition.\n */\n registerSchema(schemaDefinition) {\n this.schemaDefinition = schemaDefinition;\n console.info('Schema registered:', this.schemaDefinition);\n }\n /**\n * Adds a custom validator for a specific field.\n */\n validator(field, fn) {\n this.validators[field] = fn;\n }\n /**\n * Validates a document synchronously.\n * Throws if an async validator is encountered.\n */\n validate(doc) {\n for (const [field, validate] of Object.entries(this.validators)) {\n const result = validate(doc[field], doc);\n if (result instanceof Promise) {\n throw new Error(`Validator for field \"${field}\" is async. Use validateAsync() instead.`);\n }\n if (!result) {\n console.log(`[error]: Validation failed for field: ${field}`);\n throw new Error(`Validation failed for field: ${field}`);\n }\n }\n }\n /**\n * Validates a document asynchronously.\n */\n async validateAsync(doc) {\n for (const [field, validate] of Object.entries(this.validators)) {\n const isValid = await validate(doc[field], doc);\n if (!isValid) {\n console.log(`[error]: Validation failed for field: ${field}`);\n throw new Error(`Validation failed for field: ${field}`);\n }\n }\n }\n /**\n * Adds an index to the schema.\n */\n index(fields, options) {\n this.indexes.push({ fields, options });\n }\n /**\n * Applies all defined indexes to a MongoDB collection.\n */\n async applyIndexes(collection) {\n for (const { fields, options } of this.indexes) {\n await collection.createIndex(fields, options);\n }\n }\n /**\n * Adds a relationship to the schema.\n */\n addRelationship(ref, localField) {\n this.relationships.push({ ref, localField });\n }\n /**\n * Retrieves all relationships defined in the schema.\n */\n getRelationships() {\n return this.relationships;\n }\n /**\n * Adds a virtual field to the schema.\n */\n virtual(name, getter) {\n this.virtuals[name] = getter;\n }\n /**\n * Applies all virtual fields to a document.\n */\n applyVirtuals(doc) {\n for (const [key, getter] of Object.entries(this.virtuals)) {\n Object.defineProperty(doc, key, {\n get: () => getter(doc),\n enumerable: true,\n });\n }\n }\n /**\n * Adds a pre-middleware handler for a specific operation.\n */\n pre(operation, fn) {\n if (!this.middleware.pre[operation]) {\n this.middleware.pre[operation] = [];\n }\n this.middleware.pre[operation].push(fn);\n return this;\n }\n /**\n * Adds a post-middleware handler for a specific operation.\n */\n post(operation, fn) {\n if (!this.middleware.post[operation]) {\n this.middleware.post[operation] = [];\n }\n this.middleware.post[operation].push(fn);\n return this;\n }\n /**\n * Returns all pre-middleware for an operation.\n */\n getPreHooks(operation) {\n return this.middleware.pre[operation] || [];\n }\n /**\n * Returns all post-middleware for an operation.\n */\n getPostHooks(operation) {\n return this.middleware.post[operation] || [];\n }\n /**\n * Backward-compatible hook reader.\n * Defaults to pre hooks to avoid breaking older callers that expect getHooks(action).\n */\n getHooks(operation, phase = 'pre') {\n return phase === 'pre'\n ? this.getPreHooks(operation)\n : this.getPostHooks(operation);\n }\n /**\n * Executes pre-middleware for an operation.\n */\n async executePre(operation, ctx) {\n const hooks = this.getPreHooks(operation);\n for (const hook of hooks) {\n await hook(ctx);\n }\n }\n /**\n * Executes post-middleware for an operation.\n */\n async executePost(operation, ctx) {\n const hooks = this.getPostHooks(operation);\n for (const hook of hooks) {\n await hook(ctx);\n }\n }\n /**\n * Executes middleware for a given phase and operation.\n */\n async executeMiddleware(phase, operation, ctx) {\n const hooks = this.getHooks(operation, phase);\n for (const hook of hooks) {\n try {\n await hook(ctx);\n }\n catch (error) {\n console.error(`[error]: Error in ${phase}:${operation} middleware:`, error);\n throw error;\n }\n }\n }\n /**\n * Backward-compatible alias.\n * If older callers use triggerMiddleware(action, data), they should be upgraded\n * to pass explicit phase + operation + context.\n */\n async triggerMiddleware(phase, operation, ctx) {\n await this.executeMiddleware(phase, operation, ctx);\n }\n /**\n * Sets garbage collection configuration.\n */\n setGCConfig(config) {\n this.gcConfig = config;\n return this;\n }\n /**\n * Gets garbage collection configuration.\n */\n getGCConfig() {\n return this.gcConfig;\n }\n}\nexports.AmbitenSchema = AmbitenSchema;\nclass Schema extends AmbitenSchema {\n constructor(schemaDefinition) {\n super(schemaDefinition);\n this.registerSchema(schemaDefinition);\n }\n async create(data) {\n await this.validateAsync(data);\n const ctx = {\n operation: 'create',\n collectionName: 'schema-test',\n doc: data,\n };\n await this.executePre('create', ctx);\n const result = data;\n this.applyVirtuals(result);\n const postCtx = {\n ...ctx,\n result,\n doc: result,\n };\n await this.executePost('create', postCtx);\n return result;\n }\n static create(schemaDefinition) {\n return new Schema(schemaDefinition);\n }\n}\nexports.Schema = Schema;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.generateAppStructure = generateAppStructure;\nconst tslib_1 = require(\"tslib\");\nconst fs_extra_1 = tslib_1.__importDefault(require(\"fs-extra\"));\nconst path_1 = tslib_1.__importDefault(require(\"path\"));\nconst utils_1 = require(\"../../utils\");\nconst generateMainEntry_1 = require(\"../generateMainEntry\");\nconst generateDefaultConfigContent_1 = require(\"../generateDefaultConfigContent\");\nconst generateGCManagerFile_1 = require(\"../generateGCManagerFile\");\nconst generateGCRunnerFile_1 = require(\"../generateGCRunnerFile\");\nfunction buildPackageJson(options) {\n const dependencies = {\n '@ambiten/core': '^1.0.0',\n mongodb: '^6.14.2',\n };\n if (options.logger?.enabled) {\n dependencies['@ambiten/logger'] = '^1.0.0';\n }\n if (options.graphql?.enabled) {\n dependencies['graphql'] = '^16.11.0';\n dependencies['@apollo/server'] = '^5.1.0';\n }\n if (options.features?.useRedisCache) {\n dependencies['redis'] = '^4.7.1';\n }\n return {\n name: options.projectName ?? 'my-ambiten-app',\n description: 'A Ambiten-powered application',\n private: true,\n version: '1.0.0',\n type: 'commonjs',\n main: 'dist/main.js',\n scripts: {\n dev: 'ts-node src/main.ts',\n build: 'tsc',\n start: 'node dist/main.js',\n },\n license: 'ISC',\n dependencies,\n devDependencies: {\n typescript: '^5.9.3',\n 'ts-node': '^10.9.2',\n '@types/node': '^22.15.30',\n },\n };\n}\nfunction buildTsConfig() {\n return {\n compilerOptions: {\n \"target\": \"ES2021\",\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"rootDir\": './src',\n \"outDir\": './dist',\n \"sourceMap\": true,\n \"declaration\": true,\n \"declarationMap\": true,\n \"esModuleInterop\": true,\n \"resolveJsonModule\": true,\n \"strict\": true,\n \"noImplicitAny\": true,\n \"noImplicitReturns\": true,\n \"noUncheckedIndexedAccess\": true,\n \"exactOptionalPropertyTypes\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"skipLibCheck\": true,\n types: ['node'],\n lib: ['ES2021']\n },\n include: ['src/**/*'],\n exclude: ['node_modules', 'dist']\n };\n}\nfunction generateInitAmbitenTS() {\n return `import { AmbitenBootstrapFactory } from '@ambiten/core';\nimport type { AmbitenRuntime } from '@ambiten/core';\n\nexport async function run(): Promise<AmbitenRuntime> {\n return AmbitenBootstrapFactory.create();\n}\n`;\n}\nfunction generateGraphqlStarterTS() {\n return `/**\n * Optional GraphQL starter file.\n *\n * Use this file if you want to separate GraphQL setup from your bootstrap flow.\n * If your bootstrap already initializes GraphQL, this file can be removed.\n */\n\nexport {};\n`;\n}\nasync function generateAppStructure(projectRoot, options, logger) {\n const srcDir = path_1.default.join(projectRoot, 'src');\n const coreDir = path_1.default.join(srcDir, 'core');\n const utilsDir = path_1.default.join(srcDir, 'utils');\n const typesDir = path_1.default.join(srcDir, 'types');\n const modelsDir = path_1.default.join(srcDir, 'models');\n const graphqlDir = path_1.default.join(srcDir, 'graphql');\n const gcDir = path_1.default.join(srcDir, 'gc');\n await fs_extra_1.default.ensureDir(srcDir);\n logger?.addDir(srcDir);\n await fs_extra_1.default.ensureDir(coreDir);\n logger?.addDir(coreDir);\n await fs_extra_1.default.ensureDir(utilsDir);\n logger?.addDir(utilsDir);\n await fs_extra_1.default.ensureDir(typesDir);\n logger?.addDir(typesDir);\n await fs_extra_1.default.ensureDir(modelsDir);\n logger?.addDir(modelsDir);\n if (options.graphql?.enabled) {\n await fs_extra_1.default.ensureDir(graphqlDir);\n logger?.addDir(graphqlDir);\n }\n if (options.advanced?.garbageCollector?.enabled) {\n await fs_extra_1.default.ensureDir(gcDir);\n logger?.addDir(gcDir);\n }\n const mainPath = path_1.default.join(srcDir, 'main.ts');\n await fs_extra_1.default.writeFile(mainPath, (0, generateMainEntry_1.generateMainTS)(options));\n logger?.addFile(mainPath);\n const initAmbitenPath = path_1.default.join(coreDir, 'initAmbiten.ts');\n await fs_extra_1.default.writeFile(initAmbitenPath, generateInitAmbitenTS());\n logger?.addFile(initAmbitenPath);\n const helperPath = path_1.default.join(utilsDir, 'helper.ts');\n await fs_extra_1.default.writeFile(helperPath, `export function noop(): void {}\\n`);\n logger?.addFile(helperPath);\n const configTypesPath = path_1.default.join(typesDir, 'config.ts');\n await fs_extra_1.default.writeFile(configTypesPath, `export {};\\n`);\n logger?.addFile(configTypesPath);\n if (options.graphql?.enabled) {\n const schemaPath = path_1.default.join(graphqlDir, 'schema.gql');\n await fs_extra_1.default.writeFile(schemaPath, `type Query {\n hello: String\n}\n`);\n logger?.addFile(schemaPath);\n const resolversPath = path_1.default.join(graphqlDir, 'resolvers.ts');\n await fs_extra_1.default.writeFile(resolversPath, `export const resolvers = {\n Query: {\n hello: () => 'Hello, world!',\n },\n};\n`);\n logger?.addFile(resolversPath);\n await fs_extra_1.default.writeFile(path_1.default.join(graphqlDir, 'graphql.ts'), generateGraphqlStarterTS());\n }\n if (options.advanced?.garbageCollector?.enabled) {\n const gcManagerPath = path_1.default.join(gcDir, 'gcManager.ts');\n await fs_extra_1.default.writeFile(gcManagerPath, (0, generateGCManagerFile_1.generateGCManager)());\n logger?.addFile(gcManagerPath);\n const gcRunnerPath = path_1.default.join(gcDir, 'gcRunner.ts');\n await fs_extra_1.default.writeFile(gcRunnerPath, (0, generateGCRunnerFile_1.generateGCRunner)());\n logger?.addFile(gcRunnerPath);\n }\n const configPath = path_1.default.join(projectRoot, 'ambiten.config.json');\n await fs_extra_1.default.writeFile(configPath, (0, generateDefaultConfigContent_1.DEFAULT_CONFIG_CONTENT)(options));\n logger?.addFile(configPath);\n const packageJsonPath = path_1.default.join(projectRoot, 'package.json');\n await fs_extra_1.default.writeJson(packageJsonPath, buildPackageJson(options), { spaces: 2 });\n logger?.addFile(packageJsonPath);\n const tsconfigPath = path_1.default.join(projectRoot, 'tsconfig.json');\n await fs_extra_1.default.writeJson(tsconfigPath, buildTsConfig(), { spaces: 2 });\n logger?.addFile(tsconfigPath);\n const gitignorePath = path_1.default.join(projectRoot, '.gitignore');\n await fs_extra_1.default.writeFile(gitignorePath, `node_modules\ndist\nlib\n.store\n.env\n`);\n logger?.addFile(gitignorePath);\n if (options.advanced?.autoInstall) {\n const packageManager = (0, utils_1.detectPackageManager)(projectRoot);\n try {\n await (0, utils_1.installPackages)([], projectRoot);\n console.log((0, utils_1.colorize)(`[Installing dependencies]: Installed project dependencies using ${packageManager}.`, 'green'));\n }\n catch (error) {\n console.log((0, utils_1.colorize)('⚠️ Dependency installation failed or was interrupted. Skipping install.', 'yellow'), error);\n }\n }\n else {\n const packageManager = (0, utils_1.detectPackageManager)(projectRoot);\n const installCommand = packageManager === 'npm'\n ? 'npm install'\n : `${packageManager} install`;\n console.log((0, utils_1.colorize)('[Skipping install]: Set advanced.autoInstall=true to install dependencies automatically.', 'blue'));\n console.log((0, utils_1.colorize)(`[Next steps]: cd ${projectRoot} && ${installCommand}`, 'blue'));\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.rolePermissions = void 0;\nexports.rolePermissions = {\n admin: ['create', 'read', 'update', 'delete'],\n user: ['create', 'read', 'update'],\n viewer: ['read'],\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.generateGCManager = generateGCManager;\nfunction generateGCManager() {\n return `import { AmbitenModel } from '@ambiten/core';\nimport { ObjectId } from 'mongodb';\n\nexport interface GarbageCollectorOptions {\n /**\n * Retention period in days.\n */\n retentionPeriod?: number;\n dateField?: string;\n}\n\nexport async function runGarbageCollector(\n model: AmbitenModel<any>,\n options: GarbageCollectorOptions = {}\n): Promise<void> {\n const retentionPeriod = options.retentionPeriod ?? 7;\n const dateField = options.dateField ?? 'deletedAt';\n\n const cutoff = new Date(\n Date.now() - retentionPeriod * 24 * 60 * 60 * 1000\n );\n\n const expiredDocs = await model.find({\n [dateField]: { $lt: cutoff }\n });\n\n for (const doc of expiredDocs) {\n await model.deleteOne({ _id: new ObjectId(doc._id) });\n console.log(\\`🗑️ Deleted expired document: \\${doc._id}\\`);\n }\n\n console.log('✅ Garbage collection completed.');\n}\n`;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.hasManualTransactionMethods = hasManualTransactionMethods;\nfunction hasManualTransactionMethods(session) {\n return (typeof session.startTransaction === 'function' &&\n typeof session.commitTransaction === 'function' &&\n typeof session.abortTransaction === 'function');\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.initMultiTenancy = void 0;\nconst MultiTenantManager_1 = require(\"../MultiTenantManager\");\n/**\n * Initializes multi-tenancy by registering tenants with their respective MongoDB URIs.\n * Supports both lazy (on-demand) and eager connection strategies.\n *\n * @param {Record<string, string>} tenants - A record of tenant IDs mapped to their MongoDB URIs.\n * @param {InitMultiTenancyOptions} [options={}] - Optional configuration for multi-tenancy initialization.\n * @param {boolean} [options.lazy=false] - If `true`, tenants are registered lazily (connected on-demand).\n * @param {AmbitenConfig} [options.config] - Optional configuration, including a logger for logging messages.\n * @returns {Promise<void>} A promise that resolves when all tenants are registered.\n * @throws {Error} If a tenant's MongoDB URI is invalid or missing.\n * @throws {Error} If a tenant is already registered and `lazy` is `false`.\n * @example\n * // Initialize multi-tenancy with eager connection. Practically, you should use applyMultiTenancy instead.\n * that implements this function.\n * await initMultiTenancy({\n * 'tenant-a': 'mongodb://localhost:27017/tenant-a',\n * 'tenant-b': 'mongodb://localhost:27017/tenant-b'\n * }, {\n * lazy: false,\n * config: {}\n */\nconst initMultiTenancy = async (tenants, // tenantId => MongoDB URI\noptions = {}) => {\n const { lazy = false, config } = options;\n for (const [tenantId, uri] of Object.entries(tenants)) {\n if (!uri || typeof uri !== 'string' || !uri.startsWith('mongodb')) {\n throw new Error(`Invalid MongoDB URI for tenant \"${tenantId}\": ${uri}`);\n }\n if (MultiTenantManager_1.MultiTenantManager.hasTenant(tenantId)) {\n config?.logger?.warn?.(`Tenant \"${tenantId}\" is already registered. Skipping.`);\n continue;\n }\n if (lazy) {\n // Ensure logger implements all required methods for core/src/types/logger.types.ts\n if (config?.enabled && config.logger) {\n const logger = config.logger;\n return logger;\n }\n MultiTenantManager_1.MultiTenantManager.registerLazyTenant(tenantId, uri);\n continue;\n }\n else {\n // Eagerly connect\n await MultiTenantManager_1.MultiTenantManager.registerTenant(tenantId, uri);\n }\n }\n};\nexports.initMultiTenancy = initMultiTenancy;\nfunction impl_Logger(logger) {\n const { info, warn, error, fatal, debug } = logger;\n return {\n info: info?.bind(logger) ?? (() => { }),\n warn: warn?.bind(logger) ?? (() => { }),\n error: error?.bind(logger) ?? (() => { }),\n fatal: fatal?.bind(logger) ?? (() => { }),\n debug: debug?.bind(logger) ?? (() => { }),\n };\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenGraphQL = void 0;\nrequire(\"dotenv/config\");\nconst schema_1 = require(\"@graphql-tools/schema\");\nconst graphql_tag_1 = require(\"graphql-tag\");\nconst mongodb_1 = require(\"mongodb\");\nconst redis_manager_1 = require(\"../redis-manager\");\nconst utils_1 = require(\"../utils\");\nclass AmbitenGraphQL {\n options;\n typeDefs = [];\n resolvers = [];\n useRedis;\n provider;\n subscriber = null;\n publisher = null;\n constructor(options) {\n this.options = options;\n this.useRedis = options.useRedis !== false;\n this.typeDefs = options.customTypeDefs ?? [];\n this.resolvers = options.customResolvers ?? [];\n this.provider = options.provider;\n }\n customTypeDefs(schema) {\n if (Array.isArray(schema)) {\n this.typeDefs.push(...schema);\n }\n else {\n this.typeDefs.push(schema);\n }\n return this;\n }\n customResolvers(resolver) {\n this.resolvers.push(resolver);\n return this;\n }\n toModelContext(context, collectionName) {\n return {\n tenantId: context.tenantId,\n dbName: context.dbName,\n collectionName: collectionName ?? context.collectionName,\n session: context.session\n };\n }\n async getCollection(context, collectionName) {\n const ctx = this.toModelContext(context, collectionName);\n return context.provider.collection(collectionName, ctx);\n }\n async ensureRedis() {\n if (!this.useRedis) {\n return;\n }\n const client = await redis_manager_1.redis.get();\n if (!client) {\n return;\n }\n if (!client.isOpen && typeof client.connect === 'function') {\n await client.connect();\n }\n if (!this.publisher) {\n this.publisher = typeof client.duplicate === 'function' ? client.duplicate() : client;\n if (this.publisher?.connect && !this.publisher.isOpen) {\n await this.publisher.connect();\n }\n }\n if (!this.subscriber) {\n this.subscriber = typeof client.duplicate === 'function' ? client.duplicate() : client;\n if (this.subscriber?.connect && !this.subscriber.isOpen) {\n await this.subscriber.connect();\n }\n }\n }\n async publishEvent(channel, payload) {\n if (!this.useRedis) {\n return;\n }\n await this.ensureRedis();\n const client = await redis_manager_1.redis.get();\n if (this.publisher?.publish) {\n await this.publisher.publish(channel, JSON.stringify(payload));\n return;\n }\n if (client?.publish) {\n await client.publish(channel, JSON.stringify(payload));\n }\n }\n defaultTypeDefs() {\n return (0, graphql_tag_1.gql) `\n scalar JSON\n\n type Document {\n _id: ID!\n }\n\n type Query {\n findOne(collection: String!, id: ID!): JSON\n findAll(collection: String!): [JSON!]!\n }\n\n type Mutation {\n insertOne(collection: String!, data: JSON!): JSON\n updateOne(collection: String!, id: ID!, data: JSON!): JSON\n deleteOne(collection: String!, id: ID!): Boolean\n }\n\n type Subscription {\n documentInserted(collection: String!): JSON\n documentUpdated(collection: String!): JSON\n documentDeleted(collection: String!): JSON\n }\n `;\n }\n defaultResolvers() {\n return {\n Query: {\n findOne: async (_, { collection, id }, context) => {\n const col = await this.getCollection(context, collection);\n return col.findOne({ _id: new mongodb_1.ObjectId(id) });\n },\n findAll: async (_, { collection }, context) => {\n const col = await this.getCollection(context, collection);\n return col.find({}).toArray();\n }\n },\n Mutation: {\n insertOne: async (_, { collection, data }, context) => {\n const col = await this.getCollection(context, collection);\n const result = await col.insertOne(data);\n const newDoc = await col.findOne({ _id: result.insertedId });\n await this.publishEvent(`${utils_1.DB_CHANGE_EVENT}`, {\n documentInserted: {\n action: 'insertOne',\n collectionName: collection,\n doc: newDoc,\n tenantId: context.tenantId\n }\n });\n return newDoc;\n },\n updateOne: async (_, { collection, id, data }, context) => {\n const col = await this.getCollection(context, collection);\n await col.updateOne({ _id: new mongodb_1.ObjectId(id) }, { $set: data });\n const updatedDoc = await col.findOne({ _id: new mongodb_1.ObjectId(id) });\n await this.publishEvent(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'updateOne',\n collectionName: collection,\n doc: updatedDoc,\n tenantId: context.tenantId\n }\n });\n return updatedDoc;\n },\n deleteOne: async (_, { collection, id }, context) => {\n const col = await this.getCollection(context, collection);\n const result = await col.deleteOne({ _id: new mongodb_1.ObjectId(id) });\n if (result.deletedCount === 1) {\n await this.publishEvent(`${utils_1.DB_CHANGE_EVENT}`, {\n documentDeleted: {\n action: 'deleteOne',\n collectionName: collection,\n id,\n tenantId: context.tenantId\n }\n });\n return true;\n }\n return false;\n }\n },\n Subscription: {\n documentInserted: {\n subscribe: async () => {\n if (!this.useRedis) {\n return null;\n }\n await this.ensureRedis();\n return this.subscriber;\n }\n },\n documentUpdated: {\n subscribe: async () => {\n if (!this.useRedis) {\n return null;\n }\n await this.ensureRedis();\n return this.subscriber;\n }\n },\n documentDeleted: {\n subscribe: async () => {\n if (!this.useRedis) {\n return undefined;\n }\n await this.ensureRedis();\n return this.subscriber;\n }\n }\n }\n };\n }\n subscriptions() {\n return this.useRedis;\n }\n async generateSchema() {\n await this.ensureRedis();\n return (0, schema_1.makeExecutableSchema)({\n typeDefs: [this.defaultTypeDefs(), ...this.typeDefs],\n resolvers: [this.defaultResolvers(), ...this.resolvers]\n });\n }\n}\nexports.AmbitenGraphQL = AmbitenGraphQL;\n;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ErrorType = void 0;\nvar ErrorType;\n(function (ErrorType) {\n ErrorType[\"AmbitenError\"] = \"AmbitenError\";\n ErrorType[\"AmbitenErrorType\"] = \"AmbitenErrorType\";\n ErrorType[\"AmbitenErrorStack\"] = \"AmbitenErrorStack\";\n ErrorType[\"AmbitenErrorMessage\"] = \"AmbitenErrorMessage\";\n ErrorType[\"AmbitenErrorCause\"] = \"AmbitenErrorCause\";\n ErrorType[\"AmbitenCollectionError\"] = \"CollectionError\";\n ErrorType[\"AmbitenParseError\"] = \"ParseError\";\n ErrorType[\"AmbitenBulkWriteError\"] = \"MongoBulkWriteError\";\n ErrorType[\"AmbitenConnectionError\"] = \"ConnectionError\";\n ErrorType[\"AmbitenSchemaError\"] = \"SchemaError\";\n ErrorType[\"AmbitenModelError\"] = \"ModelError\";\n ErrorType[\"INITIALIZATION_ERROR\"] = \"INITIALIZATION_ERROR\";\n ErrorType[\"Ambiten_ERROR\"] = \"Ambiten_ERROR\";\n ErrorType[\"NULL_OR_UNDEFINED\"] = \"NULL_OR_UNDEFINED\";\n ErrorType[\"INVALID_SCHEME_ERROR\"] = \"INVALID_SCHEME_ERROR\";\n ErrorType[\"CONNECTION_ERROR\"] = \"CONNECTION_ERROR\";\n ErrorType[\"UNEXPECTED_ERROR\"] = \"UNEXPECTED_ERROR\";\n ErrorType[\"SCHEMA_ERROR\"] = \"SCHEMA_ERROR\";\n ErrorType[\"SCHEMA_VALIDATION_ERROR\"] = \"SCHEMA_VALIDATION_ERROR\";\n ErrorType[\"NOT_FOUND\"] = \"NOT_FOUND\";\n ErrorType[\"NO_DATABASE_FOUND\"] = \"NO_DATABASE_FOUND\";\n ErrorType[\"NOT_FOUND_IN_CACHE\"] = \"NOT_FOUND_IN_CACHE\";\n ErrorType[\"VALIDATION_ERROR\"] = \"VALIDATION_ERROR\";\n ErrorType[\"UNIQUE_CONSTRAINT_VIOLATION\"] = \"UNIQUE_CONSTRAINT_VIOLATION\";\n})(ErrorType || (exports.ErrorType = ErrorType = {}));\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AuthService = void 0;\nconst tslib_1 = require(\"tslib\");\nconst jsonwebtoken_1 = tslib_1.__importDefault(require(\"jsonwebtoken\"));\nrequire(\"dotenv/config\");\nconst SECRET = process.env.JWT_SECRET;\nconst REFRESH_SECRET = process.env.REFRESH_SECRET;\nconst REFRESH_EXPIRATION = process.env.REFRESH_EXPIRATION || '7d';\nconst JWT_EXPIRATION = process.env.JWT_EXPIRATION || '1d';\nclass AuthService {\n static generateToken(user) {\n return jsonwebtoken_1.default.sign(user, SECRET, {\n expiresIn: JWT_EXPIRATION\n });\n }\n static generateRefreshToken(user) {\n return jsonwebtoken_1.default.sign(user, REFRESH_SECRET, {\n expiresIn: REFRESH_EXPIRATION\n });\n }\n static verifyToken(token) {\n return jsonwebtoken_1.default.verify(token, SECRET);\n }\n}\nexports.AuthService = AuthService;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isValidObjectId = void 0;\nexports.isObjectId = isObjectId;\nexports.castId = castId;\nconst symbols_1 = require(\"./symbols\");\nconst mongodb_1 = require(\"mongodb\");\nObject.defineProperty(mongodb_1.ObjectId.prototype, \"_id\", {\n configurable: true,\n enumerable: true,\n get: function () {\n return this.toHexString();\n }\n});\nif (!Object.prototype.hasOwnProperty.call(mongodb_1.ObjectId.prototype, 'valueOf')) {\n mongodb_1.ObjectId.prototype.valueOf = function objectIdValueOf() {\n return this.toString();\n };\n}\nconst isValidObjectId = (id) => {\n return /^[0-9a-fA-F]{24}$/.test(id);\n};\nexports.isValidObjectId = isValidObjectId;\nmongodb_1.ObjectId.prototype.toJSON = function objectIdToJSON() {\n return this.toHexString();\n};\nmongodb_1.ObjectId.prototype[symbols_1.objectIdSymbol] = true;\nfunction isObjectId(id) {\n if (id == null)\n return false;\n if (typeof id !== \"object\")\n return false;\n if (id.constructor !== mongodb_1.ObjectId)\n return false;\n if (id[symbols_1.objectIdSymbol] !== true)\n return false;\n return true;\n}\n// Casts a string to an ObjectId\nfunction castId(inputId) {\n if (typeof inputId === \"string\") {\n const _id = inputId;\n if (!(0, exports.isValidObjectId)(_id)) {\n throw new Error(\"Invalid ObjectId format in castId\");\n }\n if (!isObjectId(inputId)) {\n throw new Error(\"Invalid ObjectId in castId\");\n }\n return mongodb_1.ObjectId.createFromHexString(_id);\n }\n return inputId;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenBootstrap\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./rbac/rbacMiddleware\"), exports);\ntslib_1.__exportStar(require(\"./rbac/rbacTypes\"), exports);\ntslib_1.__exportStar(require(\"./authorization/auth\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ensureModelNameSafe = ensureModelNameSafe;\n/**\n * Ensures that the provided model name is a valid, non-empty string.\n * Throws an error if the model name is invalid.\n *\n * @param {string} collectionName - The collection name to validate.\n * @returns {string} - The validated model name.\n * @throws {Error} - If the model name is invalid.\n * @example\n * const safeModelName = ensureModelNameSafe('MyModel123');\n */\nfunction ensureModelNameSafe(collectionName) {\n if (!collectionName || typeof collectionName !== 'string') {\n throw new Error('Model name must be a non-empty string');\n }\n const trimmedName = collectionName.trim();\n if (trimmedName.length === 0) {\n throw new Error('Model name cannot be just whitespace');\n }\n // Optional: Enforce allowed characters (letters, numbers, underscores)\n const nameRegex = /^[A-Za-z0-9_]+$/;\n if (!nameRegex.test(trimmedName)) {\n throw new Error('Model name must only contain letters, numbers, and underscores');\n }\n return trimmedName;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getModelFilesFromPath = getModelFilesFromPath;\nexports.loadModelsFromPath = loadModelsFromPath;\nconst tslib_1 = require(\"tslib\");\nconst fs_1 = tslib_1.__importDefault(require(\"fs\"));\nconst path_1 = tslib_1.__importDefault(require(\"path\"));\nfunction getModelFilesFromPath(dirPath) {\n const files = [];\n fs_1.default.readdirSync(dirPath).forEach((file) => {\n const fullPath = path_1.default.join(dirPath, file);\n const stat = fs_1.default.statSync(fullPath);\n if (stat.isDirectory()) {\n files.push(...getModelFilesFromPath(fullPath)); // Recursively load subfolders\n }\n else if (/\\.(ts|js)$/.test(file)) {\n files.push(fullPath);\n }\n });\n return files;\n}\n;\nasync function loadModelsFromPath(dirPath) {\n const modelFiles = getModelFilesFromPath(dirPath);\n const models = [];\n for (const file of modelFiles) {\n try {\n const modelModule = await import(file);\n if (modelModule.default) {\n models.push(modelModule.default);\n }\n else {\n console.warn(`No default export found in ${file}`);\n }\n }\n catch (error) {\n console.error(`Error loading model from ${file}:`, error);\n }\n }\n return models;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenGraphQL\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenGC\"), exports);\ntslib_1.__exportStar(require(\"./gcCron.node\"), exports);\ntslib_1.__exportStar(require(\"./gcManager\"), exports);\ntslib_1.__exportStar(require(\"./gcCron.browser\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.authorize = authorize;\nconst AuthUtils_1 = require(\"../../utils/AuthUtils\");\n/**\n * Middleware to authorize access to routes based on user roles.\n * This middleware checks if the request contains a valid JWT token,\n * @param roles - An array of roles that are allowed to access the route.\n * @returns\n */\nfunction authorize(roles) {\n return (req, res, next) => {\n let token;\n const authHeader = req.headers?.authorization || req.headers.Authorization;\n if (typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {\n token = authHeader.split(' ')[1];\n }\n if (!token) {\n return res.status(401).json({ error: \"Access token required\" });\n }\n try {\n const decoded = AuthUtils_1.AuthService.verifyToken(token);\n console.info(`Decoded token: ${JSON.stringify(decoded)}`);\n if (!decoded) {\n return res.status(401).json({ error: \"Unauthorized\" });\n }\n if (!roles.includes(decoded.role)) {\n return res.status(403).json({ error: \"Access Denied\" });\n }\n return decoded;\n next();\n }\n catch {\n res.status(401).json({ error: \"Unauthorized\" });\n }\n };\n}\n","module.exports = __WEBPACK_EXTERNAL_MODULE__8535__;","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenModelRegistry = void 0;\nexports.clearModelRegistryForTests = clearModelRegistryForTests;\nconst modelRegistry = new Set();\n/**\n * AmbitenModelRegistry manages registered Ambiten model instances.\n */\nexports.AmbitenModelRegistry = {\n registerModel(model) {\n modelRegistry.add(model);\n },\n getRegisteredModel(model) {\n return modelRegistry.has(model) ? model : null;\n },\n isModelRegistered(model) {\n return modelRegistry.has(model);\n },\n unregisterModel(model) {\n modelRegistry.delete(model);\n },\n getAllModels() {\n return [...modelRegistry];\n },\n clear() {\n modelRegistry.clear();\n }\n};\nconst registeredModels = [];\nfunction clearModelRegistryForTests() {\n for (const model of registeredModels) {\n exports.AmbitenModelRegistry.unregisterModel(model);\n }\n registeredModels.length = 0;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenContext\"), exports);\ntslib_1.__exportStar(require(\"./helpers/transactionSession\"), exports);\ntslib_1.__exportStar(require(\"./helpers/runManualTransaction\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenGC = void 0;\nconst tslib_1 = require(\"tslib\");\nconst cron = tslib_1.__importStar(require(\"node-cron\"));\nconst utils_1 = require(\"../utils\");\nconst gcManager_1 = require(\"./gcManager\");\nclass AmbitenGC {\n options;\n enabled;\n intervalMs;\n intervalRef = null;\n cronTask = null;\n constructor(options = {}) {\n this.options = options;\n this.enabled = options.enabled !== false;\n this.intervalMs = options.interval\n ? this.parseInterval(options.interval)\n : 60_000;\n if (options.retentionPeriod) {\n this.intervalMs = options.retentionPeriod * 24 * 60 * 60 * 1000;\n }\n if (!this.enabled) {\n this.log('info', '[AmbitenGC] Garbage Collector is disabled.');\n return;\n }\n if (options.cron) {\n this.cronTask = cron.schedule(options.cron, () => {\n void this.runOnce();\n });\n this.log('info', `[AmbitenGC] Cron schedule set to: ${options.cron}`);\n return;\n }\n if (options.interval) {\n this.start();\n this.log('info', `[AmbitenGC] Interval set to: ${options.interval}`);\n return;\n }\n this.log('info', '[AmbitenGC] Initialized. Manual run mode enabled.');\n }\n /**\n * Starts interval-based garbage collection.\n */\n start() {\n if (!this.enabled) {\n return;\n }\n if (this.intervalRef) {\n return;\n }\n this.intervalRef = setInterval(() => {\n void this.runOnce();\n }, this.intervalMs);\n this.log('info', `[AmbitenGC] Started GC loop every ${this.intervalMs} ms`);\n }\n /**\n * Stops interval or cron-based garbage collection.\n */\n stop() {\n if (this.intervalRef) {\n clearInterval(this.intervalRef);\n this.intervalRef = null;\n }\n if (this.cronTask) {\n this.cronTask.stop();\n this.cronTask = null;\n }\n this.log('info', '[AmbitenGC] Stopped.');\n }\n /**\n * Runs garbage collection once across registered models.\n *\n * @param ctx - Optional model execution context override.\n * @returns Summary of the GC run.\n */\n async runOnce(ctx) {\n if (!this.enabled) {\n return {\n scanned: 0,\n succeeded: 0,\n failed: 0,\n models: []\n };\n }\n const result = await (0, gcManager_1.runGarbageCollectorOnAllModels)({\n ctx: ctx ?? this.options.ctx,\n continueOnError: this.options.continueOnError ?? true\n });\n if (this.options.logResults) {\n this.log(result.failed > 0 ? 'warn' : 'info', `[AmbitenGC] Completed. scanned=${result.scanned}, succeeded=${result.succeeded}, failed=${result.failed}`);\n }\n return result;\n }\n /**\n * Parses interval strings such as \"30s\", \"5m\", \"1h\", or \"1d\".\n *\n * @param duration - Interval duration.\n * @returns Duration in milliseconds.\n * @throws {Error} When the interval format is invalid.\n */\n parseInterval(duration) {\n const match = duration.match(/^(\\d+)([smhd])$/);\n if (!match) {\n throw new Error(`Invalid interval format: ${duration}`);\n }\n const [, num, unit] = match;\n const value = Number.parseInt(num, 10);\n switch (unit) {\n case 's':\n return value * 1000;\n case 'm':\n return value * 60 * 1000;\n case 'h':\n return value * 60 * 60 * 1000;\n case 'd':\n return value * 24 * 60 * 60 * 1000;\n default:\n throw new Error(`Unknown time unit: ${unit}`);\n }\n }\n log(level, message, meta) {\n const logger = this.options.logger;\n if (logger?.[level]) {\n logger[level]?.(message, meta);\n return;\n }\n if (level === 'error') {\n console.error((0, utils_1.colorize)(message, 'red'), meta ?? '');\n return;\n }\n if (level === 'warn') {\n console.warn((0, utils_1.colorize)(message, 'yellow'), meta ?? '');\n return;\n }\n console.log((0, utils_1.colorize)(message, 'blue'), meta ?? '');\n }\n}\nexports.AmbitenGC = AmbitenGC;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.invalidateTenantCache = invalidateTenantCache;\n/**\n * Invalidates the cache for a specific tenant by deleting all keys that match the tenant ID.\n * Optionally, a namespace can be provided to further filter the keys.\n *\n * @param {RedisClientType} client - The Redis client instance.\n * @param {string} tenantId - The ID of the tenant whose cache should be invalidated.\n * @param {string} [namespace] - Optional namespace to filter keys.\n * @example\n * // Invalidate cache for tenant 'tenant123'\n * invalidateTenantCache(redisClient, 'tenant123');\n * @example\n * // Invalidate cache for tenant 'tenant123' with namespace 'users'\n * invalidateTenantCache(redisClient, 'tenant123', 'users');\n */\nasync function invalidateTenantCache(client, tenantId, namespace) {\n const pattern = namespace\n ? `ambiten:${tenantId}:${namespace}:*`\n : `ambiten:${tenantId}:*`;\n const keys = await client.keys(pattern);\n if (keys.length) {\n await client.del(keys);\n console.info(`🔁 Cleared ${keys.length} cache entries for ${tenantId}${namespace ? ` (${namespace})` : ''}`);\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.eventTypes = void 0;\nexports.eventTypes = [\n 'pre-save',\n 'post-save',\n 'pre-update',\n 'post-update',\n 'pre-delete',\n 'post-delete',\n 'aggregate',\n 'disconnect',\n 'connect',\n 'dropDatabase',\n 'createIndex',\n 'dropIndex',\n 'create',\n 'find',\n 'findOne',\n 'insertOne',\n 'insertMany',\n 'updateOne',\n 'updateMany',\n 'deleteOne',\n 'deleteMany',\n 'transaction'\n];\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.startGarbageCollector = void 0;\nconst utils_1 = require(\"../utils\");\nconst startGarbageCollector = () => {\n // No-op for browsers\n console.warn((0, utils_1.colorize)('[GC] Garbage collector is disabled in the browser.', 'red'));\n};\nexports.startGarbageCollector = startGarbageCollector;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.measureQuery = measureQuery;\nconst perf_hooks_1 = require(\"perf_hooks\");\nconst ambitenContext_1 = require(\"../context/ambitenContext\");\nasync function measureQuery(meta, executor) {\n if (!ambitenContext_1.AmbitenContext.hasActiveContext()) {\n throw new Error('[Ambiten] Missing runtime context.');\n }\n const logger = ambitenContext_1.AmbitenContext.getLogger();\n const observer = ambitenContext_1.AmbitenContext.getObserver();\n const loggerMeta = ambitenContext_1.AmbitenContext.getLoggerMeta() ?? {};\n const tenantId = ambitenContext_1.AmbitenContext.getTenantId();\n const requestId = ambitenContext_1.AmbitenContext.getRequestId();\n const dbName = ambitenContext_1.AmbitenContext.getDbName();\n const collectionName = meta.collectionName ?? ambitenContext_1.AmbitenContext.getCollectionName();\n const budgetAfterIncrement = ambitenContext_1.AmbitenContext.incrementQueries();\n const start = perf_hooks_1.performance.now();\n try {\n const result = await executor();\n const durationMs = Math.round((perf_hooks_1.performance.now() - start) * 100) / 100;\n const budgetAfterTime = ambitenContext_1.AmbitenContext.addQueryTime(durationMs);\n const payload = {\n operation: meta.operation,\n collectionName,\n durationMs,\n status: 'success',\n tenantId,\n requestId,\n dbName,\n filter: meta.filter,\n update: meta.update,\n pipeline: meta.pipeline,\n documentCount: meta.documentCount,\n queriesExecuted: budgetAfterIncrement.queriesExecuted,\n maxQueries: budgetAfterIncrement.maxQueries,\n totalBudgetUsed: budgetAfterTime.totalTimeMs,\n ...loggerMeta,\n ...(meta.extra ?? {})\n };\n setImmediate(() => {\n observer?.onQuery?.(payload);\n if (logger?.info) {\n logger.info('[Ambiten Query]', payload);\n }\n else if (ambitenContext_1.AmbitenContext.isDebug()) {\n console.log('[Ambiten Query]', payload);\n }\n });\n return result;\n }\n catch (error) {\n const durationMs = Math.round((perf_hooks_1.performance.now() - start) * 100) / 100;\n const budgetAfterTime = ambitenContext_1.AmbitenContext.addQueryTime(durationMs);\n const payload = {\n operation: meta.operation,\n collectionName,\n durationMs,\n status: 'error',\n tenantId,\n requestId,\n dbName,\n filter: meta.filter,\n update: meta.update,\n pipeline: meta.pipeline,\n documentCount: meta.documentCount,\n queriesExecuted: budgetAfterTime.queriesExecuted,\n maxQueries: budgetAfterTime.maxQueries,\n totalBudgetUsed: budgetAfterTime.totalTimeMs,\n errorMessage: error?.message,\n errorName: error?.name,\n ...loggerMeta,\n ...(meta.extra ?? {})\n };\n setImmediate(() => {\n observer?.onQueryError?.({\n ...payload,\n error\n });\n if (logger?.error) {\n logger.error('[Ambiten Query Error]', payload);\n }\n else if (ambitenContext_1.AmbitenContext.isDebug()) {\n console.error('[Ambiten Query Error]', payload);\n }\n });\n throw error;\n }\n}\n;\n","module.exports = require(\"@ambiten/logger\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./debugLog\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenModel = void 0;\nconst tslib_1 = require(\"tslib\");\nrequire(\"dotenv/config\");\nconst mongodb_1 = require(\"mongodb\");\nconst ambitenClient_1 = require(\"./ambitenClient\");\nconst ambitenSchema_1 = require(\"./ambitenSchema\");\nconst events_1 = tslib_1.__importDefault(require(\"events\"));\nconst graphql_subscriptions_1 = require(\"graphql-subscriptions\");\nconst tanancy_1 = require(\"../tanancy\");\nconst redis_manager_1 = require(\"../redis-manager\");\nconst utils_1 = require(\"../utils\");\nconst context_1 = require(\"../context\");\nconst instrumentation_1 = require(\"../instrumentation\");\nconst debug_1 = require(\"../debug\");\nconst pubsub = new graphql_subscriptions_1.PubSub();\n/**\n * A MongoDB-backed model with schema validation, middleware, multi-tenancy,\n * transactions, caching, soft-delete support, and query instrumentation.\n *\n * @typeParam T - The MongoDB document shape handled by this model.\n */\nclass AmbitenModel {\n _provider;\n _collectionName;\n _collectionOverride;\n _schema;\n _initialized = false;\n _defaultCtx;\n _modelGCConfig;\n _gcConfig;\n _gcTimer;\n eventEmitter = new events_1.default();\n beforeMiddlewares = new Map();\n afterMiddlewares = new Map();\n _softDeleteConfig;\n /**\n * Creates a new model instance.\n *\n * @param options - Model configuration including collection, schema, provider,\n * default context, and optional GC configuration.\n */\n constructor(options) {\n if (!options) {\n const message = 'AmbitenModel options are required.';\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.NULL_OR_UNDEFINED, message, { details: { providedOptions: options, typeError: utils_1.ErrorType.AmbitenModelError } });\n }\n if (!options.collectionName) {\n const message = 'collectionName is required.';\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.NULL_OR_UNDEFINED, message, { details: { providedOptions: options, typeError: utils_1.ErrorType.AmbitenModelError } });\n }\n this._collectionName = options.collectionName;\n this._schema =\n options.schema ?? new ambitenSchema_1.AmbitenSchema({});\n this._provider = options.provider ?? ambitenClient_1.AmbitenClient.init();\n this._collectionOverride = options.collection;\n this._modelGCConfig = options.gcConfig;\n if (options.ctx?.db) {\n const fixedDb = options.ctx.db;\n this._provider = { db: async () => fixedDb };\n }\n if (options.ctx?.tenantId || options.ctx?.dbName || options.ctx?.collectionName) {\n this._defaultCtx = {\n tenantId: options.ctx?.tenantId,\n dbName: options.ctx?.dbName,\n collectionName: options.ctx?.collectionName,\n db: options.ctx?.db,\n session: options.ctx?.session,\n config: options.ctx?.config,\n };\n }\n const schemaGCConfig = this.resolveSchemaGCConfig();\n if (this.isGCEnabled() || schemaGCConfig) {\n utils_1.AmbitenModelRegistry.registerModel(this);\n }\n this.initMiddleware();\n }\n /**\n * Merges an explicit operation context with the model default context and the\n * current runtime context.\n *\n * @param ctx - Optional operation context.\n * @returns A merged context or `undefined` when no context values are present.\n */\n mergeCtx(ctx) {\n const runtimeCtx = context_1.AmbitenContext.get();\n const merged = {\n tenantId: ctx?.tenantId ?? this._defaultCtx?.tenantId ?? runtimeCtx.tenantId,\n dbName: ctx?.dbName ?? this._defaultCtx?.dbName ?? runtimeCtx.dbName,\n db: ctx?.db ?? this._defaultCtx?.db,\n collectionName: ctx?.collectionName ??\n this._defaultCtx?.collectionName ??\n runtimeCtx.collectionName,\n config: ctx?.config ?? this._defaultCtx?.config,\n session: ctx?.session ?? this._defaultCtx?.session ?? runtimeCtx.session,\n withDeleted: ctx?.withDeleted,\n onlyDeleted: ctx?.onlyDeleted,\n hardDelete: ctx?.hardDelete,\n };\n return Object.values(merged).some((value) => value !== undefined)\n ? merged\n : undefined;\n }\n /**\n * Ensures a runtime Ambiten context exists before executing an instrumented action.\n *\n * This allows model methods to remain safe when invoked outside adapter-managed\n * request lifecycles while still preserving tenant-aware instrumentation.\n *\n * @param ctx - Optional model context.\n * @param action - The action to execute inside a runtime context.\n * @returns The action result.\n */\n async runWithModelContext(ctx, action) {\n if (context_1.AmbitenContext.hasActiveContext()) {\n return action();\n }\n const merged = this.mergeCtx(ctx);\n return context_1.AmbitenContext.run({\n tenantId: merged?.tenantId,\n dbName: merged?.dbName,\n collectionName: merged?.collectionName ?? this._collectionName,\n session: merged?.session,\n }, action);\n }\n isGCEnabled() {\n return this._modelGCConfig?.enableGC === true;\n }\n resolveSchemaGCConfig() {\n return this._schema.getGCConfig?.();\n }\n /**\n * Resolves the MongoDB collection for the current model and context.\n *\n * @param ctx - Optional model context.\n * @returns The resolved MongoDB collection.\n */\n async getCollection(ctx) {\n if (this._collectionOverride) {\n return this._collectionOverride;\n }\n this.ensureConfigured();\n const db = await this.resolveDb(ctx);\n const collectionName = this.resolveCollectionName(ctx);\n (0, debug_1.debugLog)('Resolved collection', {\n collectionName,\n dbName: db.databaseName,\n tenantId: this.mergeCtx(ctx)?.tenantId,\n });\n return db.collection(collectionName);\n }\n /**\n * Resolves a registered tenant configuration.\n *\n * @param tenantId - The tenant identifier.\n * @returns The tenant configuration.\n */\n getResolvedTenant(tenantId) {\n const tenant = tanancy_1.MultiTenantManager.getTenant(tenantId);\n if (!tenant) {\n throw new Error(`Tenant \"${tenantId}\" is not registered.`);\n }\n return { ...tenant };\n }\n /**\n * Resolves the MongoDB database for the current operation.\n *\n * @param ctx - Optional model context.\n * @returns The resolved MongoDB database instance.\n */\n async resolveDb(ctx) {\n const resolvedCtx = this.mergeCtx(ctx);\n if (resolvedCtx?.db) {\n return resolvedCtx.db;\n }\n if (resolvedCtx?.tenantId) {\n const tenant = this.getResolvedTenant(resolvedCtx.tenantId);\n const client = await tanancy_1.MultiTenantManager.getClient(resolvedCtx.tenantId);\n if (!client) {\n throw new Error(`MongoClient for tenant \"${resolvedCtx.tenantId}\" is not available.`);\n }\n const dbName = resolvedCtx.dbName ?? tenant.dbName;\n if (!dbName) {\n throw new Error(`No database name configured for tenant \"${resolvedCtx.tenantId}\".`);\n }\n return client.db(dbName);\n }\n const db = await this._provider.db(resolvedCtx);\n if (!db || typeof db.collection !== 'function') {\n throw new Error(`AmbitenModel: provider.db() did not return a valid Db instance for collection \"${this._collectionName}\".`);\n }\n return db;\n }\n /**\n * Resolves the collection name for the current operation.\n *\n * @param ctx - Optional model context.\n * @returns The collection name.\n */\n resolveCollectionName(ctx) {\n const resolvedCtx = this.mergeCtx(ctx);\n const collectionName = resolvedCtx?.collectionName ?? this._collectionName;\n if (!collectionName || typeof collectionName !== 'string' || !collectionName.trim()) {\n throw new Error('AmbitenModel: collectionName is not configured.');\n }\n return collectionName.trim();\n }\n /**\n * Resolves the client session for the current operation.\n *\n * @param ctx - Optional model context.\n * @returns The MongoDB client session if available.\n */\n resolveSession(ctx) {\n return this.mergeCtx(ctx)?.session;\n }\n /**\n * Resolves the MongoDB client session to use for an operation.\n *\n * Precedence order:\n * 1. Explicit externally supplied session\n * 2. Per-call model context session\n * 3. Active runtime session from AmbitenContext\n *\n * This ensures explicit caller intent always overrides implicit runtime state.\n *\n * @param ctx - Optional model execution context.\n * @param externalSession - Optional explicit session supplied by the caller.\n * @returns The resolved MongoDB client session, or `undefined` when no session is available.\n */\n resolveSessionStrict(ctx, externalSession) {\n return externalSession ?? ctx?.session ?? context_1.AmbitenContext.getSession();\n }\n /**\n * Subscribes to a model event.\n *\n * @param event - Event type.\n * @param listener - Event listener callback.\n */\n on(event, listener) {\n this.eventEmitter.on(event, listener);\n }\n /**\n * Subscribes to a model event once.\n *\n * @param event - Event type.\n * @param listener - Event listener callback.\n */\n once(event, listener) {\n this.eventEmitter.once(event, listener);\n }\n /**\n * Removes a subscribed event listener.\n *\n * @param event - Event type.\n * @param listener - Event listener callback.\n */\n off(event, listener) {\n this.eventEmitter.off(event, listener);\n }\n /**\n * Removes a specific event listener.\n *\n * @param event - Event type.\n * @param listener - Event listener callback.\n */\n removeListener(event, listener) {\n this.eventEmitter.removeListener(event, listener);\n }\n /**\n * Ensures the model has the minimum configuration required to operate.\n */\n ensureConfigured() {\n if (!this._collectionName || typeof this._collectionName !== 'string') {\n throw new Error('AmbitenModel: collectionName is not configured.');\n }\n if (!this._provider || typeof this._provider.db !== 'function') {\n throw new Error('AmbitenModel: provider is not configured. Provide a valid DbProvider with a db(ctx) method.');\n }\n }\n /**\n * Initializes the model by validating configuration, resolving the collection,\n * and creating the GC TTL index when enabled.\n */\n async init() {\n if (this._initialized)\n return;\n try {\n this.ensureConfigured();\n if (!this._schema) {\n this._schema = new ambitenSchema_1.AmbitenSchema({});\n }\n await this.getCollection();\n if (this.isGCEnabled() && this._modelGCConfig) {\n await this.ensureGCIndex(this._modelGCConfig);\n }\n this._initialized = true;\n }\n catch (error) {\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.INITIALIZATION_ERROR, `Failed to initialize AmbitenModel: ${error?.message ?? String(error)}`, {\n details: {\n operation: 'init',\n TypeError: utils_1.ErrorType.INITIALIZATION_ERROR,\n }\n });\n }\n }\n /**\n * Returns a model instance bound to a default context.\n *\n * @param ctx - Context to bind to the cloned model.\n * @returns A cloned model instance with merged default context.\n */\n bind(ctx) {\n const clone = Object.create(this);\n clone._defaultCtx = { ...this._defaultCtx, ...ctx };\n return clone;\n }\n /**\n * Registers or reconfigures the model.\n *\n * @param options - Model registration options.\n */\n async registerModel(options) {\n const { ctx, collectionName, schema, collection } = options;\n if (!collectionName) {\n throw new Error('Collection name is required.');\n }\n this._collectionName = collectionName;\n this._collectionOverride = collection;\n this._schema = schema ?? new ambitenSchema_1.AmbitenSchema({});\n if (ctx) {\n this._defaultCtx = {\n ...this._defaultCtx,\n ...ctx,\n };\n }\n this._initialized = false;\n this.ensureConfigured();\n await this.init();\n }\n /**\n * Ensures the TTL index used by the garbage collector exists.\n *\n * @param gc - GC configuration.\n */\n async ensureGCIndex(gc) {\n if (!gc.enableGC || !gc.ttl) {\n return;\n }\n const col = await this.getCollection();\n const field = gc.field ??\n gc.updatedAtField ??\n gc.createdAtField ??\n 'updatedAt';\n await col.createIndex({ [field]: 1 }, {\n expireAfterSeconds: gc.ttl,\n name: gc.indexName ?? `${this._collectionName}_${field}_ttl`,\n background: true\n });\n }\n /**\n * Returns the schema attached to this model.\n */\n get schema() {\n return this._schema;\n }\n /**\n * Returns the schema attached to this model.\n */\n getSchema() {\n return this.schema;\n }\n /**\n * Validates a document against the model schema.\n * Throws an error if validation fails.\n * @param doc - Document to validate.\n */\n validate(doc) {\n if (this._schema) {\n this._schema.validate(doc);\n }\n }\n /**\n * Validates a document asynchronously against the model schema.\n * Useful for schemas that perform async validation, such as checking uniqueness\n * @param doc - Document to validate.\n * @returns The validated document.\n */\n async validateAsync(doc) {\n if (this._schema) {\n await this._schema.validateAsync(doc);\n }\n return doc;\n }\n /**\n * Initializes internal schema middleware for relationships, aggregation, and\n * change notifications. This is called during model initialization and ensures that all registered\n * middleware is set up before any operations are performed.\n */\n initMiddleware() {\n if (!this._schema)\n return;\n this._schema.pre('create', async (ctx) => {\n const doc = ctx.doc;\n if (!doc)\n return;\n const relationships = this._schema.getRelationships() ?? [];\n for (const { ref, localField } of relationships) {\n const relatedCollection = (await this.getCollection()).db?.collection(ref);\n const filter = { [localField]: doc._id };\n await relatedCollection?.updateMany(filter, {\n $set: { [localField]: doc._id },\n });\n }\n });\n this._schema.post('create', async (ctx) => {\n const doc = (ctx.result ?? ctx.doc);\n if (!doc)\n return;\n const relationships = this._schema.getRelationships() ?? [];\n for (const { ref, localField } of relationships) {\n const relatedCollection = (await this.getCollection()).db?.collection(ref);\n const filter = { [localField]: doc._id };\n await relatedCollection?.updateOne(filter, {\n $set: { [localField]: doc._id },\n });\n }\n await pubsub.publish('DB_CHANGE', {\n dbChange: {\n action: 'create',\n doc,\n },\n });\n });\n this._schema.post('updateOne', async (ctx) => {\n const filter = ctx.filter;\n const update = ctx.update;\n if (!filter || !update)\n return;\n const relationships = this._schema.getRelationships() ?? [];\n for (const { ref, localField } of relationships) {\n const relatedCollection = (await this.getCollection()).db?.collection(ref);\n const updateFilter = { [localField]: update.$set?._id };\n await relatedCollection?.updateOne(updateFilter, {\n $set: { [localField]: update.$set?._id },\n });\n }\n await pubsub.publish('DB_CHANGE', {\n dbChange: {\n action: 'updateOne',\n filter,\n update,\n },\n });\n });\n this._schema.pre('deleteOne', async (ctx) => {\n const doc = (ctx.doc ?? ctx.result);\n if (!doc)\n return;\n const relationships = this._schema.getRelationships() ?? [];\n for (const { ref, localField } of relationships) {\n const relatedCollection = (await this.getCollection()).db?.collection(ref);\n const filter = { [localField]: doc._id };\n await relatedCollection?.deleteOne(filter);\n }\n });\n this._schema.pre('aggregate', async (ctx) => {\n const pipeline = ctx.pipeline;\n if (!pipeline)\n return;\n const relationships = this._schema.getRelationships() ?? [];\n for (const { ref, localField } of relationships) {\n pipeline.unshift({\n $lookup: {\n from: ref,\n localField: localField,\n foreignField: '_id',\n as: ref,\n },\n });\n }\n });\n this._schema.post('aggregate', async (ctx) => {\n const result = ctx.result;\n if (!result)\n return;\n const relationships = this._schema.getRelationships() ?? [];\n for (const doc of result) {\n for (const { ref } of relationships) {\n delete doc[ref];\n }\n }\n await pubsub.publish('DB_CHANGE', {\n dbChange: {\n action: 'aggregate',\n result,\n },\n });\n });\n }\n /**\n * Creates a new document in the model collection.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered create middlewares,\n * validates the incoming document against the model schema, triggers schema\n * create hooks, invalidates relevant cache patterns, and publishes a database\n * change event after successful insertion.\n *\n * @param doc - The document to insert.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns The created document as a normalized model result.\n * @throws {Error} When the provided document is missing or invalid.\n */\n async create(doc, ctx) {\n await this.init();\n if (!doc || typeof doc !== 'object') {\n throw new Error('Document must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'create',\n collectionName: this.resolveCollectionName(ctx),\n documentCount: 1\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('create', ctx, {\n doc: doc\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('create', middlewareCtx);\n const nextDoc = (middlewareCtx.doc ?? doc);\n middlewareCtx.doc = nextDoc;\n this.validate(nextDoc);\n await this.schema.executePre('create', this.buildHookPayload('create', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: nextDoc,\n meta: middlewareCtx.meta\n }));\n const insertResult = await col.insertOne(nextDoc, session ? { session } : undefined);\n const createdDoc = {\n ...nextDoc,\n _id: insertResult.insertedId\n };\n await this.schema.executePost('create', this.buildHookPayload('create', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: createdDoc,\n result: createdDoc,\n meta: middlewareCtx.meta\n }));\n const payload = this.toModelResult(createdDoc);\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('create', middlewareCtx);\n const finalResult = (middlewareCtx.result ?? payload);\n await this.invalidateCachePatterns('create', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentInserted: {\n action: 'create',\n collectionName: middlewareCtx.collectionName,\n doc: finalResult,\n meta: middlewareCtx.meta\n }\n });\n return finalResult;\n }));\n }\n /**\n * Finds documents matching the provided filter.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered find middlewares, supports\n * optional result caching, triggers schema find hooks, and returns normalized\n * model results.\n *\n * @param filter - MongoDB filter used to match documents.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @param options - Optional query-level features such as caching.\n * @returns An array of normalized model results.\n * @throws {Error} When the filter is invalid.\n */\n async find(filter = {}, ctx, options) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'find',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('find', ctx, { filter });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('find', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const cache = options?.cache ? this.resolveCache(options) : null;\n await this.schema.executePre('find', this.buildHookPayload('create', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n meta: middlewareCtx.meta\n }));\n let cacheKey = null;\n if (cache) {\n cacheKey = this.buildCacheKey('find', {\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName\n });\n const cached = await cache.get(cacheKey, {\n ttlSeconds: typeof options?.cache === 'object' ? options.cache.ttl : undefined,\n tenantId: middlewareCtx.tenantId,\n namespace: middlewareCtx.collectionName\n });\n if (cached) {\n middlewareCtx.result = cached;\n await this.schema.executePost('find', this.buildHookPayload('find', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n result: cached,\n meta: {\n ...(middlewareCtx.meta ?? {}),\n cacheHit: true\n }\n }));\n await this.runAfterMiddlewares('find', middlewareCtx);\n return (middlewareCtx.result ?? cached);\n }\n }\n const cursor = col.find(effectiveFilter, session ? { session } : undefined);\n const results = await cursor.toArray();\n const payload = this.toModelResults(results);\n await this.schema.executePost('find', this.buildHookPayload('find', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n result: payload,\n meta: middlewareCtx.meta\n }));\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('find', middlewareCtx);\n const finalResult = (middlewareCtx.result ?? payload);\n if (cache && cacheKey) {\n await cache.set(cacheKey, finalResult, {\n ttlSeconds: typeof options?.cache === 'object' ? options.cache.ttl : undefined,\n tenantId: middlewareCtx.tenantId,\n namespace: middlewareCtx.collectionName\n });\n }\n return finalResult;\n }));\n }\n /**\n * Finds a single document matching the provided filter.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered findOne middlewares,\n * supports optional result caching, triggers schema find hooks, and returns a\n * normalized model result when a document is found.\n *\n * @param filter - MongoDB filter used to match the document.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @param options - Optional query-level features such as caching.\n * @returns The matched document as a normalized model result, or `null` if no document matched.\n * @throws {Error} When the filter is missing or invalid.\n */\n async findOne(filter, ctx, options) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'findOne',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('findOne', ctx, {\n filter\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('findOne', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const cache = options?.cache ? this.resolveCache(options) : null;\n let cacheKey = null;\n await this.schema.executePre('findOne', this.buildHookPayload('findOne', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n meta: middlewareCtx.meta\n }));\n if (cache) {\n cacheKey = this.buildCacheKey('findOne', {\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName\n });\n const cached = await cache.get(cacheKey, {\n ttlSeconds: typeof options?.cache === 'object' ? options.cache.ttl : undefined,\n tenantId: middlewareCtx.tenantId,\n namespace: middlewareCtx.collectionName\n });\n if (cached !== null && cached !== undefined) {\n middlewareCtx.result = cached;\n await this.schema.executePost('findOne', this.buildHookPayload('findOne', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n result: cached,\n meta: {\n ...(middlewareCtx.meta ?? {}),\n cacheHit: true\n }\n }));\n await this.runAfterMiddlewares('findOne', middlewareCtx);\n return (middlewareCtx.result ?? cached);\n }\n }\n const result = await col.findOne(effectiveFilter, session ? { session } : undefined);\n const payload = result\n ? this.toModelResult(result)\n : null;\n await this.schema.executePost('findOne', {\n operation: 'findOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n result: payload,\n meta: middlewareCtx.meta\n });\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('findOne', middlewareCtx);\n const finalResult = (middlewareCtx.result ?? payload);\n if (cache && cacheKey && finalResult !== null) {\n await cache.set(cacheKey, finalResult, {\n ttlSeconds: typeof options?.cache === 'object' ? options.cache.ttl : undefined,\n tenantId: middlewareCtx.tenantId,\n namespace: middlewareCtx.collectionName\n });\n }\n return finalResult;\n }));\n }\n /**\n * Updates a single document matching the provided filter.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered update middlewares,\n * triggers schema update hooks, invalidates relevant cache patterns, and\n * publishes a database change event after completion.\n *\n * @param filter - MongoDB filter used to identify the document to update.\n * @param update - MongoDB update document to apply.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the update document is missing or invalid.\n */\n async updateOne(filter, update, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!update || typeof update !== 'object') {\n throw new Error('Update must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'updateOne',\n collectionName: this.resolveCollectionName(ctx),\n filter,\n update\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('updateOne', ctx, {\n filter,\n update\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('updateOne', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n const effectiveUpdate = (middlewareCtx.update ?? update);\n middlewareCtx.filter = effectiveFilter;\n middlewareCtx.update = effectiveUpdate;\n await this.schema.executePre('updateOne', {\n operation: 'updateOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: effectiveUpdate,\n meta: middlewareCtx.meta\n });\n const result = await col.updateOne(effectiveFilter, effectiveUpdate, session ? { session } : undefined);\n const updateResult = {\n acknowledged: result?.acknowledged,\n matchedCount: result?.matchedCount,\n modifiedCount: result?.modifiedCount,\n upsertedCount: result?.upsertedCount,\n upsertedId: result?.upsertedId\n };\n await this.schema.executePost('updateOne', {\n operation: 'updateOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: updateResult,\n meta: middlewareCtx.meta\n });\n middlewareCtx.result = updateResult;\n await this.runAfterMiddlewares('updateOne', middlewareCtx);\n await this.invalidateCachePatterns('updateOne', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'updateOne',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: updateResult,\n meta: middlewareCtx.meta\n }\n });\n }));\n }\n /**\n * Inserts multiple documents into the model collection.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered bulkInsert middlewares,\n * validates each incoming document against the model schema, triggers schema\n * bulk insert hooks, invalidates relevant cache patterns, and publishes a\n * database change event after successful insertion.\n *\n * @param docs - The documents to insert.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n */\n async bulkInsert(docs, ctx) {\n await this.init();\n if (!Array.isArray(docs) || docs.length === 0) {\n return;\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'bulkInsert',\n collectionName: this.resolveCollectionName(ctx),\n documentCount: docs.length\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('bulkInsert', ctx, {\n docs: docs\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('bulkInsert', middlewareCtx);\n const nextDocs = (middlewareCtx.docs ?? docs);\n middlewareCtx.docs = nextDocs;\n if (!Array.isArray(nextDocs) || nextDocs.length === 0) {\n middlewareCtx.result = [];\n await this.runAfterMiddlewares('bulkInsert', middlewareCtx);\n return;\n }\n for (const nextDoc of nextDocs) {\n if (!nextDoc || typeof nextDoc !== 'object') {\n throw new Error('Each document must be a valid object.');\n }\n this.validate(nextDoc);\n }\n const meta = this.buildOperationMeta(middlewareCtx.meta, {\n bulkWrite: true\n });\n await this.schema.executePre('bulkInsert', this.buildHookPayload('bulkInsert', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n docs: nextDocs,\n meta\n }));\n const result = await col.insertMany(nextDocs, {\n ordered: false,\n ...(session ? { session } : {})\n });\n const insertedDocs = nextDocs.map((doc, index) => ({\n ...doc,\n _id: result.insertedIds[index]\n }));\n await this.schema.executePost('bulkInsert', this.buildHookPayload('bulkInsert', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n docs: insertedDocs,\n result: insertedDocs,\n meta\n }));\n middlewareCtx.result = this.toModelResults(insertedDocs);\n await this.runAfterMiddlewares('bulkInsert', middlewareCtx);\n await this.invalidateCachePatterns('bulkInsert', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentInserted: {\n action: 'bulkInsert',\n collectionName: middlewareCtx.collectionName,\n docs: middlewareCtx.result,\n meta\n }\n });\n }));\n }\n /**\n * Updates multiple documents using MongoDB bulk write semantics.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered bulkUpdate middlewares,\n * triggers schema bulk update hooks, invalidates relevant cache patterns, and\n * publishes a database change event after completion.\n *\n * Each update entry is translated into an `updateOne` bulk operation using\n * `$set` with the provided partial update document.\n *\n * @param updates - Array of filter/update pairs to execute as bulk updates.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n * @throws {Error} When the updates payload is invalid.\n */\n async bulkUpdate(updates, ctx) {\n await this.init();\n if (!Array.isArray(updates)) {\n throw new Error('Updates must be a valid array.');\n }\n if (updates.length === 0) {\n return;\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'bulkUpdate',\n collectionName: this.resolveCollectionName(ctx),\n documentCount: updates.length\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('bulkUpdate', ctx, {\n bulkUpdates: updates\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('bulkUpdate', middlewareCtx);\n const nextUpdates = middlewareCtx.bulkUpdates ?? updates;\n middlewareCtx.bulkUpdates = nextUpdates;\n const meta = this.buildOperationMeta(middlewareCtx.meta, {\n bulkWrite: true\n });\n middlewareCtx.meta = meta;\n if (!Array.isArray(nextUpdates) || nextUpdates.length === 0) {\n middlewareCtx.result = {\n acknowledged: true,\n matchedCount: 0,\n modifiedCount: 0,\n upsertedCount: 0,\n insertedCount: 0,\n deletedCount: 0\n };\n await this.runAfterMiddlewares('bulkUpdate', middlewareCtx);\n return;\n }\n for (const entry of nextUpdates) {\n if (!entry || typeof entry !== 'object') {\n throw new Error('Each bulk update entry must be a valid object.');\n }\n if (!entry.filter || typeof entry.filter !== 'object') {\n throw new Error('Each bulk update filter must be a valid object.');\n }\n if (!entry.update || typeof entry.update !== 'object') {\n throw new Error('Each bulk update document must be a valid object.');\n }\n }\n const bulkOps = nextUpdates.map(({ filter, update }) => ({\n updateOne: {\n filter: filter,\n update: { $set: update }\n }\n }));\n await this.schema.executePre('bulkUpdate', this.buildHookPayload('bulkUpdate', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n bulkUpdates: nextUpdates,\n meta\n }));\n const result = await col.bulkWrite(bulkOps, {\n ordered: false,\n ...(session ? { session } : {})\n });\n const bulkResult = {\n acknowledged: result?.isOk?.() ?? true,\n matchedCount: result?.matchedCount,\n modifiedCount: result?.modifiedCount,\n upsertedCount: result?.upsertedCount,\n insertedCount: result?.insertedCount,\n deletedCount: result?.deletedCount\n };\n await this.schema.executePost('bulkUpdate', this.buildHookPayload('bulkUpdate', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n bulkUpdates: nextUpdates,\n result: bulkResult,\n meta\n }));\n middlewareCtx.result = bulkResult;\n await this.runAfterMiddlewares('bulkUpdate', middlewareCtx);\n await this.invalidateCachePatterns('bulkUpdate', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'bulkUpdate',\n collectionName: middlewareCtx.collectionName,\n bulkUpdates: nextUpdates,\n result: bulkResult,\n meta\n }\n });\n }));\n }\n /**\n * Deletes a single document matching the provided filter.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered delete middlewares,\n * supports middleware-driven soft delete flows, triggers schema delete or\n * update hooks as appropriate, invalidates relevant cache patterns, and\n * publishes a database change event after completion.\n *\n * When middleware metadata enables soft delete, the matched document is updated\n * instead of being physically removed from the collection.\n *\n * @param filter - MongoDB filter used to identify the document to delete.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When soft delete is enabled but no softDeleteUpdate payload is provided.\n */\n async deleteOne(filter, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'deleteOne',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('deleteOne', ctx, {\n filter\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('deleteOne', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const doc = await col.findOne(effectiveFilter, session ? { session } : undefined);\n if (!doc) {\n middlewareCtx.result = null;\n await this.runAfterMiddlewares('deleteOne', middlewareCtx);\n return;\n }\n const payload = this.toModelResult(doc);\n middlewareCtx.result = payload;\n const meta = this.buildOperationMeta(middlewareCtx.meta);\n middlewareCtx.meta = meta;\n if (meta.softDelete === true) {\n const softDeleteUpdate = middlewareCtx.update;\n if (!softDeleteUpdate) {\n throw new Error('Soft delete is enabled but no soft delete update payload was provided.');\n }\n await this.schema.executePre('updateOne', this.buildHookPayload('deleteOne', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n result: payload,\n meta\n }));\n await col.updateOne(effectiveFilter, softDeleteUpdate, session ? { session } : undefined);\n await this.schema.executePost('updateOne', this.buildHookPayload('deleteOne', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n result: payload,\n meta\n }));\n }\n else {\n await this.schema.triggerMiddleware('pre', 'deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n ...payload\n });\n await this.schema.executePre('deleteOne', this.buildHookPayload('deleteOne', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: payload,\n result: payload,\n meta\n }));\n await col.deleteOne(effectiveFilter, session ? { session } : undefined);\n await this.schema.triggerMiddleware('post', 'deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n ...payload\n });\n await this.schema.executePost('deleteOne', this.buildHookPayload('deleteOne', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: payload,\n result: payload,\n meta\n }));\n }\n await this.runAfterMiddlewares('deleteOne', middlewareCtx);\n await this.invalidateCachePatterns('deleteOne', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentDeleted: {\n action: meta.softDelete ? 'softDelete' : 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n meta: middlewareCtx.meta\n }\n });\n }));\n }\n /**\n * Deletes multiple documents matching the provided filter.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered deleteMany middlewares,\n * supports middleware-driven soft delete flows, triggers schema delete or\n * update hooks as appropriate, invalidates relevant cache patterns, and\n * publishes a database change event after completion.\n *\n * When middleware metadata enables soft delete, matched documents are updated\n * instead of being physically removed from the collection.\n *\n * @param filter - MongoDB filter used to identify the documents to delete.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When soft delete is enabled but no softDeleteUpdate payload is provided.\n */\n async deleteMany(filter, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'deleteMany',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('deleteMany', ctx, {\n filter\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('deleteMany', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const meta = this.buildOperationMeta(middlewareCtx.meta);\n middlewareCtx.meta = meta;\n const docs = await col.find(effectiveFilter, session ? { session } : undefined).toArray();\n if (docs.length === 0) {\n middlewareCtx.result = {\n deletedCount: 0,\n docs: []\n };\n await this.runAfterMiddlewares('deleteMany', middlewareCtx);\n return;\n }\n const existingDocs = this.toModelResults(docs);\n if (meta.softDelete === true) {\n const softDeleteUpdate = middlewareCtx.update;\n if (!softDeleteUpdate) {\n throw new Error('Soft delete is enabled but no soft delete update payload was provided.');\n }\n const softDeleteMeta = this.buildOperationMeta(meta, {\n softDelete: true\n });\n await this.schema.executePre('updateMany', this.buildHookPayload('deleteMany', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n docs: docs,\n result: existingDocs,\n meta: softDeleteMeta\n }));\n const result = await col.updateMany(effectiveFilter, softDeleteUpdate, session ? { session } : undefined);\n const softDeleteResult = {\n deletedCount: result.modifiedCount,\n docs: existingDocs,\n softDeleted: true\n };\n await this.schema.executePost('updateMany', this.buildHookPayload('deleteMany', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n docs: docs,\n result: softDeleteResult,\n meta: softDeleteMeta\n }));\n middlewareCtx.result = softDeleteResult;\n }\n else {\n await this.schema.triggerMiddleware('pre', 'deleteMany', {\n operation: 'deleteMany',\n collectionName: middlewareCtx.collectionName,\n docs: docs\n });\n await this.schema.executePre('deleteMany', this.buildHookPayload('deleteMany', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n docs: docs,\n result: existingDocs,\n meta\n }));\n const result = await col.deleteMany(effectiveFilter, session ? { session } : undefined);\n const deleteResult = {\n deletedCount: result?.deletedCount ?? 0,\n docs: existingDocs\n };\n await this.schema.triggerMiddleware('post', 'deleteMany', {\n operation: 'deleteMany',\n collectionName: middlewareCtx.collectionName,\n docs: docs\n });\n await this.schema.executePost('deleteMany', this.buildHookPayload('deleteMany', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n docs: docs,\n result: deleteResult,\n meta\n }));\n middlewareCtx.result = deleteResult;\n }\n await this.runAfterMiddlewares('deleteMany', middlewareCtx);\n await this.invalidateCachePatterns('deleteMany', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentDeleted: {\n action: meta.softDelete ? 'softDeleteMany' : 'deleteMany',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n result: middlewareCtx.result,\n meta: middlewareCtx.meta\n }\n });\n }));\n }\n /**\n * Populates a single reference field on a document by resolving the related\n * document from another model.\n *\n * This helper performs a follow-up lookup using the referenced field value as\n * the `_id` of the related document. If the target field is empty or\n * undefined, the original document is returned unchanged.\n *\n * @typeParam K - The related model document type.\n * @param doc - The source document containing the reference field.\n * @param field - The field on the source document that stores the related document identifier.\n * @param relatedModel - The model used to resolve the related document.\n * @returns The source document with the populated field replaced by the related\n * document result, or `null` when the input document is invalid.\n */\n async populateOne(doc, field, relatedModel) {\n await this.init();\n if (!doc || typeof doc !== 'object') {\n return null;\n }\n const referenceValue = doc[field];\n if (referenceValue === undefined || referenceValue === null) {\n return doc;\n }\n const relatedDoc = await relatedModel.findOne({\n _id: referenceValue\n });\n return {\n ...doc,\n [field]: relatedDoc\n };\n }\n /**\n * Populates an array reference field on a document by resolving the related\n * documents from another model.\n *\n * This helper performs a follow-up lookup using the referenced field values as\n * `_id` values of the related documents. If the target field is empty,\n * undefined, or not an array, the original document is returned unchanged.\n *\n * @typeParam K - The related model document type.\n * @param doc - The source document containing the reference array field.\n * @param field - The field on the source document that stores related document identifiers.\n * @param relatedModel - The model used to resolve the related documents.\n * @returns The source document with the populated field replaced by the related\n * document results, or `null` when the input document is invalid.\n */\n async populateMany(doc, field, relatedModel) {\n await this.init();\n if (!doc || typeof doc !== 'object') {\n return null;\n }\n const referenceValues = doc[field];\n if (!Array.isArray(referenceValues) || referenceValues.length === 0) {\n return doc;\n }\n const relatedDocs = await relatedModel.find({\n _id: { $in: referenceValues }\n });\n return {\n ...doc,\n [field]: relatedDocs\n };\n }\n /**\n * Creates a new document inside a transaction-aware runtime context.\n *\n * This transactional variant runs within the active Ambiten runtime context,\n * executes registered create middlewares, validates the incoming document,\n * triggers schema create hooks with transactional metadata, invalidates\n * relevant cache patterns, and publishes a database change event after\n * successful insertion.\n *\n * @param doc - The document to insert.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and transaction-aware runtime overrides.\n * @returns The created document as a normalized model result.\n * @throws {Error} When the provided document is missing or invalid.\n */\n async createWithTransaction(doc, ctx) {\n await this.init();\n if (!doc || typeof doc !== 'object') {\n throw new Error('Document must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async () => (0, instrumentation_1.measureQuery)({\n operation: 'create',\n collectionName: this.resolveCollectionName(ctx),\n documentCount: 1\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('create', ctx, {\n doc: doc,\n meta: { transactional: true }\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('create', middlewareCtx);\n const nextDoc = (middlewareCtx.doc ?? doc);\n middlewareCtx.doc = nextDoc;\n const meta = this.buildOperationMeta(middlewareCtx.meta, {\n transactional: true\n });\n this.validate(nextDoc);\n await this.schema.executePre('create', this.buildHookPayload('create', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: nextDoc,\n meta\n }));\n const result = await col.insertOne(nextDoc, session ? { session } : undefined);\n const createdDoc = {\n ...nextDoc,\n _id: result.insertedId\n };\n await this.schema.executePost('create', this.buildHookPayload('create', ctx, {\n operation: 'create',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: createdDoc,\n result: createdDoc,\n meta\n }));\n const payload = this.toModelResult(createdDoc);\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('create', middlewareCtx);\n await this.invalidateCachePatterns('create', middlewareCtx);\n const finalResult = (middlewareCtx.result ?? payload);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentInserted: {\n action: 'create',\n collectionName: middlewareCtx.collectionName,\n doc: finalResult,\n meta\n }\n });\n return finalResult;\n }), ctx));\n }\n /**\n * Executes multiple MongoDB bulk write operations inside a transaction-aware\n * runtime context.\n *\n * This transactional variant runs within the active Ambiten runtime context,\n * executes registered bulk update middlewares, triggers schema bulk update\n * hooks with transactional metadata, invalidates relevant cache patterns, and\n * publishes a database change event after completion.\n *\n * @param operations - MongoDB bulk write operations to execute.\n * @param options - Optional MongoDB bulk write options.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and transaction-aware runtime overrides.\n * @returns The MongoDB bulk write result.\n * @throws {Error} When the operations payload is missing or invalid.\n */\n async bulkWriteWithTransaction(operations, options = {}, ctx) {\n await this.init();\n if (!Array.isArray(operations)) {\n throw new Error('Operations must be a valid array.');\n }\n if (operations.length === 0) {\n throw new Error('Operations array must not be empty.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async () => (0, instrumentation_1.measureQuery)({\n operation: 'bulkWrite',\n collectionName: this.resolveCollectionName(ctx),\n documentCount: operations.length,\n extra: {\n bulkWrite: true\n }\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('bulkUpdate', ctx, {\n bulkOperations: operations,\n meta: {\n transactional: true,\n bulkWrite: true\n }\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('bulkUpdate', middlewareCtx);\n const nextOperations = middlewareCtx.bulkOperations ?? operations;\n middlewareCtx.bulkOperations = nextOperations;\n const meta = this.buildOperationMeta(middlewareCtx.meta, {\n transactional: true,\n bulkWrite: true\n });\n middlewareCtx.meta = meta;\n await this.schema.executePre('bulkUpdate', this.buildHookPayload('bulkUpdate', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n bulkOperations: nextOperations,\n meta\n }));\n const result = await col.bulkWrite(nextOperations, {\n ...options,\n ...(session ? { session } : {})\n });\n const bulkResultSummary = {\n acknowledged: result?.isOk?.() ?? true,\n matchedCount: result?.matchedCount,\n modifiedCount: result?.modifiedCount,\n upsertedCount: result?.upsertedCount,\n insertedCount: result?.insertedCount,\n deletedCount: result?.deletedCount\n };\n await this.schema.executePost('bulkUpdate', this.buildHookPayload('bulkUpdate', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n bulkOperations: nextOperations,\n result: bulkResultSummary,\n meta\n }));\n middlewareCtx.result = bulkResultSummary;\n await this.runAfterMiddlewares('bulkUpdate', middlewareCtx);\n await this.invalidateCachePatterns('bulkWrite', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n bulkWrite: {\n action: 'bulkWrite',\n collectionName: middlewareCtx.collectionName,\n result: bulkResultSummary,\n meta\n }\n });\n return result;\n }), ctx));\n }\n /**\n * Deletes a single document inside a transaction-aware runtime context.\n *\n * This transactional variant runs within the active Ambiten runtime context,\n * executes registered delete middlewares, triggers schema delete hooks with\n * transactional metadata, invalidates relevant cache patterns, and publishes a\n * database change event after completion.\n *\n * @param filter - MongoDB filter used to identify the document to delete.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and transaction-aware runtime overrides.\n * @returns `true` when a document was deleted, otherwise `false`.\n * @throws {Error} When the filter is missing or invalid.\n */\n async deleteWithTransaction(filter, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async () => (0, instrumentation_1.measureQuery)({\n operation: 'deleteOne',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const meta = {\n transactional: true\n };\n const middlewareCtx = this.buildMiddlewareContext('deleteOne', ctx, {\n filter,\n meta\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('deleteOne', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const existingDoc = await col.findOne(effectiveFilter, session ? { session } : undefined);\n if (!existingDoc) {\n middlewareCtx.result = null;\n await this.runAfterMiddlewares('deleteOne', middlewareCtx);\n return false;\n }\n const payload = this.toModelResult(existingDoc);\n middlewareCtx.result = payload;\n await this.schema.triggerMiddleware('pre', 'deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n ...payload\n });\n await this.schema.executePre('deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: existingDoc,\n result: payload,\n meta\n });\n const result = await col.deleteOne(effectiveFilter, session ? { session } : undefined);\n await this.schema.triggerMiddleware('post', 'deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n ...payload\n });\n await this.schema.executePost('deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: existingDoc,\n result: payload,\n meta\n });\n await this.runAfterMiddlewares('deleteOne', middlewareCtx);\n await this.invalidateCachePatterns('deleteOne', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentDeleted: {\n action: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n meta\n }\n });\n return result.deletedCount === 1;\n }), ctx));\n }\n /**\n * Updates a single document inside a transaction-aware runtime context.\n *\n * This transactional variant runs within the active Ambiten runtime context,\n * executes registered update middlewares, validates the projected updated\n * document, triggers schema update hooks with transactional metadata,\n * invalidates relevant cache patterns, and publishes a database change event\n * after completion.\n *\n * @param filter - MongoDB filter used to identify the document to update.\n * @param update - MongoDB update document to apply.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and transaction-aware runtime overrides.\n * @returns The updated document as a normalized model result, or `null` if no\n * document matched the filter.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the update document is missing or invalid.\n */\n async updateWithTransaction(filter, update, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!update || typeof update !== 'object') {\n throw new Error('Update must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async () => (0, instrumentation_1.measureQuery)({\n operation: 'updateOne',\n collectionName: this.resolveCollectionName(ctx),\n filter,\n update\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const meta = {\n transactional: true\n };\n const middlewareCtx = this.buildMiddlewareContext('updateOne', ctx, {\n filter,\n update,\n meta\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('updateOne', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n const effectiveUpdate = (middlewareCtx.update ?? update);\n middlewareCtx.filter = effectiveFilter;\n middlewareCtx.update = effectiveUpdate;\n const existingDoc = await col.findOne(effectiveFilter, session ? { session } : undefined);\n if (!existingDoc) {\n middlewareCtx.result = null;\n await this.runAfterMiddlewares('updateOne', middlewareCtx);\n return null;\n }\n const projectedUpdatedDoc = {\n ...existingDoc,\n ...(effectiveUpdate.$set ?? {})\n };\n this.validate(projectedUpdatedDoc);\n await this.schema.executePre('updateOne', {\n operation: 'updateOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: effectiveUpdate,\n meta\n });\n await col.updateOne(effectiveFilter, effectiveUpdate, session ? { session } : undefined);\n const result = await col.findOne(effectiveFilter, session ? { session } : undefined);\n const payload = result\n ? this.toModelResult(result)\n : null;\n await this.schema.executePost('updateOne', {\n operation: 'updateOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: payload,\n meta\n });\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('updateOne', middlewareCtx);\n await this.invalidateCachePatterns('updateOne', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'updateOne',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: payload,\n meta\n }\n });\n return (middlewareCtx.result ?? payload);\n }), ctx));\n }\n /**\n * Finds a single document matching the provided filter and updates it.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered findOneAndUpdate\n * middlewares, triggers schema update hooks, invalidates relevant cache\n * patterns, and publishes a database change event after completion.\n *\n * The updated document is returned in its post-update state when a matching\n * document is found.\n *\n * @param filter - MongoDB filter used to identify the document to update.\n * @param update - MongoDB update document to apply.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns The updated document as a normalized model result, or `null` if no\n * document matched the filter.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the update document is missing or invalid.\n */\n async findOneAndUpdate(filter, update, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!update || typeof update !== 'object') {\n throw new Error('Update must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'findOneAndUpdate',\n collectionName: this.resolveCollectionName(ctx),\n filter,\n update\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('findOneAndUpdate', ctx, {\n filter,\n update\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('findOneAndUpdate', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n const effectiveUpdate = (middlewareCtx.update ?? update);\n middlewareCtx.filter = effectiveFilter;\n middlewareCtx.update = effectiveUpdate;\n await this.schema.executePre('updateOne', {\n operation: 'findOneAndUpdate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: effectiveUpdate,\n meta: middlewareCtx.meta\n });\n const updateResult = await col.findOneAndUpdate(effectiveFilter, effectiveUpdate, {\n returnDocument: 'after',\n ...(session ? { session } : {})\n });\n const updatedDoc = updateResult &&\n typeof updateResult === 'object' &&\n 'value' in updateResult\n ? updateResult.value\n : updateResult;\n const payload = updatedDoc\n ? this.toModelResult(updatedDoc)\n : null;\n await this.schema.executePost('updateOne', {\n operation: 'findOneAndUpdate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: payload,\n meta: middlewareCtx.meta\n });\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('findOneAndUpdate', middlewareCtx);\n await this.invalidateCachePatterns('findOneAndUpdate', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'findOneAndUpdate',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: payload,\n meta: middlewareCtx.meta\n }\n });\n return (middlewareCtx.result ?? payload);\n }));\n }\n /**\n * Finds a single document matching the provided filter and deletes it.\n *\n * Supports both hard delete and middleware-driven soft delete flows.\n * When soft delete is enabled via middleware metadata, the matched document\n * is updated using the provided soft-delete update operation instead of being\n * physically removed from the collection.\n *\n * The operation:\n * - runs within the active Ambiten runtime context\n * - is instrumented through {@link measureQuery}\n * - executes registered before/after model middlewares\n * - triggers schema delete/update hooks as appropriate\n * - invalidates relevant cache patterns after mutation\n * - publishes a database change event through PubSub\n *\n * @param filter - MongoDB filter used to identify the document to delete.\n * @param ctx - Optional model execution context for tenant, database,\n * session, cache, and collection overrides.\n * @returns The deleted document as a model result, or `null` if no document matched.\n * @throws {Error} When the filter is missing or invalid.\n */\n async findOneAndDelete(filter, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'findOneAndDelete',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('findOneAndDelete', ctx, { filter });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('findOneAndDelete', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const meta = this.buildOperationMeta(middlewareCtx.meta);\n middlewareCtx.meta = meta;\n const existingDoc = await col.findOne(effectiveFilter, session ? { session } : undefined);\n if (!existingDoc) {\n middlewareCtx.result = null;\n await this.runAfterMiddlewares('findOneAndDelete', middlewareCtx);\n return null;\n }\n const existingPayload = this.toModelResult(existingDoc);\n middlewareCtx.result = existingPayload;\n if (meta.softDelete === true) {\n const softDeleteUpdate = middlewareCtx.update ?? this.buildSoftDeleteUpdate();\n middlewareCtx.update = softDeleteUpdate;\n const softDeleteMeta = this.buildOperationMeta(meta, {\n softDelete: true\n });\n await this.schema.executePre('updateOne', this.buildHookPayload('findOneAndDelete', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n result: existingPayload,\n meta: softDeleteMeta\n }));\n await col.updateOne(effectiveFilter, softDeleteUpdate, session ? { session } : undefined);\n await this.schema.executePost('updateOne', this.buildHookPayload('findOneAndDelete', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n result: existingPayload,\n meta: softDeleteMeta\n }));\n await this.runAfterMiddlewares('findOneAndDelete', middlewareCtx);\n await this.invalidateCachePatterns('findOneAndDelete', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentDeleted: {\n action: 'softDeleteOne',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n meta: softDeleteMeta\n }\n });\n return (middlewareCtx.result ?? existingPayload);\n }\n await this.schema.triggerMiddleware('pre', 'deleteOne', {\n operation: 'findOneAndDelete',\n collectionName: middlewareCtx.collectionName,\n ...existingPayload\n });\n await this.schema.executePre('deleteOne', this.buildHookPayload('findOneAndDelete', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: existingDoc,\n result: existingPayload,\n meta\n }));\n const deleteOptions = session ? { session } : {};\n const deleteResult = await col.findOneAndDelete(effectiveFilter, deleteOptions);\n const deletedDoc = deleteResult &&\n typeof deleteResult === 'object' &&\n 'value' in deleteResult\n ? deleteResult.value\n : deleteResult;\n const finalPayload = deletedDoc\n ? this.toModelResult(deletedDoc)\n : existingPayload;\n await this.schema.triggerMiddleware('post', 'deleteOne', {\n operation: 'findOneAndDelete',\n collectionName: middlewareCtx.collectionName,\n ...(finalPayload ?? {})\n });\n await this.schema.executePost('deleteOne', this.buildHookPayload('findOneAndDelete', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: existingDoc,\n result: finalPayload,\n meta\n }));\n middlewareCtx.result = finalPayload;\n await this.runAfterMiddlewares('findOneAndDelete', middlewareCtx);\n await this.invalidateCachePatterns('findOneAndDelete', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentDeleted: {\n action: 'findOneAndDelete',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n result: finalPayload,\n meta\n }\n });\n return (middlewareCtx.result ?? finalPayload);\n }));\n }\n /**\n * Finds a single document matching the provided filter and replaces it with the\n * supplied replacement document.\n *\n * This operation runs inside the active Ambiten runtime context, executes model\n * middlewares, triggers schema update hooks, invalidates relevant cache entries,\n * and publishes a database change event after a successful replacement.\n *\n * The replacement document is fully validated before being persisted.\n *\n * @param filter - MongoDB filter used to identify the document to replace.\n * @param replacement - The full replacement document that will overwrite the matched document.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns The replaced document in its updated form, or `null` if no document matched the filter.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the replacement document fails validation.\n */\n async findOneAndReplace(filter, replacement, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!replacement || typeof replacement !== 'object') {\n throw new Error('Replacement document must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'findOneAndReplace',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('findOneAndReplace', ctx, {\n filter,\n doc: replacement\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('findOneAndReplace', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n const nextReplacement = (middlewareCtx.doc ?? replacement);\n middlewareCtx.filter = effectiveFilter;\n middlewareCtx.doc = nextReplacement;\n this.validate(nextReplacement);\n await this.schema.executePre('updateOne', {\n operation: 'findOneAndReplace',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n doc: nextReplacement\n });\n const replaceResult = await col.findOneAndReplace(effectiveFilter, nextReplacement, {\n returnDocument: 'after',\n ...(session ? { session } : {})\n });\n const replacedDoc = replaceResult &&\n typeof replaceResult === 'object' &&\n 'value' in replaceResult\n ? replaceResult.value\n : replaceResult;\n const payload = replacedDoc\n ? this.toModelResult(replacedDoc)\n : null;\n await this.schema.executePost('updateOne', {\n operation: 'findOneAndReplace',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n doc: nextReplacement,\n result: replacedDoc\n });\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('findOneAndReplace', middlewareCtx);\n await this.invalidateCachePatterns('findOneAndReplace', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'findOneAndReplace',\n filter: effectiveFilter,\n replacement: nextReplacement\n }\n });\n return (middlewareCtx.result ?? payload);\n }));\n }\n /**\n * Finds a single document matching the provided filter and updates it. If no\n * matching document exists, a new one is inserted using MongoDB upsert\n * semantics.\n *\n * This operation runs within the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered model middlewares, triggers\n * schema update hooks, invalidates relevant cache patterns, and publishes a\n * database change event after completion.\n *\n * @param filter - MongoDB filter used to identify the document to update or insert.\n * @param update - MongoDB update document applied to the matched document or to the inserted document during upsert.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns The updated or newly upserted document in its final state, or `null`\n * if no document could be resolved from the operation result.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the update document is missing or invalid.\n */\n async findOneAndUpsert(filter, update, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!update || typeof update !== 'object') {\n throw new Error('Update must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'findOneAndUpsert',\n collectionName: this.resolveCollectionName(ctx),\n filter,\n update\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('findOneAndUpsert', ctx, {\n filter,\n update\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('findOneAndUpsert', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n const effectiveUpdate = (middlewareCtx.update ?? update);\n middlewareCtx.filter = effectiveFilter;\n middlewareCtx.update = effectiveUpdate;\n await this.schema.executePre('updateOne', {\n operation: 'findOneAndUpsert',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate\n });\n const upsertResult = await col.findOneAndUpdate(effectiveFilter, effectiveUpdate, {\n upsert: true,\n returnDocument: 'after',\n ...(session ? { session } : {})\n });\n const updatedDoc = upsertResult &&\n typeof upsertResult === 'object' &&\n 'value' in upsertResult\n ? upsertResult.value\n : upsertResult;\n const payload = updatedDoc\n ? this.toModelResult(updatedDoc)\n : null;\n await this.schema.executePost('updateOne', {\n operation: 'findOneAndUpsert',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: updatedDoc\n });\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('findOneAndUpsert', middlewareCtx);\n await this.invalidateCachePatterns('findOneAndUpsert', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'findOneAndUpsert',\n filter: effectiveFilter,\n update: effectiveUpdate\n }\n });\n return (middlewareCtx.result ?? payload);\n }));\n }\n /**\n * Finds a single document matching the provided filter and updates it inside a\n * transaction. If no document matches, a new one is inserted using MongoDB\n * upsert semantics.\n *\n * This transactional variant runs inside the active Ambiten runtime context,\n * executes registered model middlewares, triggers schema update hooks with\n * transactional metadata, invalidates relevant cache patterns, and publishes a\n * database change event after completion.\n *\n * @param filter - MongoDB filter used to identify the document to update or insert.\n * @param update - MongoDB update document applied to the matched document or inserted document.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and transaction-aware runtime overrides.\n * @returns The updated or newly inserted document in its final state, or `null`\n * if no document could be resolved from the operation result.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the update document is missing or invalid.\n */\n async findOneAndUpsertWithTransaction(filter, update, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!update || typeof update !== 'object') {\n throw new Error('Update must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const col = await this.getCollection(ctx);\n const session = this.resolveSession(ctx);\n const middlewareCtx = this.buildMiddlewareContext('findOneAndUpsert', ctx, {\n filter,\n update,\n meta: {\n transactional: true\n }\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('findOneAndUpsert', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n const effectiveUpdate = (middlewareCtx.update ?? update);\n middlewareCtx.filter = effectiveFilter;\n middlewareCtx.update = effectiveUpdate;\n await this.schema.executePre('updateOne', {\n operation: 'findOneAndUpsert',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n meta: {\n transactional: true\n }\n });\n const upsertResult = await col.findOneAndUpdate(effectiveFilter, effectiveUpdate, {\n upsert: true,\n returnDocument: 'after',\n ...(session ? { session } : {})\n });\n const updatedDoc = upsertResult &&\n typeof upsertResult === 'object' &&\n 'value' in upsertResult\n ? upsertResult.value\n : upsertResult;\n const payload = updatedDoc\n ? this.toModelResult(updatedDoc)\n : null;\n await this.schema.executePost('updateOne', {\n operation: 'findOneAndUpsert',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: updatedDoc,\n meta: {\n transactional: true\n }\n });\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('findOneAndUpsert', middlewareCtx);\n await this.invalidateCachePatterns('findOneAndUpsert', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'findOneAndUpsert',\n filter: effectiveFilter,\n update: effectiveUpdate,\n meta: {\n transactional: true\n }\n }\n });\n return (middlewareCtx.result ?? payload);\n }, ctx));\n }\n /**\n * Finds a single document matching the provided filter and updates it inside a\n * secure transaction. If no document matches, a new one is inserted using\n * MongoDB upsert semantics.\n *\n * This secure transactional variant enforces an admin-only authorization rule\n * before performing the operation. It runs inside the active Ambiten runtime\n * context, executes registered model middlewares, triggers schema update hooks\n * with transactional and security metadata, invalidates relevant cache patterns,\n * and publishes a database change event after completion.\n *\n * @param filter - MongoDB filter used to identify the document to update or insert.\n * @param update - MongoDB update document applied to the matched document or inserted document.\n * @param user - Authenticated user performing the operation. Must have the `admin` role.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and transaction-aware runtime overrides.\n * @returns The updated or newly inserted document in its final state, or `null`\n * if no document could be resolved from the operation result.\n * @throws {Error} When the user is not authorized to perform the operation.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the update document is missing or invalid.\n */\n async findOneAndUpsertWithTransactionSecure(filter, update, user, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!update || typeof update !== 'object') {\n throw new Error('Update must be a valid object.');\n }\n if (!user) {\n throw new Error('User is required.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async () => {\n if (user.role !== 'admin') {\n throw new Error('Unauthorized');\n }\n const meta = {\n transactional: true,\n secure: true,\n userId: user.id,\n userRole: user.role\n };\n const collectionName = this.resolveCollectionName(ctx);\n const col = await this.getCollection(ctx);\n const session = this.resolveSession(ctx);\n const middlewareCtx = this.buildMiddlewareContext('findOneAndUpsert', ctx, {\n filter,\n update,\n meta\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('findOneAndUpsert', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n const effectiveUpdate = (middlewareCtx.update ?? update);\n middlewareCtx.filter = effectiveFilter;\n middlewareCtx.update = effectiveUpdate;\n await this.schema.executePre('updateOne', {\n operation: 'findOneAndUpsert',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n meta\n });\n const upsertResult = await col.findOneAndUpdate(effectiveFilter, effectiveUpdate, {\n upsert: true,\n returnDocument: 'after',\n ...(session ? { session } : {})\n });\n const updatedDoc = upsertResult &&\n typeof upsertResult === 'object' &&\n 'value' in upsertResult\n ? upsertResult.value\n : upsertResult;\n const payload = updatedDoc\n ? this.toModelResult(updatedDoc)\n : null;\n await this.schema.executePost('updateOne', {\n operation: 'findOneAndUpsert',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: updatedDoc,\n meta\n });\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('findOneAndUpsert', middlewareCtx);\n await this.invalidateCachePatterns('findOneAndUpsert', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'findOneAndUpsert',\n filter: effectiveFilter,\n update: effectiveUpdate,\n meta\n }\n });\n return (middlewareCtx.result ?? payload);\n }, ctx));\n }\n /**\n * Deletes a single document matching the provided filter using an admin-only\n * secure operation.\n *\n * This method enforces authorization before executing the delete flow. It runs\n * inside the active Ambiten runtime context, is instrumented through\n * {@link measureQuery}, executes registered model middlewares, triggers schema\n * delete hooks with security metadata, invalidates relevant cache patterns, and\n * publishes a database change event after a successful deletion.\n *\n * @param filter - MongoDB filter used to identify the document to delete.\n * @param user - Authenticated user performing the operation. Must have the `admin` role.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n * @throws {Error} When the user is not authorized to perform the operation.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the user payload is missing.\n */\n async deleteSecure(filter, user, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!user) {\n throw new Error('User is required.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'deleteOne',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n if (user.role !== 'admin') {\n throw new Error('Unauthorized');\n }\n const meta = {\n secure: true,\n userId: user.id,\n userRole: user.role\n };\n const collectionName = this.resolveCollectionName(ctx);\n const col = await this.getCollection(ctx);\n const session = this.resolveSession(ctx);\n const middlewareCtx = this.buildMiddlewareContext('deleteOne', ctx, {\n filter,\n meta\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('deleteOne', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const doc = await col.findOne(effectiveFilter, session ? { session } : undefined);\n if (!doc) {\n middlewareCtx.result = null;\n await this.runAfterMiddlewares('deleteOne', middlewareCtx);\n return;\n }\n const payload = this.toModelResult(doc);\n middlewareCtx.result = payload;\n await this.schema.executePre('deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n ...doc,\n meta\n });\n await col.deleteOne(effectiveFilter, session ? { session } : undefined);\n await this.schema.executePost('deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n ...doc,\n meta\n });\n await this.runAfterMiddlewares('deleteOne', middlewareCtx);\n await this.invalidateCachePatterns('deleteOne', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentDeleted: {\n action: 'deleteOne',\n filter: effectiveFilter,\n meta\n }\n });\n }));\n }\n /**\n * Executes an aggregation pipeline against the model collection.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered aggregate middlewares,\n * supports optional query-result caching, and publishes a database change event\n * after execution.\n *\n * When caching is enabled through {@link QueryOptions}, the aggregation result\n * is stored and reused using a tenant-aware cache key derived from the\n * collection, pipeline, options, and runtime context.\n *\n * @typeParam U - The aggregation result document shape.\n * @param pipeline - MongoDB aggregation pipeline stages.\n * @param options - Optional MongoDB aggregation options.\n * @param externalSession - Optional explicit client session to use for the aggregation.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @param queryOptions - Optional query-level features such as caching.\n * @returns The aggregation result array.\n * @throws {Error} When the pipeline is missing or invalid.\n */\n async aggregate(pipeline, options = {}, externalSession, ctx, queryOptions) {\n await this.init();\n if (!Array.isArray(pipeline)) {\n throw new Error('Pipeline must be a valid array.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'aggregate',\n collectionName: this.resolveCollectionName(ctx),\n pipeline\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const col = await this.getCollection(ctx);\n const resolvedSession = this.resolveSessionStrict(ctx, externalSession);\n const middlewareCtx = this.buildMiddlewareContext('aggregate', ctx, {\n pipeline\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('aggregate', middlewareCtx);\n const effectivePipeline = (middlewareCtx.pipeline ?? pipeline);\n middlewareCtx.pipeline = effectivePipeline;\n const cache = queryOptions?.cache\n ? this.resolveCache(queryOptions)\n : null;\n await this.schema.executePre('aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session: resolvedSession,\n pipeline: effectivePipeline,\n meta: middlewareCtx.meta\n });\n let cacheKey = null;\n if (cache) {\n cacheKey = this.buildCacheKey('aggregate', {\n collectionName: middlewareCtx.collectionName,\n pipeline: effectivePipeline,\n options,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName\n });\n const cached = await cache.get(cacheKey, {\n ttlSeconds: typeof queryOptions?.cache === 'object'\n ? queryOptions.cache.ttl\n : undefined,\n tenantId: middlewareCtx.tenantId,\n namespace: middlewareCtx.collectionName\n });\n if (cached) {\n middlewareCtx.result = cached;\n await this.runAfterMiddlewares('aggregate', middlewareCtx);\n return (middlewareCtx.result ?? cached);\n }\n }\n const cursor = col.aggregate(effectivePipeline, {\n ...options,\n ...(resolvedSession ? { session: resolvedSession } : {})\n });\n const result = await cursor.toArray();\n await this.schema.executePost('aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session: resolvedSession,\n pipeline: effectivePipeline,\n result,\n meta: middlewareCtx.meta\n });\n middlewareCtx.result = result;\n await this.runAfterMiddlewares('aggregate', middlewareCtx);\n const finalResult = (middlewareCtx.result ?? result);\n if (cache && cacheKey) {\n await cache.set(cacheKey, finalResult, {\n ttlSeconds: typeof queryOptions?.cache === 'object'\n ? queryOptions.cache.ttl\n : undefined,\n tenantId: middlewareCtx.tenantId,\n namespace: middlewareCtx.collectionName\n });\n }\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n dbChange: {\n action: 'aggregate',\n pipeline: effectivePipeline\n }\n });\n return finalResult;\n }));\n }\n /**\n * Executes an aggregation pipeline inside a transaction-aware runtime context.\n *\n * This transactional variant runs within the active Ambiten runtime context,\n * executes registered aggregate middlewares, triggers schema aggregate hooks,\n * instruments the query through {@link measureQuery}, and publishes a database\n * change event after execution.\n *\n * @typeParam U - The aggregation result document shape.\n * @param pipeline - MongoDB aggregation pipeline stages.\n * @param options - Optional MongoDB aggregation options.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and transaction-aware runtime overrides.\n * @returns The aggregation result array.\n * @throws {Error} When the pipeline is missing or invalid.\n */\n async aggregateWithTransaction(pipeline, options = {}, ctx) {\n await this.init();\n if (!Array.isArray(pipeline)) {\n throw new Error('Pipeline must be a valid array.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async () => (0, instrumentation_1.measureQuery)({\n operation: 'aggregate',\n collectionName: this.resolveCollectionName(ctx),\n pipeline\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const col = await this.getCollection(ctx);\n const session = this.resolveSession(ctx);\n const middlewareCtx = this.buildMiddlewareContext('aggregate', ctx, {\n pipeline,\n meta: {\n transactional: true\n }\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('aggregate', middlewareCtx);\n const effectivePipeline = (middlewareCtx.pipeline ?? pipeline);\n middlewareCtx.pipeline = effectivePipeline;\n await this.schema.executePre('aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n pipeline: effectivePipeline,\n meta: {\n ...(middlewareCtx.meta ?? {}),\n transactional: true\n }\n });\n const cursor = col.aggregate(effectivePipeline, {\n ...options,\n ...(session ? { session } : {})\n });\n const result = await cursor.toArray();\n await this.schema.executePost('aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n pipeline: effectivePipeline,\n result,\n meta: {\n ...(middlewareCtx.meta ?? {}),\n transactional: true\n }\n });\n middlewareCtx.result = result;\n await this.runAfterMiddlewares('aggregate', middlewareCtx);\n const finalResult = (middlewareCtx.result ?? result);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n dbChange: {\n action: 'aggregate',\n pipeline: effectivePipeline,\n meta: {\n transactional: true\n }\n }\n });\n return finalResult;\n }), ctx));\n }\n /**\n * Executes the provided operation within a transaction-aware runtime context.\n *\n * Resolution order:\n * 1. Reuse an existing session from the merged model context when available.\n * 2. Start a provider-managed session when the active database provider\n * exposes a session factory.\n * 3. Fall back to {@link AmbitenContext.withTransaction} to resolve a client\n * and execute the operation inside a transaction.\n *\n * When an existing session is supplied, the current transaction boundary is\n * reused and no new transaction is started.\n *\n * @typeParam R - The operation result type.\n * @param operation - Callback executed with the resolved MongoDB client session.\n * @param ctx - Optional model execution context used to resolve tenant,\n * database, collection, and session overrides.\n * @returns The resolved operation result.\n */\n async withTransaction(operation, ctx) {\n const baseCtx = this.mergeCtx(ctx) ?? {};\n const collectionName = baseCtx.collectionName ?? this._collectionName;\n const existingSession = baseCtx.session;\n const runtimeBase = {\n tenantId: baseCtx.tenantId,\n dbName: baseCtx.dbName,\n collectionName\n };\n if (existingSession) {\n return context_1.AmbitenContext.run({\n ...runtimeBase,\n session: existingSession\n }, async () => operation(existingSession));\n }\n if (this._provider?.startSession) {\n const session = await this.getSession(baseCtx);\n return await context_1.AmbitenContext.run({\n ...runtimeBase,\n session\n }, async () => (0, context_1.runManualTransaction)(session, operation));\n }\n return context_1.AmbitenContext.run(runtimeBase, async () => context_1.AmbitenContext.withTransaction(operation));\n }\n /**\n * Executes the provided operation inside a transaction-aware Ambiten runtime context.\n *\n * This helper ensures the operation runs with a resolved MongoDB client session\n * and within the active Ambiten runtime context for the current tenant,\n * database, and collection. If a session already exists in the merged model\n * context, that session is reused and no new transaction boundary is created.\n *\n * Use this method when multiple model operations must be executed atomically\n * within a single transactional unit of work.\n *\n * @typeParam R - The operation result type.\n * @param operation - Callback executed with the resolved MongoDB client session.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, and session overrides.\n * @returns The resolved result of the transactional operation.\n */\n async runInTransaction(operation, ctx) {\n await this.init();\n if (typeof operation !== 'function') {\n throw new Error('Operation must be a valid function.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async (session) => operation(session), ctx));\n }\n async getSession(ctx) {\n if (!this._provider?.startSession) {\n throw new Error('Transaction support is not available. Provider does not implement startSession().');\n }\n return this._provider.startSession(this.mergeCtx(ctx));\n }\n /**\n * Creates a readable stream for an aggregation pipeline.\n *\n * This method runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered aggregate middlewares,\n * triggers schema aggregate hooks, and publishes a database change event after\n * the aggregation stream is created.\n *\n * This method instruments stream creation only. It does not track the full\n * lifecycle of stream consumption unless additional listeners are attached by\n * the caller or by a higher-level observability layer.\n *\n * @typeParam U - The aggregation result document shape.\n * @param pipeline - MongoDB aggregation pipeline stages.\n * @param options - Optional MongoDB aggregation options.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A readable stream for the aggregation result set.\n * @throws {Error} When the pipeline is missing or invalid.\n */\n async streamAggregation(pipeline, options = {}, ctx) {\n await this.init();\n if (!Array.isArray(pipeline)) {\n throw new Error('Pipeline must be a valid array.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'aggregate',\n collectionName: this.resolveCollectionName(ctx),\n pipeline,\n extra: {\n streaming: true\n }\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('aggregate', ctx, {\n pipeline,\n meta: {\n streaming: true\n }\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('aggregate', middlewareCtx);\n const effectivePipeline = (middlewareCtx.pipeline ?? pipeline);\n middlewareCtx.pipeline = effectivePipeline;\n const meta = {\n ...(middlewareCtx.meta ?? {}),\n streaming: true\n };\n await this.schema.triggerMiddleware('pre', 'aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n pipeline: effectivePipeline,\n meta\n });\n await this.schema.executePre('aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n pipeline: effectivePipeline,\n meta\n });\n const stream = col.aggregate(effectivePipeline, {\n ...options,\n ...(session ? { session } : {})\n }).stream();\n await this.schema.triggerMiddleware('post', 'aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n result: stream,\n meta\n });\n await this.schema.executePost('aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n pipeline: effectivePipeline,\n result: stream,\n meta\n });\n middlewareCtx.result = stream;\n await this.runAfterMiddlewares('aggregate', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n dbChange: {\n action: 'aggregateStream',\n collectionName: middlewareCtx.collectionName,\n pipeline: effectivePipeline,\n meta\n }\n });\n return stream;\n }));\n }\n /**\n * Aggregates documents in the collection using a pipeline with caching.\n * @param {object[]} pipeline - The aggregation pipeline.\n * @param {string} cacheKey - The cache key.\n * @param {number} [cacheDuration=300] - The cache duration in seconds.\n * @returns {Promise<T[]>} The aggregation result as an array.\n * @throws {Error} If the pipeline is not valid or the cache key is not a string.\n */\n async aggregateWithCache(pipeline, cacheKey, cacheDuration = 300) {\n await this.init();\n if (!Array.isArray(pipeline)) {\n throw new Error('Pipeline must be an array of objects.');\n }\n const cachedResult = await redis_manager_1.redis.get(cacheKey);\n if (cachedResult) {\n console.info(`[info]: Cache hit: ${cacheKey}`);\n return JSON.parse(cachedResult);\n }\n else if (typeof cacheKey !== 'string') {\n throw new Error('Cache key must be a string.');\n }\n else {\n console.info(`[info]: Cache miss: ${cacheKey}`);\n }\n const col = await this.getCollection();\n const result = await col.aggregate(pipeline).toArray();\n await redis_manager_1.redis.set(cacheKey, JSON.stringify(result) || '');\n await redis_manager_1.redis.expire(cacheKey, cacheDuration);\n console.info('Cache set:', cacheKey);\n this.schema.triggerMiddleware('post', 'aggregate', {\n operation: 'aggregate',\n collectionName: this.resolveCollectionName(col),\n result: [result]\n });\n await pubsub.publish(\"DB_CHANGE\", { dbChange: { action: \"aggregate\", result } });\n return result || [];\n }\n /**\n * Cursor-based pagination using _id comparison instead of skip.\n * @param filter - The filter for documents.\n * @param pageSize - Number of documents per page.\n * @param lastId - Last document _id from the previous page.\n * @returns {Promise<T[]>} Array of documents for the current page.\n * This method uses the _id field for pagination, which is more efficient than using skip.\n *\n */\n async paginatedFind(filter, pageSize, lastId) {\n await this.init();\n const query = filter;\n if (lastId) {\n query._id = { $gt: new mongodb_1.ObjectId(lastId) }; // Fetch only newer documents\n }\n const col = await this.getCollection();\n const results = await col.find(query).limit(pageSize).toArray();\n return results.map(({ _id, ...rest }) => rest);\n }\n ;\n /**\n * Opens a MongoDB change stream on the model collection and registers a change\n * callback.\n *\n * This helper initializes the model, resolves the collection within the active\n * Ambiten runtime context, creates a change stream, and subscribes the provided\n * callback to `\"change\"` events.\n *\n * The method is intentionally lightweight: it manages change stream creation,\n * but does not yet instrument the full lifecycle of emitted change events. That\n * can be added later by higher-level observability or evidence collection\n * layers.\n *\n * @param callback - Function invoked whenever a change event is emitted by the collection change stream.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns The active MongoDB change stream.\n * @throws {Error} When the callback is not a valid function.\n */\n async watchChanges(callback, ctx) {\n await this.init();\n if (typeof callback !== 'function') {\n throw new Error('Callback must be a valid function.');\n }\n return this.runWithModelContext(ctx, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const col = await this.getCollection(ctx);\n const changeStream = col.watch();\n changeStream.on('change', callback);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n dbChange: {\n action: 'watchChanges',\n collectionName\n }\n });\n return changeStream;\n });\n }\n /**\n * Creates an index on the model collection.\n *\n * @param fields - Index field specification where each key maps to ascending\n * (`1`) or descending (`-1`) index order.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the index has been created.\n * @throws {Error} When the field specification is missing or invalid.\n */\n async createIndex(fields, ctx) {\n await this.init();\n if (!fields || typeof fields !== 'object') {\n throw new Error('Index fields must be a valid object.');\n }\n const entries = Object.entries(fields);\n if (entries.length === 0) {\n throw new Error('Index fields must contain at least one entry.');\n }\n for (const [, direction] of entries) {\n if (direction !== 1 && direction !== -1) {\n throw new Error('Index direction must be either 1 or -1.');\n }\n }\n return this.runWithModelContext(ctx, async () => {\n const col = await this.getCollection(ctx);\n await col.createIndex(fields);\n });\n }\n /**\n * Drops an index from the collection by its name.\n * @param {string} indexName - The name of the index to drop.\n * @returns {Promise<void>} Resolves when the index is dropped.\n */\n async dropIndex(indexName) {\n await this.init();\n const col = await this.getCollection();\n await col.dropIndex(indexName);\n }\n // ============== Invalidation ==============//\n async invalidateCachePatterns(operation, ctx) {\n const tenantId = ctx.tenantId ?? 'default';\n const dbName = ctx.dbName ?? 'default';\n const collectionName = ctx.collectionName ?? this._collectionName;\n const basePatterns = [\n `Ambiten:${tenantId}:${dbName}:${collectionName}:find:*`,\n `Ambiten:${tenantId}:${dbName}:${collectionName}:findOne:*`\n ];\n const patterns = operation === 'aggregate'\n ? [\n ...basePatterns,\n `Ambiten:${tenantId}:${dbName}:${collectionName}:aggregate:*`\n ]\n : [\n ...basePatterns,\n `Ambiten:${tenantId}:${dbName}:${collectionName}:aggregate:*`\n ];\n await Promise.all([...new Set(patterns)].map((pattern) => AmbitenModel.invalidatePattern(pattern)));\n }\n /**\n * Invalidates all cache entries matching the provided Redis key pattern.\n *\n * This method uses Redis `SCAN` to iterate over matching keys in batches and\n * deletes them using a pipelined multi-operation for better efficiency.\n *\n * @param pattern - Redis key pattern to invalidate.\n * @returns The number of successfully deleted keys.\n * @throws {Error} When the pattern is invalid or cache invalidation fails.\n */\n static async invalidatePattern(pattern) {\n if (typeof pattern !== 'string' || pattern.trim().length === 0) {\n throw new Error('Pattern must be a non-empty string.');\n }\n const normalizedPattern = pattern.trim();\n const scanCount = 100;\n let deletedCount = 0;\n let cursor = 0;\n try {\n do {\n const result = await redis_manager_1.redis.scan(cursor, {\n MATCH: normalizedPattern,\n COUNT: scanCount\n });\n const nextCursor = Array.isArray(result) ? Number(result[0]) : 0;\n const keys = Array.isArray(result) ? result[1] : [];\n if (Array.isArray(keys) && keys.length > 0) {\n const multi = redis_manager_1.redis.multi();\n for (const key of keys) {\n multi.del(key);\n }\n const execResult = await multi.exec();\n if (Array.isArray(execResult)) {\n deletedCount += execResult.filter((entry) => {\n if (Array.isArray(entry)) {\n const [err, value] = entry;\n return !err && value === 1;\n }\n return entry === 1;\n }).length;\n }\n }\n cursor = nextCursor;\n } while (cursor !== 0);\n return deletedCount;\n }\n catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to invalidate cache pattern \"${normalizedPattern}\": ${message}`);\n }\n }\n getContext() {\n return { ctx: {} };\n }\n /**\n * Invalidates cache entries for the current model scope using a pattern.\n *\n * This helper resolves tenant, database, and collection scope from the\n * provided context and applies the pattern within the Ambiten cache namespace.\n *\n * @param pattern - Partial cache pattern (e.g. \"find:*\", \"aggregate:*\").\n * @param ctx - Optional model execution context.\n * @returns Number of deleted cache entries.\n * @throws {Error} When the pattern is invalid.\n */\n async invalidateModelPattern(pattern, ctx) {\n await this.init();\n if (typeof pattern !== 'string' || pattern.trim().length === 0) {\n throw new Error('Pattern must be a non-empty string.');\n }\n return this.runWithModelContext(ctx, async () => {\n const tenantId = ctx?.tenantId ?? 'default';\n const dbName = ctx?.dbName ?? 'default';\n const collectionName = ctx?.collectionName ?? this._collectionName;\n const fullPattern = `Ambiten:${tenantId}:${dbName}:${collectionName}:${pattern.trim()}`;\n return AmbitenModel.invalidatePattern(fullPattern);\n });\n }\n /**\n * Invalidates cache entries related to a specific document within the current\n * model scope.\n *\n * This helper is useful only when document-specific cache keys are part of the\n * active cache strategy.\n *\n * @param doc - The document whose cache entries should be invalidated.\n * @param ctx - Optional model execution context.\n * @returns A promise that resolves when invalidation completes.\n * @throws {Error} When the document is missing a valid `_id`.\n */\n async invalidateDocumentCache(doc, ctx) {\n await this.init();\n if (!doc || typeof doc !== 'object' || !('_id' in doc) || !doc._id) {\n throw new Error('Document must contain a valid _id.');\n }\n return this.runWithModelContext(ctx, async () => {\n const merged = this.mergeCtx(ctx);\n const tenantId = merged?.tenantId ?? 'default';\n const dbName = merged?.dbName ?? 'default';\n const collectionName = merged?.collectionName ?? this._collectionName;\n const pattern = `Ambiten:${tenantId}:${dbName}:${collectionName}:*${String(doc._id)}*`;\n return AmbitenModel.invalidatePattern(pattern);\n });\n }\n /**\n * Returns cache statistics for the active Redis cache backend.\n *\n * This helper retrieves Redis memory and keyspace statistics, along with Ambiten\n * cache hit/miss counters. When a tenant identifier is provided, it also counts\n * cache keys scoped to that tenant within the Ambiten cache namespace.\n *\n * @param tenantId - Optional tenant identifier used to count tenant-scoped cache keys.\n * @returns Cache statistics for the current Redis backend.\n * @throws {Error} When cache statistics cannot be retrieved.\n */\n static async getCacheStats(tenantId) {\n try {\n const memoryInfo = await redis_manager_1.redis.info('memory');\n const keyspaceInfo = await redis_manager_1.redis.info('keyspace');\n const matches = Array.from(keyspaceInfo.matchAll(/db\\d+:keys=(\\d+)/g));\n const totalKeys = matches.reduce((sum, match) => {\n return sum + Number(match[1] ?? 0);\n }, 0);\n const memoryMatch = memoryInfo.match(/used_memory:(\\d+)/);\n const memoryUsageBytes = memoryMatch ? Number(memoryMatch[1]) : 0;\n const hitsRaw = (await redis_manager_1.redis.get('Ambiten:cache:stats:hits')) ?? '0';\n const missesRaw = (await redis_manager_1.redis.get('Ambiten:cache:stats:misses')) ?? '0';\n const totalHits = Number.parseInt(hitsRaw, 10) || 0;\n const totalMisses = Number.parseInt(missesRaw, 10) || 0;\n const totalRequests = totalHits + totalMisses;\n const hitRate = totalRequests > 0\n ? Math.round((totalHits / totalRequests) * 100)\n : 0;\n const missRate = totalRequests > 0\n ? Math.round((totalMisses / totalRequests) * 100)\n : 0;\n let tenantKeys;\n if (tenantId) {\n const pattern = `Ambiten:${tenantId}:*`;\n let cursor = 0;\n let count = 0;\n do {\n const result = await redis_manager_1.redis.scan(cursor, {\n MATCH: pattern,\n COUNT: 100\n });\n const nextCursor = Array.isArray(result) ? Number(result[0]) : 0;\n const keys = Array.isArray(result) ? result[1] : [];\n if (Array.isArray(keys)) {\n count += keys.length;\n }\n cursor = nextCursor;\n } while (cursor !== 0);\n tenantKeys = count;\n }\n return {\n totalKeys,\n tenantKeys,\n memoryUsageMb: Math.round(memoryUsageBytes / 1024 / 1024),\n memoryUsageBytes,\n hitRate,\n missRate,\n totalHits,\n totalMisses,\n totalRequests,\n tenantId: tenantId ?? null,\n timestamp: new Date().toISOString()\n };\n }\n catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to get cache stats: ${message}`);\n }\n }\n /**\n * Runs a custom command on the collection.\n * @param {string} command - The command to run.\n * @param {...any} args - The arguments for the command.\n * @returns {Promise<any>} The result of the command.\n */\n async runCommand(command, ...args) {\n await this.init();\n const dbCommand = { [command]: 1, ...args };\n const col = await this.getCollection();\n return col.db.command(dbCommand);\n }\n /**\n * Runs garbage collection for expired documents in the model collection.\n *\n * This operation uses the model GC configuration to locate expired documents\n * and either soft-delete them or permanently delete them. When configured,\n * expired documents may be archived before deletion.\n *\n * The operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered GC-related middlewares,\n * triggers schema update/delete hooks as appropriate, invalidates relevant\n * cache patterns, and publishes a garbage collection event after completion.\n *\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when garbage collection completes.\n */\n async runGC(ctx) {\n await this.init();\n const config = this.resolveSchemaGCConfig();\n if (!config || !config.ttlField || !config.expiresIn) {\n return;\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'runGC',\n collectionName: this.resolveCollectionName(ctx)\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const meta = {\n gc: true\n };\n const middlewareCtx = this.buildMiddlewareContext('runGC', ctx, { meta });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('runGC', middlewareCtx);\n const expireDate = new Date(Date.now() - Number(config.expiresIn));\n const gcFilter = {\n [config.ttlField]: { $lt: expireDate }\n };\n const effectiveFilter = (middlewareCtx.filter ?? gcFilter);\n middlewareCtx.filter = effectiveFilter;\n const expiredDocs = await col.find(effectiveFilter, session ? { session } : undefined).toArray();\n if (expiredDocs.length === 0) {\n middlewareCtx.result = {\n scanned: 0,\n affected: 0,\n archived: 0,\n deleted: 0,\n softDeleted: 0\n };\n await this.runAfterMiddlewares('runGC', middlewareCtx);\n return;\n }\n let archived = 0;\n let deleted = 0;\n let softDeleted = 0;\n if (config.softDelete) {\n const softDeleteUpdate = {\n $set: {\n deletedAt: new Date(),\n isDeleted: true\n }\n };\n await this.schema.executePre('updateMany', {\n operation: 'runGC',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n docs: expiredDocs,\n meta: {\n ...(middlewareCtx.meta ?? {}),\n gc: true,\n softDelete: true\n }\n });\n const result = await col.updateMany(effectiveFilter, softDeleteUpdate, session ? { session } : undefined);\n softDeleted = result.modifiedCount;\n await this.schema.executePost('updateMany', {\n operation: 'runGC',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n docs: expiredDocs,\n result: {\n scanned: expiredDocs.length,\n affected: softDeleted,\n archived: 0,\n deleted: 0,\n softDeleted\n },\n meta: {\n ...(middlewareCtx.meta ?? {}),\n gc: true,\n softDelete: true\n }\n });\n }\n else {\n if (config.archiveBeforeDelete) {\n const archiveDocs = expiredDocs.map((doc) => ({\n ...doc,\n _archivedAt: new Date(),\n _from: col.collectionName\n }));\n await col.db.collection('Ambiten_archives').insertMany(archiveDocs, session ? { session } : undefined);\n archived = archiveDocs.length;\n }\n await this.schema.triggerMiddleware('pre', 'deleteMany', {\n operation: 'runGC',\n collectionName: middlewareCtx.collectionName,\n docs: expiredDocs\n });\n await this.schema.executePre('deleteMany', {\n operation: 'runGC',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n docs: expiredDocs,\n result: this.toModelResults(expiredDocs),\n meta: {\n ...(middlewareCtx.meta ?? {}),\n gc: true\n }\n });\n const result = await col.deleteMany(effectiveFilter, session ? { session } : undefined);\n deleted = result.deletedCount ?? 0;\n await this.schema.triggerMiddleware('post', 'deleteMany', {\n operation: 'runGC',\n collectionName: middlewareCtx.collectionName,\n docs: expiredDocs\n });\n await this.schema.executePost('deleteMany', {\n operation: 'runGC',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n docs: expiredDocs,\n result: {\n scanned: expiredDocs.length,\n affected: deleted,\n archived,\n deleted,\n softDeleted: 0\n },\n meta: {\n ...(middlewareCtx.meta ?? {}),\n gc: true\n }\n });\n }\n const gcResult = {\n scanned: expiredDocs.length,\n affected: softDeleted || deleted,\n archived,\n deleted,\n softDeleted\n };\n middlewareCtx.result = gcResult;\n await this.runAfterMiddlewares('runGC', middlewareCtx);\n await this.invalidateCachePatterns('runGC', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n garbageCollection: {\n action: 'runGC',\n collectionName: middlewareCtx.collectionName,\n ...gcResult,\n meta: {\n ...(middlewareCtx.meta ?? {}),\n gc: true\n }\n }\n });\n }));\n }\n /**\n * Starts the automatic garbage collection process.\n * @param {number} intervalMs - The interval in milliseconds for the garbage collection to run.\n */\n startAutoGC(intervalMs = 3600000) {\n setInterval(() => this.runGC().catch(console.error), intervalMs);\n }\n /**\n * Resolves instrumentation context for model operations by combining explicit\n * model context with the active runtime context.\n *\n * This helper is used to provide stable metadata for logging, observers,\n * tracing, and query instrumentation.\n *\n * @param ctx - Optional model execution context.\n * @returns Resolved instrumentation metadata for the current operation.\n */\n resolveInstrumentationContext(ctx) {\n const runtimeCtx = context_1.AmbitenContext.get();\n const merged = this.mergeCtx(ctx);\n return {\n tenantId: merged?.tenantId,\n dbName: merged?.dbName,\n collectionName: merged?.collectionName ?? this._collectionName,\n session: merged?.session,\n requestId: runtimeCtx.requestId\n };\n }\n /**\n * Builds normalized operation metadata by merging existing middleware metadata\n * with operation-specific overrides.\n *\n * @param base - Existing operation metadata.\n * @param overrides - Additional metadata flags or values to apply.\n * @returns Normalized operation metadata.\n */\n buildOperationMeta(base, overrides) {\n return {\n ...(base ?? {}),\n ...(overrides ?? {}),\n extra: {\n ...(base?.extra ?? {}),\n ...(overrides?.extra ?? {})\n }\n };\n }\n /**\n * Builds a normalized hook payload for schema middleware and instrumentation.\n *\n * @param operation - Operation name.\n * @param ctx - Optional model execution context.\n * @param payload - Additional hook payload fields.\n * @returns Normalized hook payload.\n */\n buildHookPayload(operation, ctx, payload = {}) {\n const instrumentation = this.resolveInstrumentationContext(ctx);\n return {\n operation,\n collectionName: payload.collectionName ?? instrumentation.collectionName,\n tenantId: payload.tenantId ?? instrumentation.tenantId,\n dbName: payload.dbName ?? instrumentation.dbName,\n session: payload.session ?? instrumentation.session,\n filter: payload.filter,\n update: payload.update,\n doc: payload.doc,\n docs: payload.docs,\n pipeline: payload.pipeline,\n result: payload.result,\n meta: payload.meta\n };\n }\n //=============== Cache ====================//\n /**\n * Resolves a cache adapter for the current query options.\n *\n * This helper returns a lightweight Redis-backed cache interface when caching\n * is enabled in the provided query options. Cache failures are treated as\n * non-fatal so query execution can continue even when Redis is unavailable or\n * a cache payload is invalid.\n *\n * @param options - Optional query options that may enable caching.\n * @returns A cache adapter when caching is enabled, otherwise `null`.\n */\n resolveCache(options) {\n if (!options?.cache) {\n return null;\n }\n return {\n get: async (key, meta) => {\n try {\n const cached = await redis_manager_1.redis.get(key);\n if (!cached) {\n await AmbitenModel.trackCacheMiss();\n return null;\n }\n const parsed = JSON.parse(cached);\n await AmbitenModel.trackCacheHit();\n return parsed;\n }\n catch {\n return null;\n }\n },\n set: async (key, value, meta) => {\n try {\n const ttl = meta?.ttlSeconds ?? 300;\n await redis_manager_1.redis.set(key, JSON.stringify(value), {\n EX: ttl\n });\n }\n catch {\n // Best-effort cache write. Intentionally ignored.\n }\n }\n };\n }\n /**\n * Builds a deterministic cache key for a query operation.\n *\n * The cache key is scoped by tenant, database, collection, and operation, and\n * uses a normalized serialized payload to ensure stable cache identity across\n * semantically equivalent query inputs.\n *\n * @param operation - Query operation name.\n * @param payload - Cache identity payload for the operation.\n * @returns A deterministic tenant-aware cache key.\n */\n buildCacheKey(operation, payload) {\n const tenantId = String(payload.tenantId ?? 'default');\n const dbName = String(payload.dbName ?? 'default');\n const collectionName = String(payload.collectionName ?? this._collectionName);\n const { tenantId: _tenantId, dbName: _dbName, collectionName: _collectionName, ...rest } = payload;\n const normalizedPayload = this.sortObjectDeep(rest);\n const serialized = JSON.stringify(normalizedPayload);\n return `Ambiten:${tenantId}:${dbName}:${collectionName}:${operation}:${serialized}`;\n }\n static async trackCacheMiss() {\n try {\n const today = new Date().toISOString().slice(0, 10);\n const retentionSeconds = 86400 * 7;\n const pipeline = redis_manager_1.redis.multi();\n pipeline.incr('Ambiten:cache:stats:misses');\n pipeline.incr(`Ambiten:cache:stats:misses:${today}`);\n pipeline.expire(`Ambiten:cache:stats:misses:${today}`, retentionSeconds);\n await pipeline.exec();\n }\n catch {\n // Best-effort telemetry. Intentionally ignored.\n }\n }\n static async trackCacheHit() {\n try {\n const today = new Date().toISOString().slice(0, 10);\n const retentionSeconds = 86400 * 7;\n const pipeline = redis_manager_1.redis.multi();\n pipeline.incr('Ambiten:cache:stats:hits');\n pipeline.incr(`Ambiten:cache:stats:hits:${today}`);\n pipeline.expire(`Ambiten:cache:stats:hits:${today}`, retentionSeconds);\n await pipeline.exec();\n }\n catch {\n // Best-effort telemetry. Intentionally ignored.\n }\n }\n static async cacheResult(key, data, ttl = 3600) {\n if (typeof key !== 'string' || key.trim().length === 0) {\n throw new Error('Cache key must be a non-empty string.');\n }\n if (!Number.isFinite(ttl) || ttl <= 0) {\n throw new Error('TTL must be a positive number.');\n }\n try {\n await redis_manager_1.redis.set(key, JSON.stringify(data));\n await redis_manager_1.redis.expire(key, ttl);\n }\n catch {\n // Best-effort cache write. Intentionally ignored.\n }\n }\n /**\n * Clears a cached result by its key.\n * @param {string} key - The cache key.\n * @returns {Promise<void>} Resolves when the cache is cleared.\n */\n static async clearCache(key) {\n if (!key || typeof key !== 'string') {\n throw new Error('Cache key must be a non-empty string');\n }\n try {\n await redis_manager_1.redis.del(key);\n }\n catch (error) {\n console.error('Error clearing cache:', error);\n throw new Error(`Failed to clear cache for key \"${key}\": ${error}`);\n }\n }\n /**\n * Warms cache entries for selected model queries.\n *\n * When query definitions are provided, this helper executes the corresponding\n * `find` operations and stores the results using Ambiten's scoped cache key\n * strategy. When no queries are provided, it warms a default collection-wide\n * `find({})` cache entry, subject to a safety threshold for large collections.\n *\n * This helper is best suited for controlled cache priming scenarios such as\n * startup warmup, scheduled maintenance, or high-traffic query preparation.\n *\n * @param queries - Optional list of query definitions to warm.\n * @param defaultTtl - Default TTL in seconds for warmed entries.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when cache warming completes.\n * @throws {Error} When cache warming fails.\n */\n async warmCache(queries, defaultTtl = 3600, ctx) {\n await this.init();\n if (!Number.isFinite(defaultTtl) || defaultTtl <= 0) {\n throw new Error('Default TTL must be a positive number.');\n }\n return this.runWithModelContext(ctx, async () => {\n const cache = this.resolveCache({ cache: { ttl: defaultTtl } });\n if (!cache) {\n return;\n }\n const instrumentation = this.resolveInstrumentationContext(ctx);\n const col = await this.getCollection(ctx);\n const session = this.resolveSession(ctx);\n const warmQueries = queries && queries.length > 0\n ? queries\n : [{ filter: {}, ttl: defaultTtl }];\n if ((!queries || queries.length === 0)) {\n const totalDocs = await col.countDocuments({}, session ? { session } : undefined);\n if (totalDocs > 1000) {\n return;\n }\n }\n for (const query of warmQueries) {\n const filter = (query.filter ?? {});\n const ttl = query.ttl ?? defaultTtl;\n const docs = await col.find(filter, session ? { session } : undefined).toArray();\n const payload = this.toModelResults(docs);\n const cacheKey = this.buildCacheKey('find', {\n collectionName: instrumentation.collectionName,\n filter,\n tenantId: instrumentation.tenantId,\n dbName: instrumentation.dbName\n });\n await cache.set(cacheKey, payload, {\n ttlSeconds: ttl,\n tenantId: instrumentation.tenantId,\n namespace: instrumentation.collectionName\n });\n }\n });\n }\n // We want to avoids cache-key drift from key ordering.\n sortObjectDeep(value) {\n if (Array.isArray(value)) {\n return value.map((item) => this.sortObjectDeep(item));\n }\n if (value instanceof Date) {\n return value.toISOString();\n }\n if (value && typeof value === 'object') {\n return Object.keys(value)\n .sort()\n .reduce((acc, key) => {\n acc[key] = this.sortObjectDeep(value[key]);\n return acc;\n }, {});\n }\n return value;\n }\n toModelResult(doc) {\n const { _id, ...rest } = doc;\n return {\n ...rest,\n _id: _id.toString()\n };\n }\n toModelResults(docs = []) {\n return docs.map((doc) => this.toModelResult(doc));\n }\n /**\n * Restores a single soft-deleted document matching the provided filter.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered restore middlewares,\n * triggers schema update hooks, invalidates relevant cache patterns, and\n * publishes a document restoration event after completion.\n *\n * The actual restore behavior is driven by the update document returned from\n * {@link buildRestoreUpdate}.\n *\n * @param filter - MongoDB filter used to identify the document to restore.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n * @throws {Error} When the filter is missing or invalid.\n */\n async restoreOne(filter, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'restoreOne',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const meta = {\n restore: true\n };\n const middlewareCtx = this.buildMiddlewareContext('restoreOne', ctx, {\n filter,\n meta\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('restoreOne', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const restoreUpdate = this.buildRestoreUpdate();\n const existingDoc = await col.findOne(effectiveFilter, session ? { session } : undefined);\n if (!existingDoc) {\n middlewareCtx.result = null;\n await this.runAfterMiddlewares('restoreOne', middlewareCtx);\n return;\n }\n await this.schema.executePre('restoreOne', {\n operation: 'restoreOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: restoreUpdate,\n meta\n });\n const result = await col.updateOne(effectiveFilter, restoreUpdate, session ? { session } : undefined);\n const restoredDoc = await col.findOne(effectiveFilter, session ? { session } : undefined);\n const restoreResult = {\n acknowledged: result.acknowledged,\n matchedCount: result.matchedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.upsertedCount,\n upsertedId: result.upsertedId,\n restored: restoredDoc\n ? this.toModelResult(restoredDoc)\n : null\n };\n await this.schema.executePost('restoreOne', {\n operation: 'restoreOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: restoreUpdate,\n result: restoreResult,\n meta\n });\n middlewareCtx.result = restoreResult;\n await this.runAfterMiddlewares('restoreOne', middlewareCtx);\n await this.invalidateCachePatterns('restoreOne', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentRestored: {\n action: 'restoreOne',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n result: restoreResult,\n meta\n }\n });\n }));\n }\n /**\n * Restores multiple soft-deleted documents matching the provided filter.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered restore middlewares,\n * triggers schema update hooks, invalidates relevant cache patterns, and\n * publishes a document restoration event after completion.\n *\n * The actual restore behavior is driven by the update document returned from\n * {@link buildRestoreUpdate}.\n *\n * @param filter - MongoDB filter used to identify the documents to restore.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n * @throws {Error} When the filter is missing or invalid.\n */\n async restoreMany(filter, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'restoreMany',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const meta = {\n restore: true\n };\n const middlewareCtx = this.buildMiddlewareContext('restoreMany', ctx, {\n filter,\n meta\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('restoreMany', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const restoreUpdate = this.buildRestoreUpdate();\n const existingDocs = await col.find(effectiveFilter, session ? { session } : undefined).toArray();\n if (existingDocs.length === 0) {\n middlewareCtx.result = {\n restoredCount: 0,\n docs: []\n };\n await this.runAfterMiddlewares('restoreMany', middlewareCtx);\n return;\n }\n await this.schema.executePre('updateMany', {\n operation: 'restoreMany',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: restoreUpdate,\n docs: existingDocs,\n meta\n });\n const result = await col.updateMany(effectiveFilter, restoreUpdate, session ? { session } : undefined);\n const restoredDocs = await col.find(effectiveFilter, session ? { session } : undefined).toArray();\n const restoreResult = {\n acknowledged: result.acknowledged,\n matchedCount: existingDocs.length,\n modifiedCount: result.modifiedCount,\n restoredCount: result.modifiedCount,\n docs: this.toModelResults(restoredDocs)\n };\n await this.schema.executePost('updateMany', {\n operation: 'restoreMany',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: restoreUpdate,\n docs: restoredDocs,\n result: restoreResult,\n meta\n });\n middlewareCtx.result = restoreResult;\n await this.runAfterMiddlewares('restoreMany', middlewareCtx);\n await this.invalidateCachePatterns('restoreMany', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentRestored: {\n action: 'restoreMany',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n result: restoreResult,\n meta\n }\n });\n }));\n }\n buildRestoreUpdate() {\n const deletedAtField = this._softDeleteConfig?.deletedAtField ?? 'deletedAt';\n const isDeletedField = this._softDeleteConfig?.isDeletedField ?? 'isDeleted';\n return {\n $set: {\n [deletedAtField]: null,\n [isDeletedField]: false\n }\n };\n }\n //================ Middleware Context and Execution =================//\n buildMiddlewareContext(operation, ctx, payload = {}) {\n const merged = this.mergeCtx(ctx);\n return {\n operation,\n modelName: this.constructor.name,\n collectionName: payload.collectionName ??\n merged?.collectionName ??\n this._collectionName,\n tenantId: payload.tenantId ?? merged?.tenantId,\n dbName: payload.dbName ?? merged?.dbName,\n session: payload.session ?? merged?.session,\n withDeleted: payload.withDeleted ?? merged?.withDeleted,\n onlyDeleted: payload.onlyDeleted ?? merged?.onlyDeleted,\n hardDelete: payload.hardDelete ?? merged?.hardDelete,\n filter: payload.filter,\n update: payload.update,\n doc: payload.doc,\n docs: payload.docs,\n pipeline: payload.pipeline,\n bulkUpdates: payload.bulkUpdates,\n bulkOperations: payload.bulkOperations,\n result: payload.result,\n meta: payload.meta\n };\n }\n setSoftDeleteConfig(config) {\n this._softDeleteConfig = config;\n }\n /**\n * Builds the update document used for soft delete operations.\n *\n * The generated update sets the configured deleted timestamp field and\n * deleted-state flag field to mark the document as logically deleted without\n * physically removing it from the collection.\n *\n * @returns MongoDB update document for soft delete flows.\n */\n buildSoftDeleteUpdate() {\n const deletedAtField = this._softDeleteConfig?.deletedAtField ?? 'deletedAt';\n const isDeletedField = this._softDeleteConfig?.isDeletedField ?? 'isDeleted';\n return {\n $set: {\n [deletedAtField]: new Date(),\n [isDeletedField]: true\n }\n };\n }\n // Middleware runners/execution methods\n async runBeforeMiddlewares(operation, ctx) {\n const handlers = this.beforeMiddlewares.get(operation) ?? [];\n for (const handler of handlers) {\n await handler(ctx);\n }\n }\n async runAfterMiddlewares(operation, ctx) {\n const handlers = this.afterMiddlewares.get(operation) ?? [];\n for (const handler of handlers) {\n await handler(ctx);\n }\n }\n // Middleware registration methods\n before(operation, handler) {\n const existing = this.beforeMiddlewares.get(operation) ?? [];\n existing.push(handler);\n this.beforeMiddlewares.set(operation, existing);\n return this;\n }\n after(operation, handler) {\n const existing = this.afterMiddlewares.get(operation) ?? [];\n existing.push(handler);\n this.afterMiddlewares.set(operation, existing);\n return this;\n }\n beforeFind(handler) {\n return this.before('find', handler);\n }\n afterFind(handler) {\n return this.after('find', handler);\n }\n beforeFindOne(handler) {\n return this.before('findOne', handler);\n }\n afterFindOne(handler) {\n return this.after('findOne', handler);\n }\n beforeSave(handler) {\n return this.before('create', handler);\n }\n afterSave(handler) {\n return this.after('create', handler);\n }\n beforeUpdateOne(handler) {\n return this.before('updateOne', handler);\n }\n afterUpdateOne(handler) {\n return this.after('updateOne', handler);\n }\n beforeDeleteOne(handler) {\n return this.before('deleteOne', handler);\n }\n afterDeleteOne(handler) {\n return this.after('deleteOne', handler);\n }\n beforeDeleteMany(handler) {\n return this.before('deleteMany', handler);\n }\n afterDeleteMany(handler) {\n return this.after('deleteMany', handler);\n }\n beforeBulkInsert(handler) {\n return this.before('bulkInsert', handler);\n }\n afterBulkInsert(handler) {\n return this.after('bulkInsert', handler);\n }\n beforeBulkUpdate(handler) {\n return this.before('bulkUpdate', handler);\n }\n afterBulkUpdate(handler) {\n return this.after('bulkUpdate', handler);\n }\n beforeAggregate(handler) {\n return this.before('aggregate', handler);\n }\n afterAggregate(handler) {\n return this.after('aggregate', handler);\n }\n beforeFindOneAndUpdate(handler) {\n return this.before('findOneAndUpdate', handler);\n }\n afterFindOneAndUpdate(handler) {\n return this.after('findOneAndUpdate', handler);\n }\n beforeFindOneAndDelete(handler) {\n return this.before('findOneAndDelete', handler);\n }\n afterFindOneAndDelete(handler) {\n return this.after('findOneAndDelete', handler);\n }\n beforeFindOneAndReplace(handler) {\n return this.before('findOneAndReplace', handler);\n }\n afterFindOneAndReplace(handler) {\n return this.after('findOneAndReplace', handler);\n }\n beforeFindOneAndUpsert(handler) {\n return this.before('findOneAndUpsert', handler);\n }\n afterFindOneAndUpsert(handler) {\n return this.after('findOneAndUpsert', handler);\n }\n}\nexports.AmbitenModel = AmbitenModel;\n;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n;\n","\"use strict\";\n/**\n * @author Emmanuel Nodolomwanyi - Ambiten Team\n * @package - @Ambiten/core\n * @version 1.0.0\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.measureQueryForBrowser = exports.AmbitenBootstrapFactory = void 0;\nconst tslib_1 = require(\"tslib\");\nconst lib_core_1 = require(\"./lib-core\");\n/**\n * Ambiten Core Library for Browser\n * This module provides core functionalities for Ambiten in a browser environment.\n * It includes database operations, configuration, and more.\n * @module Ambiten Core Browser Module\n * @version 1.0.0\n */\nconsole.log('Ambiten Core Library Loaded for (Browser)');\nwindow.AmbitenClient = lib_core_1.AmbitenClient;\nwindow.Buffer = Buffer;\ntslib_1.__exportStar(require(\"./lib-core\"), exports);\nvar bootstrap_1 = require(\"./lib-core/bootstrap\");\nObject.defineProperty(exports, \"AmbitenBootstrapFactory\", { enumerable: true, get: function () { return bootstrap_1.AmbitenBootstrapFactory; } });\ntslib_1.__exportStar(require(\"./config\"), exports);\ntslib_1.__exportStar(require(\"./graphql\"), exports);\ntslib_1.__exportStar(require(\"./tanancy\"), exports);\ntslib_1.__exportStar(require(\"./context\"), exports);\ntslib_1.__exportStar(require(\"./plugins\"), exports);\ntslib_1.__exportStar(require(\"./debug\"), exports);\nvar instrumentation_1 = require(\"./instrumentation\");\nObject.defineProperty(exports, \"measureQueryForBrowser\", { enumerable: true, get: function () { return instrumentation_1.measureQueryForBrowser; } });\ntslib_1.__exportStar(require(\"./ambiten-cache\"), exports);\ntslib_1.__exportStar(require(\"./utils/builders\"), exports);\ntslib_1.__exportStar(require(\"./utils\"), exports);\ntslib_1.__exportStar(require(\"./gc\"), exports);\ntslib_1.__exportStar(require(\"./redis-manager\"), exports);\ntslib_1.__exportStar(require(\"./types\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./createModel\"), exports);\ntslib_1.__exportStar(require(\"./schema\"), exports);\ntslib_1.__exportStar(require(\"./getTenantDb\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n;\n;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenError-handler\"), exports);\ntslib_1.__exportStar(require(\"./errorTypes\"), exports);\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(9590);\n"],"names":["root","factory","exports","module","require","define","amd","self","__WEBPACK_EXTERNAL_MODULE__2947__","__WEBPACK_EXTERNAL_MODULE__3911__","__WEBPACK_EXTERNAL_MODULE__8535__","Object","defineProperty","value","resolveAmbitenOption","values","undefined","detectPackageManager","getInstallCommand","manager","packages","join","installPackages","async","cwd","process","args","length","Promise","resolve","reject","child","child_process_1","spawn","stdio","shell","platform","on","code","Error","tslib_1","__webpack_require__","fs_1","__importDefault","path_1","default","existsSync","userAgent","env","npm_config_user_agent","includes","objectIdSymbol","schemaTypeSymbol","AmbitenSymbol","Symbol","for","__exportStar","webpackEmptyAsyncContext","req","then","e","keys","id","createBootstrapLogger","config","transportConfigs","enabled","logger_1","setupLogger","level","colorize","loggerConfig","json","transports","formatOptions","hooks","contextProvider","enableMetrics","circuitBreaker","compress","DEFAULT_CONFIG_CONTENT","options","configVersion","projectName","connection","uri","dbName","multiTenant","headerKey","tenants","initOptions","lazy","retryAttempts","logger","type","filename","frequency","maxSize","flushInterval","logInterval","graphql","subscriptions","playground","schemaOutputPath","features","models","schemas","typeDefs","resolvers","useRedisCache","redisUri","advanced","autoInstall","garbageCollector","retentionPeriod","logResults","gcCron","JSON","stringify","Model","lib_core_1","AmbitenModel","provider","AmbitenClient","init","createAmbitenClientModule","mongodb_1","utils_1","tanancy_1","context_1","_opts","_uri","_client","_db","collectionRef","_connected","_defaultDbName","_overrideDbName","static","Map","constructor","this","MONGO_URI","defaultUri","DB_NAME","MongoClient","directConnection","minPoolSize","maxPoolSize","serverSelectionTimeoutMS","db","ensureMongoDependency","opts","key","String","existing","instances","get","client","tenantResolver","set","console","error","exit","ctx","tenantId","resolver","tenantClient","getClient","resolvedTenantDbName","MultiTenantManager","getTenantDbName","message","createAmbitenError","ErrorType","CONNECTION_ERROR","details","operation","validateUri","VALIDATION_ERROR","providedUri","test","connect","useCollection","collectionName","trim","scope","resolveClientScope","collection","getCollection","toString","getClusterInfo","helloResult","admin","command","hello","msg","log","setName","hosts","resolveRuntime","AmbitenContext","tenant","getTenant","resolveDbFromTenant","session","useDatabase","withDatabase","merged","startSession","close","resolveDbName","overrideDbName","input","requestId","withContext","context","callback","run","logWithContext","meta","enrichedMeta","loggerMeta","withTenant","withScope","resetDatabase","dropCollection","providedCollectionName","resolvedCollectionName","drop","dropDatabase","result","disconnect","isConnected","handleTopologyEvent","event","TopologyOpeningEvent","topologyId","TopologyClosedEvent","warn","handleLogBatch","batch","transporter","Array","isArray","remaining","slice","writes","map","eventName","name","eventType","toLowerCase","write","timestamp","Date","toISOString","source","all","DB_CHANGE_EVENT","DOCUMENT_DELETED_EVENT","DOCUMENT_UPDATED_EVENT","DOCUMENT_INSERTED_EVENT","debugLog","isDebug","getLogger","getLoggerMeta","payload","getTenantId","getRequestId","getDbName","getCollectionName","debug","ensureRedis","publisher","subscriber","redis_manager_1","redis","isOpen","duplicate","err","getTenantModel","builders_1","MultiTenantManager_1","tenantModelsCache","params","has","tenantCache","cacheKey","resolvedDbName","createTenantProvider","model","schema","resolveRuntimeConfig","resolveAmbitenOption_1","methodTenantId","modelTenantId","methodDbName","modelDbName","clientDbName","methodCollectionName","modelCollectionName","methodSession","modelSession","checkPermission","getCachedData","setCachedData","invalidateTenantCache","role","exists","del","info","enforceRBAC","permission","wrapped","parent","user","writable","configurable","__originalResolver","__rbacAction","getRBACAction","getOriginalResolver","rbacTypes_1","buildCacheKey","parse","allowedActions","rolePermissions","permissions","cachedData","data","ttl","EX","roleKey","loadAmbitenConfig","configPath","candidates","DEFAULT_CONFIG_FILENAME","finalPath","parsed","candidate","fs_extra_1","pathExists","raw","readFile","rawConfig","cfg","compressLogFiles","normalizeAmbitenConfig","validate","ajv","compile","ambiten_config_schema_json_1","errors","location","instancePath","extra","keyword","additionalProperty","assertValidAmbitenConfig","ajv_1","allErrors","useDefaults","strict","coerceTypes","now","isValidDuration","formatDuration","parseDuration","duration","match","isValid","parseInt","unit","ms","seconds","Math","floor","minutes","hours","days","AmbitenError","cause","super","captureStackTrace","toJSON","AmbitenBootstrapFactory","config_1","index_1","__1","gc_1","invalidateTenantCache_1","AmbitenBootstrap","gc","adapter","onConnectHooks","connectCallbacks","onConnect","push","initialize","configFilePathOrObject","initializeLogger","initializeRedis","initializeMongoProvider","initializeSchema","initializeModel","initializeMultiTenancy","initializeGraphQL","runOnConnectHooks","initializeGarbageCollector","mongoClient","configureAmbitenContext","Schema","registerSchema","gcConfig","registerModel","initMultiTenancy","tenantCount","AmbitenGraphQL","useRedis","customTypeDefs","customResolvers","generateSchema","hook","AmbitenGC","cron","continueOnError","registerMultiTenancy","multiTenantConfig","cache","fetcher","cacheWithRedis","invalidateCache","namespace","getRedisClient","getMongoClient","getModel","getSchema","getGraphQL","getGCRunner","shutdown","create","bootstrap","node_async_hooks_1","runManualTransaction_1","DEFAULT_AMBITEN_BUDGET","maxQueries","Infinity","queriesExecuted","totalTimeMs","storage","AsyncLocalStorage","transactionResolver","getStore","budget","normalizeBudget","hasActiveContext","patch","current","assign","clear","configureTransactionResolver","getSession","getObserver","observer","getBudget","state","normalized","setBudget","assertQueryBudget","incrementQueries","addQueryTime","durationMs","Boolean","AMBITEN_DEBUG","withTransaction","resolveClient","endSession","runManualTransaction","hasTransactionResolver","measureQueryForBrowser","_meta","executor","getTenantDB","dbCache","runGarbageCollectorOnAllModels","ModelRegistry_1","AmbitenModelRegistry","getAllModels","scanned","succeeded","failed","modelContext","getContext","runGC","success","runGarbageCollector","ambiten_cache_1","AmbitenCache","wrap","generateProject","generateProjectWithConfig","templates_1","startedAt","projectRoot","entryFilePath","ensureDir","createScaffoldLogger","resolvedOptions","generateAppStructure","printSummary","files","dirs","normalize","p","relative","replace","addFile","filePath","addDir","dirPath","enabledFeatures","filter","disabledFeatures","toFixed","color_palatte_1","forEach","d","f","feature","SchemaType","Types","ObjectId","applySoftDelete","DEFAULTS","applyReadFilter","withDeleted","onlyDeleted","excludeDeletedByDefault","mergeFilter","buildNotDeletedFilter","buildOnlyDeletedFilter","beforeFind","beforeFindOne","beforeFindOneAndUpdate","beforeFindOneAndReplace","beforeFindOneAndUpsert","beforeAggregate","stage","$match","pipeline","beforeDeleteOne","hardDelete","update","buildSoftDeleteUpdate","softDelete","beforeDeleteMany","beforeFindOneAndDelete","setSoftDeleteConfig","deletedAtField","isDeletedField","field","deletedByField","$and","$or","$exists","$ne","original","$set","transactionSession_1","hasManualTransactionMethods","startTransaction","commitTransaction","abortTransaction","text","hasTenant","registerLazyTenant","validateTenantId","normalizedTenantId","tenantConfig","extractDbNameFromUri","metadata","registerTenant","getConnectedTenant","connected","from","find","getAllConnectedTenants","getAllTenants","isEnabled","size","removeTenant","delete","clearTenants","startsWith","parts","split","lastPart","generateMainTS","createAmbitenCache","buildKey","prefix","namespacedKey","cached","emit","ttlSeconds","invalidate","invalidatePattern","pattern","scan","cursor","deletedCount","MATCH","COUNT","nextCursor","Number","scheduleGarbageCollector","cronExpr","schedule","gcManager_1","__importStar","createSchema","AmbitenSchema","redisClient","RedisService","getInstance","TenantContext","tenantStorage","setTenantId","store","connectRedis","url","redis_1","DEFAULT_RECONNECT","retries","min","redisUrl","REDIS_URI","currentClient","createStub","publish","subscribe","multi","incr","expire","exec","createClient","socket","reconnectStrategy","quit","channel","listener","generateGCRunner","getEventOptions","eventOptionMap","getEventType","k","et","describeEvent","logEvent","logDefaultEvent","aggregate","createIndex","dropIndex","findOne","insertOne","insertMany","updateOne","updateMany","deleteOne","deleteMany","transaction","eventDesc","schemaDefinition","indexes","virtuals","validators","relationships","middleware","pre","post","validator","fn","doc","entries","validateAsync","index","fields","applyIndexes","addRelationship","ref","localField","getRelationships","virtual","getter","applyVirtuals","enumerable","getPreHooks","getPostHooks","getHooks","phase","executePre","executePost","executeMiddleware","triggerMiddleware","setGCConfig","getGCConfig","postCtx","srcDir","coreDir","utilsDir","typesDir","modelsDir","graphqlDir","gcDir","mainPath","writeFile","generateMainEntry_1","initAmbitenPath","helperPath","configTypesPath","schemaPath","resolversPath","gcManagerPath","generateGCManagerFile_1","generateGCManager","gcRunnerPath","generateGCRunnerFile_1","generateDefaultConfigContent_1","packageJsonPath","writeJson","dependencies","mongodb","description","private","version","main","scripts","dev","build","start","license","devDependencies","typescript","buildPackageJson","spaces","tsconfigPath","compilerOptions","target","moduleResolution","rootDir","outDir","sourceMap","declaration","declarationMap","esModuleInterop","resolveJsonModule","noImplicitAny","noImplicitReturns","noUncheckedIndexedAccess","exactOptionalPropertyTypes","forceConsistentCasingInFileNames","skipLibCheck","types","lib","include","exclude","gitignorePath","packageManager","installCommand","viewer","schema_1","graphql_tag_1","toModelContext","publishEvent","defaultTypeDefs","gql","defaultResolvers","Query","_","_id","findAll","toArray","Mutation","col","newDoc","insertedId","documentInserted","action","updatedDoc","documentUpdated","documentDeleted","Subscription","makeExecutableSchema","AuthService","jsonwebtoken_1","SECRET","JWT_SECRET","REFRESH_SECRET","REFRESH_EXPIRATION","JWT_EXPIRATION","generateToken","sign","expiresIn","generateRefreshToken","verifyToken","token","verify","isValidObjectId","isObjectId","castId","inputId","createFromHexString","symbols_1","prototype","toHexString","hasOwnProperty","call","valueOf","ensureModelNameSafe","trimmedName","getModelFilesFromPath","loadModelsFromPath","modelFiles","file","modelModule","readdirSync","fullPath","statSync","isDirectory","authorize","roles","res","next","authHeader","headers","authorization","Authorization","status","decoded","AuthUtils_1","clearModelRegistryForTests","registeredModels","unregisterModel","modelRegistry","Set","add","getRegisteredModel","isModelRegistered","intervalMs","intervalRef","cronTask","interval","parseInterval","runOnce","setInterval","stop","clearInterval","num","eventTypes","startGarbageCollector","measureQuery","ambitenContext_1","budgetAfterIncrement","perf_hooks_1","performance","round","budgetAfterTime","documentCount","totalBudgetUsed","setImmediate","onQuery","errorMessage","errorName","onQueryError","ambitenClient_1","ambitenSchema_1","events_1","graphql_subscriptions_1","instrumentation_1","debug_1","pubsub","PubSub","_provider","_collectionName","_collectionOverride","_schema","_initialized","_defaultCtx","_modelGCConfig","_gcConfig","_gcTimer","eventEmitter","beforeMiddlewares","afterMiddlewares","_softDeleteConfig","NULL_OR_UNDEFINED","providedOptions","typeError","AmbitenModelError","fixedDb","schemaGCConfig","resolveSchemaGCConfig","isGCEnabled","initMiddleware","mergeCtx","runtimeCtx","some","runWithModelContext","enableGC","ensureConfigured","resolveDb","resolveCollectionName","databaseName","getResolvedTenant","resolvedCtx","resolveSession","resolveSessionStrict","externalSession","once","off","removeListener","ensureGCIndex","INITIALIZATION_ERROR","TypeError","bind","clone","updatedAtField","createdAtField","expireAfterSeconds","indexName","background","relatedCollection","dbChange","updateFilter","unshift","$lookup","foreignField","as","middlewareCtx","buildMiddlewareContext","runBeforeMiddlewares","nextDoc","buildHookPayload","insertResult","createdDoc","toModelResult","runAfterMiddlewares","finalResult","invalidateCachePatterns","effectiveFilter","resolveCache","cacheHit","results","toModelResults","effectiveUpdate","updateResult","acknowledged","matchedCount","modifiedCount","upsertedCount","upsertedId","bulkInsert","docs","nextDocs","buildOperationMeta","bulkWrite","ordered","insertedDocs","insertedIds","bulkUpdate","updates","bulkUpdates","nextUpdates","insertedCount","entry","bulkOps","bulkResult","isOk","softDeleteUpdate","existingDocs","softDeleteMeta","softDeleteResult","softDeleted","deleteResult","populateOne","relatedModel","referenceValue","relatedDoc","populateMany","referenceValues","relatedDocs","$in","createWithTransaction","transactional","bulkWriteWithTransaction","operations","bulkOperations","nextOperations","bulkResultSummary","deleteWithTransaction","existingDoc","updateWithTransaction","projectedUpdatedDoc","findOneAndUpdate","returnDocument","findOneAndDelete","existingPayload","deleteOptions","deletedDoc","finalPayload","findOneAndReplace","replacement","nextReplacement","replaceResult","replacedDoc","findOneAndUpsert","upsertResult","upsert","findOneAndUpsertWithTransaction","findOneAndUpsertWithTransactionSecure","secure","userId","userRole","deleteSecure","queryOptions","resolvedSession","effectivePipeline","aggregateWithTransaction","baseCtx","existingSession","runtimeBase","runInTransaction","streamAggregation","streaming","stream","aggregateWithCache","cacheDuration","cachedResult","paginatedFind","pageSize","lastId","query","$gt","limit","rest","watchChanges","changeStream","watch","direction","patterns","normalizedPattern","execResult","invalidateModelPattern","fullPattern","invalidateDocumentCache","getCacheStats","memoryInfo","keyspaceInfo","totalKeys","matchAll","reduce","sum","memoryMatch","memoryUsageBytes","hitsRaw","missesRaw","totalHits","totalMisses","totalRequests","hitRate","missRate","tenantKeys","count","memoryUsageMb","runCommand","dbCommand","ttlField","expireDate","gcFilter","$lt","expiredDocs","affected","archived","deleted","deletedAt","isDeleted","archiveBeforeDelete","archiveDocs","_archivedAt","_from","gcResult","garbageCollection","startAutoGC","catch","resolveInstrumentationContext","base","overrides","instrumentation","trackCacheMiss","trackCacheHit","_tenantId","_dbName","normalizedPayload","sortObjectDeep","today","retentionSeconds","cacheResult","isFinite","clearCache","warmCache","queries","defaultTtl","warmQueries","countDocuments","item","sort","acc","restoreOne","restore","restoreUpdate","buildRestoreUpdate","restoredDoc","restoreResult","restored","documentRestored","restoreMany","restoredCount","restoredDocs","modelName","handlers","handler","before","after","afterFind","afterFindOne","beforeSave","afterSave","beforeUpdateOne","afterUpdateOne","afterDeleteOne","afterDeleteMany","beforeBulkInsert","afterBulkInsert","beforeBulkUpdate","afterBulkUpdate","afterAggregate","afterFindOneAndUpdate","afterFindOneAndDelete","afterFindOneAndReplace","afterFindOneAndUpsert","window","Buffer","bootstrap_1","__webpack_module_cache__","moduleId","cachedModule","__webpack_modules__","o","obj","prop"],"ignoreList":[],"sourceRoot":""}
1
+ {"version":3,"file":"index-browser.js","mappings":"CAAA,SAAAA,EAAAC,GACA,iBAAAC,SAAA,iBAAAC,OACAA,OAAAD,QAAAD,EAAAG,QAAA,MAAAA,QAAA,QAAAA,QAAA,UACA,mBAAAC,QAAAA,OAAAC,IACAD,OAAA,4CAAAJ,GACA,iBAAAC,QACAA,QAAA,uBAAAD,EAAAG,QAAA,MAAAA,QAAA,QAAAA,QAAA,UAEAJ,EAAA,uBAAAC,EAAAD,EAAA,GAAAA,EAAA,KAAAA,EAAA,MACC,CATD,CASCO,KAAA,CAAAC,EAAAC,EAAAC,qCCRDC,OAAAC,eAAAV,EAAA,cAA+CW,OAAA,IAC/CX,EAAAY,qBACA,SAAAC,GACA,UAAAF,KAAAE,EACA,QAAAC,IAAAH,EACA,OAAAA,CAGA,yBCRAF,OAAAC,eAAAV,EAAA,cAA+CW,OAAA,6BCA/CF,OAAAC,eAAAV,EAAA,cAA+CW,OAAA,IAC/CX,EAAAe,qBAA4BA,EAC5Bf,EAAAgB,kBAsBA,SAAAC,EAAAC,GACA,OAAAD,GACA,WACA,wBAAAC,GAAAC,KAAA,MACA,WACA,wBAAAD,GAAAC,KAAA,MAEA,QACA,2BAAAD,GAAAC,KAAA,MAEA,EA/BAnB,EAAAoB,gBAgCAC,eAAAH,EAAA,GAAAI,EAAAC,QAAAD,OACA,MAAAL,EAAAF,EAAAO,GACAE,EAAA,IAAAN,EAAAO,OACA,YACA,QAAAR,EACA,cAAAC,GACA,UAAAA,SACA,IAAAQ,QAAA,CAAAC,EAAAC,KACA,MAAAC,GAAA,EAAAC,EAAAC,OAAAd,EAAAO,EAAA,CACAF,MACAU,MAAA,UACAC,MAAA,UAAAV,QAAAW,WAEAL,EAAAM,GAAA,QAAAP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ACxBD,EAAAgB,aAAqBf,EAAQ,MAAevC,GAC5CsC,EAAAgB,aAAqBf,EAAQ,MAAUvC,GACvCsC,EAAAgB,aAAqBf,EAAQ,MAAevC,2BCJ5CS,OAAAC,eAAAV,EAAA,cAA+CW,OAAA,8BCA/CF,OAAAC,eAAAV,EAAA,cAA+CW,OAAA,IAC/C,MAAA2B,EAAgBC,EAAQ,MACxBD,EAAAgB,aAAqBf,EAAQ,MAAwBvC,GACrDsC,EAAAgB,aAAqBf,EAAQ,MAAcvC,KCH3CioC,EAAA,GAGA,SAAA1lC,EAAA2lC,GAEA,IAAAC,EAAAF,EAAAC,GACA,QAAApnC,IAAAqnC,EACA,OAAAA,EAAAnoC,QAGA,IAAAC,EAAAgoC,EAAAC,GAAA,CAGAloC,QAAA,IAOA,OAHAooC,EAAAF,GAAAjoC,EAAAA,EAAAD,QAAAuC,GAGAtC,EAAAD,OACA,QCtBAuC,EAAA8lC,EAAA,CAAAC,EAAAC,IAAA9nC,OAAAwyB,UAAAE,eAAAC,KAAAkV,EAAAC,GCGAhmC,EAAA","sources":["webpack://ambitencore-browser/webpack/universalModuleDefinition","webpack://ambitencore-browser/./src/utils/resolveAmbitenOption.ts","webpack://ambitencore-browser/./src/types/db.provider.ts","webpack://ambitencore-browser/./src/utils/detect-package-manager.ts","webpack://ambitencore-browser/./src/utils/symbols.ts","webpack://ambitencore-browser/./src/types/GCConfig.ts","webpack://ambitencore-browser/external commonjs \"jsonwebtoken\"","webpack://ambitencore-browser/./src/tanancy/index.ts","webpack://ambitencore-browser/./src/utils/index.ts","webpack://ambitencore-browser/./src/types/graphql.type.ts","webpack://ambitencore-browser/./src/utils/ lazy referencedExports: default, default namespace object","webpack://ambitencore-browser/./src/types/result.utils.types.ts","webpack://ambitencore-browser/external commonjs \"buffer\"","webpack://ambitencore-browser/./src/utils/logger.ts","webpack://ambitencore-browser/./src/templates/generateDefaultConfigContent.ts","webpack://ambitencore-browser/./src/utils/builders/createModel.ts","webpack://ambitencore-browser/./src/config/index.ts","webpack://ambitencore-browser/./src/templates/index.ts","webpack://ambitencore-browser/./src/lib-core/ambitenClient.ts","webpack://ambitencore-browser/external commonjs \"graphql-tag\"","webpack://ambitencore-browser/./src/plugins/index.ts","webpack://ambitencore-browser/./src/utils/events.ts","webpack://ambitencore-browser/./src/debug/debugLog.ts","webpack://ambitencore-browser/./src/utils/ensureRedis.ts","webpack://ambitencore-browser/./src/types/document.ts","webpack://ambitencore-browser/./src/tanancy/TenantModelResolver.ts","webpack://ambitencore-browser/external commonjs \"mongodb\"","webpack://ambitencore-browser/./src/utils/resolveRuntimeConfig.ts","webpack://ambitencore-browser/./src/middleware/rbac/rbacMiddleware.ts","webpack://ambitencore-browser/./src/config/loadAmbitenConfig.ts","webpack://ambitencore-browser/external commonjs \"node-cron\"","webpack://ambitencore-browser/./src/utils/time.ts","webpack://ambitencore-browser/external umd \"fs\"","webpack://ambitencore-browser/./src/utils/error/ambitenError-handler.ts","webpack://ambitencore-browser/./src/lib-core/bootstrap/ambitenBootstrap.ts","webpack://ambitencore-browser/./src/context/ambitenContext.ts","webpack://ambitencore-browser/./src/ambiten-cache/index.ts","webpack://ambitencore-browser/./src/types/index.ts","webpack://ambitencore-browser/./src/types/middleware/types.ts","webpack://ambitencore-browser/./src/instrumentation/measureQuery.browser.ts","webpack://ambitencore-browser/./src/types/bootstrapClient.type.ts","webpack://ambitencore-browser/./src/utils/builders/getTenantDb.ts","webpack://ambitencore-browser/./src/redis-manager/index.ts","webpack://ambitencore-browser/./src/gc/gcManager.ts","webpack://ambitencore-browser/./src/instrumentation/index.ts","webpack://ambitencore-browser/external umd \"path\"","webpack://ambitencore-browser/external commonjs \"graphql-subscriptions\"","webpack://ambitencore-browser/./src/utils/cacheWithRedis.ts","webpack://ambitencore-browser/./src/init-cli/generate.project.ts","webpack://ambitencore-browser/./src/utils/scaffoldLoger.ts","webpack://ambitencore-browser/./src/types/schema.type.ts","webpack://ambitencore-browser/external commonjs \"dotenv/config\"","webpack://ambitencore-browser/external commonjs \"fs-extra\"","webpack://ambitencore-browser/./src/plugins/softDelete/applySoftDelete.ts","webpack://ambitencore-browser/./src/context/helpers/runManualTransaction.ts","webpack://ambitencore-browser/./src/utils/color-palatte.ts","webpack://ambitencore-browser/./src/tanancy/MultiTenantManager.ts","webpack://ambitencore-browser/./src/types/ambiten.client.type.ts","webpack://ambitencore-browser/external commonjs \"tslib\"","webpack://ambitencore-browser/./src/templates/generateMainEntry.ts","webpack://ambitencore-browser/./src/utils/configureAmbitenContext.ts","webpack://ambitencore-browser/./src/ambiten-cache/ambitenCache.ts","webpack://ambitencore-browser/external commonjs \"ajv\"","webpack://ambitencore-browser/external commonjs \"@graphql-tools/schema\"","webpack://ambitencore-browser/./src/gc/gcCron.node.ts","webpack://ambitencore-browser/./src/lib-core/index.ts","webpack://ambitencore-browser/./src/utils/builders/schema.ts","webpack://ambitencore-browser/./src/index.ts","webpack://ambitencore-browser/./src/tanancy/TenantContext.ts","webpack://ambitencore-browser/./src/redis-manager/redisClient.ts","webpack://ambitencore-browser/./src/templates/generateGCRunnerFile.ts","webpack://ambitencore-browser/./src/utils/eventOptions.ts","webpack://ambitencore-browser/./src/lib-core/ambitenSchema.ts","webpack://ambitencore-browser/./src/templates/scaffold/structureGenerator.ts","webpack://ambitencore-browser/./src/middleware/rbac/rbacTypes.ts","webpack://ambitencore-browser/./src/templates/generateGCManagerFile.ts","webpack://ambitencore-browser/./src/context/helpers/transactionSession.ts","webpack://ambitencore-browser/./src/types/logger.types.ts","webpack://ambitencore-browser/./src/tanancy/init/initMultiTenancy.ts","webpack://ambitencore-browser/./src/graphql/ambitenGraphQL.ts","webpack://ambitencore-browser/./src/utils/error/errorTypes.ts","webpack://ambitencore-browser/./src/utils/AuthUtils.ts","webpack://ambitencore-browser/./src/plugins/softDelete/types.ts","webpack://ambitencore-browser/./src/utils/castId.ts","webpack://ambitencore-browser/./src/lib-core/bootstrap/index.ts","webpack://ambitencore-browser/./src/middleware/index.ts","webpack://ambitencore-browser/./src/utils/ensureModelNameSafe.ts","webpack://ambitencore-browser/./src/utils/modelLoader.ts","webpack://ambitencore-browser/./src/graphql/index.ts","webpack://ambitencore-browser/./src/gc/index.ts","webpack://ambitencore-browser/./src/middleware/authorization/auth.ts","webpack://ambitencore-browser/external umd \"false\"","webpack://ambitencore-browser/./src/utils/ModelRegistry.ts","webpack://ambitencore-browser/./src/context/index.ts","webpack://ambitencore-browser/./src/gc/ambitenGC.ts","webpack://ambitencore-browser/./src/utils/invalidateTenantCache.ts","webpack://ambitencore-browser/./src/types/event.type.ts","webpack://ambitencore-browser/./src/gc/gcCron.browser.ts","webpack://ambitencore-browser/./src/instrumentation/measureQueryWithErrors.ts","webpack://ambitencore-browser/external commonjs \"@ambiten/logger\"","webpack://ambitencore-browser/./src/debug/index.ts","webpack://ambitencore-browser/./src/lib-core/ambitenModelFactory.ts","webpack://ambitencore-browser/./src/types/ambitenConfig.ts","webpack://ambitencore-browser/./src/browser.ts","webpack://ambitencore-browser/./src/types/user.type.ts","webpack://ambitencore-browser/./src/utils/builders/index.ts","webpack://ambitencore-browser/./src/types/ambiten.model.type.ts","webpack://ambitencore-browser/./src/utils/error/index.ts","webpack://ambitencore-browser/webpack/bootstrap","webpack://ambitencore-browser/webpack/runtime/hasOwnProperty shorthand","webpack://ambitencore-browser/webpack/startup"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"fs\"), require(\"path\"), require(\"false\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"ambitencore-browser\", [\"fs\", \"path\", \"false\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"ambitencore-browser\"] = factory(require(\"fs\"), require(\"path\"), require(\"false\"));\n\telse\n\t\troot[\"ambitencore-browser\"] = factory(root[\"fs\"], root[\"path\"], root[\"false\"]);\n})(self, (__WEBPACK_EXTERNAL_MODULE__2947__, __WEBPACK_EXTERNAL_MODULE__3911__, __WEBPACK_EXTERNAL_MODULE__8535__) => {\nreturn ","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.resolveAmbitenOption = resolveAmbitenOption;\nfunction resolveAmbitenOption(values) {\n for (const value of values) {\n if (value !== undefined)\n return value;\n }\n return undefined;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.detectPackageManager = detectPackageManager;\nexports.getInstallCommand = getInstallCommand;\nexports.installPackages = installPackages;\nconst tslib_1 = require(\"tslib\");\nconst fs_1 = tslib_1.__importDefault(require(\"fs\"));\nconst path_1 = tslib_1.__importDefault(require(\"path\"));\nconst child_process_1 = require(\"child_process\");\nfunction detectPackageManager(cwd = process.cwd()) {\n if (fs_1.default.existsSync(path_1.default.join(cwd, 'pnpm-lock.yaml')))\n return 'pnpm';\n if (fs_1.default.existsSync(path_1.default.join(cwd, 'yarn.lock')))\n return 'yarn';\n if (fs_1.default.existsSync(path_1.default.join(cwd, 'package-lock.json')))\n return 'npm';\n const userAgent = process.env.npm_config_user_agent ?? '';\n if (userAgent.includes('pnpm'))\n return 'pnpm';\n if (userAgent.includes('yarn'))\n return 'yarn';\n if (userAgent.includes('npm'))\n return 'npm';\n return 'npm';\n}\nfunction getInstallCommand(manager, packages) {\n switch (manager) {\n case 'pnpm':\n return ['pnpm', ['add', ...packages].join(' ')];\n case 'yarn':\n return ['yarn', ['add', ...packages].join(' ')];\n case 'npm':\n default:\n return ['npm', ['install', ...packages].join(' ')];\n }\n}\nasync function installPackages(packages = [], cwd = process.cwd()) {\n const manager = detectPackageManager(cwd);\n const args = packages.length === 0\n ? ['install']\n : manager === 'npm'\n ? ['install', ...packages]\n : ['add', ...packages];\n await new Promise((resolve, reject) => {\n const child = (0, child_process_1.spawn)(manager, args, {\n cwd,\n stdio: 'inherit',\n shell: process.platform === 'win32',\n });\n child.on('error', reject);\n child.on('close', (code) => {\n if (code === 0) {\n resolve();\n return;\n }\n reject(new Error(`${manager} ${args.join(' ')} failed with exit code ${code}`));\n });\n });\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.objectIdSymbol = exports.schemaTypeSymbol = exports.AmbitenSymbol = void 0;\nexports.AmbitenSymbol = Symbol('Ambiten');\nexports.schemaTypeSymbol = Symbol('AmbitenSchemaType');\nexports.objectIdSymbol = Symbol.for('AmbitenObjectId');\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","module.exports = require(\"jsonwebtoken\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./MultiTenantManager\"), exports);\ntslib_1.__exportStar(require(\"./TenantContext\"), exports);\ntslib_1.__exportStar(require(\"./TenantModelResolver\"), exports);\ntslib_1.__exportStar(require(\"./init/initMultiTenancy\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./builders/createModel\"), exports);\ntslib_1.__exportStar(require(\"./builders/schema\"), exports);\ntslib_1.__exportStar(require(\"./ensureModelNameSafe\"), exports);\ntslib_1.__exportStar(require(\"./ModelRegistry\"), exports);\ntslib_1.__exportStar(require(\"./castId\"), exports);\ntslib_1.__exportStar(require(\"./symbols\"), exports);\ntslib_1.__exportStar(require(\"./error/ambitenError-handler\"), exports);\ntslib_1.__exportStar(require(\"./error\"), exports);\ntslib_1.__exportStar(require(\"./AuthUtils\"), exports);\ntslib_1.__exportStar(require(\"./events\"), exports);\ntslib_1.__exportStar(require(\"./cacheWithRedis\"), exports);\ntslib_1.__exportStar(require(\"./logger\"), exports);\ntslib_1.__exportStar(require(\"./eventOptions\"), exports);\ntslib_1.__exportStar(require(\"./time\"), exports);\ntslib_1.__exportStar(require(\"./modelLoader\"), exports);\ntslib_1.__exportStar(require(\"./scaffoldLoger\"), exports);\ntslib_1.__exportStar(require(\"./ensureRedis\"), exports);\ntslib_1.__exportStar(require(\"./resolveAmbitenOption\"), exports);\ntslib_1.__exportStar(require(\"./resolveRuntimeConfig\"), exports);\ntslib_1.__exportStar(require(\"./configureAmbitenContext\"), exports);\ntslib_1.__exportStar(require(\"./color-palatte\"), exports);\ntslib_1.__exportStar(require(\"./detect-package-manager\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","function webpackEmptyAsyncContext(req) {\n\t// Here Promise.resolve().then() is used instead of new Promise() to prevent\n\t// uncaught exception popping up in devtools\n\treturn Promise.resolve().then(() => {\n\t\tvar e = new Error(\"Cannot find module '\" + req + \"'\");\n\t\te.code = 'MODULE_NOT_FOUND';\n\t\tthrow e;\n\t});\n}\nwebpackEmptyAsyncContext.keys = () => ([]);\nwebpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;\nwebpackEmptyAsyncContext.id = 1077;\nmodule.exports = webpackEmptyAsyncContext;","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","module.exports = require(\"buffer\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createBootstrapLogger = createBootstrapLogger;\nconst logger_1 = require(\"@ambiten/logger\");\nfunction createBootstrapLogger(config = {\n transportConfigs: []\n}) {\n if (!config?.enabled) {\n return (0, logger_1.setupLogger)({\n level: 'warn',\n colorize: false,\n });\n }\n const loggerConfig = {\n level: config.level ?? 'info',\n colorize: config.colorize ?? true,\n json: config.json ?? false,\n transports: config.transports ?? [],\n formatOptions: config.formatOptions,\n hooks: config.hooks,\n contextProvider: config.contextProvider,\n enableMetrics: config.enableMetrics ?? { enabled: false },\n circuitBreaker: config.circuitBreaker,\n compress: config.compress ?? { enabled: false },\n };\n return (0, logger_1.setupLogger)(loggerConfig);\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DEFAULT_CONFIG_CONTENT = DEFAULT_CONFIG_CONTENT;\nfunction DEFAULT_CONFIG_CONTENT(options) {\n const config = {\n configVersion: '1.0.0',\n projectName: options.projectName ?? 'my-ambiten-app',\n connection: {\n uri: options.connection?.uri ?? 'mongodb://localhost:27017/my-ambiten-app',\n options: {\n dbName: options.connection?.options?.dbName ??\n options.projectName ??\n 'my-ambiten-app',\n },\n },\n ...(options.multiTenant?.enabled\n ? {\n multiTenant: {\n enabled: true,\n headerKey: options.multiTenant.headerKey ?? 'x-tenant-id',\n tenants: options.multiTenant.tenants ?? {},\n initOptions: {\n lazy: options.multiTenant.initOptions?.lazy ?? false,\n retryAttempts: options.multiTenant.initOptions?.retryAttempts ?? 3,\n },\n },\n }\n : {}),\n ...(options.logger?.enabled\n ? {\n logger: {\n enabled: true,\n level: options.logger.level ?? 'info',\n colorize: options.logger.colorize ?? true,\n json: options.logger.json ?? false,\n transportConfigs: [\n {\n \"type\": \"console\",\n \"options\": {}\n },\n {\n \"type\": \"rotating-file\",\n \"options\": {\n \"filename\": \"./logs/ambiten.log\",\n \"frequency\": \"hourly\",\n \"maxSize\": 200,\n \"compress\": false,\n \"flushInterval\": 1000\n }\n }\n ],\n enableMetrics: typeof options.logger.enableMetrics === 'boolean'\n ? {\n enabled: options.logger.enableMetrics,\n logInterval: 60000,\n }\n : options.logger.enableMetrics ?? {\n enabled: false,\n logInterval: 60000,\n },\n compress: typeof options.logger.compress === 'boolean'\n ? {\n enabled: options.logger.compress,\n }\n : options.logger.compress ?? {\n enabled: false,\n },\n }\n }\n : {}),\n ...(options.graphql?.enabled\n ? {\n graphql: {\n enabled: true,\n subscriptions: options.graphql.subscriptions ?? false,\n playground: options.graphql.playground ?? true,\n schemaOutputPath: options.graphql.schemaOutputPath ?? './src/graphql/schema.gql',\n },\n }\n : {}),\n features: {\n models: options.features?.models ?? './src/models',\n schemas: options.features?.schemas ?? './src/schemas',\n ...(options.graphql?.enabled\n ? {\n typeDefs: options.features?.typeDefs ?? './src/graphql/typeDefs',\n resolvers: options.features?.resolvers ?? './src/graphql/resolvers',\n }\n : {}),\n useRedisCache: options.features?.useRedisCache ?? false,\n redisUri: options.features?.redisUri ?? '',\n },\n advanced: {\n autoInstall: options.advanced?.autoInstall ?? false,\n circuitBreaker: {\n enabled: options.advanced?.circuitBreaker?.enabled ?? true,\n retryAttempts: options.advanced?.circuitBreaker?.retryAttempts ?? 5,\n },\n garbageCollector: {\n enabled: options.advanced?.garbageCollector?.enabled ?? false,\n retentionPeriod: options.advanced?.garbageCollector?.retentionPeriod ?? 30,\n logResults: options.advanced?.garbageCollector?.logResults ?? true,\n },\n gcCron: options.advanced?.gcCron ?? '* * * * *',\n },\n };\n return JSON.stringify(config, null, 2);\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Model = void 0;\nconst lib_core_1 = require(\"../../lib-core\");\n/**\n * Creates a new model for a MongoDB collection.\n * In Multi-Tenancy mode, the model will be created for the specified tenant.\n * If no tenant ID is provided, the model will be created for the default tenant.\n * Note: Once a the applyMultiTenancy() middleware is applied to a connection to register tenant/s, the tenantId will be automatically set for all models created after that.\n * This allows you to create models for different tenants without having to specify the tenantId each time. Then a tenantId or db instance or client instance is required to create a model.\n * @template T - The type of the document in the collection.\n * @param {CreateModelParams<T>} params - The parameters for creating the model.\n * @returns {AmbitenModel<T>} The created model.\n *\n * @example\n * const userSchema = createSchema({\n * name: { type: String, required: true },\n * age: { type: Number, required: true },\n * email: { type: String, required: true },\n * });\n *\n * const userModel = Model({\n * name: 'users',\n * schema: userSchema,\n * provider: (client/db - whichever you naming is)/new MyCustomDbProvider(), // Your custom database provider instance\n * ctx: {\n * tenantId: 'tenant-a', // Optional: specify tenant ID if using multi-tenancy\n * dbName: 'myDatabase', // Optional: specify database name if needed\n * } read docs for more details on what context options you can provide\n * });\n */\nconst Model = (options) => {\n return new lib_core_1.AmbitenModel({\n ...options,\n provider: options.provider ?? lib_core_1.AmbitenClient.init()\n });\n};\nexports.Model = Model;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./loadAmbitenConfig\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./generateDefaultConfigContent\"), exports);\ntslib_1.__exportStar(require(\"./generateMainEntry\"), exports);\ntslib_1.__exportStar(require(\"./scaffold/structureGenerator\"), exports);\ntslib_1.__exportStar(require(\"./generateGCManagerFile\"), exports);\ntslib_1.__exportStar(require(\"./generateGCRunnerFile\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenClient = void 0;\nexports.createAmbitenClientModule = createAmbitenClientModule;\n/* eslint-disable @typescript-eslint/no-require-imports */\nconst mongodb_1 = require(\"mongodb\");\nrequire(\"dotenv/config\");\nconst utils_1 = require(\"../utils\");\nconst tanancy_1 = require(\"../tanancy\");\nconst context_1 = require(\"../context\");\nconst AmbitenSymbol = Symbol.for('Ambiten:default');\n/**\n * AmbitenClient is a MongoDB client wrapper that provides a simplified interface\n * for connecting to and interacting with MongoDB databases.\n */\nclass AmbitenClient {\n _opts;\n _uri;\n _client;\n _db;\n collectionRef;\n _connected = false;\n _defaultDbName;\n _overrideDbName;\n static instances = new Map();\n static defaultUri = 'mongodb://127.0.0.1:27017';\n constructor(_opts) {\n this._opts = _opts;\n this._uri = _opts.uri || process.env.MONGO_URI || AmbitenClient.defaultUri;\n this._defaultDbName =\n _opts?.options?.dbName ||\n process.env.DB_NAME ||\n 'Ambiten_default_db';\n this._client = new mongodb_1.MongoClient(this._uri, {\n directConnection: true,\n minPoolSize: 5,\n maxPoolSize: 50,\n serverSelectionTimeoutMS: 5000\n });\n this._db = this._client.db(this._opts.options?.dbName);\n this.ensureMongoDependency();\n }\n static init(opts) {\n const key = String(AmbitenSymbol);\n const existing = this.instances.get(key);\n if (existing) {\n return existing;\n }\n const client = createAmbitenClientModule({\n uri: opts?.uri ?? this.defaultUri ?? process.env.MONGO_URI,\n options: { dbName: opts?.options?.dbName },\n tenantResolver: opts?.tenantResolver\n });\n this.instances.set(key, client);\n return client;\n }\n ensureMongoDependency() {\n try {\n const { MongoClient } = require('mongodb');\n void MongoClient;\n }\n catch {\n console.error('\\n❌ Missing peer dependency: \"mongodb\".\\n' +\n 'Please install it in your project before continuing:\\n\\n' +\n ' npm i mongodb\\n');\n process.exit(1);\n }\n }\n /**\n * Resolution order:\n * 1. explicit ctx.db\n * 2. tenant-aware db resolution\n * 3. explicit ctx.dbName on base client\n * 4. mutable override dbName\n * 5. default dbName\n */\n async db(ctx) {\n if (ctx?.db) {\n return ctx.db;\n }\n if (ctx?.tenantId) {\n const resolver = this._opts.tenantResolver;\n if (!resolver) {\n throw new Error('Multi-tenancy not enabled. Provide tenantResolver to AmbitenClient or avoid passing tenantId.');\n }\n const tenantClient = await resolver.getClient(ctx.tenantId);\n if (!tenantClient) {\n throw new Error(`Tenant \"${ctx.tenantId}\" is not registered.`);\n }\n const resolvedTenantDbName = ctx.dbName ??\n tanancy_1.MultiTenantManager.getTenantDbName(ctx.tenantId) ??\n this._defaultDbName;\n return tenantClient.db(resolvedTenantDbName);\n }\n if (!this._client || !this._connected) {\n const message = 'AmbitenClient not connected. call connect() first.';\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.CONNECTION_ERROR, message, {\n details: {\n operation: 'db'\n }\n });\n }\n if (ctx?.dbName) {\n return this._client.db(ctx.dbName);\n }\n if (this._overrideDbName) {\n return this._client.db(this._overrideDbName);\n }\n return this._client.db(this._defaultDbName);\n }\n static async db(ctx) {\n return this.init().db(ctx);\n }\n validateUri(uri) {\n if (!uri || typeof uri !== 'string') {\n const message = 'Missing MongoDB URI. Set MONGODB_URI (or pass uri explicitly).';\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.VALIDATION_ERROR, message, {\n details: {\n operation: 'validateUri',\n providedUri: uri,\n }\n });\n }\n if (!/^mongodb(\\+srv)?:\\/\\//.test(uri)) {\n const message = `Invalid MongoDB URI \"${uri}\". It must start with \"mongodb://\" or \"mongodb+srv://\".`;\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.VALIDATION_ERROR, message, {\n details: {\n operation: 'validateUri',\n providedUri: uri,\n }\n });\n }\n }\n async connect() {\n this.validateUri(this._opts.uri);\n if (!this._client) {\n this._client = new mongodb_1.MongoClient(this._opts.uri);\n }\n if (!this._connected) {\n await this._client.connect();\n this._connected = true;\n }\n return this;\n }\n async client(ctx) {\n if (ctx?.tenantId) {\n const resolver = this._opts.tenantResolver;\n if (!resolver) {\n throw new Error('Multi-tenancy not enabled. Provide tenantResolver to AmbitenClient or avoid passing tenantId.');\n }\n const tenantClient = await resolver.getClient(ctx.tenantId);\n if (!tenantClient) {\n throw new Error(`Tenant \"${ctx.tenantId}\" is not registered.`);\n }\n return tenantClient;\n }\n if (!this._client) {\n throw new Error('Client not initialized. Call `connect()` first.');\n }\n return this._client;\n }\n async useCollection(collectionName) {\n if (!collectionName || typeof collectionName !== 'string' || !collectionName.trim()) {\n throw new Error('Collection name is required.');\n }\n if (!this._client) {\n throw new Error('Client not initialized. Call `connect()` first.');\n }\n const scope = this.resolveClientScope({ collectionName });\n const db = this._client.db(scope.dbName);\n if (!db || typeof db.collection !== 'function') {\n throw new Error('Database name is required in client options.');\n }\n const collection = db.collection(scope.collectionName);\n this.collectionRef = collection;\n return collection;\n }\n async collection(collectionName, ctx) {\n const db = await this.db(ctx);\n return db.collection(collectionName);\n }\n async getCollection(collectionName, ctx) {\n if (!this._client || typeof this._client.db !== 'function') {\n return {\n toString: () => collectionName\n };\n }\n return this.collection(collectionName, ctx);\n }\n async getClusterInfo() {\n if (!this._client) {\n throw new Error('Client not initialized. Call `connect()` first.');\n }\n const dbName = this._opts?.options?.dbName;\n if (!dbName) {\n throw new Error('Database name is required in client options.');\n }\n const helloResult = await this._client\n .db(dbName)\n .admin()\n .command({ hello: 1 });\n if (helloResult?.msg === 'isdbgrid') {\n console.log('MongoDB is running in a sharded cluster.');\n return { type: 'sharded' };\n }\n if (helloResult?.setName || helloResult?.hosts) {\n console.log('MongoDB is running as a replica set.');\n return {\n type: 'replicaSet',\n setName: helloResult.setName,\n hosts: helloResult.hosts\n };\n }\n console.log('MongoDB is running as a standalone instance.');\n return { type: 'standalone' };\n }\n /**\n * Resolves database + session + runtime binding\n */\n static async resolveRuntime() {\n const ctx = context_1.AmbitenContext.get();\n if (!ctx?.tenantId) {\n throw new Error(\"Tenant not resolved in context.\");\n }\n const tenant = tanancy_1.MultiTenantManager.getTenant(ctx.tenantId);\n if (!tenant) {\n throw new Error(`Tenant not found: ${ctx.tenantId}`);\n }\n const db = this.resolveDbFromTenant(tenant, ctx);\n return {\n db,\n session: ctx?.session,\n };\n }\n /**\n * Mutable legacy helper. Prefer withDatabase() or withScope() in request-safe flows.\n */\n async useDatabase(dbName) {\n if (!dbName) {\n throw new Error('Database name is required.');\n }\n const client = await this.client();\n this._overrideDbName = dbName;\n return {\n db: client.db(dbName),\n client\n };\n }\n withDatabase(dbName) {\n return {\n db: async (ctx) => {\n const merged = { ...ctx, dbName: ctx?.dbName ?? dbName };\n return this.db(merged);\n },\n connect: async () => {\n await this.connect();\n return this;\n },\n client: async (ctx) => {\n const merged = { ...ctx, dbName: ctx?.dbName ?? dbName };\n return this.client(merged);\n },\n collection: async (collectionName, ctx) => {\n const merged = { ...ctx, dbName: ctx?.dbName ?? dbName };\n return this.collection(collectionName, merged);\n },\n startSession: async (ctx) => {\n const merged = {\n ...ctx, dbName: ctx?.dbName ?? dbName, session: ctx?.session\n };\n return this.startSession(merged);\n },\n close: async () => {\n await this.close();\n }\n };\n }\n /**\n * Resolves the active database name.\n *\n * @param overrideDbName - Optional database override.\n * @returns The resolved database name.\n * @throws {Error} When no database name can be resolved.\n */\n resolveDbName(overrideDbName) {\n return this.resolveClientScope({ dbName: overrideDbName }).dbName;\n }\n /**\n * Resolves the active client execution scope by combining explicit method\n * arguments, active Ambiten runtime context, and client-level defaults.\n *\n * Resolution priority:\n * 1. Explicit method arguments\n * 2. Active Ambiten runtime context\n * 3. Client configuration\n * 4. Client defaults\n *\n * This method does not mutate runtime context or client configuration.\n *\n * @param input - Optional scope overrides for database, collection, and session.\n * @returns The resolved execution scope for client-level operations.\n * @throws {Error} When no database name can be resolved.\n */\n resolveClientScope(input = {}) {\n const ctx = context_1.AmbitenContext.get();\n const dbName = input.dbName ??\n ctx.dbName ??\n this._opts?.options?.dbName ??\n this._defaultDbName;\n if (!dbName) {\n throw new Error('Database name is required in client options.');\n }\n const collectionName = input.collectionName ??\n ctx.collectionName;\n return {\n tenantId: ctx.tenantId,\n requestId: ctx.requestId,\n dbName,\n collectionName: collectionName?.trim() || undefined,\n session: input.session ?? ctx.session\n };\n }\n static resolveDbFromTenant(tenant, ctx) {\n if (!tenant?.client) {\n throw new Error(`Tenant \"${ctx?.tenantId}\" has no MongoDB client.`);\n }\n const dbName = ctx?.dbName ?? tenant.dbName;\n if (!dbName) {\n throw new Error(`Database name not resolved for tenant \"${ctx?.tenantId}\".`);\n }\n return tenant.client.db(dbName);\n }\n ;\n async withContext(context, callback) {\n return context_1.AmbitenContext.run({\n tenantId: context.tenantId,\n requestId: context.requestId,\n dbName: context.dbName,\n collectionName: context.collectionName,\n session: context.session\n }, callback);\n }\n logWithContext(level, message, meta = {}) {\n const ctx = context_1.AmbitenContext.get();\n const enrichedMeta = {\n requestId: ctx.requestId,\n tenantId: ctx.tenantId,\n ...ctx.loggerMeta,\n ...meta\n };\n this._opts.options?.config?.logger?.[level]?.(message, enrichedMeta);\n }\n withTenant(tenantId) {\n return {\n db: async (ctx) => {\n const merged = { ...ctx, tenantId: ctx?.tenantId ?? tenantId };\n return this.db(merged);\n },\n connect: async () => {\n await this.connect();\n return this;\n },\n client: async (ctx) => {\n const merged = { ...ctx, tenantId: ctx?.tenantId ?? tenantId };\n return this.client(merged);\n },\n collection: async (collectionName, ctx) => {\n const merged = { ...ctx, tenantId: ctx?.tenantId ?? tenantId };\n return this.collection(collectionName, merged);\n },\n startSession: async (ctx) => {\n const merged = { ...ctx, tenantId: ctx.tenantId ?? tenantId };\n return this.startSession(merged);\n },\n close: async () => {\n await this.close();\n }\n };\n }\n withScope(scope) {\n return {\n db: async (ctx) => {\n const merged = {\n ...ctx,\n tenantId: ctx?.tenantId ?? scope.tenantId,\n dbName: ctx?.dbName ?? scope.dbName\n };\n return this.db(merged);\n },\n connect: async () => {\n await this.connect();\n return this;\n },\n client: async (ctx) => {\n const merged = {\n ...ctx,\n tenantId: ctx?.tenantId ?? scope.tenantId,\n dbName: ctx?.dbName ?? scope.dbName\n };\n return this.client(merged);\n },\n collection: async (collectionName, ctx) => {\n const merged = {\n ...ctx,\n tenantId: ctx?.tenantId ?? scope.tenantId,\n dbName: ctx?.dbName ?? scope.dbName\n };\n return this.collection(collectionName, merged);\n },\n startSession: async (ctx) => {\n const merged = {\n ...ctx,\n tenantId: ctx?.tenantId ?? scope.tenantId,\n dbName: ctx?.dbName ?? scope.dbName\n };\n return this.startSession(merged);\n },\n close: async () => {\n await this.close();\n }\n };\n }\n resetDatabase() {\n this._overrideDbName = undefined;\n }\n async startSession(ctx) {\n const client = await this.client(ctx);\n return client.startSession();\n }\n async dropCollection(collectionName, ctx) {\n if (!this._client && !ctx?.db) {\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.CONNECTION_ERROR, 'Client not initialized. Call `connect()` first.', {\n details: {\n operation: 'dropCollection',\n providedCollectionName: collectionName\n }\n });\n }\n const resolvedCollectionName = collectionName?.trim() ||\n this.collectionRef?.collectionName;\n if (!resolvedCollectionName) {\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.VALIDATION_ERROR, 'Collection name is required.', {\n details: {\n operation: 'dropCollection',\n providedCollectionName: collectionName\n }\n });\n }\n const db = ctx?.db ?? this._client.db(this.resolveDbName(ctx?.dbName));\n await db.collection(resolvedCollectionName).drop();\n }\n async dropDatabase(ctx) {\n if (!this._client && !ctx?.db) {\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.CONNECTION_ERROR, 'Client not initialized. Call `connect()` first.', {\n details: {\n operation: 'dropDatabase'\n }\n });\n }\n const db = ctx?.db ??\n this._client.db(this.resolveDbName(ctx?.dbName));\n const result = await db.dropDatabase();\n return result === undefined ? true : result;\n }\n async close() {\n if (this._client) {\n await this._client.close?.();\n }\n this._client = null;\n this._db = null;\n this._connected = false;\n console.log('[info]: Disconnected from MongoDB');\n }\n async disconnect() {\n await this.close();\n }\n isConnected() {\n return this._connected;\n }\n static handleTopologyEvent(event) {\n if (event instanceof mongodb_1.TopologyOpeningEvent) {\n console.log(`Topology opened: ${event.topologyId}`);\n }\n else if (event instanceof mongodb_1.TopologyClosedEvent) {\n console.log(`Topology closed: ${event.topologyId}`);\n }\n else {\n console.warn(`[warning]: Unknown topology event: ${event}`);\n }\n }\n ;\n static async handleLogBatch(batch, transporter) {\n if (!Array.isArray(batch) || batch.length === 0) {\n console.warn('[warning]: Received an empty log batch or invalid format.');\n return;\n }\n const ctx = context_1.AmbitenContext.get();\n this.handleTopologyEvent(batch[0]);\n const remaining = batch.slice(1);\n if (remaining.length === 0)\n return;\n if (!transporter) {\n console.warn(`[warning]: No transporter provided; ${remaining.length} topology event(s) will not be processed.`);\n return;\n }\n const writes = remaining.map((event) => {\n const eventName = event.constructor?.name ?? 'TopologyEvent';\n const eventType = eventName.toLowerCase().includes('opening')\n ? 'opening'\n : eventName.toLowerCase().includes('closed')\n ? 'closed'\n : 'unknown';\n const message = `Topology event: ${eventName}`;\n return transporter.write({\n level: 'info',\n timestamp: new Date().toISOString(),\n message,\n source: 'AmbitenTopology',\n context: {\n requestId: ctx?.requestId,\n tenantId: ctx?.tenantId,\n collectionName: ctx?.collectionName,\n dbName: ctx?.dbName,\n },\n meta: {\n eventType,\n topologyId: event.topologyId,\n },\n }, message);\n });\n await Promise.all(writes);\n }\n}\nexports.AmbitenClient = AmbitenClient;\nfunction createAmbitenClientModule(opts) {\n return new AmbitenClient(opts);\n}\n","module.exports = require(\"graphql-tag\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./softDelete/applySoftDelete\"), exports);\ntslib_1.__exportStar(require(\"./softDelete/types\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.DB_CHANGE_EVENT = exports.DOCUMENT_DELETED_EVENT = exports.DOCUMENT_UPDATED_EVENT = exports.DOCUMENT_INSERTED_EVENT = void 0;\nexports.DOCUMENT_INSERTED_EVENT = 'DOCUMENT_INSERTED';\nexports.DOCUMENT_UPDATED_EVENT = 'DOCUMENT_UPDATED';\nexports.DOCUMENT_DELETED_EVENT = 'DOCUMENT_DELETED';\nexports.DB_CHANGE_EVENT = 'DB_CHANGE_EVENT';\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.debugLog = debugLog;\nconst context_1 = require(\"../context\");\nfunction debugLog(message, meta = {}) {\n if (!context_1.AmbitenContext.isDebug())\n return;\n const logger = context_1.AmbitenContext.getLogger();\n const loggerMeta = context_1.AmbitenContext.getLoggerMeta() ?? {};\n const payload = {\n tenantId: context_1.AmbitenContext.getTenantId(),\n requestId: context_1.AmbitenContext.getRequestId(),\n dbName: context_1.AmbitenContext.getDbName(),\n collectionName: context_1.AmbitenContext.getCollectionName(),\n ...loggerMeta,\n ...meta\n };\n if (logger?.debug) {\n logger.debug(message, payload);\n return;\n }\n console.debug(`[AMBITEN_DEBUG] ${message}`, payload);\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ensureRedis = ensureRedis;\nconst redis_manager_1 = require(\"../redis-manager\");\nasync function ensureRedis() {\n let publisher = this.publisher;\n let subscriber = this.subscriber;\n try {\n const client = await redis_manager_1.redis.get();\n if (!client) {\n console.log('⚠️ Redis client not available from redis manager; skipping Redis initialization');\n return this;\n }\n if (!client.isOpen && typeof client.connect === 'function') {\n await client.connect();\n }\n if (!publisher) {\n publisher = typeof client.duplicate === 'function' ? client.duplicate() : client;\n if (publisher && typeof publisher.connect === 'function') {\n await publisher.connect();\n }\n this.publisher = publisher;\n }\n if (!subscriber) {\n subscriber = typeof client.duplicate === 'function' ? client.duplicate() : client;\n if (subscriber && typeof subscriber.connect === 'function') {\n await subscriber.connect();\n }\n this.subscriber = subscriber;\n }\n console.log('[info] Ensuring Redis connection...');\n console.log('[info] Redis connection established');\n return this;\n }\n catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n console.log('[info] ⚠️ Redis connection skipped or failed:', message);\n return this;\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getTenantModel = void 0;\nconst builders_1 = require(\"../utils/builders\");\nconst MultiTenantManager_1 = require(\"./MultiTenantManager\");\nconst context_1 = require(\"../context\");\nconst tenantModelsCache = new Map();\nfunction createTenantProvider(tenantId, dbName) {\n return {\n async db(ctx) {\n const client = await MultiTenantManager_1.MultiTenantManager.getClient(tenantId);\n if (!client) {\n throw new Error(`Tenant \"${tenantId}\" not registered.`);\n }\n const resolvedDbName = ctx?.dbName ?? dbName;\n return resolvedDbName ? client.db(resolvedDbName) : client.db();\n },\n };\n}\nconst getTenantModel = async (params) => {\n const collectionName = params?.collectionName?.trim();\n const tenantId = params?.tenantId ?? context_1.AmbitenContext.getTenantId();\n if (!collectionName) {\n throw new Error(\"collectionName is required.\");\n }\n if (!tenantId) {\n throw new Error(\"tenantId is required to run tenant context\");\n }\n if (!tenantModelsCache.has(tenantId)) {\n tenantModelsCache.set(tenantId, new Map());\n }\n const tenantCache = tenantModelsCache.get(tenantId);\n const cacheKey = params.dbName\n ? `${collectionName}::${params.dbName}`\n : collectionName;\n if (tenantCache.has(cacheKey)) {\n return tenantCache.get(cacheKey);\n }\n const provider = createTenantProvider(tenantId, params.dbName);\n const model = (0, builders_1.Model)({\n collectionName,\n schema: params.schema,\n provider,\n });\n tenantCache.set(cacheKey, model);\n return model;\n};\nexports.getTenantModel = getTenantModel;\n// import { AmbitenSchema } from '../lib-core';\n// import { MultiTenantManager } from './MultiTenantManager';\n// import { TenantContext } from './TenantContext';\n// import { Model } from '../utils/builders/createModel';\n// import { ensureModelNameSafe } from '../utils/ensureModelNameSafe'; // <- wherever you put it\n// import { Document } from '../types';\n// import { Db } from 'mongodb';\n// type DbProvider = { db(ctx?: { dbName?: string }): Promise<Db> };\n// /**\n// * Parameters required to resolve a tenant-specific model.\n// * @template T - The type of the document in the model.\n// */\n// export type GetTanantModelParams<T extends Document> = {\n// collectionName: string;\n// tenantId: string;\n// schema?: AmbitenSchema<T>;\n// };\n// const tenantModelsCache: Map<string, Map<string, ReturnType<typeof Model>>> = new Map();\n// /**\n// * Resolves a tenant-specific model by creating or retrieving it from the cache.\n// * Ensures that each tenant has its own isolated model instance.\n// *\n// * @template T - The type of the document in the model.\n// * @param {GetTanantModelParams<T>} param - The parameters required to resolve the model.\n// * @param {string} param.modelName - The name of the model to resolve.\n// * @param {AmbitenSchema<T>} [param.schema] - The schema definition for the model (optional).\n// * @param {string} param.tenantId - The ID of the tenant for which the model is being resolved.\n// * @returns {Promise<any>} A promise that resolves to the tenant-specific model instance.\n// * @throws {Error} If no tenant context is found or the tenant is not registered.\n// * @example\n// * const userModel = await getTenantModel({\n// * modelName: 'User',\n// * schema: UserSchema,\n// * tenantId: 'tenant123'\n// * });\n// * // userModel is now a tenant-specific model for the 'User' collection in 'tenant123'\n// * @example\n// * const productModel = await getTenantModel({\n// * modelName: 'Product',\n// * schema: ProductSchema,\n// * tenantId: 'tenant456'\n// * });\n// */\n// export const getTenantModel = async <T extends Document>\n// (param: GetTanantModelParams<T>): Promise<any> => {\n// const safeCollectionName = ensureModelNameSafe(param.collectionName);\n// const schema = param.schema;\n// // const client = await MultiTenantManager.getClient(param.tenantId);\n// const tenantId = param.tenantId ?? TenantContext.getTenantId();\n// if (!tenantId) throw new Error('No tenant context found');\n// if (!tenantModelsCache.has(tenantId)) {\n// tenantModelsCache.set(tenantId, new Map());\n// }\n// const clientCache = tenantModelsCache.get(tenantId)!;\n// if (clientCache.has(safeCollectionName)) {\n// return clientCache.get(safeCollectionName);\n// }\n// const provider = tenantDbProvider(tenantId);\n// const model = Model({\n// collectionName: safeCollectionName,\n// schema,\n// provider: provider\n// });\n// clientCache.set(safeCollectionName, model as unknown as ReturnType<typeof Model>);\n// return model;\n// };\n","module.exports = require(\"mongodb\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.resolveRuntimeConfig = resolveRuntimeConfig;\nconst context_1 = require(\"../context\");\nconst resolveAmbitenOption_1 = require(\"./resolveAmbitenOption\");\nfunction resolveRuntimeConfig(input) {\n const ctx = context_1.AmbitenContext.get();\n return {\n tenantId: (0, resolveAmbitenOption_1.resolveAmbitenOption)([\n input.methodTenantId,\n ctx?.tenantId,\n input.modelTenantId\n ]),\n dbName: (0, resolveAmbitenOption_1.resolveAmbitenOption)([\n input.methodDbName,\n ctx?.dbName,\n input.modelDbName,\n input.clientDbName\n ]),\n collectionName: (0, resolveAmbitenOption_1.resolveAmbitenOption)([\n input.methodCollectionName,\n ctx?.collectionName,\n input.modelCollectionName\n ]),\n session: (0, resolveAmbitenOption_1.resolveAmbitenOption)([\n input.methodSession,\n ctx?.session,\n input.modelSession\n ]),\n requestId: ctx?.requestId,\n loggerMeta: ctx?.loggerMeta\n };\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.checkPermission = checkPermission;\nexports.getCachedData = getCachedData;\nexports.setCachedData = setCachedData;\nexports.invalidateTenantCache = invalidateTenantCache;\nexports.enforceRBAC = enforceRBAC;\nexports.getRBACAction = getRBACAction;\nexports.getOriginalResolver = getOriginalResolver;\nconst redis_manager_1 = require(\"../../redis-manager\");\nconst rbacTypes_1 = require(\"./rbacTypes\");\nfunction buildCacheKey(role, key) {\n if (Array.isArray(role)) {\n return `${role.join(',')}:${key}`;\n }\n if (role && typeof role === 'object') {\n if ('tenantId' in role)\n return `${role.tenantId}:${key}`;\n // If role is actually a role object or other shape, fallback to JSON-safe string\n try {\n const convertCredentials = JSON.parse(JSON.stringify(role));\n return `${convertCredentials}:${key}`;\n }\n catch (err) {\n return `${String(role)}:${key}`;\n }\n }\n return `${role}:${key}`;\n}\n;\n// const tenantCache: Map<string, any> = new Map();\n/**\n * Check if a user has a specific permission\n * @param role The role of the user\n * @param permission The permission to check\n * @returns A promise that resolves to true if the user has the permission, false otherwise\n * @example\n * const hasPermission = await checkPermission('admin', 'createUser');\n * if (hasPermission) {\n * // User has permission to create a user\n * } else {\n * // User does not have permission to create a user\n * }\n */\nasync function checkPermission(role, permission) {\n const cacheKey = buildCacheKey(role, 'permissions');\n let allowedActions = await getCachedData(role, 'permissions');\n if (!allowedActions) {\n console.info(`Cache miss for role \"${role}\". Fetching permissions...`);\n // Fetch permissions from the rolePermissions object\n allowedActions = rbacTypes_1.rolePermissions[role] || [];\n if (allowedActions.length > 0) {\n console.info(`Permissions found for role \"${role}\": ${allowedActions.join(', ')}`);\n }\n else {\n console.warn(`No permissions found for role \"${role}\"`);\n }\n }\n ;\n const cacheExists = await redis_manager_1.redis.exists(cacheKey);\n if (cacheExists) {\n console.info(`Cache hit for role \"${role}\"`);\n }\n // If allowedActions is not already cached, set it\n if (allowedActions) {\n allowedActions = Promise.resolve(rbacTypes_1.rolePermissions[role] || []);\n await setCachedData(role, 'permissions', await allowedActions, 500); // Cache for 500s\n }\n return Promise.resolve(rbacTypes_1.rolePermissions[role] || []).then(permissions => {\n if (permissions.includes(permission)) {\n console.info(`Permission granted for role \"${role}\" to perform action \"${permission}\"`);\n return true;\n }\n else {\n console.warn(`Permission denied for role \"${role}\" to perform action \"${permission}\"`);\n return false;\n }\n });\n}\n/**\n * Get cached data for a specific role and key\n * @param role The role or tenant object\n * @param key The key to retrieve from the cache\n * @return {Promise<any>} A promise that resolves to the cached data or null if not found\n * This function retrieves cached data from Redis based on the provided role and key.\n * It constructs a unique cache key using the role and key, checks if the data exists in the cache,\n * and returns the parsed data if found. If the data is not found, it logs a cache miss and returns null.\n * @throws {Error} If there is an issue with the Redis operation\n * @example\n * // Get cached permissions for role 'admin'\n * const cachedPermissions = await getCachedData('admin', 'permissions');\n * if (cachedPermissions) {\n * console.log('Cached permissions:', cachedPermissions);\n * } else {\n * console.log('No cached permissions found');\n * }\n */\nasync function getCachedData(role, key) {\n const cacheKey = buildCacheKey(role, key);\n const cachedData = await redis_manager_1.redis.get(cacheKey);\n if (cachedData) {\n console.info(`Cache hit for key \"${cacheKey}\"`);\n }\n else {\n console.warn(`Cache miss for key \"${cacheKey}\"`);\n }\n try {\n return cachedData ? JSON.parse(JSON.stringify(cachedData)) : null;\n }\n catch (err) {\n console.warn(`Failed to parse cached data for key ${cacheKey}:`, err);\n // If parsing fails, return raw value to avoid crashing\n return cachedData;\n }\n}\n;\nasync function setCachedData(role, key, data, ttl) {\n // Build a consistent cache key and store JSON-stringified data with TTL\n const cacheKey = buildCacheKey(role, key);\n try {\n await redis_manager_1.redis?.set(cacheKey, JSON.stringify(data), { EX: ttl });\n console.info(`Cache set for ${cacheKey}:`, data);\n }\n catch (err) {\n console.error(`Failed to set cache for ${cacheKey}:`, err);\n }\n // Only log permissions if role is a string or array with values\n let roleKey;\n if (typeof role === 'string') {\n roleKey = role;\n }\n else if (Array.isArray(role) && role.length > 0) {\n roleKey = role[0];\n }\n else if (role && typeof role === 'object' && 'tenantId' in role) {\n roleKey = role.tenantId;\n }\n if (roleKey) {\n const permissions = rbacTypes_1.rolePermissions[roleKey] || [];\n if (permissions.length > 0) {\n console.info(`Permissions cached for role \"${roleKey}\": ${permissions.join(', ')}`);\n }\n else {\n console.warn(`No permissions found for role \"${roleKey}\" to cache`);\n }\n }\n else {\n console.warn(`Role key is not a string, cannot cache permissions`);\n }\n return;\n}\n/**\n * Invalidate the cache for a specific tenant and role\n * @param tenantId The ID of the tenant\n * @param role The role to invalidate cache for\n * @return {Promise<void>}\n * This function removes the cached permissions for the specified tenant and role.\n * It is useful when permissions change and you want to ensure the cache reflects the latest state.\n * It logs the invalidation action and deletes the cache entry from Redis.\n * This is particularly important in multi-tenant applications where each tenant may have different permissions.\n * @throws {Error} If there is an issue with the Redis operation\n * @example\n * // Invalidate cache for tenant 'tenant123' with role 'admin'\n * await invalidateTenantCache('tenant123', 'admin');\n */\nasync function invalidateTenantCache(tenantId, role) {\n try {\n const cacheKey = `${tenantId}:permissions:${role}`;\n const cacheExists = await redis_manager_1.redis.exists(cacheKey);\n if (cacheExists) {\n await redis_manager_1.redis.del(cacheKey);\n console.info(`Cache invalidated for tenant ${tenantId} and role ${role}`);\n }\n else {\n console.warn(`No cache found for tenant ${tenantId} and role ${role}`);\n }\n }\n catch (error) {\n console.error(`Error invalidating cache for tenant ${tenantId} and role ${role}:`, error);\n throw new Error(`Failed to invalidate cache for tenant ${tenantId} and role ${role}`);\n }\n return;\n}\n/**\n * Middleware to enforce RBAC (Role-Based Access Control) on GraphQL resolvers\n * @param resolver The original resolver function\n * @param permission The required permission for the action\n * @returns A wrapped resolver function that checks permissions\n * @throws {Error} If the user does not have the required permission\n * @example\n * // Wrap a resolver with RBAC enforcement\n * const securedResolver = enforceRBAC(originalResolver, 'createUser');\n *\n * // Use the secured resolver in your GraphQL schema\n * const resolvers = {\n * Mutation: {\n * createUser: securedResolver,\n * \t}, };\n *\n * In this example, the `enforceRBAC` function wraps the `originalResolver` and checks if the user has the 'createUser' permission before allowing access to the resolver. If the user lacks the required permission, an error is thrown, preventing unauthorized access.\n * * This middleware is essential for implementing fine-grained access control in GraphQL APIs, ensuring that only authorized users can perform specific actions based on their roles and permissions.\n * @remarks This function is designed to be used in GraphQL resolvers to enforce role-based access control (RBAC). It checks if the user has the necessary permissions before allowing access to the resolver function. If the user lacks the required permission, an error is thrown, preventing unauthorized access.\n * * @see {@link checkPermission} for checking user permissions\n * * @see {@link Role} and {@link Permission} for role and permission types\n * * @see {@link rolePermissions} for the mapping of roles to permissions\n * * @see {@link getCachedData} and {@link setCachedData} for caching permissions\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nfunction enforceRBAC(resolver, permission) {\n const wrapped = async (parent, args, context, info) => {\n const { user } = context;\n // Ensure we pass the user's role (string) and await the async permission check\n if (!user || !(await checkPermission(user.role, permission))) {\n throw new Error('Unauthorized: You do not have permission to perform this action.');\n }\n return await resolver(parent, args, context, info);\n };\n // Preserve function name (useful for logging, debugging)\n Object.defineProperty(wrapped, 'name', {\n value: resolver.name || 'anonymous',\n writable: false,\n configurable: true,\n });\n // Attach metadata\n wrapped.__originalResolver = resolver;\n wrapped.__rbacAction = permission;\n return wrapped;\n}\n/**\n * Get the RBAC action from a wrapped resolver\n * @param resolver The wrapped resolver function\n * @returns The RBAC action\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nfunction getRBACAction(resolver) {\n return resolver.__rbacAction || null;\n}\n/**\n * Get the original resolver function from a wrapped resolver\n * @param resolver The wrapped resolver function\n * @returns The original resolver function\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nfunction getOriginalResolver(resolver) {\n return resolver.__originalResolver || resolver;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.loadAmbitenConfig = loadAmbitenConfig;\nconst tslib_1 = require(\"tslib\");\nconst fs_extra_1 = tslib_1.__importDefault(require(\"fs-extra\"));\nconst path_1 = tslib_1.__importDefault(require(\"path\"));\nconst ajv_1 = tslib_1.__importDefault(require(\"ajv\"));\nconst ambiten_config_schema_json_1 = tslib_1.__importDefault(require(\"./ambiten.config.schema.json\"));\nconst ajv = new ajv_1.default({\n allErrors: true,\n useDefaults: true,\n strict: false,\n coerceTypes: true,\n});\nlet validate = null;\nconst DEFAULT_CONFIG_FILENAME = 'ambiten.config.json';\nfunction normalizeAmbitenConfig(rawConfig) {\n const cfg = { ...rawConfig };\n if (typeof cfg.logger === 'boolean') {\n cfg.logger = { enabled: cfg.logger };\n }\n if (cfg.logger && typeof cfg.logger === 'object') {\n if (typeof cfg.logger.enableMetrics === 'boolean') {\n cfg.logger.enableMetrics = {\n enabled: cfg.logger.enableMetrics,\n logInterval: 60000,\n };\n }\n if (!cfg.logger.enableMetrics) {\n cfg.logger.enableMetrics = {\n enabled: false,\n logInterval: 60000,\n };\n }\n if (typeof cfg.logger.compressLogFiles === 'boolean') {\n cfg.logger.compressLogFiles = {\n enabled: cfg.logger.compressLogFiles,\n };\n }\n if (!cfg.logger.compressLogFiles) {\n cfg.logger.compressLogFiles = {\n enabled: false,\n };\n }\n }\n if (typeof cfg.graphql === 'boolean') {\n cfg.graphql = { enabled: cfg.graphql };\n }\n if (typeof cfg.advanced === 'boolean') {\n cfg.advanced = {\n garbageCollector: { enabled: cfg.advanced },\n };\n }\n if (cfg.advanced && typeof cfg.advanced.garbageCollector === 'boolean') {\n cfg.advanced.garbageCollector = {\n enabled: cfg.advanced.garbageCollector,\n };\n }\n if (!cfg.features) {\n cfg.features = {};\n }\n if (typeof cfg.features.useRedisCache === 'undefined') {\n cfg.features.useRedisCache = false;\n }\n return cfg;\n}\nfunction assertValidAmbitenConfig(config) {\n if (!config.connection?.uri) {\n throw new Error('Invalid config: \"connection.uri\" is required.');\n }\n if (config.multiTenant?.enabled &&\n config.multiTenant.tenants &&\n typeof config.multiTenant.tenants !== 'object') {\n throw new Error('Invalid config: \"multiTenant.tenants\" must be a tenant-to-URI map.');\n }\n}\nasync function loadAmbitenConfig(configPath) {\n const candidates = configPath\n ? [path_1.default.resolve(configPath)]\n : [\n path_1.default.resolve(process.cwd(), DEFAULT_CONFIG_FILENAME),\n path_1.default.resolve(process.cwd(), 'config', DEFAULT_CONFIG_FILENAME),\n path_1.default.resolve(process.cwd(), 'src', 'config', DEFAULT_CONFIG_FILENAME),\n path_1.default.resolve(__dirname, DEFAULT_CONFIG_FILENAME),\n path_1.default.resolve(__dirname, '..', DEFAULT_CONFIG_FILENAME),\n ];\n let finalPath;\n for (const candidate of candidates) {\n if (await fs_extra_1.default.pathExists(candidate)) {\n finalPath = candidate;\n break;\n }\n }\n if (!finalPath) {\n throw new Error(`Config file not found at any of: ${candidates.join(', ')}`);\n }\n let parsed;\n try {\n const raw = await fs_extra_1.default.readFile(finalPath, 'utf-8');\n parsed = normalizeAmbitenConfig(JSON.parse(raw));\n }\n catch (err) {\n throw new Error(`[Ambiten] Failed to parse config file: ${err}`);\n }\n if (!validate) {\n validate = ajv.compile(ambiten_config_schema_json_1.default);\n }\n const isValid = validate(parsed);\n if (!isValid) {\n console.error(JSON.stringify(validate.errors, null, 2));\n const errors = validate.errors\n ?.map((e) => {\n const location = e.instancePath || '(root)';\n const extra = e.keyword === 'additionalProperties'\n ? `: ${e.params.additionalProperty}`\n : '';\n return `${location} ${e.message}${extra}`;\n })\n .join('; ');\n throw new Error(`[Ambiten] Invalid configuration: ${errors}`);\n }\n assertValidAmbitenConfig(parsed);\n parsed.graphql ??= { enabled: false };\n parsed.features ??= { useRedisCache: false };\n parsed.advanced ??= {\n circuitBreaker: { enabled: false },\n garbageCollector: { enabled: false },\n };\n return parsed;\n}\n;\n","module.exports = require(\"node-cron\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.now = exports.isValidDuration = exports.formatDuration = exports.parseDuration = void 0;\nconst parseDuration = (duration) => {\n const match = duration.match(/^(\\d+)([smhd])$/);\n const isValid = (0, exports.isValidDuration)(duration);\n if (!match || !isValid) {\n throw new Error(`Invalid duration format: ${duration}. Expected format is <number><unit> where unit is one of 's', 'm', 'h', or 'd'.`);\n }\n const value = parseInt(match[1], 10);\n const unit = match[2];\n switch (unit) {\n case 's': return value * 1000; // seconds to milliseconds\n case 'm': return value * 60 * 1000; // minutes to milliseconds\n case 'h': return value * 60 * 60 * 1000; // hours to milliseconds\n case 'd': return value * 24 * 60 * 60 * 1000; // days to milliseconds\n default: throw new Error(`Unknown time unit: ${unit}`);\n }\n};\nexports.parseDuration = parseDuration;\nconst formatDuration = (ms) => {\n const seconds = Math.floor(ms / 1000);\n const minutes = Math.floor(seconds / 60);\n const hours = Math.floor(minutes / 60);\n const days = Math.floor(hours / 24);\n if (days > 0)\n return `${days}d`;\n if (hours > 0)\n return `${hours}h`;\n if (minutes > 0)\n return `${minutes}m`;\n return `${seconds}s`;\n};\nexports.formatDuration = formatDuration;\nconst isValidDuration = (duration) => {\n return /^(\\d+)([smhd])$/.test(duration);\n};\nexports.isValidDuration = isValidDuration;\nexports.now = new Date();\n","module.exports = __WEBPACK_EXTERNAL_MODULE__2947__;","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenError = void 0;\nexports.createAmbitenError = createAmbitenError;\nclass AmbitenError extends Error {\n type;\n details;\n constructor(options) {\n super(options.message, { cause: options.cause });\n this.name = options.type;\n this.type = options.type;\n this.details = options.details;\n Error.captureStackTrace?.(this, AmbitenError);\n }\n toJSON() {\n return {\n name: this.name,\n type: this.type,\n message: this.message,\n details: this.details,\n cause: this.cause instanceof Error\n ? {\n name: this.cause.name,\n message: this.cause.message\n }\n : this.cause\n };\n }\n}\nexports.AmbitenError = AmbitenError;\nfunction createAmbitenError(type, message, options = {}) {\n return new AmbitenError({\n type,\n message,\n cause: options.cause,\n details: options.details\n });\n}\n;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenBootstrapFactory = void 0;\nconst config_1 = require(\"../../config\");\nconst logger_1 = require(\"@ambiten/logger\");\nconst index_1 = require(\"../index\");\nconst __1 = require(\"../..\");\nconst redis_manager_1 = require(\"../../redis-manager\");\nconst utils_1 = require(\"../../utils\");\nconst tanancy_1 = require(\"../../tanancy\");\nconst gc_1 = require(\"../../gc\");\nconst invalidateTenantCache_1 = require(\"../../utils/invalidateTenantCache\");\n/**\n * AmbitenBootstrap is the main entry point for initializing\n * and managing the Ambiten application stack when you opt for the CLI.\n * It handles MongoDB, Redis, and GraphQL setup,\n * along with custom hooks for post-connection logic.\n * @example\n *\n * ```bash\n * npx Ambiten-core my-project\n * cd my-project\n * ```\n *\n * This will create a new Ambiten project in the 'my-project' directory.\n * You can then customize the configuration file and start using Ambiten in your application.\n *\n * ---\n *\n * Add flags as needed:\n *\n * ```bash\n * npx Ambiten init my-app --with-graphql --multi-tenant --with-redis\n * cd my-app\n * ```\n * This will create a new Ambiten project with Redis caching, GraphQL support, and multi-tenancy enabled.\n * enabling them in the configuration file.\n *\n * ---\n *\n * You can also use AmbitenBootstrap programmatically in your application:\n * ```ts\n * @example\n * import { AmbitenBootstrapFactory } from '@Ambiten/core';\n * async function start() {\n * const Ambiten = await AmbitenBootstrapFactory.create();\n * const db = Ambiten.getMongoClient();\n * await db.connect();\n * const graphql = await Ambiten.getGraphQL();\n * // You can now use the GraphQL instance to generate schema or start a server\n * // or perform other GraphQL related operations\n * graphql.generateSchema();\n * Ambiten.getRedisClient();\n * }\n * start();\n * ```\n *\n *\n * @param {string} [configFilePathOrObject] - Optional path to a custom configuration file or a config object.\n * If not provided, it defaults to 'Ambiten.config.json'.\n * @returns {Promise<void>} - A promise that resolves when the initialization is complete.\n *\n * // Now you can use Ambiten.getMongoClient(), Ambiten.getRedisClient(), etc.\n */\nclass AmbitenBootstrap {\n config;\n provider;\n model;\n schema;\n graphql;\n gc;\n logger;\n adapter;\n onConnectHooks = [];\n connectCallbacks = [];\n isConnected;\n constructor(adapter) {\n this.adapter = adapter;\n }\n onConnect(callback) {\n if (!this.isConnected) {\n callback();\n return;\n }\n this.connectCallbacks.push(callback);\n }\n /**\n * Initializes the Ambiten application stack.\n */\n async initialize(configFilePathOrObject) {\n this.config =\n configFilePathOrObject && typeof configFilePathOrObject === 'object'\n ? configFilePathOrObject\n : await (0, config_1.loadAmbitenConfig)(configFilePathOrObject);\n this.initializeLogger();\n await this.initializeRedis();\n await this.initializeMongoProvider();\n this.initializeSchema();\n await this.initializeModel();\n await this.initializeMultiTenancy();\n await this.initializeGraphQL();\n await this.runOnConnectHooks();\n await this.initializeGarbageCollector();\n }\n initializeLogger() {\n const loggerConfig = this.config.logger;\n const defaultTransportConfigs = [\n { type: 'console', options: {} },\n {\n type: 'rotating-file',\n options: {\n filename: './logs/ambiten.log',\n frequency: 'daily',\n compress: false,\n flushInterval: 1000,\n },\n },\n ];\n this.logger = (0, logger_1.setupLogger)({\n ...loggerConfig,\n transports: undefined,\n transportConfigs: loggerConfig?.transportConfigs?.length\n ? loggerConfig.transportConfigs\n : defaultTransportConfigs,\n });\n this.logger.info('Logger initialized', {\n source: 'AmbitenBootstrap',\n });\n }\n async initializeRedis() {\n if (!this.config.features?.useRedisCache || !this.config.features.redisUri) {\n return;\n }\n await redis_manager_1.redis.get(this.config.features.redisUri);\n this.getLogger().info('Redis connected', {\n source: 'AmbitenBootstrap'\n });\n }\n async initializeMongoProvider() {\n const resolvedDbName = this.config.connection?.options?.dbName ||\n this.config.projectName ||\n undefined;\n this.provider =\n this.config.mongoClient ??\n this.config.provider ??\n (0, index_1.createAmbitenClientModule)({\n uri: this.config.connection?.uri || 'mongodb://localhost:27017',\n options: {\n dbName: resolvedDbName,\n ...this.config.connection?.options,\n },\n });\n await this.provider.connect();\n (0, utils_1.configureAmbitenContext)(this.provider);\n if (this.logger) {\n this.getLogger().info('MongoDB connected via AmbitenClientModule', {\n source: 'AmbitenBootstrap'\n });\n }\n else {\n console.log((0, utils_1.colorize)('MongoDB connected via AmbitenClientModule', 'blue'));\n }\n }\n initializeSchema() {\n this.schema = new index_1.Schema(typeof this.config.schema === 'object'\n ? this.config.schema\n : {});\n if (this.config.schema) {\n this.schema.registerSchema(this.config.schema);\n this.getLogger().info('Schema registered', { source: 'AmbitenBootstrap' });\n }\n else {\n this.getLogger().warn('No schema provided, using default schema', { source: 'AmbitenBootstrap' });\n }\n }\n async initializeModel() {\n const collectionName = this.config.model?.collectionName || 'default';\n this.model = (0, utils_1.Model)({\n collectionName,\n schema: this.schema,\n provider: this.provider,\n ctx: this.config.model?.ctx,\n collection: this.config.model?.collection,\n gcConfig: this.config.model?.gcConfig,\n });\n if (this.config.model) {\n await this.model.registerModel({\n ...this.config.model,\n collectionName,\n schema: this.schema,\n provider: this.provider,\n });\n if (this.logger) {\n this.getLogger().info(`Model registered: ${collectionName}`, {\n source: 'AmbitenBootstrap'\n });\n }\n else {\n console.log((0, utils_1.colorize)(`Model registered: ${collectionName}`, 'blue'));\n }\n }\n }\n async initializeMultiTenancy() {\n if (!this.config.multiTenant?.enabled)\n return;\n const tenants = this.config.multiTenant.tenants || {};\n const initOptions = this.config.multiTenant.initOptions || {};\n await (0, tanancy_1.initMultiTenancy)(tenants, initOptions);\n this.getLogger().info('Multi-tenancy initialized', {\n source: 'AmbitenBootstrap',\n tenantCount: Object.keys(tenants).length,\n lazy: initOptions.lazy ?? false,\n });\n }\n async initializeGraphQL() {\n if (!this.config.graphql?.enabled) {\n return;\n }\n this.graphql = new __1.AmbitenGraphQL({\n useRedis: this.config.features?.useRedisCache ?? false,\n customTypeDefs: this.config.features?.typeDefs\n ? Array.isArray(this.config.features.typeDefs)\n ? this.config.features.typeDefs\n : [this.config.features.typeDefs]\n : [],\n customResolvers: this.config.features?.resolvers\n ? Array.isArray(this.config.features.resolvers)\n ? this.config.features.resolvers\n : [this.config.features.resolvers]\n : [],\n provider: this.provider\n });\n await this.graphql.generateSchema();\n if (this.logger) {\n this.getLogger().info('GraphQL schema generated');\n this.getLogger().info('GraphQL initialized');\n }\n else {\n console.log((0, utils_1.colorize)('GraphQL schema generated', 'blue'));\n console.log((0, utils_1.colorize)('GraphQL initialized', 'blue'));\n }\n }\n async runOnConnectHooks() {\n for (const hook of this.onConnectHooks) {\n await hook();\n }\n }\n async initializeGarbageCollector() {\n if (!this.config.advanced?.garbageCollector?.enabled)\n return;\n this.gc = new gc_1.AmbitenGC({\n enabled: this.config.advanced.garbageCollector.enabled ?? true,\n cron: this.config.advanced.gcCron || '0 0 * * *',\n logResults: this.config.advanced.garbageCollector.logResults ?? true,\n continueOnError: true\n });\n console.log('✅ Garbage Collector initialized');\n }\n async registerMultiTenancy(options) {\n const multiTenantConfig = this.config.multiTenant;\n const logger = this.config.logger?.logger;\n if (!multiTenantConfig?.enabled) {\n logger?.warn('Multi-tenancy is not enabled.', {\n source: 'AmbitenBootstrap',\n });\n return;\n }\n const tenants = options?.tenants ?? multiTenantConfig.tenants;\n if (!tenants || Object.keys(tenants).length === 0) {\n logger?.warn('Multi-tenancy is enabled but no tenants were provided.', {\n source: 'AmbitenBootstrap',\n });\n return;\n }\n await (0, tanancy_1.initMultiTenancy)(tenants, {\n lazy: options?.lazy ?? multiTenantConfig.initOptions?.lazy ?? true,\n config: this.config.logger,\n });\n logger?.info('Multi-tenancy registered successfully.', {\n source: 'AmbitenBootstrap',\n tenantCount: Object.keys(tenants).length,\n });\n }\n async cache(key, fetcher, options = {}) {\n if (!redis_manager_1.redis) {\n throw new Error('Redis is not initialized');\n }\n return (0, utils_1.cacheWithRedis)(redis_manager_1.redis, key, fetcher, options);\n }\n async invalidateCache(tenantId, namespace) {\n if (!redis_manager_1.redis) {\n throw new Error('No Redis client available');\n }\n const logger = this.config.logger?.logger;\n if (!tenantId) {\n throw new Error('Tenant ID is required to invalidate cache');\n }\n logger?.info('Invalidating cache for tenant:', {\n source: 'AmbitenBootstrap',\n tenantId,\n namespace: namespace\n });\n await (0, invalidateTenantCache_1.invalidateTenantCache)(redis_manager_1.redis, tenantId, namespace);\n }\n /**\n * Returns the Redis client if Redis is enabled in the configuration.\n */\n async getRedisClient() {\n if (this.config.features?.useRedisCache && this.config.features.redisUri) {\n await redis_manager_1.redis.get(this.config.features.redisUri);\n }\n return redis_manager_1.redis;\n }\n getMongoClient() {\n return this.provider;\n }\n getModel() {\n return this.model;\n }\n getSchema() {\n return this.schema;\n }\n getGraphQL() {\n if (!this.graphql) {\n throw new Error('GraphQL is not initialized.');\n }\n return this.graphql;\n }\n getGCRunner() {\n if (!this.gc) {\n throw new Error('Garbage Collector is not initialized.');\n }\n return this.gc;\n }\n getLogger() {\n return this.logger;\n }\n async shutdown() {\n const logger = this.config.logger?.logger;\n if (redis_manager_1.redis.isOpen) {\n await redis_manager_1.redis.disconnect();\n logger?.info('🧹 Redis connection closed', {\n source: 'AmbitenBootstrap'\n });\n }\n if (this.provider) {\n await this.provider.close();\n logger?.log?.('info', 'MongoDB connection closed');\n }\n logger?.log?.('info', 'Shutdown complete');\n }\n}\n;\n/**\n * Factory which returns the instance of the main AmbitenBootstrap and\n * Attached a method AmbitenBootstrap.create() which initializes the AmbitenBootstrap.\n * This class encapsulates the logic for initializing the Ambiten application stack,\n * including MongoDB, Multi-Tenancy, Redis, GraphQL logger etc. setup.\n * It can be used to create a fully configured Ambiten application.\n * with optional configuration parameters.\n * @example\n * const Ambiten = await AmbitenBootstrapFactory.create();\n * const db = Ambiten.getMongoClient();\n * await db.connect();\n * const graphql = await Ambiten.getGraphQL();\n * // You can now use the GraphQL instance to generate schema or start a server\n * // or perform other GraphQL related operations\n * graphql.generateSchema();\n * Ambiten.getRedisClient();\n * // or with custom config\n * const Ambiten = await AmbitenBootstrapFactory.create(customConfig);\n * @param {AmbitenConfig} [config] - Optional configuration object for Ambiten.\n * @returns {Promise<AmbitenBootstrap>} - A promise that resolves to an instance of AmbitenBootstrap.\n */\nclass AmbitenBootstrapFactory {\n static async create(options = {}) {\n const bootstrap = new AmbitenBootstrap(options.adapter);\n await bootstrap.initialize(options.config);\n return bootstrap;\n }\n}\nexports.AmbitenBootstrapFactory = AmbitenBootstrapFactory;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenContext = void 0;\nconst node_async_hooks_1 = require(\"node:async_hooks\");\nconst runManualTransaction_1 = require(\"./helpers/runManualTransaction\");\nconst DEFAULT_AMBITEN_BUDGET = {\n maxQueries: Infinity,\n queriesExecuted: 0,\n totalTimeMs: 0\n};\nclass AmbitenContextManager {\n storage = new node_async_hooks_1.AsyncLocalStorage();\n transactionResolver;\n run(context, callback) {\n const parent = this.storage.getStore() ?? {};\n const merged = {\n ...parent,\n ...context,\n budget: context.budget\n ? this.normalizeBudget(context.budget)\n : parent.budget\n ? this.normalizeBudget(parent.budget)\n : undefined\n };\n return this.storage.run(merged, callback);\n }\n get() {\n return this.storage.getStore() ?? {};\n }\n hasActiveContext() {\n return this.storage.getStore() !== undefined;\n }\n set(patch) {\n const current = this.storage.getStore();\n if (!current)\n return;\n Object.assign(current, patch);\n }\n clear() {\n const current = this.storage.getStore();\n if (!current)\n return;\n for (const key of Object.keys(current)) {\n delete current[key];\n }\n }\n configureTransactionResolver(resolver) {\n this.transactionResolver = resolver;\n }\n getTenantId() {\n return this.get().tenantId;\n }\n getRequestId() {\n return this.get().requestId;\n }\n getDbName() {\n return this.get().dbName;\n }\n getCollectionName() {\n return this.get().collectionName;\n }\n getSession() {\n return this.get().session;\n }\n getLogger() {\n return this.get().logger;\n }\n getLoggerMeta() {\n return this.get().loggerMeta;\n }\n getObserver() {\n return this.get().observer;\n }\n normalizeBudget(budget) {\n return {\n maxQueries: budget?.maxQueries ?? DEFAULT_AMBITEN_BUDGET.maxQueries,\n queriesExecuted: budget?.queriesExecuted ?? DEFAULT_AMBITEN_BUDGET.queriesExecuted,\n totalTimeMs: budget?.totalTimeMs ?? DEFAULT_AMBITEN_BUDGET.totalTimeMs\n };\n }\n getBudget() {\n const state = this.get();\n const normalized = this.normalizeBudget(state.budget);\n state.budget = normalized;\n return normalized;\n }\n setBudget(budget) {\n const state = this.get();\n state.budget = this.normalizeBudget(budget);\n }\n assertQueryBudget() {\n const state = this.get();\n const budget = this.getBudget();\n if (budget.queriesExecuted >= budget.maxQueries) {\n throw new Error(`[Ambiten] Tenant ${state.tenantId ?? 'unknown'} exceeded query budget for this request.`);\n }\n }\n incrementQueries() {\n this.assertQueryBudget();\n const budget = this.getBudget();\n budget.queriesExecuted += 1;\n return budget;\n }\n addQueryTime(durationMs) {\n const budget = this.getBudget();\n budget.totalTimeMs += durationMs;\n return budget;\n }\n isDebug() {\n const ctx = this.get();\n return Boolean(ctx.debug ||\n process.env.AMBITEN_DEBUG === 'true' ||\n process.env.AMBITEN_DEBUG === '1');\n }\n async withTransaction(callback) {\n const current = this.get();\n if (current.session) {\n return callback(current.session);\n }\n if (!this.transactionResolver) {\n throw new Error('AmbitenContext transaction resolver is not configured.');\n }\n const client = await this.transactionResolver.resolveClient(current.tenantId, current.dbName);\n if (!client) {\n throw new Error(`No MongoClient available for${current.tenantId ? ` tenant \"${current.tenantId}\"` : ' current context'}.`);\n }\n const session = client.startSession();\n if (typeof session.withTransaction === 'function') {\n try {\n let result;\n await session.withTransaction(async () => {\n result = await this.run({ session }, () => callback(session));\n return result;\n });\n return result;\n }\n finally {\n await session.endSession();\n }\n }\n return this.run({ session }, () => (0, runManualTransaction_1.runManualTransaction)(session, callback));\n }\n hasTransactionResolver() {\n return Boolean(this.transactionResolver);\n }\n}\nexports.AmbitenContext = new AmbitenContextManager();\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenCache\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenConfig\"), exports);\ntslib_1.__exportStar(require(\"./schema.type\"), exports);\ntslib_1.__exportStar(require(\"./ambiten.model.type\"), exports);\ntslib_1.__exportStar(require(\"./user.type\"), exports);\ntslib_1.__exportStar(require(\"./ambiten.client.type\"), exports);\ntslib_1.__exportStar(require(\"./document\"), exports);\ntslib_1.__exportStar(require(\"./event.type\"), exports);\ntslib_1.__exportStar(require(\"./graphql.type\"), exports);\ntslib_1.__exportStar(require(\"./GCConfig\"), exports);\ntslib_1.__exportStar(require(\"./logger.types\"), exports);\ntslib_1.__exportStar(require(\"./db.provider\"), exports);\ntslib_1.__exportStar(require(\"./result.utils.types\"), exports);\ntslib_1.__exportStar(require(\"./bootstrapClient.type\"), exports);\ntslib_1.__exportStar(require(\"./middleware/types\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.measureQueryForBrowser = measureQueryForBrowser;\nasync function measureQueryForBrowser(_meta, executor) {\n return executor();\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getTenantDB = void 0;\nconst lib_core_1 = require(\"../../lib-core\");\nconst dbCache = new Map();\n/**\n * Retrieves the database instance for a specific tenant.\n * If the database is already cached, it returns the cached instance.\n * Otherwise, it initializes a new database connection for the tenant, caches it, and returns it.\n *\n * @param {string} tenantId - The ID of the tenant whose database is to be retrieved.\n * @returns {Promise<Db>} A promise that resolves to the MongoDB database instance for the tenant.\n * @throws {Error} If the database for the specified tenant is not found.\n */\nconst getTenantDB = async (tenantId) => {\n if (dbCache.has(tenantId)) {\n return dbCache.get(tenantId);\n }\n const db = lib_core_1.AmbitenClient.init().withDatabase(tenantId);\n if (!db)\n throw new Error(`Database not found for tenant: ${tenantId}`);\n dbCache.set(tenantId, await db.db());\n return await db.db();\n};\nexports.getTenantDB = getTenantDB;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./redisClient\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.runGarbageCollectorOnAllModels = runGarbageCollectorOnAllModels;\nexports.runGarbageCollector = runGarbageCollector;\nconst ModelRegistry_1 = require(\"../utils/ModelRegistry\");\nconst utils_1 = require(\"../utils\");\n/**\n * Runs garbage collection on all registered Ambiten model instances.\n *\n * This delegates cleanup to each model's `runGC()` method so the operation\n * remains context-aware and preserves middleware, schema hooks, query\n * instrumentation, cache invalidation, and event publishing.\n *\n * @param options - Optional garbage collection execution options.\n * @returns Summary of the garbage collection run.\n */\nasync function runGarbageCollectorOnAllModels(options = {}) {\n const models = ModelRegistry_1.AmbitenModelRegistry.getAllModels();\n const result = {\n scanned: models.length,\n succeeded: 0,\n failed: 0,\n models: []\n };\n for (const model of models) {\n const modelContext = model.getContext?.();\n const collectionName = modelContext?.ctx?.collectionName;\n try {\n if (typeof model.runGC !== 'function') {\n throw new Error('Registered model does not implement runGC().');\n }\n await model.runGC(options.ctx);\n result.succeeded += 1;\n result.models.push({\n collectionName,\n success: true\n });\n }\n catch (error) {\n result.failed += 1;\n result.models.push({\n collectionName,\n success: false,\n error\n });\n console.error((0, utils_1.colorize)(`[GC] Failed on collection \"${collectionName ?? 'unknown'}\"`, 'red'), error);\n if (!options.continueOnError) {\n throw error;\n }\n }\n }\n return result;\n}\n/**\n * Runs garbage collection on a single Ambiten model instance.\n *\n * @param model - Registered Ambiten model instance.\n * @param ctx - Optional model execution context.\n */\nasync function runGarbageCollector(model, ctx) {\n await model.runGC(ctx);\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./measureQueryWithErrors\"), exports);\ntslib_1.__exportStar(require(\"./measureQuery.browser\"), exports);\n","module.exports = __WEBPACK_EXTERNAL_MODULE__3911__;","module.exports = require(\"graphql-subscriptions\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.cacheWithRedis = cacheWithRedis;\nconst ambiten_cache_1 = require(\"../ambiten-cache\");\n/**\n * Caches a value in Redis with optional tenant and namespace scoping.\n * If the value is not found in cache, it runs the provided fetcher function\n * to get the value, caches it, and then returns it.\n *\n * @param {string} key - The cache key to use.\n * @param {() => Promise<T>} fetcher - A function that fetches the value if not cached.\n * @param {AmbitenCacheOptions} options - Options for caching behavior.\n * @returns {Promise<T>} - The cached or fetched value.\n * @example\n * const value = await cacheWithRedis(redisClient, 'myKey', async () => {\n * // Fetch from database or external API\n * return await fetchDataFromSource();\n */\nasync function cacheWithRedis(client, key, fetcher, options = {}) {\n const cache = new ambiten_cache_1.AmbitenCache(client);\n return await cache.wrap(key, fetcher, options);\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.generateProject = generateProject;\nexports.generateProjectWithConfig = generateProjectWithConfig;\nconst tslib_1 = require(\"tslib\");\nconst fs_extra_1 = tslib_1.__importDefault(require(\"fs-extra\"));\nconst path_1 = tslib_1.__importDefault(require(\"path\"));\nconst templates_1 = require(\"../templates\");\nconst utils_1 = require(\"../utils\");\nasync function generateProject(options) {\n const startedAt = Date.now();\n const projectName = options.projectName?.trim() || 'Ambiten-app';\n const projectRoot = path_1.default.resolve(process.cwd(), projectName);\n const configPath = path_1.default.join(projectRoot, 'Ambiten.config.json');\n const entryFilePath = path_1.default.join(projectRoot, 'src', 'main.ts');\n console.log((0, utils_1.colorize)(`\\n🚀 Creating project \"${projectName}\"`, 'green'));\n console.log((0, utils_1.colorize)(`📁 Location: ${projectRoot}\\n`, 'blue'));\n await fs_extra_1.default.ensureDir(projectRoot);\n const logger = (0, utils_1.createScaffoldLogger)(projectRoot);\n const resolvedOptions = {\n ...options,\n projectName,\n };\n await (0, templates_1.generateAppStructure)(projectRoot, resolvedOptions, logger);\n const durationMs = Date.now() - startedAt;\n logger.printSummary(projectName, resolvedOptions, durationMs);\n return {\n projectRoot,\n configPath,\n entryFilePath,\n };\n}\nasync function generateProjectWithConfig(config) {\n return generateProject({\n ...config,\n projectName: config.projectName || 'Ambiten-app',\n });\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createScaffoldLogger = createScaffoldLogger;\nconst tslib_1 = require(\"tslib\");\nconst path_1 = tslib_1.__importDefault(require(\"path\"));\nconst color_palatte_1 = require(\"./color-palatte\");\nfunction createScaffoldLogger(projectRoot) {\n const log = {\n files: [],\n dirs: [],\n };\n const normalize = (p) => path_1.default.relative(projectRoot, p).replace(/\\\\/g, '/');\n return {\n addFile(filePath) {\n log.files.push(normalize(filePath));\n },\n addDir(dirPath) {\n log.dirs.push(normalize(dirPath) + '/');\n },\n printSummary(projectName, options, durationMs) {\n const enabledFeatures = [\n options.multiTenant?.enabled ? 'Multi-tenancy' : null,\n options.graphql?.enabled ? 'GraphQL' : null,\n options.logger?.enabled ? 'Logger' : null,\n options.features?.useRedisCache ? 'Redis Cache' : null,\n options.advanced?.garbageCollector?.enabled ? 'Garbage Collector' : null,\n ].filter(Boolean);\n const disabledFeatures = [\n !options.multiTenant?.enabled ? 'Multi-tenancy' : null,\n !options.graphql?.enabled ? 'GraphQL' : null,\n !options.logger?.enabled ? 'Logger' : null,\n !options.features?.useRedisCache ? 'Redis Cache' : null,\n !options.advanced?.garbageCollector?.enabled ? 'Garbage Collector' : null,\n ].filter(Boolean);\n const seconds = (durationMs / 1000).toFixed(2);\n console.log('');\n console.log((0, color_palatte_1.colorize)(`✔ Project scaffold completed in ${seconds}s`, 'green'));\n console.log('');\n if (log.dirs.length) {\n console.log((0, color_palatte_1.colorize)('Directories:', 'blue'));\n log.dirs.forEach((d) => {\n console.log((0, color_palatte_1.colorize)(` + ${d}`, 'green'));\n });\n console.log('');\n }\n if (log.files.length) {\n console.log((0, color_palatte_1.colorize)('Files:', 'blue'));\n log.files.forEach((f) => {\n console.log((0, color_palatte_1.colorize)(` + ${f}`, 'green'));\n });\n console.log('');\n }\n console.log((0, color_palatte_1.colorize)('Feature summary:', 'blue'));\n enabledFeatures.forEach((feature) => {\n console.log((0, color_palatte_1.colorize)(` ✓ ${feature}`, 'green'));\n });\n disabledFeatures.forEach((feature) => {\n console.log((0, color_palatte_1.colorize)(` ✗ ${feature}`, 'yellow'));\n });\n console.log('');\n console.log((0, color_palatte_1.colorize)('Next steps:', 'blue'));\n console.log((0, color_palatte_1.colorize)(` cd ${projectName}`, 'green'));\n console.log((0, color_palatte_1.colorize)(` pnpm install`, 'green'));\n console.log((0, color_palatte_1.colorize)(` pnpm dev`, 'green'));\n console.log('');\n },\n };\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SchemaType = void 0;\nconst mongodb_1 = require(\"mongodb\");\n/**\n * MongoDB schema types.\n */\nexports.SchemaType = {\n Types: { ObjectId: mongodb_1.ObjectId },\n};\n","module.exports = require(\"dotenv/config\");","module.exports = require(\"fs-extra\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.applySoftDelete = applySoftDelete;\nconst DEFAULTS = {\n field: 'deletedAt',\n deletedAtField: 'deletedAt',\n deletedByField: 'deletedBy',\n isDeletedField: 'isDeleted',\n enabled: true,\n excludeDeletedByDefault: true\n};\nfunction buildNotDeletedFilter(options) {\n return {\n $and: [\n {\n $or: [\n { [options.deletedAtField]: { $exists: false } },\n { [options.deletedAtField]: null }\n ]\n },\n {\n $or: [\n { [options.isDeletedField]: { $exists: false } },\n { [options.isDeletedField]: false }\n ]\n }\n ]\n };\n}\nfunction buildOnlyDeletedFilter(options) {\n return {\n $or: [\n { [options.deletedAtField]: { $ne: null } },\n { [options.isDeletedField]: true }\n ]\n };\n}\nfunction mergeFilter(original, extra) {\n if (!original || Object.keys(original).length === 0) {\n return extra;\n }\n return {\n $and: [original, extra]\n };\n}\nfunction buildSoftDeleteUpdate(options) {\n return {\n $set: {\n [options.deletedAtField]: new Date(),\n [options.isDeletedField]: true\n }\n };\n}\nfunction applySoftDelete(model, opts = {}) {\n const options = { ...DEFAULTS, ...opts };\n if (!options.enabled) {\n return model;\n }\n const applyReadFilter = (ctx) => {\n if (ctx.withDeleted === true) {\n return;\n }\n if (ctx.onlyDeleted === true) {\n ctx.filter = mergeFilter(ctx.filter, buildOnlyDeletedFilter(options));\n return;\n }\n if (options.excludeDeletedByDefault) {\n ctx.filter = mergeFilter(ctx.filter, buildNotDeletedFilter(options));\n }\n };\n model.beforeFind((ctx) => {\n applyReadFilter(ctx);\n });\n model.beforeFindOne((ctx) => {\n applyReadFilter(ctx);\n });\n model.beforeFindOneAndUpdate((ctx) => {\n applyReadFilter(ctx);\n });\n model.beforeFindOneAndReplace((ctx) => {\n applyReadFilter(ctx);\n });\n model.beforeFindOneAndUpsert((ctx) => {\n applyReadFilter(ctx);\n });\n model.beforeAggregate((ctx) => {\n if (ctx.withDeleted === true) {\n return;\n }\n const stage = ctx.onlyDeleted === true\n ? { $match: buildOnlyDeletedFilter(options) }\n : options.excludeDeletedByDefault\n ? { $match: buildNotDeletedFilter(options) }\n : null;\n if (!stage) {\n return;\n }\n ctx.pipeline = [stage, ...(ctx.pipeline ?? [])];\n });\n model.beforeDeleteOne((ctx) => {\n if (ctx.hardDelete === true) {\n return;\n }\n ctx.filter = mergeFilter(ctx.filter, buildNotDeletedFilter(options));\n ctx.update = buildSoftDeleteUpdate(options);\n ctx.meta = {\n ...(ctx.meta ?? {}),\n softDelete: true\n };\n });\n model.beforeDeleteMany((ctx) => {\n if (ctx.hardDelete === true) {\n return;\n }\n ctx.filter = mergeFilter(ctx.filter, buildNotDeletedFilter(options));\n ctx.update = buildSoftDeleteUpdate(options);\n ctx.meta = {\n ...(ctx.meta ?? {}),\n softDelete: true\n };\n });\n model.beforeFindOneAndDelete((ctx) => {\n ctx.filter = mergeFilter(ctx.filter, buildNotDeletedFilter(options));\n if (ctx.hardDelete === true) {\n return;\n }\n ctx.update = buildSoftDeleteUpdate(options);\n ctx.meta = {\n ...(ctx.meta ?? {}),\n softDelete: true\n };\n });\n model.setSoftDeleteConfig({\n deletedAtField: options.deletedAtField,\n isDeletedField: options.isDeletedField\n });\n return model;\n}\n;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.runManualTransaction = runManualTransaction;\nconst transactionSession_1 = require(\"./transactionSession\");\nasync function runManualTransaction(session, operation) {\n if (!(0, transactionSession_1.hasManualTransactionMethods)(session)) {\n throw new Error('Session does not implement manual transaction methods.');\n }\n session.startTransaction();\n try {\n const result = await operation(session);\n await session.commitTransaction();\n return result;\n }\n catch (error) {\n await session.abortTransaction();\n throw error;\n }\n finally {\n await session.endSession();\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.colorize = void 0;\n;\nconst colorize = (text, platform) => {\n switch (platform) {\n case 'red':\n return `\\x1b[31m${text}\\x1b[0m`; // Red color\n case 'green':\n return `\\x1b[32m${text}\\x1b[0m`; // Green color\n case 'magenta':\n return `\\x1b[35m${text}\\x1b[0m`; // Magenta color\n case 'cyan':\n return `\\x1b[36m${text}\\x1b[0m`; // Cyan color\n case 'yellow':\n return `\\x1b[33m${text}\\x1b[0m`; // Yellow color\n case 'blue':\n return `\\x1b[34m${text}\\x1b[0m`; // Blue color\n default:\n break;\n }\n return `\\x1b[36m${text}\\x1b[0m`;\n};\nexports.colorize = colorize;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.MultiTenantManager = void 0;\nconst mongodb_1 = require(\"mongodb\");\n/**\n * MultiTenantManager is responsible for managing tenant configurations and MongoDB client connections in a multi-tenant application.\n * It supports both lazy and immediate tenant registration, allowing for flexible connection management based on application needs.\n */\nclass MultiTenantManager {\n static tenants = new Map();\n constructor() { }\n /**\n * Checks if a tenant is already registered.\n * @param {string} tenantId - The ID of the tenant to check.\n * @returns {boolean} `true` if the tenant is registered, `false` otherwise.\n */\n static hasTenant(tenantId) {\n return this.tenants.has(tenantId);\n }\n /**\n * Registers a tenant for lazy connection.\n * Connection is established only when the tenant is accessed for the first time.\n *\n * @param {string} tenantId - The tenant ID.\n * @param {string} uri - The MongoDB URI.\n * @param {RegisterTenantOptions} [options] - Optional tenant registration settings.\n */\n static registerLazyTenant(tenantId, uri, options = {}) {\n this.validateTenantId(tenantId);\n this.validateUri(uri);\n const normalizedTenantId = tenantId.trim();\n const tenantConfig = {\n tenantId: normalizedTenantId,\n uri: uri.trim(),\n dbName: options.dbName?.trim() || this.extractDbNameFromUri(uri) || normalizedTenantId,\n client: undefined,\n lazy: true,\n metadata: options.metadata\n };\n this.tenants.set(normalizedTenantId, tenantConfig);\n return tenantConfig;\n }\n /**\n * Registers a tenant and establishes a connection immediately.\n *\n * @param {string} tenantId - The tenant ID.\n * @param {string} uri - The MongoDB URI.\n * @param {RegisterTenantOptions} [options] - Optional tenant registration settings.\n * @returns {Promise<MongoClient>} The connected MongoClient instance.\n */\n static async registerTenant(tenantId, uri, options = {}) {\n this.validateTenantId(tenantId);\n this.validateUri(uri);\n const normalizedTenantId = tenantId.trim();\n const existing = this.tenants.get(normalizedTenantId);\n if (existing?.client) {\n return existing.client;\n }\n const client = options.client ?? new mongodb_1.MongoClient(uri);\n if (!options.client) {\n await client.connect();\n }\n const tenantConfig = {\n tenantId: normalizedTenantId,\n uri: uri.trim(),\n dbName: options.dbName?.trim() || this.extractDbNameFromUri(uri) || normalizedTenantId,\n client,\n lazy: false,\n metadata: options.metadata\n };\n this.tenants.set(normalizedTenantId, tenantConfig);\n return client;\n }\n /**\n * Retrieves the MongoClient instance for a specific tenant.\n * If the tenant was registered lazily, connection is established on first access.\n *\n * @param {string} tenantId - The tenant ID.\n * @returns {Promise<MongoClient | null>} The MongoClient or null if not registered.\n */\n static async getClient(tenantId) {\n this.validateTenantId(tenantId);\n const normalizedTenantId = tenantId.trim();\n const tenant = this.tenants.get(normalizedTenantId);\n if (!tenant)\n return null;\n if (tenant.client) {\n return tenant.client;\n }\n if (tenant.lazy) {\n const client = new mongodb_1.MongoClient(tenant.uri);\n await client.connect();\n this.tenants.set(normalizedTenantId, {\n ...tenant,\n client,\n lazy: false\n });\n return client;\n }\n return null;\n }\n /**\n * Retrieves the full tenant configuration.\n *\n * @param {string} tenantId - The tenant ID.\n * @returns {TenantConfig | undefined} The tenant configuration if found.\n */\n static getTenant(tenantId) {\n this.validateTenantId(tenantId);\n return this.tenants.get(tenantId.trim());\n }\n /**\n * Retrieves the configured database name for a tenant.\n *\n * @param {string} tenantId - The tenant ID.\n * @returns {string | undefined} The database name if found.\n */\n static getTenantDbName(tenantId) {\n return this.getTenant(tenantId)?.dbName;\n }\n /**\n * Returns the first connected tenant ID.\n * Useful for backward compatibility, though not ideal in multi-tenant flows.\n */\n static getConnectedTenant() {\n const connected = Array.from(this.tenants.values()).find(tenant => !!tenant.client);\n return connected?.tenantId || '';\n }\n /**\n * Returns all currently connected tenant IDs.\n */\n static getAllConnectedTenants() {\n return Array.from(this.tenants.values())\n .filter(tenant => !!tenant.client)\n .map(tenant => tenant.tenantId);\n }\n /**\n * Returns all registered tenant configs.\n */\n static getAllTenants() {\n return Array.from(this.tenants.values());\n }\n /**\n * Returns true if at least one tenant is registered.\n */\n static isEnabled() {\n return this.tenants.size > 0;\n }\n /**\n * Removes a tenant from the registry.\n */\n static removeTenant(tenantId) {\n this.validateTenantId(tenantId);\n return this.tenants.delete(tenantId.trim());\n }\n /**\n * Clears all tenants from the registry.\n */\n static clearTenants() {\n this.tenants.clear();\n }\n static validateTenantId(tenantId) {\n if (!tenantId || typeof tenantId !== 'string' || !tenantId.trim()) {\n throw new Error('Tenant ID is required.');\n }\n }\n static validateUri(uri) {\n if (!uri || typeof uri !== 'string' || !uri.trim()) {\n throw new Error('MongoDB URI is required.');\n }\n if (!uri.startsWith('mongodb://') && !uri.startsWith('mongodb+srv://')) {\n throw new Error(`Invalid MongoDB URI: ${uri}`);\n }\n }\n static extractDbNameFromUri(uri) {\n try {\n const withoutQuery = uri.split('?')[0];\n const parts = withoutQuery.split('/');\n const lastPart = parts[parts.length - 1];\n if (!lastPart || lastPart.includes(':')) {\n return undefined;\n }\n return lastPart.trim() || undefined;\n }\n catch {\n return undefined;\n }\n }\n}\nexports.MultiTenantManager = MultiTenantManager;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n;\n","module.exports = require(\"tslib\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.generateMainTS = generateMainTS;\nfunction generateMainTS(options) {\n return `import { run } from './core/initAmbiten';\n\nasync function main() {\n const app = await run();\n\n if (typeof app?.onConnect === 'function') {\n app.onConnect(() => {\n console.log('✅ Ambiten application initialized successfully.');\n });\n }\n\n return app;\n}\n\nmain().catch((error) => {\n console.error('❌ Failed to start application:', error);\n process.exit(1);\n});\n`;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.configureAmbitenContext = configureAmbitenContext;\nconst context_1 = require(\"../context\");\nconst tanancy_1 = require(\"../tanancy\");\n/**\n * Configures the Ambiten runtime context with a transaction client resolver.\n *\n * The resolver is used by {@link AmbitenContext.withTransaction} to obtain the\n * correct MongoDB client for the current runtime scope. Tenant-specific clients\n * are resolved first when a tenant identifier is available; otherwise the\n * configured provider client factory is used.\n *\n * @param provider - Bootstrap client/provider used to resolve MongoDB clients.\n */\nfunction configureAmbitenContext(provider) {\n context_1.AmbitenContext.configureTransactionResolver({\n resolveClient: async (tenantId, dbName) => {\n if (tenantId) {\n const tenantClient = await tanancy_1.MultiTenantManager.getClient(tenantId);\n if (tenantClient) {\n return tenantClient;\n }\n }\n if (typeof provider.client === 'function') {\n const ctx = {\n tenantId,\n dbName\n };\n return provider.client(ctx);\n }\n return undefined;\n }\n });\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenCache = void 0;\nexports.createAmbitenCache = createAmbitenCache;\nconst redis_manager_1 = require(\"../redis-manager\");\nconst context_1 = require(\"../context\");\nclass AmbitenCache {\n client;\n constructor(client = redis_manager_1.redis) {\n this.client = client;\n }\n /**\n * Builds a tenant-aware cache key.\n * Key format: {prefix}:{tenantId}:{namespace}:{key}\n * - prefix: Optional string to namespace cache keys (default: \"Ambiten\")\n * - tenantId: Resolved tenant ID for multi-tenancy (explicit > context > \"default\")\n * - namespace: Optional string to further namespace keys (default: \"cache\")\n * - key: The original cache key provided by the caller\n *\n * Resolution priority:\n * 1. Explicit tenantId from options\n * 2. Active Ambiten runtime tenantId\n * 3. \"default\"\n */\n buildKey(key, options = {}) {\n const ctx = context_1.AmbitenContext.get();\n const prefix = options.prefix ?? 'Ambiten';\n const tenantId = options.tenantId ?? ctx.tenantId ?? 'default';\n const namespace = options.namespace ?? 'cache';\n return [prefix, tenantId, namespace, key]\n .filter(Boolean)\n .join(':');\n }\n /**\n * Reads and deserializes a cached value.\n */\n async get(key, options) {\n const namespacedKey = this.buildKey(key, options);\n const cached = await this.client.get(namespacedKey);\n if (cached === null || cached === undefined) {\n this.emit('miss', namespacedKey);\n return null;\n }\n try {\n this.emit('hit', namespacedKey);\n return JSON.parse(cached);\n }\n catch {\n await this.client.del(namespacedKey);\n this.emit('corrupt', namespacedKey);\n return null;\n }\n }\n /**\n * Serializes and writes a cached value.\n */\n async set(key, value, options = {}) {\n const namespacedKey = this.buildKey(key, options);\n await this.client.set(namespacedKey, JSON.stringify(value), { EX: options.ttlSeconds ?? 60 });\n this.emit('set', namespacedKey);\n }\n /**\n * Returns cached value if available, otherwise computes, stores, and returns it.\n */\n async wrap(key, fetcher, options = {}) {\n const existing = await this.get(key, options);\n if (existing !== null) {\n return existing;\n }\n const result = await fetcher();\n await this.set(key, result, options);\n return result;\n }\n /**\n * Invalidates one cache key.\n */\n async invalidate(key, options) {\n const namespacedKey = this.buildKey(key, options);\n await this.client.del(namespacedKey);\n this.emit('invalidate', namespacedKey);\n }\n /**\n * Invalidates cache keys by pattern using SCAN.\n */\n async invalidatePattern(pattern) {\n if (!pattern || typeof pattern !== 'string') {\n throw new Error('Pattern must be a non-empty string.');\n }\n if (!this.client.scan) {\n throw new Error('Cache client does not support scan().');\n }\n let cursor = 0;\n let deletedCount = 0;\n do {\n const result = await this.client.scan(cursor, {\n MATCH: pattern,\n COUNT: 100\n });\n const nextCursor = Array.isArray(result)\n ? Number(result[0])\n : result.cursor;\n const keys = Array.isArray(result)\n ? result[1]\n : result.keys;\n if (keys.length > 0) {\n await this.client.del(keys);\n deletedCount += keys.length;\n }\n cursor = nextCursor;\n } while (cursor !== 0);\n if (deletedCount > 0) {\n this.emit('invalidatePattern', pattern);\n }\n return deletedCount;\n }\n /**\n * Internal event hook point for future observability and policy integrations.\n */\n emit(event, key) {\n void event;\n void key;\n }\n}\nexports.AmbitenCache = AmbitenCache;\nfunction createAmbitenCache(client = redis_manager_1.redis) {\n return new AmbitenCache(client);\n}\n","module.exports = require(\"ajv\");","module.exports = require(\"@graphql-tools/schema\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.scheduleGarbageCollector = scheduleGarbageCollector;\nconst tslib_1 = require(\"tslib\");\nconst cron = tslib_1.__importStar(require(\"node-cron\"));\nconst gcManager_1 = require(\"./gcManager\");\nconst ModelRegistry_1 = require(\"../utils/ModelRegistry\");\nconst utils_1 = require(\"../utils\");\n/**\n * Schedules registry-driven garbage collection.\n *\n * The cron task uses registered model instances and delegates cleanup to\n * `model.runGC()` so Ambiten's runtime context, middleware, schema hooks,\n * instrumentation, cache invalidation, and events remain centralized.\n *\n * @param options - Cron expression or scheduler options.\n * @returns The scheduled cron task.\n */\nfunction scheduleGarbageCollector(options = '0 * * * *') {\n const cronExpr = typeof options === 'string'\n ? options\n : options.cronExpr ?? '0 * * * *';\n const ctx = typeof options === 'string'\n ? undefined\n : options.ctx;\n const continueOnError = typeof options === 'string'\n ? true\n : options.continueOnError ?? true;\n return cron.schedule(cronExpr, async () => {\n try {\n const models = ModelRegistry_1.AmbitenModelRegistry.getAllModels();\n if (models.length === 0) {\n console.warn((0, utils_1.colorize)('[GC] Skipping GC: no registered models found.', 'yellow'));\n return;\n }\n console.log((0, utils_1.colorize)(`[GC] Running garbage collector at ${new Date().toISOString()}`, 'blue'));\n const result = await (0, gcManager_1.runGarbageCollectorOnAllModels)({\n ctx,\n continueOnError\n });\n console.log((0, utils_1.colorize)(`[GC] Completed. scanned=${result.scanned}, succeeded=${result.succeeded}, failed=${result.failed}`, result.failed > 0 ? 'yellow' : 'blue'));\n }\n catch (error) {\n console.error((0, utils_1.colorize)('[GC] Error running garbage collector', 'red'), error);\n }\n });\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenClient\"), exports);\ntslib_1.__exportStar(require(\"./ambitenModelFactory\"), exports);\ntslib_1.__exportStar(require(\"./ambitenSchema\"), exports);\ntslib_1.__exportStar(require(\"./bootstrap\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createSchema = void 0;\nconst lib_core_1 = require(\"../../lib-core\");\n/**\n * Creates a new AmbitenSchema instance with the provided schema definition.\n * @param {SchemaDefinition<T> | Record<keyof T, any>} schema - The schema definition for the document.\n * @returns {AmbitenSchema<T>} The created AmbitenSchema instance.\n *\n * @template T - The type of the document.\n * @example\n * const userSchema = createSchema({\n * name: { type: String, required: true },\n * age: { type: Number, required: true },\n * email: { type: String, required: true },\n * });\n * const userModel = new AmbitenModel(userSchema, 'users', db);\n *\n * const user = await userModel.create({ name: 'John Doe', age: 30, email: 'example.com' });\n * console.log(user); // { _id: '...', name: 'John Doe', age: 30, email: 'example.com' }\n *\n */\nconst createSchema = (schema) => {\n return new lib_core_1.AmbitenSchema(schema);\n};\nexports.createSchema = createSchema;\n","\"use strict\";\n/**\n * @author Emmanuel Nodolomwanyi - Ambiten Team\n * @package - @Ambiten/core\n * @version 1.0.0\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.measureQueryForBrowser = exports.AmbitenBootstrapFactory = exports.AmbitenSchema = exports.AmbitenModel = exports.createAmbitenClientModule = exports.AmbitenClient = exports.initializeRedis = void 0;\nconst tslib_1 = require(\"tslib\");\nconst redis_manager_1 = require(\"./redis-manager\");\n/**\n * Ambiten Core Library\n * This library provides core functionalities for Ambiten, ORM/ODM solution\n * for MongoDB in Node.js and Browser environments.\n * @module Ambiten Core Library\n * @version 1.0.0\n */\nconsole.log('Ambiten Core Library Loaded. \\n (Node.js environment detected.)');\nconst initializeRedis = async ({ useRedis = false } = {}) => {\n if (useRedis) {\n const redisClient = redis_manager_1.RedisService.getInstance();\n const client = await redisClient.getClient();\n if (!client.isOpen) {\n await client.connect();\n }\n }\n};\nexports.initializeRedis = initializeRedis;\ntslib_1.__exportStar(require(\"./lib-core/index\"), exports);\ntslib_1.__exportStar(require(\"./lib-core/bootstrap/index\"), exports);\ntslib_1.__exportStar(require(\"./config/index\"), exports);\ntslib_1.__exportStar(require(\"./redis-manager/index\"), exports);\ntslib_1.__exportStar(require(\"./tanancy/index\"), exports);\ntslib_1.__exportStar(require(\"./context/index\"), exports);\ntslib_1.__exportStar(require(\"./plugins/index\"), exports);\ntslib_1.__exportStar(require(\"./instrumentation/index\"), exports);\ntslib_1.__exportStar(require(\"./debug/index\"), exports);\ntslib_1.__exportStar(require(\"./ambiten-cache/index\"), exports);\ntslib_1.__exportStar(require(\"./init-cli/generate.project\"), exports);\ntslib_1.__exportStar(require(\"./middleware/index\"), exports);\ntslib_1.__exportStar(require(\"./graphql/index\"), exports);\ntslib_1.__exportStar(require(\"./utils/index\"), exports);\ntslib_1.__exportStar(require(\"./utils/builders/index\"), exports);\ntslib_1.__exportStar(require(\"./gc/index\"), exports);\ntslib_1.__exportStar(require(\"./types/index\"), exports);\nvar ambitenClient_1 = require(\"./lib-core/ambitenClient\");\nObject.defineProperty(exports, \"AmbitenClient\", { enumerable: true, get: function () { return ambitenClient_1.AmbitenClient; } });\nObject.defineProperty(exports, \"createAmbitenClientModule\", { enumerable: true, get: function () { return ambitenClient_1.createAmbitenClientModule; } });\nvar ambitenModelFactory_1 = require(\"./lib-core/ambitenModelFactory\");\nObject.defineProperty(exports, \"AmbitenModel\", { enumerable: true, get: function () { return ambitenModelFactory_1.AmbitenModel; } });\nvar ambitenSchema_1 = require(\"./lib-core/ambitenSchema\");\nObject.defineProperty(exports, \"AmbitenSchema\", { enumerable: true, get: function () { return ambitenSchema_1.AmbitenSchema; } });\nvar ambitenBootstrap_1 = require(\"./lib-core/bootstrap/ambitenBootstrap\");\nObject.defineProperty(exports, \"AmbitenBootstrapFactory\", { enumerable: true, get: function () { return ambitenBootstrap_1.AmbitenBootstrapFactory; } });\nvar instrumentation_1 = require(\"./instrumentation\");\nObject.defineProperty(exports, \"measureQueryForBrowser\", { enumerable: true, get: function () { return instrumentation_1.measureQueryForBrowser; } });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TenantContext = void 0;\n/**\n * This is legacy code and is not intended for public use. It may be removed in future versions without warning.\n * @deprecated\n * @internal\n * TenantContext provides a thread-safe way to manage tenant-specific data using AsyncLocalStorage.\n * This is particularly useful in multi-tenant applications where you need to track the current tenant across asynchronous operations.\n */\nconst node_async_hooks_1 = require(\"node:async_hooks\");\nconst tenantStorage = new node_async_hooks_1.AsyncLocalStorage();\n/**\n * @deprecated\n * @internal\n *\n * This is legacy code and is not intended for public use. It may be removed in future versions without warning.\n * Provides a thread-safe context for managing tenant-specific data using `AsyncLocalStorage`.\n * This is useful for multi-tenant applications where the current tenant needs to be tracked across asynchronous operations.\n */\nclass TenantContext {\n /**\n * Runs a callback function within a specific tenant context.\n * @param {string} tenantId - The ID of the tenant to set in the context.\n * @param {() => void} callback - The callback function to execute within the tenant context.\n */\n static run(tenantId, callback) {\n if (!tenantId) {\n throw new Error('tenantId is required to run tenant context');\n }\n tenantStorage.run({ tenantId: tenantId }, callback);\n }\n /**\n * Sets the tenant ID in the current context.\n * @param {string} tenantId - The ID of the tenant to set.\n */\n static setTenantId(tenantId) {\n const store = tenantStorage.getStore();\n if (store)\n store.tenantId = tenantId;\n }\n /**\n * Retrieves the tenant ID from the current context.\n * @returns {string | undefined} The tenant ID, or `undefined` if no tenant ID is set.\n */\n static getTenantId() {\n return tenantStorage.getStore()?.tenantId;\n }\n /**\n * Clears the tenant ID from the current context.\n */\n static clear() {\n const store = tenantStorage.getStore();\n if (store)\n store.tenantId = undefined;\n }\n}\nexports.TenantContext = TenantContext;\n;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.RedisService = exports.redis = void 0;\nexports.connectRedis = connectRedis;\nrequire(\"dotenv/config\");\nconst redis_1 = require(\"redis\");\nconst DEFAULT_RECONNECT = (retries) => Math.min(retries * 50, 1000);\nconst redisUrl = process.env.REDIS_URI;\nlet currentClient = null;\nconst createStub = () => ({\n isOpen: false,\n connect: async () => null,\n disconnect: async () => null,\n publish: async () => 0,\n subscribe: async () => null,\n duplicate: () => createStub(),\n get: async () => null,\n set: async () => 'OK',\n del: async () => 0,\n exists: async () => 0,\n scan: async () => ({\n cursor: 0,\n keys: [],\n }),\n multi: () => ({\n incr() {\n return this;\n },\n expire() {\n return this;\n },\n exec: async () => [],\n }),\n});\nexports.redis = {\n async getClient(uri) {\n if (currentClient && currentClient.isOpen) {\n return currentClient;\n }\n const url = uri || redisUrl;\n if (!url) {\n return createStub();\n }\n try {\n const client = (0, redis_1.createClient)({\n url,\n socket: {\n reconnectStrategy: DEFAULT_RECONNECT,\n },\n });\n await client.connect();\n currentClient = client;\n return client;\n }\n catch {\n return createStub();\n }\n },\n async disconnect() {\n if (currentClient) {\n try {\n if (currentClient.isOpen &&\n typeof currentClient.disconnect === 'function') {\n await currentClient.disconnect();\n }\n else if (currentClient.isOpen &&\n typeof currentClient.quit === 'function') {\n await currentClient.quit();\n }\n }\n catch {\n // swallow disconnect errors\n }\n }\n currentClient = null;\n },\n get isOpen() {\n return !!currentClient?.isOpen;\n },\n async get(key) {\n const client = await this.getClient();\n return client.get?.(key);\n },\n async set(key, value, options) {\n const client = await this.getClient();\n return client.set?.(key, value, options);\n },\n async del(...keys) {\n const client = await this.getClient();\n return client.del?.(keys);\n },\n async exists(key) {\n const client = await this.getClient();\n return client.exists?.(key);\n },\n async scan(cursor = 0, options) {\n const client = await this.getClient();\n if (typeof client.scan !== 'function') {\n return {\n cursor: 0,\n keys: [],\n };\n }\n return client.scan(cursor, options);\n },\n async publish(channel, message) {\n const client = await this.getClient();\n return client.publish?.(channel, message);\n },\n async subscribe(channel, listener) {\n const client = await this.getClient();\n return client.subscribe?.(channel, listener);\n },\n duplicate() {\n if (currentClient?.duplicate) {\n return currentClient.duplicate();\n }\n return createStub();\n },\n multi() {\n if (currentClient?.multi) {\n return currentClient.multi();\n }\n return createStub().multi?.();\n },\n};\nclass RedisService {\n static getInstance() {\n return new RedisService();\n }\n async connect(url) {\n await exports.redis.getClient(url);\n }\n getClient() {\n return exports.redis.getClient();\n }\n async close() {\n await exports.redis.disconnect();\n }\n}\nexports.RedisService = RedisService;\nasync function connectRedis() {\n return {\n connect: async (url) => exports.redis.getClient(url),\n };\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.generateGCRunner = generateGCRunner;\nfunction generateGCRunner() {\n return `/**\n * Garbage collector runner\n *\n * Replace the imports below with your actual bootstrap/model entry points.\n */\n\nimport { runGarbageCollector } from './gcManager';\n// import { UserModel } from '../models/UserModel';\n\nasync function main() {\n // Example:\n // await runGarbageCollector(UserModel, { retentionPeriod: 7 });\n console.log('⚠️ Update gcRunner.ts with your model imports before using it.');\n}\n\nmain().catch((error) => {\n console.error('❌ Garbage collector failed:', error);\n process.exit(1);\n});\n`;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getEventOptions = getEventOptions;\nexports.getEventType = getEventType;\nexports.describeEvent = describeEvent;\nexports.logEvent = logEvent;\nexports.logDefaultEvent = logDefaultEvent;\nconst logger_1 = require(\"@ambiten/logger\");\n/**\n * Mapping from event type to option key.\n */\nconst eventOptionMap = {\n \"pre-save\": \"save\",\n \"post-save\": \"save\",\n \"pre-update\": \"update\",\n \"post-update\": \"update\",\n \"pre-delete\": \"delete\",\n \"post-delete\": \"delete\",\n \"aggregate\": \"aggregate\",\n \"disconnect\": \"disconnect\",\n \"connect\": \"connect\",\n \"dropDatabase\": \"dropDatabase\",\n \"createIndex\": \"index\",\n \"dropIndex\": \"index\",\n \"create\": \"create\",\n \"find\": \"find\",\n \"findOne\": \"find\",\n \"insertOne\": \"insertOne\",\n \"insertMany\": \"insertMany\",\n \"updateOne\": \"updateOne\",\n \"updateMany\": \"updateMany\",\n \"deleteOne\": \"deleteOne\",\n \"deleteMany\": \"deleteMany\",\n \"pre-bulkWrite\": \"bulkWrite\",\n \"post-bulkWrite\": \"bulkWrite\",\n \"pre-insertMany\": \"insertMany\",\n \"post-insertMany\": \"insertMany\",\n \"pre-updateMany\": \"updateMany\",\n \"post-updateMany\": \"updateMany\",\n \"pre-deleteMany\": \"deleteMany\",\n \"post-deleteMany\": \"deleteMany\",\n \"transaction\": \"transaction\"\n};\n/**\n * Returns the options object for the given event type.\n * @param eventType - The type of the event.\n * @returns The options for the event.\n */\nfunction getEventOptions(eventType) {\n const key = eventOptionMap[eventType] || eventType;\n return { [key]: true };\n}\n/**\n * Returns the event type based on the options provided.\n * @param options - The options for the event.\n * @returns The event type, or null if not found.\n */\nfunction getEventType(options) {\n const key = Object.keys(options).find((k) => Object.values(eventOptionMap).includes(k));\n if (!key)\n return null;\n // Find the first eventType that maps to this key\n const eventType = Object.keys(eventOptionMap).find((et) => eventOptionMap[et] === key);\n return eventType || null;\n}\n/**\n * Returns a human-readable description for the given event type.\n * @param eventType - The type of the event.\n * @returns The event description.\n */\nfunction describeEvent(eventType) {\n const descriptions = {\n \"pre-save\": \"Before Save\",\n \"post-save\": \"After Save\",\n \"pre-update\": \"Before Update\",\n \"post-update\": \"After Update\",\n \"pre-delete\": \"Before Delete\",\n \"post-delete\": \"After Delete\",\n aggregate: \"Aggregation\",\n disconnect: \"Disconnect\",\n connect: \"Connect\",\n dropDatabase: \"Drop Database\",\n createIndex: \"Create Index\",\n dropIndex: \"Drop Index\",\n create: \"Create\",\n find: \"Find\",\n findOne: \"Find One\",\n insertOne: \"Insert One\",\n insertMany: \"Insert Many\",\n updateOne: \"Update One\",\n updateMany: \"Update Many\",\n deleteOne: \"Delete One\",\n deleteMany: \"Delete Many\",\n };\n return descriptions[eventType] || eventType;\n}\n;\n/**\n * Logs the event action using a provided logger.\n * @param logger - The logger instance (must have a log method).\n * @param eventType - The type of the event.\n * @param message - Optional custom message.\n * @param level - Log level (default: 'info').\n * @param context - Optional context or payload to log.\n */\nfunction logEvent(logger, eventType, message, level = 'info', context) {\n const eventDesc = describeEvent(eventType);\n const logMsg = message\n ? `[Ambiten EVENT]: ${eventDesc}: ${message}`\n : `[Ambiten] Event: ${eventDesc}`;\n const log = {\n level,\n message: logMsg,\n context\n };\n logger.info(`${log.level}${log.message} ${log.context ? JSON.stringify(log.context) : ''}`);\n}\n;\n/**\n * Logs an event with a default logger.\n * @param eventType - The type of the event.\n * @param message - Optional custom message.\n * @param context - Optional context or payload to log.\n * @param level - Log level (default: 'info').\n */\nfunction logDefaultEvent(eventType, message, level, context) {\n const logger = (0, logger_1.setupLogger)(); // Get the default logger instance\n logEvent(logger, eventType, message, level, context);\n return eventType;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Schema = exports.AmbitenSchema = void 0;\n/**\n * The AmbitenSchema class allows you to define a schema for MongoDB documents.\n * It supports:\n * - schema definition\n * - custom validation\n * - indexes\n * - relationships\n * - virtual fields\n * - context-aware middleware\n * - garbage collection metadata\n */\nclass AmbitenSchema {\n schemaDefinition;\n indexes = [];\n virtuals = {};\n validators = {};\n relationships = [];\n gcConfig;\n middleware = {\n pre: {},\n post: {},\n };\n /**\n * Creates an instance of AmbitenSchema.\n * @param schemaDefinition - The schema definition for the document.\n */\n constructor(schemaDefinition) {\n this.schemaDefinition = schemaDefinition;\n }\n /**\n * Retrieves the schema definition.\n */\n getSchema() {\n return this.schemaDefinition;\n }\n /**\n * Re-registers the schema definition.\n */\n registerSchema(schemaDefinition) {\n this.schemaDefinition = schemaDefinition;\n console.info('Schema registered:', this.schemaDefinition);\n }\n /**\n * Adds a custom validator for a specific field.\n */\n validator(field, fn) {\n this.validators[field] = fn;\n }\n /**\n * Validates a document synchronously.\n * Throws if an async validator is encountered.\n */\n validate(doc) {\n for (const [field, validate] of Object.entries(this.validators)) {\n const result = validate(doc[field], doc);\n if (result instanceof Promise) {\n throw new Error(`Validator for field \"${field}\" is async. Use validateAsync() instead.`);\n }\n if (!result) {\n console.log(`[error]: Validation failed for field: ${field}`);\n throw new Error(`Validation failed for field: ${field}`);\n }\n }\n }\n /**\n * Validates a document asynchronously.\n */\n async validateAsync(doc) {\n for (const [field, validate] of Object.entries(this.validators)) {\n const isValid = await validate(doc[field], doc);\n if (!isValid) {\n console.log(`[error]: Validation failed for field: ${field}`);\n throw new Error(`Validation failed for field: ${field}`);\n }\n }\n }\n /**\n * Adds an index to the schema.\n */\n index(fields, options) {\n this.indexes.push({ fields, options });\n }\n /**\n * Applies all defined indexes to a MongoDB collection.\n */\n async applyIndexes(collection) {\n for (const { fields, options } of this.indexes) {\n await collection.createIndex(fields, options);\n }\n }\n /**\n * Adds a relationship to the schema.\n */\n addRelationship(ref, localField) {\n this.relationships.push({ ref, localField });\n }\n /**\n * Retrieves all relationships defined in the schema.\n */\n getRelationships() {\n return this.relationships;\n }\n /**\n * Adds a virtual field to the schema.\n */\n virtual(name, getter) {\n this.virtuals[name] = getter;\n }\n /**\n * Applies all virtual fields to a document.\n */\n applyVirtuals(doc) {\n for (const [key, getter] of Object.entries(this.virtuals)) {\n Object.defineProperty(doc, key, {\n get: () => getter(doc),\n enumerable: true,\n });\n }\n }\n /**\n * Adds a pre-middleware handler for a specific operation.\n */\n pre(operation, fn) {\n if (!this.middleware.pre[operation]) {\n this.middleware.pre[operation] = [];\n }\n this.middleware.pre[operation].push(fn);\n return this;\n }\n /**\n * Adds a post-middleware handler for a specific operation.\n */\n post(operation, fn) {\n if (!this.middleware.post[operation]) {\n this.middleware.post[operation] = [];\n }\n this.middleware.post[operation].push(fn);\n return this;\n }\n /**\n * Returns all pre-middleware for an operation.\n */\n getPreHooks(operation) {\n return this.middleware.pre[operation] || [];\n }\n /**\n * Returns all post-middleware for an operation.\n */\n getPostHooks(operation) {\n return this.middleware.post[operation] || [];\n }\n /**\n * Backward-compatible hook reader.\n * Defaults to pre hooks to avoid breaking older callers that expect getHooks(action).\n */\n getHooks(operation, phase = 'pre') {\n return phase === 'pre'\n ? this.getPreHooks(operation)\n : this.getPostHooks(operation);\n }\n /**\n * Executes pre-middleware for an operation.\n */\n async executePre(operation, ctx) {\n const hooks = this.getPreHooks(operation);\n for (const hook of hooks) {\n await hook(ctx);\n }\n }\n /**\n * Executes post-middleware for an operation.\n */\n async executePost(operation, ctx) {\n const hooks = this.getPostHooks(operation);\n for (const hook of hooks) {\n await hook(ctx);\n }\n }\n /**\n * Executes middleware for a given phase and operation.\n */\n async executeMiddleware(phase, operation, ctx) {\n const hooks = this.getHooks(operation, phase);\n for (const hook of hooks) {\n try {\n await hook(ctx);\n }\n catch (error) {\n console.error(`[error]: Error in ${phase}:${operation} middleware:`, error);\n throw error;\n }\n }\n }\n /**\n * Backward-compatible alias.\n * If older callers use triggerMiddleware(action, data), they should be upgraded\n * to pass explicit phase + operation + context.\n */\n async triggerMiddleware(phase, operation, ctx) {\n await this.executeMiddleware(phase, operation, ctx);\n }\n /**\n * Sets garbage collection configuration.\n */\n setGCConfig(config) {\n this.gcConfig = config;\n return this;\n }\n /**\n * Gets garbage collection configuration.\n */\n getGCConfig() {\n return this.gcConfig;\n }\n}\nexports.AmbitenSchema = AmbitenSchema;\nclass Schema extends AmbitenSchema {\n constructor(schemaDefinition) {\n super(schemaDefinition);\n this.registerSchema(schemaDefinition);\n }\n async create(data) {\n await this.validateAsync(data);\n const ctx = {\n operation: 'create',\n collectionName: 'schema-test',\n doc: data,\n };\n await this.executePre('create', ctx);\n const result = data;\n this.applyVirtuals(result);\n const postCtx = {\n ...ctx,\n result,\n doc: result,\n };\n await this.executePost('create', postCtx);\n return result;\n }\n static create(schemaDefinition) {\n return new Schema(schemaDefinition);\n }\n}\nexports.Schema = Schema;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.generateAppStructure = generateAppStructure;\nconst tslib_1 = require(\"tslib\");\nconst fs_extra_1 = tslib_1.__importDefault(require(\"fs-extra\"));\nconst path_1 = tslib_1.__importDefault(require(\"path\"));\nconst utils_1 = require(\"../../utils\");\nconst generateMainEntry_1 = require(\"../generateMainEntry\");\nconst generateDefaultConfigContent_1 = require(\"../generateDefaultConfigContent\");\nconst generateGCManagerFile_1 = require(\"../generateGCManagerFile\");\nconst generateGCRunnerFile_1 = require(\"../generateGCRunnerFile\");\nfunction buildPackageJson(options) {\n const dependencies = {\n '@ambiten/core': '^1.0.0',\n mongodb: '^6.14.2',\n };\n if (options.logger?.enabled) {\n dependencies['@ambiten/logger'] = '^1.0.0';\n }\n if (options.graphql?.enabled) {\n dependencies['graphql'] = '^16.11.0';\n dependencies['@apollo/server'] = '^5.1.0';\n }\n if (options.features?.useRedisCache) {\n dependencies['redis'] = '^4.7.1';\n }\n return {\n name: options.projectName ?? 'my-ambiten-app',\n description: 'A Ambiten-powered application',\n private: true,\n version: '1.0.0',\n type: 'commonjs',\n main: 'dist/main.js',\n scripts: {\n dev: 'ts-node src/main.ts',\n build: 'tsc',\n start: 'node dist/main.js',\n },\n license: 'ISC',\n dependencies,\n devDependencies: {\n typescript: '^5.9.3',\n 'ts-node': '^10.9.2',\n '@types/node': '^22.15.30',\n },\n };\n}\nfunction buildTsConfig() {\n return {\n compilerOptions: {\n \"target\": \"ES2021\",\n \"module\": \"commonjs\",\n \"moduleResolution\": \"node\",\n \"rootDir\": './src',\n \"outDir\": './dist',\n \"sourceMap\": true,\n \"declaration\": true,\n \"declarationMap\": true,\n \"esModuleInterop\": true,\n \"resolveJsonModule\": true,\n \"strict\": true,\n \"noImplicitAny\": true,\n \"noImplicitReturns\": true,\n \"noUncheckedIndexedAccess\": true,\n \"exactOptionalPropertyTypes\": true,\n \"forceConsistentCasingInFileNames\": true,\n \"skipLibCheck\": true,\n types: ['node'],\n lib: ['ES2021']\n },\n include: ['src/**/*'],\n exclude: ['node_modules', 'dist']\n };\n}\nfunction generateInitAmbitenTS() {\n return `import { AmbitenBootstrapFactory } from '@ambiten/core';\nimport type { AmbitenRuntime } from '@ambiten/core';\n\nexport async function run(): Promise<AmbitenRuntime> {\n return AmbitenBootstrapFactory.create();\n}\n`;\n}\nfunction generateGraphqlStarterTS() {\n return `/**\n * Optional GraphQL starter file.\n *\n * Use this file if you want to separate GraphQL setup from your bootstrap flow.\n * If your bootstrap already initializes GraphQL, this file can be removed.\n */\n\nexport {};\n`;\n}\nasync function generateAppStructure(projectRoot, options, logger) {\n const srcDir = path_1.default.join(projectRoot, 'src');\n const coreDir = path_1.default.join(srcDir, 'core');\n const utilsDir = path_1.default.join(srcDir, 'utils');\n const typesDir = path_1.default.join(srcDir, 'types');\n const modelsDir = path_1.default.join(srcDir, 'models');\n const graphqlDir = path_1.default.join(srcDir, 'graphql');\n const gcDir = path_1.default.join(srcDir, 'gc');\n await fs_extra_1.default.ensureDir(srcDir);\n logger?.addDir(srcDir);\n await fs_extra_1.default.ensureDir(coreDir);\n logger?.addDir(coreDir);\n await fs_extra_1.default.ensureDir(utilsDir);\n logger?.addDir(utilsDir);\n await fs_extra_1.default.ensureDir(typesDir);\n logger?.addDir(typesDir);\n await fs_extra_1.default.ensureDir(modelsDir);\n logger?.addDir(modelsDir);\n if (options.graphql?.enabled) {\n await fs_extra_1.default.ensureDir(graphqlDir);\n logger?.addDir(graphqlDir);\n }\n if (options.advanced?.garbageCollector?.enabled) {\n await fs_extra_1.default.ensureDir(gcDir);\n logger?.addDir(gcDir);\n }\n const mainPath = path_1.default.join(srcDir, 'main.ts');\n await fs_extra_1.default.writeFile(mainPath, (0, generateMainEntry_1.generateMainTS)(options));\n logger?.addFile(mainPath);\n const initAmbitenPath = path_1.default.join(coreDir, 'initAmbiten.ts');\n await fs_extra_1.default.writeFile(initAmbitenPath, generateInitAmbitenTS());\n logger?.addFile(initAmbitenPath);\n const helperPath = path_1.default.join(utilsDir, 'helper.ts');\n await fs_extra_1.default.writeFile(helperPath, `export function noop(): void {}\\n`);\n logger?.addFile(helperPath);\n const configTypesPath = path_1.default.join(typesDir, 'config.ts');\n await fs_extra_1.default.writeFile(configTypesPath, `export {};\\n`);\n logger?.addFile(configTypesPath);\n if (options.graphql?.enabled) {\n const schemaPath = path_1.default.join(graphqlDir, 'schema.gql');\n await fs_extra_1.default.writeFile(schemaPath, `type Query {\n hello: String\n}\n`);\n logger?.addFile(schemaPath);\n const resolversPath = path_1.default.join(graphqlDir, 'resolvers.ts');\n await fs_extra_1.default.writeFile(resolversPath, `export const resolvers = {\n Query: {\n hello: () => 'Hello, world!',\n },\n};\n`);\n logger?.addFile(resolversPath);\n await fs_extra_1.default.writeFile(path_1.default.join(graphqlDir, 'graphql.ts'), generateGraphqlStarterTS());\n }\n if (options.advanced?.garbageCollector?.enabled) {\n const gcManagerPath = path_1.default.join(gcDir, 'gcManager.ts');\n await fs_extra_1.default.writeFile(gcManagerPath, (0, generateGCManagerFile_1.generateGCManager)());\n logger?.addFile(gcManagerPath);\n const gcRunnerPath = path_1.default.join(gcDir, 'gcRunner.ts');\n await fs_extra_1.default.writeFile(gcRunnerPath, (0, generateGCRunnerFile_1.generateGCRunner)());\n logger?.addFile(gcRunnerPath);\n }\n const configPath = path_1.default.join(projectRoot, 'ambiten.config.json');\n await fs_extra_1.default.writeFile(configPath, (0, generateDefaultConfigContent_1.DEFAULT_CONFIG_CONTENT)(options));\n logger?.addFile(configPath);\n const packageJsonPath = path_1.default.join(projectRoot, 'package.json');\n await fs_extra_1.default.writeJson(packageJsonPath, buildPackageJson(options), { spaces: 2 });\n logger?.addFile(packageJsonPath);\n const tsconfigPath = path_1.default.join(projectRoot, 'tsconfig.json');\n await fs_extra_1.default.writeJson(tsconfigPath, buildTsConfig(), { spaces: 2 });\n logger?.addFile(tsconfigPath);\n const gitignorePath = path_1.default.join(projectRoot, '.gitignore');\n await fs_extra_1.default.writeFile(gitignorePath, `node_modules\ndist\nlib\n.store\n.env\n`);\n logger?.addFile(gitignorePath);\n if (options.advanced?.autoInstall) {\n const packageManager = (0, utils_1.detectPackageManager)(projectRoot);\n try {\n await (0, utils_1.installPackages)([], projectRoot);\n console.log((0, utils_1.colorize)(`[Installing dependencies]: Installed project dependencies using ${packageManager}.`, 'green'));\n }\n catch (error) {\n console.log((0, utils_1.colorize)('⚠️ Dependency installation failed or was interrupted. Skipping install.', 'yellow'), error);\n }\n }\n else {\n const packageManager = (0, utils_1.detectPackageManager)(projectRoot);\n const installCommand = packageManager === 'npm'\n ? 'npm install'\n : `${packageManager} install`;\n console.log((0, utils_1.colorize)('[Skipping install]: Set advanced.autoInstall=true to install dependencies automatically.', 'blue'));\n console.log((0, utils_1.colorize)(`[Next steps]: cd ${projectRoot} && ${installCommand}`, 'blue'));\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.rolePermissions = void 0;\nexports.rolePermissions = {\n admin: ['create', 'read', 'update', 'delete'],\n user: ['create', 'read', 'update'],\n viewer: ['read'],\n};\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.generateGCManager = generateGCManager;\nfunction generateGCManager() {\n return `import { AmbitenModel } from '@ambiten/core';\nimport { ObjectId } from 'mongodb';\n\nexport interface GarbageCollectorOptions {\n /**\n * Retention period in days.\n */\n retentionPeriod?: number;\n dateField?: string;\n}\n\nexport async function runGarbageCollector(\n model: AmbitenModel<any>,\n options: GarbageCollectorOptions = {}\n): Promise<void> {\n const retentionPeriod = options.retentionPeriod ?? 7;\n const dateField = options.dateField ?? 'deletedAt';\n\n const cutoff = new Date(\n Date.now() - retentionPeriod * 24 * 60 * 60 * 1000\n );\n\n const expiredDocs = await model.find({\n [dateField]: { $lt: cutoff }\n });\n\n for (const doc of expiredDocs) {\n await model.deleteOne({ _id: new ObjectId(doc._id) });\n console.log(\\`🗑️ Deleted expired document: \\${doc._id}\\`);\n }\n\n console.log('✅ Garbage collection completed.');\n}\n`;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.hasManualTransactionMethods = hasManualTransactionMethods;\nfunction hasManualTransactionMethods(session) {\n return (typeof session.startTransaction === 'function' &&\n typeof session.commitTransaction === 'function' &&\n typeof session.abortTransaction === 'function');\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.initMultiTenancy = void 0;\nconst MultiTenantManager_1 = require(\"../MultiTenantManager\");\n/**\n * Initializes multi-tenancy by registering tenants with their respective MongoDB URIs.\n * Supports both lazy (on-demand) and eager connection strategies.\n *\n * @param {Record<string, string>} tenants - A record of tenant IDs mapped to their MongoDB URIs.\n * @param {InitMultiTenancyOptions} [options={}] - Optional configuration for multi-tenancy initialization.\n * @param {boolean} [options.lazy=false] - If `true`, tenants are registered lazily (connected on-demand).\n * @param {AmbitenConfig} [options.config] - Optional configuration, including a logger for logging messages.\n * @returns {Promise<void>} A promise that resolves when all tenants are registered.\n * @throws {Error} If a tenant's MongoDB URI is invalid or missing.\n * @throws {Error} If a tenant is already registered and `lazy` is `false`.\n * @example\n * // Initialize multi-tenancy with eager connection. Practically, you should use applyMultiTenancy instead.\n * that implements this function.\n * await initMultiTenancy({\n * 'tenant-a': 'mongodb://localhost:27017/tenant-a',\n * 'tenant-b': 'mongodb://localhost:27017/tenant-b'\n * }, {\n * lazy: false,\n * config: {}\n */\nconst initMultiTenancy = async (tenants, // tenantId => MongoDB URI\noptions = {}) => {\n const { lazy = false, config } = options;\n for (const [tenantId, uri] of Object.entries(tenants)) {\n if (!uri || typeof uri !== 'string' || !uri.startsWith('mongodb')) {\n throw new Error(`Invalid MongoDB URI for tenant \"${tenantId}\": ${uri}`);\n }\n if (MultiTenantManager_1.MultiTenantManager.hasTenant(tenantId)) {\n config?.logger?.warn?.(`Tenant \"${tenantId}\" is already registered. Skipping.`);\n continue;\n }\n if (lazy) {\n // Ensure logger implements all required methods for core/src/types/logger.types.ts\n if (config?.enabled && config.logger) {\n const logger = config.logger;\n return logger;\n }\n MultiTenantManager_1.MultiTenantManager.registerLazyTenant(tenantId, uri);\n continue;\n }\n else {\n // Eagerly connect\n await MultiTenantManager_1.MultiTenantManager.registerTenant(tenantId, uri);\n }\n }\n};\nexports.initMultiTenancy = initMultiTenancy;\nfunction impl_Logger(logger) {\n const { info, warn, error, fatal, debug } = logger;\n return {\n info: info?.bind(logger) ?? (() => { }),\n warn: warn?.bind(logger) ?? (() => { }),\n error: error?.bind(logger) ?? (() => { }),\n fatal: fatal?.bind(logger) ?? (() => { }),\n debug: debug?.bind(logger) ?? (() => { }),\n };\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenGraphQL = void 0;\nrequire(\"dotenv/config\");\nconst schema_1 = require(\"@graphql-tools/schema\");\nconst graphql_tag_1 = require(\"graphql-tag\");\nconst mongodb_1 = require(\"mongodb\");\nconst redis_manager_1 = require(\"../redis-manager\");\nconst utils_1 = require(\"../utils\");\nclass AmbitenGraphQL {\n options;\n typeDefs = [];\n resolvers = [];\n useRedis;\n provider;\n subscriber = null;\n publisher = null;\n constructor(options) {\n this.options = options;\n this.useRedis = options.useRedis !== false;\n this.typeDefs = options.customTypeDefs ?? [];\n this.resolvers = options.customResolvers ?? [];\n this.provider = options.provider;\n }\n customTypeDefs(schema) {\n if (Array.isArray(schema)) {\n this.typeDefs.push(...schema);\n }\n else {\n this.typeDefs.push(schema);\n }\n return this;\n }\n customResolvers(resolver) {\n this.resolvers.push(resolver);\n return this;\n }\n toModelContext(context, collectionName) {\n return {\n tenantId: context.tenantId,\n dbName: context.dbName,\n collectionName: collectionName ?? context.collectionName,\n session: context.session\n };\n }\n async getCollection(context, collectionName) {\n const ctx = this.toModelContext(context, collectionName);\n return context.provider.collection(collectionName, ctx);\n }\n async ensureRedis() {\n if (!this.useRedis) {\n return;\n }\n const client = await redis_manager_1.redis.get();\n if (!client) {\n return;\n }\n if (!client.isOpen && typeof client.connect === 'function') {\n await client.connect();\n }\n if (!this.publisher) {\n this.publisher = typeof client.duplicate === 'function' ? client.duplicate() : client;\n if (this.publisher?.connect && !this.publisher.isOpen) {\n await this.publisher.connect();\n }\n }\n if (!this.subscriber) {\n this.subscriber = typeof client.duplicate === 'function' ? client.duplicate() : client;\n if (this.subscriber?.connect && !this.subscriber.isOpen) {\n await this.subscriber.connect();\n }\n }\n }\n async publishEvent(channel, payload) {\n if (!this.useRedis) {\n return;\n }\n await this.ensureRedis();\n const client = await redis_manager_1.redis.get();\n if (this.publisher?.publish) {\n await this.publisher.publish(channel, JSON.stringify(payload));\n return;\n }\n if (client?.publish) {\n await client.publish(channel, JSON.stringify(payload));\n }\n }\n defaultTypeDefs() {\n return (0, graphql_tag_1.gql) `\n scalar JSON\n\n type Document {\n _id: ID!\n }\n\n type Query {\n findOne(collection: String!, id: ID!): JSON\n findAll(collection: String!): [JSON!]!\n }\n\n type Mutation {\n insertOne(collection: String!, data: JSON!): JSON\n updateOne(collection: String!, id: ID!, data: JSON!): JSON\n deleteOne(collection: String!, id: ID!): Boolean\n }\n\n type Subscription {\n documentInserted(collection: String!): JSON\n documentUpdated(collection: String!): JSON\n documentDeleted(collection: String!): JSON\n }\n `;\n }\n defaultResolvers() {\n return {\n Query: {\n findOne: async (_, { collection, id }, context) => {\n const col = await this.getCollection(context, collection);\n return col.findOne({ _id: new mongodb_1.ObjectId(id) });\n },\n findAll: async (_, { collection }, context) => {\n const col = await this.getCollection(context, collection);\n return col.find({}).toArray();\n }\n },\n Mutation: {\n insertOne: async (_, { collection, data }, context) => {\n const col = await this.getCollection(context, collection);\n const result = await col.insertOne(data);\n const newDoc = await col.findOne({ _id: result.insertedId });\n await this.publishEvent(`${utils_1.DB_CHANGE_EVENT}`, {\n documentInserted: {\n action: 'insertOne',\n collectionName: collection,\n doc: newDoc,\n tenantId: context.tenantId\n }\n });\n return newDoc;\n },\n updateOne: async (_, { collection, id, data }, context) => {\n const col = await this.getCollection(context, collection);\n await col.updateOne({ _id: new mongodb_1.ObjectId(id) }, { $set: data });\n const updatedDoc = await col.findOne({ _id: new mongodb_1.ObjectId(id) });\n await this.publishEvent(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'updateOne',\n collectionName: collection,\n doc: updatedDoc,\n tenantId: context.tenantId\n }\n });\n return updatedDoc;\n },\n deleteOne: async (_, { collection, id }, context) => {\n const col = await this.getCollection(context, collection);\n const result = await col.deleteOne({ _id: new mongodb_1.ObjectId(id) });\n if (result.deletedCount === 1) {\n await this.publishEvent(`${utils_1.DB_CHANGE_EVENT}`, {\n documentDeleted: {\n action: 'deleteOne',\n collectionName: collection,\n id,\n tenantId: context.tenantId\n }\n });\n return true;\n }\n return false;\n }\n },\n Subscription: {\n documentInserted: {\n subscribe: async () => {\n if (!this.useRedis) {\n return null;\n }\n await this.ensureRedis();\n return this.subscriber;\n }\n },\n documentUpdated: {\n subscribe: async () => {\n if (!this.useRedis) {\n return null;\n }\n await this.ensureRedis();\n return this.subscriber;\n }\n },\n documentDeleted: {\n subscribe: async () => {\n if (!this.useRedis) {\n return undefined;\n }\n await this.ensureRedis();\n return this.subscriber;\n }\n }\n }\n };\n }\n subscriptions() {\n return this.useRedis;\n }\n async generateSchema() {\n await this.ensureRedis();\n return (0, schema_1.makeExecutableSchema)({\n typeDefs: [this.defaultTypeDefs(), ...this.typeDefs],\n resolvers: [this.defaultResolvers(), ...this.resolvers]\n });\n }\n}\nexports.AmbitenGraphQL = AmbitenGraphQL;\n;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ErrorType = void 0;\nvar ErrorType;\n(function (ErrorType) {\n ErrorType[\"AmbitenError\"] = \"AmbitenError\";\n ErrorType[\"AmbitenErrorType\"] = \"AmbitenErrorType\";\n ErrorType[\"AmbitenErrorStack\"] = \"AmbitenErrorStack\";\n ErrorType[\"AmbitenErrorMessage\"] = \"AmbitenErrorMessage\";\n ErrorType[\"AmbitenErrorCause\"] = \"AmbitenErrorCause\";\n ErrorType[\"AmbitenCollectionError\"] = \"CollectionError\";\n ErrorType[\"AmbitenParseError\"] = \"ParseError\";\n ErrorType[\"AmbitenBulkWriteError\"] = \"MongoBulkWriteError\";\n ErrorType[\"AmbitenConnectionError\"] = \"ConnectionError\";\n ErrorType[\"AmbitenSchemaError\"] = \"SchemaError\";\n ErrorType[\"AmbitenModelError\"] = \"ModelError\";\n ErrorType[\"INITIALIZATION_ERROR\"] = \"INITIALIZATION_ERROR\";\n ErrorType[\"Ambiten_ERROR\"] = \"Ambiten_ERROR\";\n ErrorType[\"NULL_OR_UNDEFINED\"] = \"NULL_OR_UNDEFINED\";\n ErrorType[\"INVALID_SCHEME_ERROR\"] = \"INVALID_SCHEME_ERROR\";\n ErrorType[\"CONNECTION_ERROR\"] = \"CONNECTION_ERROR\";\n ErrorType[\"UNEXPECTED_ERROR\"] = \"UNEXPECTED_ERROR\";\n ErrorType[\"SCHEMA_ERROR\"] = \"SCHEMA_ERROR\";\n ErrorType[\"SCHEMA_VALIDATION_ERROR\"] = \"SCHEMA_VALIDATION_ERROR\";\n ErrorType[\"NOT_FOUND\"] = \"NOT_FOUND\";\n ErrorType[\"NO_DATABASE_FOUND\"] = \"NO_DATABASE_FOUND\";\n ErrorType[\"NOT_FOUND_IN_CACHE\"] = \"NOT_FOUND_IN_CACHE\";\n ErrorType[\"VALIDATION_ERROR\"] = \"VALIDATION_ERROR\";\n ErrorType[\"UNIQUE_CONSTRAINT_VIOLATION\"] = \"UNIQUE_CONSTRAINT_VIOLATION\";\n})(ErrorType || (exports.ErrorType = ErrorType = {}));\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AuthService = void 0;\nconst tslib_1 = require(\"tslib\");\nconst jsonwebtoken_1 = tslib_1.__importDefault(require(\"jsonwebtoken\"));\nrequire(\"dotenv/config\");\nconst SECRET = process.env.JWT_SECRET;\nconst REFRESH_SECRET = process.env.REFRESH_SECRET;\nconst REFRESH_EXPIRATION = process.env.REFRESH_EXPIRATION || '7d';\nconst JWT_EXPIRATION = process.env.JWT_EXPIRATION || '1d';\nclass AuthService {\n static generateToken(user) {\n return jsonwebtoken_1.default.sign(user, SECRET, {\n expiresIn: JWT_EXPIRATION\n });\n }\n static generateRefreshToken(user) {\n return jsonwebtoken_1.default.sign(user, REFRESH_SECRET, {\n expiresIn: REFRESH_EXPIRATION\n });\n }\n static verifyToken(token) {\n return jsonwebtoken_1.default.verify(token, SECRET);\n }\n}\nexports.AuthService = AuthService;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isValidObjectId = void 0;\nexports.isObjectId = isObjectId;\nexports.castId = castId;\nconst symbols_1 = require(\"./symbols\");\nconst mongodb_1 = require(\"mongodb\");\nObject.defineProperty(mongodb_1.ObjectId.prototype, \"_id\", {\n configurable: true,\n enumerable: true,\n get: function () {\n return this.toHexString();\n }\n});\nif (!Object.prototype.hasOwnProperty.call(mongodb_1.ObjectId.prototype, 'valueOf')) {\n mongodb_1.ObjectId.prototype.valueOf = function objectIdValueOf() {\n return this.toString();\n };\n}\nconst isValidObjectId = (id) => {\n return /^[0-9a-fA-F]{24}$/.test(id);\n};\nexports.isValidObjectId = isValidObjectId;\nmongodb_1.ObjectId.prototype.toJSON = function objectIdToJSON() {\n return this.toHexString();\n};\nmongodb_1.ObjectId.prototype[symbols_1.objectIdSymbol] = true;\nfunction isObjectId(id) {\n if (id == null)\n return false;\n if (typeof id !== \"object\")\n return false;\n if (id.constructor !== mongodb_1.ObjectId)\n return false;\n if (id[symbols_1.objectIdSymbol] !== true)\n return false;\n return true;\n}\n// Casts a string to an ObjectId\nfunction castId(inputId) {\n if (typeof inputId === \"string\") {\n const _id = inputId;\n if (!(0, exports.isValidObjectId)(_id)) {\n throw new Error(\"Invalid ObjectId format in castId\");\n }\n if (!isObjectId(inputId)) {\n throw new Error(\"Invalid ObjectId in castId\");\n }\n return mongodb_1.ObjectId.createFromHexString(_id);\n }\n return inputId;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenBootstrapFactory = void 0;\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenBootstrap\"), exports);\nvar ambitenBootstrap_1 = require(\"./ambitenBootstrap\");\nObject.defineProperty(exports, \"AmbitenBootstrapFactory\", { enumerable: true, get: function () { return ambitenBootstrap_1.AmbitenBootstrapFactory; } });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./rbac/rbacMiddleware\"), exports);\ntslib_1.__exportStar(require(\"./rbac/rbacTypes\"), exports);\ntslib_1.__exportStar(require(\"./authorization/auth\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.ensureModelNameSafe = ensureModelNameSafe;\n/**\n * Ensures that the provided model name is a valid, non-empty string.\n * Throws an error if the model name is invalid.\n *\n * @param {string} collectionName - The collection name to validate.\n * @returns {string} - The validated model name.\n * @throws {Error} - If the model name is invalid.\n * @example\n * const safeModelName = ensureModelNameSafe('MyModel123');\n */\nfunction ensureModelNameSafe(collectionName) {\n if (!collectionName || typeof collectionName !== 'string') {\n throw new Error('Model name must be a non-empty string');\n }\n const trimmedName = collectionName.trim();\n if (trimmedName.length === 0) {\n throw new Error('Model name cannot be just whitespace');\n }\n // Optional: Enforce allowed characters (letters, numbers, underscores)\n const nameRegex = /^[A-Za-z0-9_]+$/;\n if (!nameRegex.test(trimmedName)) {\n throw new Error('Model name must only contain letters, numbers, and underscores');\n }\n return trimmedName;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getModelFilesFromPath = getModelFilesFromPath;\nexports.loadModelsFromPath = loadModelsFromPath;\nconst tslib_1 = require(\"tslib\");\nconst fs_1 = tslib_1.__importDefault(require(\"fs\"));\nconst path_1 = tslib_1.__importDefault(require(\"path\"));\nfunction getModelFilesFromPath(dirPath) {\n const files = [];\n fs_1.default.readdirSync(dirPath).forEach((file) => {\n const fullPath = path_1.default.join(dirPath, file);\n const stat = fs_1.default.statSync(fullPath);\n if (stat.isDirectory()) {\n files.push(...getModelFilesFromPath(fullPath)); // Recursively load subfolders\n }\n else if (/\\.(ts|js)$/.test(file)) {\n files.push(fullPath);\n }\n });\n return files;\n}\n;\nasync function loadModelsFromPath(dirPath) {\n const modelFiles = getModelFilesFromPath(dirPath);\n const models = [];\n for (const file of modelFiles) {\n try {\n const modelModule = await import(file);\n if (modelModule.default) {\n models.push(modelModule.default);\n }\n else {\n console.warn(`No default export found in ${file}`);\n }\n }\n catch (error) {\n console.error(`Error loading model from ${file}:`, error);\n }\n }\n return models;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenGraphQL\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenGC\"), exports);\ntslib_1.__exportStar(require(\"./gcCron.node\"), exports);\ntslib_1.__exportStar(require(\"./gcManager\"), exports);\ntslib_1.__exportStar(require(\"./gcCron.browser\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.authorize = authorize;\nconst AuthUtils_1 = require(\"../../utils/AuthUtils\");\n/**\n * Middleware to authorize access to routes based on user roles.\n * This middleware checks if the request contains a valid JWT token,\n * @param roles - An array of roles that are allowed to access the route.\n * @returns\n */\nfunction authorize(roles) {\n return (req, res, next) => {\n let token;\n const authHeader = req.headers?.authorization || req.headers.Authorization;\n if (typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {\n token = authHeader.split(' ')[1];\n }\n if (!token) {\n return res.status(401).json({ error: \"Access token required\" });\n }\n try {\n const decoded = AuthUtils_1.AuthService.verifyToken(token);\n console.info(`Decoded token: ${JSON.stringify(decoded)}`);\n if (!decoded) {\n return res.status(401).json({ error: \"Unauthorized\" });\n }\n if (!roles.includes(decoded.role)) {\n return res.status(403).json({ error: \"Access Denied\" });\n }\n return decoded;\n next();\n }\n catch {\n res.status(401).json({ error: \"Unauthorized\" });\n }\n };\n}\n","module.exports = __WEBPACK_EXTERNAL_MODULE__8535__;","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenModelRegistry = void 0;\nexports.clearModelRegistryForTests = clearModelRegistryForTests;\nconst modelRegistry = new Set();\n/**\n * AmbitenModelRegistry manages registered Ambiten model instances.\n */\nexports.AmbitenModelRegistry = {\n registerModel(model) {\n modelRegistry.add(model);\n },\n getRegisteredModel(model) {\n return modelRegistry.has(model) ? model : null;\n },\n isModelRegistered(model) {\n return modelRegistry.has(model);\n },\n unregisterModel(model) {\n modelRegistry.delete(model);\n },\n getAllModels() {\n return [...modelRegistry];\n },\n clear() {\n modelRegistry.clear();\n }\n};\nconst registeredModels = [];\nfunction clearModelRegistryForTests() {\n for (const model of registeredModels) {\n exports.AmbitenModelRegistry.unregisterModel(model);\n }\n registeredModels.length = 0;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenContext\"), exports);\ntslib_1.__exportStar(require(\"./helpers/transactionSession\"), exports);\ntslib_1.__exportStar(require(\"./helpers/runManualTransaction\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenGC = void 0;\nconst tslib_1 = require(\"tslib\");\nconst cron = tslib_1.__importStar(require(\"node-cron\"));\nconst utils_1 = require(\"../utils\");\nconst gcManager_1 = require(\"./gcManager\");\nclass AmbitenGC {\n options;\n enabled;\n intervalMs;\n intervalRef = null;\n cronTask = null;\n constructor(options = {}) {\n this.options = options;\n this.enabled = options.enabled !== false;\n this.intervalMs = options.interval\n ? this.parseInterval(options.interval)\n : 60_000;\n if (options.retentionPeriod) {\n this.intervalMs = options.retentionPeriod * 24 * 60 * 60 * 1000;\n }\n if (!this.enabled) {\n this.log('info', '[AmbitenGC] Garbage Collector is disabled.');\n return;\n }\n if (options.cron) {\n this.cronTask = cron.schedule(options.cron, () => {\n void this.runOnce();\n });\n this.log('info', `[AmbitenGC] Cron schedule set to: ${options.cron}`);\n return;\n }\n if (options.interval) {\n this.start();\n this.log('info', `[AmbitenGC] Interval set to: ${options.interval}`);\n return;\n }\n this.log('info', '[AmbitenGC] Initialized. Manual run mode enabled.');\n }\n /**\n * Starts interval-based garbage collection.\n */\n start() {\n if (!this.enabled) {\n return;\n }\n if (this.intervalRef) {\n return;\n }\n this.intervalRef = setInterval(() => {\n void this.runOnce();\n }, this.intervalMs);\n this.log('info', `[AmbitenGC] Started GC loop every ${this.intervalMs} ms`);\n }\n /**\n * Stops interval or cron-based garbage collection.\n */\n stop() {\n if (this.intervalRef) {\n clearInterval(this.intervalRef);\n this.intervalRef = null;\n }\n if (this.cronTask) {\n this.cronTask.stop();\n this.cronTask = null;\n }\n this.log('info', '[AmbitenGC] Stopped.');\n }\n /**\n * Runs garbage collection once across registered models.\n *\n * @param ctx - Optional model execution context override.\n * @returns Summary of the GC run.\n */\n async runOnce(ctx) {\n if (!this.enabled) {\n return {\n scanned: 0,\n succeeded: 0,\n failed: 0,\n models: []\n };\n }\n const result = await (0, gcManager_1.runGarbageCollectorOnAllModels)({\n ctx: ctx ?? this.options.ctx,\n continueOnError: this.options.continueOnError ?? true\n });\n if (this.options.logResults) {\n this.log(result.failed > 0 ? 'warn' : 'info', `[AmbitenGC] Completed. scanned=${result.scanned}, succeeded=${result.succeeded}, failed=${result.failed}`);\n }\n return result;\n }\n /**\n * Parses interval strings such as \"30s\", \"5m\", \"1h\", or \"1d\".\n *\n * @param duration - Interval duration.\n * @returns Duration in milliseconds.\n * @throws {Error} When the interval format is invalid.\n */\n parseInterval(duration) {\n const match = duration.match(/^(\\d+)([smhd])$/);\n if (!match) {\n throw new Error(`Invalid interval format: ${duration}`);\n }\n const [, num, unit] = match;\n const value = Number.parseInt(num, 10);\n switch (unit) {\n case 's':\n return value * 1000;\n case 'm':\n return value * 60 * 1000;\n case 'h':\n return value * 60 * 60 * 1000;\n case 'd':\n return value * 24 * 60 * 60 * 1000;\n default:\n throw new Error(`Unknown time unit: ${unit}`);\n }\n }\n log(level, message, meta) {\n const logger = this.options.logger;\n if (logger?.[level]) {\n logger[level]?.(message, meta);\n return;\n }\n if (level === 'error') {\n console.error((0, utils_1.colorize)(message, 'red'), meta ?? '');\n return;\n }\n if (level === 'warn') {\n console.warn((0, utils_1.colorize)(message, 'yellow'), meta ?? '');\n return;\n }\n console.log((0, utils_1.colorize)(message, 'blue'), meta ?? '');\n }\n}\nexports.AmbitenGC = AmbitenGC;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.invalidateTenantCache = invalidateTenantCache;\n/**\n * Invalidates the cache for a specific tenant by deleting all keys that match the tenant ID.\n * Optionally, a namespace can be provided to further filter the keys.\n *\n * @param {RedisClientType} client - The Redis client instance.\n * @param {string} tenantId - The ID of the tenant whose cache should be invalidated.\n * @param {string} [namespace] - Optional namespace to filter keys.\n * @example\n * // Invalidate cache for tenant 'tenant123'\n * invalidateTenantCache(redisClient, 'tenant123');\n * @example\n * // Invalidate cache for tenant 'tenant123' with namespace 'users'\n * invalidateTenantCache(redisClient, 'tenant123', 'users');\n */\nasync function invalidateTenantCache(client, tenantId, namespace) {\n const pattern = namespace\n ? `ambiten:${tenantId}:${namespace}:*`\n : `ambiten:${tenantId}:*`;\n const keys = await client.keys(pattern);\n if (keys.length) {\n await client.del(keys);\n console.info(`🔁 Cleared ${keys.length} cache entries for ${tenantId}${namespace ? ` (${namespace})` : ''}`);\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.eventTypes = void 0;\nexports.eventTypes = [\n 'pre-save',\n 'post-save',\n 'pre-update',\n 'post-update',\n 'pre-delete',\n 'post-delete',\n 'aggregate',\n 'disconnect',\n 'connect',\n 'dropDatabase',\n 'createIndex',\n 'dropIndex',\n 'create',\n 'find',\n 'findOne',\n 'insertOne',\n 'insertMany',\n 'updateOne',\n 'updateMany',\n 'deleteOne',\n 'deleteMany',\n 'transaction'\n];\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.startGarbageCollector = void 0;\nconst utils_1 = require(\"../utils\");\nconst startGarbageCollector = () => {\n // No-op for browsers\n console.warn((0, utils_1.colorize)('[GC] Garbage collector is disabled in the browser.', 'red'));\n};\nexports.startGarbageCollector = startGarbageCollector;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.measureQuery = measureQuery;\nconst perf_hooks_1 = require(\"perf_hooks\");\nconst ambitenContext_1 = require(\"../context/ambitenContext\");\nasync function measureQuery(meta, executor) {\n if (!ambitenContext_1.AmbitenContext.hasActiveContext()) {\n throw new Error('[Ambiten] Missing runtime context.');\n }\n const logger = ambitenContext_1.AmbitenContext.getLogger();\n const observer = ambitenContext_1.AmbitenContext.getObserver();\n const loggerMeta = ambitenContext_1.AmbitenContext.getLoggerMeta() ?? {};\n const tenantId = ambitenContext_1.AmbitenContext.getTenantId();\n const requestId = ambitenContext_1.AmbitenContext.getRequestId();\n const dbName = ambitenContext_1.AmbitenContext.getDbName();\n const collectionName = meta.collectionName ?? ambitenContext_1.AmbitenContext.getCollectionName();\n const budgetAfterIncrement = ambitenContext_1.AmbitenContext.incrementQueries();\n const start = perf_hooks_1.performance.now();\n try {\n const result = await executor();\n const durationMs = Math.round((perf_hooks_1.performance.now() - start) * 100) / 100;\n const budgetAfterTime = ambitenContext_1.AmbitenContext.addQueryTime(durationMs);\n const payload = {\n operation: meta.operation,\n collectionName,\n durationMs,\n status: 'success',\n tenantId,\n requestId,\n dbName,\n filter: meta.filter,\n update: meta.update,\n pipeline: meta.pipeline,\n documentCount: meta.documentCount,\n queriesExecuted: budgetAfterIncrement.queriesExecuted,\n maxQueries: budgetAfterIncrement.maxQueries,\n totalBudgetUsed: budgetAfterTime.totalTimeMs,\n ...loggerMeta,\n ...(meta.extra ?? {})\n };\n setImmediate(() => {\n observer?.onQuery?.(payload);\n if (logger?.info) {\n logger.info('[Ambiten Query]', payload);\n }\n else if (ambitenContext_1.AmbitenContext.isDebug()) {\n console.log('[Ambiten Query]', payload);\n }\n });\n return result;\n }\n catch (error) {\n const durationMs = Math.round((perf_hooks_1.performance.now() - start) * 100) / 100;\n const budgetAfterTime = ambitenContext_1.AmbitenContext.addQueryTime(durationMs);\n const payload = {\n operation: meta.operation,\n collectionName,\n durationMs,\n status: 'error',\n tenantId,\n requestId,\n dbName,\n filter: meta.filter,\n update: meta.update,\n pipeline: meta.pipeline,\n documentCount: meta.documentCount,\n queriesExecuted: budgetAfterTime.queriesExecuted,\n maxQueries: budgetAfterTime.maxQueries,\n totalBudgetUsed: budgetAfterTime.totalTimeMs,\n errorMessage: error?.message,\n errorName: error?.name,\n ...loggerMeta,\n ...(meta.extra ?? {})\n };\n setImmediate(() => {\n observer?.onQueryError?.({\n ...payload,\n error\n });\n if (logger?.error) {\n logger.error('[Ambiten Query Error]', payload);\n }\n else if (ambitenContext_1.AmbitenContext.isDebug()) {\n console.error('[Ambiten Query Error]', payload);\n }\n });\n throw error;\n }\n}\n;\n","module.exports = require(\"@ambiten/logger\");","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./debugLog\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AmbitenModel = void 0;\nconst tslib_1 = require(\"tslib\");\nrequire(\"dotenv/config\");\nconst mongodb_1 = require(\"mongodb\");\nconst ambitenClient_1 = require(\"./ambitenClient\");\nconst ambitenSchema_1 = require(\"./ambitenSchema\");\nconst events_1 = tslib_1.__importDefault(require(\"events\"));\nconst graphql_subscriptions_1 = require(\"graphql-subscriptions\");\nconst tanancy_1 = require(\"../tanancy\");\nconst redis_manager_1 = require(\"../redis-manager\");\nconst utils_1 = require(\"../utils\");\nconst context_1 = require(\"../context\");\nconst instrumentation_1 = require(\"../instrumentation\");\nconst debug_1 = require(\"../debug\");\nconst pubsub = new graphql_subscriptions_1.PubSub();\n/**\n * A MongoDB-backed model with schema validation, middleware, multi-tenancy,\n * transactions, caching, soft-delete support, and query instrumentation.\n *\n * @typeParam T - The MongoDB document shape handled by this model.\n */\nclass AmbitenModel {\n _provider;\n _collectionName;\n _collectionOverride;\n _schema;\n _initialized = false;\n _defaultCtx;\n _modelGCConfig;\n _gcConfig;\n _gcTimer;\n eventEmitter = new events_1.default();\n beforeMiddlewares = new Map();\n afterMiddlewares = new Map();\n _softDeleteConfig;\n /**\n * Creates a new model instance.\n *\n * @param options - Model configuration including collection, schema, provider,\n * default context, and optional GC configuration.\n */\n constructor(options) {\n if (!options) {\n const message = 'AmbitenModel options are required.';\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.NULL_OR_UNDEFINED, message, { details: { providedOptions: options, typeError: utils_1.ErrorType.AmbitenModelError } });\n }\n if (!options.collectionName) {\n const message = 'collectionName is required.';\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.NULL_OR_UNDEFINED, message, { details: { providedOptions: options, typeError: utils_1.ErrorType.AmbitenModelError } });\n }\n this._collectionName = options.collectionName;\n this._schema =\n options.schema ?? new ambitenSchema_1.AmbitenSchema({});\n this._provider = options.provider ?? ambitenClient_1.AmbitenClient.init();\n this._collectionOverride = options.collection;\n this._modelGCConfig = options.gcConfig;\n if (options.ctx?.db) {\n const fixedDb = options.ctx.db;\n this._provider = { db: async () => fixedDb };\n }\n if (options.ctx?.tenantId || options.ctx?.dbName || options.ctx?.collectionName) {\n this._defaultCtx = {\n tenantId: options.ctx?.tenantId,\n dbName: options.ctx?.dbName,\n collectionName: options.ctx?.collectionName,\n db: options.ctx?.db,\n session: options.ctx?.session,\n config: options.ctx?.config,\n };\n }\n const schemaGCConfig = this.resolveSchemaGCConfig();\n if (this.isGCEnabled() || schemaGCConfig) {\n utils_1.AmbitenModelRegistry.registerModel(this);\n }\n this.initMiddleware();\n }\n /**\n * Merges an explicit operation context with the model default context and the\n * current runtime context.\n *\n * @param ctx - Optional operation context.\n * @returns A merged context or `undefined` when no context values are present.\n */\n mergeCtx(ctx) {\n const runtimeCtx = context_1.AmbitenContext.get();\n const merged = {\n tenantId: ctx?.tenantId ?? this._defaultCtx?.tenantId ?? runtimeCtx.tenantId,\n dbName: ctx?.dbName ?? this._defaultCtx?.dbName ?? runtimeCtx.dbName,\n db: ctx?.db ?? this._defaultCtx?.db,\n collectionName: ctx?.collectionName ??\n this._defaultCtx?.collectionName ??\n runtimeCtx.collectionName,\n config: ctx?.config ?? this._defaultCtx?.config,\n session: ctx?.session ?? this._defaultCtx?.session ?? runtimeCtx.session,\n withDeleted: ctx?.withDeleted,\n onlyDeleted: ctx?.onlyDeleted,\n hardDelete: ctx?.hardDelete,\n };\n return Object.values(merged).some((value) => value !== undefined)\n ? merged\n : undefined;\n }\n /**\n * Ensures a runtime Ambiten context exists before executing an instrumented action.\n *\n * This allows model methods to remain safe when invoked outside adapter-managed\n * request lifecycles while still preserving tenant-aware instrumentation.\n *\n * @param ctx - Optional model context.\n * @param action - The action to execute inside a runtime context.\n * @returns The action result.\n */\n async runWithModelContext(ctx, action) {\n if (context_1.AmbitenContext.hasActiveContext()) {\n return action();\n }\n const merged = this.mergeCtx(ctx);\n return context_1.AmbitenContext.run({\n tenantId: merged?.tenantId,\n dbName: merged?.dbName,\n collectionName: merged?.collectionName ?? this._collectionName,\n session: merged?.session,\n }, action);\n }\n isGCEnabled() {\n return this._modelGCConfig?.enableGC === true;\n }\n resolveSchemaGCConfig() {\n return this._schema.getGCConfig?.();\n }\n /**\n * Resolves the MongoDB collection for the current model and context.\n *\n * @param ctx - Optional model context.\n * @returns The resolved MongoDB collection.\n */\n async getCollection(ctx) {\n if (this._collectionOverride) {\n return this._collectionOverride;\n }\n this.ensureConfigured();\n const db = await this.resolveDb(ctx);\n const collectionName = this.resolveCollectionName(ctx);\n (0, debug_1.debugLog)('Resolved collection', {\n collectionName,\n dbName: db.databaseName,\n tenantId: this.mergeCtx(ctx)?.tenantId,\n });\n return db.collection(collectionName);\n }\n /**\n * Resolves a registered tenant configuration.\n *\n * @param tenantId - The tenant identifier.\n * @returns The tenant configuration.\n */\n getResolvedTenant(tenantId) {\n const tenant = tanancy_1.MultiTenantManager.getTenant(tenantId);\n if (!tenant) {\n throw new Error(`Tenant \"${tenantId}\" is not registered.`);\n }\n return { ...tenant };\n }\n /**\n * Resolves the MongoDB database for the current operation.\n *\n * @param ctx - Optional model context.\n * @returns The resolved MongoDB database instance.\n */\n async resolveDb(ctx) {\n const resolvedCtx = this.mergeCtx(ctx);\n if (resolvedCtx?.db) {\n return resolvedCtx.db;\n }\n if (resolvedCtx?.tenantId) {\n const tenant = this.getResolvedTenant(resolvedCtx.tenantId);\n const client = await tanancy_1.MultiTenantManager.getClient(resolvedCtx.tenantId);\n if (!client) {\n throw new Error(`MongoClient for tenant \"${resolvedCtx.tenantId}\" is not available.`);\n }\n const dbName = resolvedCtx.dbName ?? tenant.dbName;\n if (!dbName) {\n throw new Error(`No database name configured for tenant \"${resolvedCtx.tenantId}\".`);\n }\n return client.db(dbName);\n }\n const db = await this._provider.db(resolvedCtx);\n if (!db || typeof db.collection !== 'function') {\n throw new Error(`AmbitenModel: provider.db() did not return a valid Db instance for collection \"${this._collectionName}\".`);\n }\n return db;\n }\n /**\n * Resolves the collection name for the current operation.\n *\n * @param ctx - Optional model context.\n * @returns The collection name.\n */\n resolveCollectionName(ctx) {\n const resolvedCtx = this.mergeCtx(ctx);\n const collectionName = resolvedCtx?.collectionName ?? this._collectionName;\n if (!collectionName || typeof collectionName !== 'string' || !collectionName.trim()) {\n throw new Error('AmbitenModel: collectionName is not configured.');\n }\n return collectionName.trim();\n }\n /**\n * Resolves the client session for the current operation.\n *\n * @param ctx - Optional model context.\n * @returns The MongoDB client session if available.\n */\n resolveSession(ctx) {\n return this.mergeCtx(ctx)?.session;\n }\n /**\n * Resolves the MongoDB client session to use for an operation.\n *\n * Precedence order:\n * 1. Explicit externally supplied session\n * 2. Per-call model context session\n * 3. Active runtime session from AmbitenContext\n *\n * This ensures explicit caller intent always overrides implicit runtime state.\n *\n * @param ctx - Optional model execution context.\n * @param externalSession - Optional explicit session supplied by the caller.\n * @returns The resolved MongoDB client session, or `undefined` when no session is available.\n */\n resolveSessionStrict(ctx, externalSession) {\n return externalSession ?? ctx?.session ?? context_1.AmbitenContext.getSession();\n }\n /**\n * Subscribes to a model event.\n *\n * @param event - Event type.\n * @param listener - Event listener callback.\n */\n on(event, listener) {\n this.eventEmitter.on(event, listener);\n }\n /**\n * Subscribes to a model event once.\n *\n * @param event - Event type.\n * @param listener - Event listener callback.\n */\n once(event, listener) {\n this.eventEmitter.once(event, listener);\n }\n /**\n * Removes a subscribed event listener.\n *\n * @param event - Event type.\n * @param listener - Event listener callback.\n */\n off(event, listener) {\n this.eventEmitter.off(event, listener);\n }\n /**\n * Removes a specific event listener.\n *\n * @param event - Event type.\n * @param listener - Event listener callback.\n */\n removeListener(event, listener) {\n this.eventEmitter.removeListener(event, listener);\n }\n /**\n * Ensures the model has the minimum configuration required to operate.\n */\n ensureConfigured() {\n if (!this._collectionName || typeof this._collectionName !== 'string') {\n throw new Error('AmbitenModel: collectionName is not configured.');\n }\n if (!this._provider || typeof this._provider.db !== 'function') {\n throw new Error('AmbitenModel: provider is not configured. Provide a valid DbProvider with a db(ctx) method.');\n }\n }\n /**\n * Initializes the model by validating configuration, resolving the collection,\n * and creating the GC TTL index when enabled.\n */\n async init() {\n if (this._initialized)\n return;\n try {\n this.ensureConfigured();\n if (!this._schema) {\n this._schema = new ambitenSchema_1.AmbitenSchema({});\n }\n await this.getCollection();\n if (this.isGCEnabled() && this._modelGCConfig) {\n await this.ensureGCIndex(this._modelGCConfig);\n }\n this._initialized = true;\n }\n catch (error) {\n throw (0, utils_1.createAmbitenError)(utils_1.ErrorType.INITIALIZATION_ERROR, `Failed to initialize AmbitenModel: ${error?.message ?? String(error)}`, {\n details: {\n operation: 'init',\n TypeError: utils_1.ErrorType.INITIALIZATION_ERROR,\n }\n });\n }\n }\n /**\n * Returns a model instance bound to a default context.\n *\n * @param ctx - Context to bind to the cloned model.\n * @returns A cloned model instance with merged default context.\n */\n bind(ctx) {\n const clone = Object.create(this);\n clone._defaultCtx = { ...this._defaultCtx, ...ctx };\n return clone;\n }\n /**\n * Registers or reconfigures the model.\n *\n * @param options - Model registration options.\n */\n async registerModel(options) {\n const { ctx, collectionName, schema, collection } = options;\n if (!collectionName) {\n throw new Error('Collection name is required.');\n }\n this._collectionName = collectionName;\n this._collectionOverride = collection;\n this._schema = schema ?? new ambitenSchema_1.AmbitenSchema({});\n if (ctx) {\n this._defaultCtx = {\n ...this._defaultCtx,\n ...ctx,\n };\n }\n this._initialized = false;\n this.ensureConfigured();\n await this.init();\n }\n /**\n * Ensures the TTL index used by the garbage collector exists.\n *\n * @param gc - GC configuration.\n */\n async ensureGCIndex(gc) {\n if (!gc.enableGC || !gc.ttl) {\n return;\n }\n const col = await this.getCollection();\n const field = gc.field ??\n gc.updatedAtField ??\n gc.createdAtField ??\n 'updatedAt';\n await col.createIndex({ [field]: 1 }, {\n expireAfterSeconds: gc.ttl,\n name: gc.indexName ?? `${this._collectionName}_${field}_ttl`,\n background: true\n });\n }\n /**\n * Returns the schema attached to this model.\n */\n get schema() {\n return this._schema;\n }\n /**\n * Returns the schema attached to this model.\n */\n getSchema() {\n return this.schema;\n }\n /**\n * Validates a document against the model schema.\n * Throws an error if validation fails.\n * @param doc - Document to validate.\n */\n validate(doc) {\n if (this._schema) {\n this._schema.validate(doc);\n }\n }\n /**\n * Validates a document asynchronously against the model schema.\n * Useful for schemas that perform async validation, such as checking uniqueness\n * @param doc - Document to validate.\n * @returns The validated document.\n */\n async validateAsync(doc) {\n if (this._schema) {\n await this._schema.validateAsync(doc);\n }\n return doc;\n }\n /**\n * Initializes internal schema middleware for relationships, aggregation, and\n * change notifications. This is called during model initialization and ensures that all registered\n * middleware is set up before any operations are performed.\n */\n initMiddleware() {\n if (!this._schema)\n return;\n this._schema.pre('create', async (ctx) => {\n const doc = ctx.doc;\n if (!doc)\n return;\n const relationships = this._schema.getRelationships() ?? [];\n for (const { ref, localField } of relationships) {\n const relatedCollection = (await this.getCollection()).db?.collection(ref);\n const filter = { [localField]: doc._id };\n await relatedCollection?.updateMany(filter, {\n $set: { [localField]: doc._id },\n });\n }\n });\n this._schema.post('create', async (ctx) => {\n const doc = (ctx.result ?? ctx.doc);\n if (!doc)\n return;\n const relationships = this._schema.getRelationships() ?? [];\n for (const { ref, localField } of relationships) {\n const relatedCollection = (await this.getCollection()).db?.collection(ref);\n const filter = { [localField]: doc._id };\n await relatedCollection?.updateOne(filter, {\n $set: { [localField]: doc._id },\n });\n }\n await pubsub.publish('DB_CHANGE', {\n dbChange: {\n action: 'create',\n doc,\n },\n });\n });\n this._schema.post('updateOne', async (ctx) => {\n const filter = ctx.filter;\n const update = ctx.update;\n if (!filter || !update)\n return;\n const relationships = this._schema.getRelationships() ?? [];\n for (const { ref, localField } of relationships) {\n const relatedCollection = (await this.getCollection()).db?.collection(ref);\n const updateFilter = { [localField]: update.$set?._id };\n await relatedCollection?.updateOne(updateFilter, {\n $set: { [localField]: update.$set?._id },\n });\n }\n await pubsub.publish('DB_CHANGE', {\n dbChange: {\n action: 'updateOne',\n filter,\n update,\n },\n });\n });\n this._schema.pre('deleteOne', async (ctx) => {\n const doc = (ctx.doc ?? ctx.result);\n if (!doc)\n return;\n const relationships = this._schema.getRelationships() ?? [];\n for (const { ref, localField } of relationships) {\n const relatedCollection = (await this.getCollection()).db?.collection(ref);\n const filter = { [localField]: doc._id };\n await relatedCollection?.deleteOne(filter);\n }\n });\n this._schema.pre('aggregate', async (ctx) => {\n const pipeline = ctx.pipeline;\n if (!pipeline)\n return;\n const relationships = this._schema.getRelationships() ?? [];\n for (const { ref, localField } of relationships) {\n pipeline.unshift({\n $lookup: {\n from: ref,\n localField: localField,\n foreignField: '_id',\n as: ref,\n },\n });\n }\n });\n this._schema.post('aggregate', async (ctx) => {\n const result = ctx.result;\n if (!result)\n return;\n const relationships = this._schema.getRelationships() ?? [];\n for (const doc of result) {\n for (const { ref } of relationships) {\n delete doc[ref];\n }\n }\n await pubsub.publish('DB_CHANGE', {\n dbChange: {\n action: 'aggregate',\n result,\n },\n });\n });\n }\n /**\n * Creates a new document in the model collection.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered create middlewares,\n * validates the incoming document against the model schema, triggers schema\n * create hooks, invalidates relevant cache patterns, and publishes a database\n * change event after successful insertion.\n *\n * @param doc - The document to insert.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns The created document as a normalized model result.\n * @throws {Error} When the provided document is missing or invalid.\n */\n async create(doc, ctx) {\n await this.init();\n if (!doc || typeof doc !== 'object') {\n throw new Error('Document must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'create',\n collectionName: this.resolveCollectionName(ctx),\n documentCount: 1\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('create', ctx, {\n doc: doc\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('create', middlewareCtx);\n const nextDoc = (middlewareCtx.doc ?? doc);\n middlewareCtx.doc = nextDoc;\n this.validate(nextDoc);\n await this.schema.executePre('create', this.buildHookPayload('create', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: nextDoc,\n meta: middlewareCtx.meta\n }));\n const insertResult = await col.insertOne(nextDoc, session ? { session } : undefined);\n const createdDoc = {\n ...nextDoc,\n _id: insertResult.insertedId\n };\n await this.schema.executePost('create', this.buildHookPayload('create', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: createdDoc,\n result: createdDoc,\n meta: middlewareCtx.meta\n }));\n const payload = this.toModelResult(createdDoc);\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('create', middlewareCtx);\n const finalResult = (middlewareCtx.result ?? payload);\n await this.invalidateCachePatterns('create', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentInserted: {\n action: 'create',\n collectionName: middlewareCtx.collectionName,\n doc: finalResult,\n meta: middlewareCtx.meta\n }\n });\n return finalResult;\n }));\n }\n /**\n * Finds documents matching the provided filter.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered find middlewares, supports\n * optional result caching, triggers schema find hooks, and returns normalized\n * model results.\n *\n * @param filter - MongoDB filter used to match documents.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @param options - Optional query-level features such as caching.\n * @returns An array of normalized model results.\n * @throws {Error} When the filter is invalid.\n */\n async find(filter = {}, ctx, options) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'find',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('find', ctx, { filter });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('find', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const cache = options?.cache ? this.resolveCache(options) : null;\n await this.schema.executePre('find', this.buildHookPayload('create', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n meta: middlewareCtx.meta\n }));\n let cacheKey = null;\n if (cache) {\n cacheKey = this.buildCacheKey('find', {\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName\n });\n const cached = await cache.get(cacheKey, {\n ttlSeconds: typeof options?.cache === 'object' ? options.cache.ttl : undefined,\n tenantId: middlewareCtx.tenantId,\n namespace: middlewareCtx.collectionName\n });\n if (cached) {\n middlewareCtx.result = cached;\n await this.schema.executePost('find', this.buildHookPayload('find', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n result: cached,\n meta: {\n ...(middlewareCtx.meta ?? {}),\n cacheHit: true\n }\n }));\n await this.runAfterMiddlewares('find', middlewareCtx);\n return (middlewareCtx.result ?? cached);\n }\n }\n const cursor = col.find(effectiveFilter, session ? { session } : undefined);\n const results = await cursor.toArray();\n const payload = this.toModelResults(results);\n await this.schema.executePost('find', this.buildHookPayload('find', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n result: payload,\n meta: middlewareCtx.meta\n }));\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('find', middlewareCtx);\n const finalResult = (middlewareCtx.result ?? payload);\n if (cache && cacheKey) {\n await cache.set(cacheKey, finalResult, {\n ttlSeconds: typeof options?.cache === 'object' ? options.cache.ttl : undefined,\n tenantId: middlewareCtx.tenantId,\n namespace: middlewareCtx.collectionName\n });\n }\n return finalResult;\n }));\n }\n /**\n * Finds a single document matching the provided filter.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered findOne middlewares,\n * supports optional result caching, triggers schema find hooks, and returns a\n * normalized model result when a document is found.\n *\n * @param filter - MongoDB filter used to match the document.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @param options - Optional query-level features such as caching.\n * @returns The matched document as a normalized model result, or `null` if no document matched.\n * @throws {Error} When the filter is missing or invalid.\n */\n async findOne(filter, ctx, options) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'findOne',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('findOne', ctx, {\n filter\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('findOne', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const cache = options?.cache ? this.resolveCache(options) : null;\n let cacheKey = null;\n await this.schema.executePre('findOne', this.buildHookPayload('findOne', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n meta: middlewareCtx.meta\n }));\n if (cache) {\n cacheKey = this.buildCacheKey('findOne', {\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName\n });\n const cached = await cache.get(cacheKey, {\n ttlSeconds: typeof options?.cache === 'object' ? options.cache.ttl : undefined,\n tenantId: middlewareCtx.tenantId,\n namespace: middlewareCtx.collectionName\n });\n if (cached !== null && cached !== undefined) {\n middlewareCtx.result = cached;\n await this.schema.executePost('findOne', this.buildHookPayload('findOne', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n result: cached,\n meta: {\n ...(middlewareCtx.meta ?? {}),\n cacheHit: true\n }\n }));\n await this.runAfterMiddlewares('findOne', middlewareCtx);\n return (middlewareCtx.result ?? cached);\n }\n }\n const result = await col.findOne(effectiveFilter, session ? { session } : undefined);\n const payload = result\n ? this.toModelResult(result)\n : null;\n await this.schema.executePost('findOne', {\n operation: 'findOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n result: payload,\n meta: middlewareCtx.meta\n });\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('findOne', middlewareCtx);\n const finalResult = (middlewareCtx.result ?? payload);\n if (cache && cacheKey && finalResult !== null) {\n await cache.set(cacheKey, finalResult, {\n ttlSeconds: typeof options?.cache === 'object' ? options.cache.ttl : undefined,\n tenantId: middlewareCtx.tenantId,\n namespace: middlewareCtx.collectionName\n });\n }\n return finalResult;\n }));\n }\n /**\n * Updates a single document matching the provided filter.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered update middlewares,\n * triggers schema update hooks, invalidates relevant cache patterns, and\n * publishes a database change event after completion.\n *\n * @param filter - MongoDB filter used to identify the document to update.\n * @param update - MongoDB update document to apply.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the update document is missing or invalid.\n */\n async updateOne(filter, update, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!update || typeof update !== 'object') {\n throw new Error('Update must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'updateOne',\n collectionName: this.resolveCollectionName(ctx),\n filter,\n update\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('updateOne', ctx, {\n filter,\n update\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('updateOne', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n const effectiveUpdate = (middlewareCtx.update ?? update);\n middlewareCtx.filter = effectiveFilter;\n middlewareCtx.update = effectiveUpdate;\n await this.schema.executePre('updateOne', {\n operation: 'updateOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: effectiveUpdate,\n meta: middlewareCtx.meta\n });\n const result = await col.updateOne(effectiveFilter, effectiveUpdate, session ? { session } : undefined);\n const updateResult = {\n acknowledged: result?.acknowledged,\n matchedCount: result?.matchedCount,\n modifiedCount: result?.modifiedCount,\n upsertedCount: result?.upsertedCount,\n upsertedId: result?.upsertedId\n };\n await this.schema.executePost('updateOne', {\n operation: 'updateOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: updateResult,\n meta: middlewareCtx.meta\n });\n middlewareCtx.result = updateResult;\n await this.runAfterMiddlewares('updateOne', middlewareCtx);\n await this.invalidateCachePatterns('updateOne', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'updateOne',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: updateResult,\n meta: middlewareCtx.meta\n }\n });\n }));\n }\n /**\n * Inserts multiple documents into the model collection.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered bulkInsert middlewares,\n * validates each incoming document against the model schema, triggers schema\n * bulk insert hooks, invalidates relevant cache patterns, and publishes a\n * database change event after successful insertion.\n *\n * @param docs - The documents to insert.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n */\n async bulkInsert(docs, ctx) {\n await this.init();\n if (!Array.isArray(docs) || docs.length === 0) {\n return;\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'bulkInsert',\n collectionName: this.resolveCollectionName(ctx),\n documentCount: docs.length\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('bulkInsert', ctx, {\n docs: docs\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('bulkInsert', middlewareCtx);\n const nextDocs = (middlewareCtx.docs ?? docs);\n middlewareCtx.docs = nextDocs;\n if (!Array.isArray(nextDocs) || nextDocs.length === 0) {\n middlewareCtx.result = [];\n await this.runAfterMiddlewares('bulkInsert', middlewareCtx);\n return;\n }\n for (const nextDoc of nextDocs) {\n if (!nextDoc || typeof nextDoc !== 'object') {\n throw new Error('Each document must be a valid object.');\n }\n this.validate(nextDoc);\n }\n const meta = this.buildOperationMeta(middlewareCtx.meta, {\n bulkWrite: true\n });\n await this.schema.executePre('bulkInsert', this.buildHookPayload('bulkInsert', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n docs: nextDocs,\n meta\n }));\n const result = await col.insertMany(nextDocs, {\n ordered: false,\n ...(session ? { session } : {})\n });\n const insertedDocs = nextDocs.map((doc, index) => ({\n ...doc,\n _id: result.insertedIds[index]\n }));\n await this.schema.executePost('bulkInsert', this.buildHookPayload('bulkInsert', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n docs: insertedDocs,\n result: insertedDocs,\n meta\n }));\n middlewareCtx.result = this.toModelResults(insertedDocs);\n await this.runAfterMiddlewares('bulkInsert', middlewareCtx);\n await this.invalidateCachePatterns('bulkInsert', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentInserted: {\n action: 'bulkInsert',\n collectionName: middlewareCtx.collectionName,\n docs: middlewareCtx.result,\n meta\n }\n });\n }));\n }\n /**\n * Updates multiple documents using MongoDB bulk write semantics.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered bulkUpdate middlewares,\n * triggers schema bulk update hooks, invalidates relevant cache patterns, and\n * publishes a database change event after completion.\n *\n * Each update entry is translated into an `updateOne` bulk operation using\n * `$set` with the provided partial update document.\n *\n * @param updates - Array of filter/update pairs to execute as bulk updates.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n * @throws {Error} When the updates payload is invalid.\n */\n async bulkUpdate(updates, ctx) {\n await this.init();\n if (!Array.isArray(updates)) {\n throw new Error('Updates must be a valid array.');\n }\n if (updates.length === 0) {\n return;\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'bulkUpdate',\n collectionName: this.resolveCollectionName(ctx),\n documentCount: updates.length\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('bulkUpdate', ctx, {\n bulkUpdates: updates\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('bulkUpdate', middlewareCtx);\n const nextUpdates = middlewareCtx.bulkUpdates ?? updates;\n middlewareCtx.bulkUpdates = nextUpdates;\n const meta = this.buildOperationMeta(middlewareCtx.meta, {\n bulkWrite: true\n });\n middlewareCtx.meta = meta;\n if (!Array.isArray(nextUpdates) || nextUpdates.length === 0) {\n middlewareCtx.result = {\n acknowledged: true,\n matchedCount: 0,\n modifiedCount: 0,\n upsertedCount: 0,\n insertedCount: 0,\n deletedCount: 0\n };\n await this.runAfterMiddlewares('bulkUpdate', middlewareCtx);\n return;\n }\n for (const entry of nextUpdates) {\n if (!entry || typeof entry !== 'object') {\n throw new Error('Each bulk update entry must be a valid object.');\n }\n if (!entry.filter || typeof entry.filter !== 'object') {\n throw new Error('Each bulk update filter must be a valid object.');\n }\n if (!entry.update || typeof entry.update !== 'object') {\n throw new Error('Each bulk update document must be a valid object.');\n }\n }\n const bulkOps = nextUpdates.map(({ filter, update }) => ({\n updateOne: {\n filter: filter,\n update: { $set: update }\n }\n }));\n await this.schema.executePre('bulkUpdate', this.buildHookPayload('bulkUpdate', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n bulkUpdates: nextUpdates,\n meta\n }));\n const result = await col.bulkWrite(bulkOps, {\n ordered: false,\n ...(session ? { session } : {})\n });\n const bulkResult = {\n acknowledged: result?.isOk?.() ?? true,\n matchedCount: result?.matchedCount,\n modifiedCount: result?.modifiedCount,\n upsertedCount: result?.upsertedCount,\n insertedCount: result?.insertedCount,\n deletedCount: result?.deletedCount\n };\n await this.schema.executePost('bulkUpdate', this.buildHookPayload('bulkUpdate', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n bulkUpdates: nextUpdates,\n result: bulkResult,\n meta\n }));\n middlewareCtx.result = bulkResult;\n await this.runAfterMiddlewares('bulkUpdate', middlewareCtx);\n await this.invalidateCachePatterns('bulkUpdate', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'bulkUpdate',\n collectionName: middlewareCtx.collectionName,\n bulkUpdates: nextUpdates,\n result: bulkResult,\n meta\n }\n });\n }));\n }\n /**\n * Deletes a single document matching the provided filter.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered delete middlewares,\n * supports middleware-driven soft delete flows, triggers schema delete or\n * update hooks as appropriate, invalidates relevant cache patterns, and\n * publishes a database change event after completion.\n *\n * When middleware metadata enables soft delete, the matched document is updated\n * instead of being physically removed from the collection.\n *\n * @param filter - MongoDB filter used to identify the document to delete.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When soft delete is enabled but no softDeleteUpdate payload is provided.\n */\n async deleteOne(filter, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'deleteOne',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('deleteOne', ctx, {\n filter\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('deleteOne', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const doc = await col.findOne(effectiveFilter, session ? { session } : undefined);\n if (!doc) {\n middlewareCtx.result = null;\n await this.runAfterMiddlewares('deleteOne', middlewareCtx);\n return;\n }\n const payload = this.toModelResult(doc);\n middlewareCtx.result = payload;\n const meta = this.buildOperationMeta(middlewareCtx.meta);\n middlewareCtx.meta = meta;\n if (meta.softDelete === true) {\n const softDeleteUpdate = middlewareCtx.update;\n if (!softDeleteUpdate) {\n throw new Error('Soft delete is enabled but no soft delete update payload was provided.');\n }\n await this.schema.executePre('updateOne', this.buildHookPayload('deleteOne', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n result: payload,\n meta\n }));\n await col.updateOne(effectiveFilter, softDeleteUpdate, session ? { session } : undefined);\n await this.schema.executePost('updateOne', this.buildHookPayload('deleteOne', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n result: payload,\n meta\n }));\n }\n else {\n await this.schema.triggerMiddleware('pre', 'deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n ...payload\n });\n await this.schema.executePre('deleteOne', this.buildHookPayload('deleteOne', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: payload,\n result: payload,\n meta\n }));\n await col.deleteOne(effectiveFilter, session ? { session } : undefined);\n await this.schema.triggerMiddleware('post', 'deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n ...payload\n });\n await this.schema.executePost('deleteOne', this.buildHookPayload('deleteOne', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: payload,\n result: payload,\n meta\n }));\n }\n await this.runAfterMiddlewares('deleteOne', middlewareCtx);\n await this.invalidateCachePatterns('deleteOne', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentDeleted: {\n action: meta.softDelete ? 'softDelete' : 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n meta: middlewareCtx.meta\n }\n });\n }));\n }\n /**\n * Deletes multiple documents matching the provided filter.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered deleteMany middlewares,\n * supports middleware-driven soft delete flows, triggers schema delete or\n * update hooks as appropriate, invalidates relevant cache patterns, and\n * publishes a database change event after completion.\n *\n * When middleware metadata enables soft delete, matched documents are updated\n * instead of being physically removed from the collection.\n *\n * @param filter - MongoDB filter used to identify the documents to delete.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When soft delete is enabled but no softDeleteUpdate payload is provided.\n */\n async deleteMany(filter, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'deleteMany',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('deleteMany', ctx, {\n filter\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('deleteMany', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const meta = this.buildOperationMeta(middlewareCtx.meta);\n middlewareCtx.meta = meta;\n const docs = await col.find(effectiveFilter, session ? { session } : undefined).toArray();\n if (docs.length === 0) {\n middlewareCtx.result = {\n deletedCount: 0,\n docs: []\n };\n await this.runAfterMiddlewares('deleteMany', middlewareCtx);\n return;\n }\n const existingDocs = this.toModelResults(docs);\n if (meta.softDelete === true) {\n const softDeleteUpdate = middlewareCtx.update;\n if (!softDeleteUpdate) {\n throw new Error('Soft delete is enabled but no soft delete update payload was provided.');\n }\n const softDeleteMeta = this.buildOperationMeta(meta, {\n softDelete: true\n });\n await this.schema.executePre('updateMany', this.buildHookPayload('deleteMany', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n docs: docs,\n result: existingDocs,\n meta: softDeleteMeta\n }));\n const result = await col.updateMany(effectiveFilter, softDeleteUpdate, session ? { session } : undefined);\n const softDeleteResult = {\n deletedCount: result.modifiedCount,\n docs: existingDocs,\n softDeleted: true\n };\n await this.schema.executePost('updateMany', this.buildHookPayload('deleteMany', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n docs: docs,\n result: softDeleteResult,\n meta: softDeleteMeta\n }));\n middlewareCtx.result = softDeleteResult;\n }\n else {\n await this.schema.triggerMiddleware('pre', 'deleteMany', {\n operation: 'deleteMany',\n collectionName: middlewareCtx.collectionName,\n docs: docs\n });\n await this.schema.executePre('deleteMany', this.buildHookPayload('deleteMany', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n docs: docs,\n result: existingDocs,\n meta\n }));\n const result = await col.deleteMany(effectiveFilter, session ? { session } : undefined);\n const deleteResult = {\n deletedCount: result?.deletedCount ?? 0,\n docs: existingDocs\n };\n await this.schema.triggerMiddleware('post', 'deleteMany', {\n operation: 'deleteMany',\n collectionName: middlewareCtx.collectionName,\n docs: docs\n });\n await this.schema.executePost('deleteMany', this.buildHookPayload('deleteMany', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n docs: docs,\n result: deleteResult,\n meta\n }));\n middlewareCtx.result = deleteResult;\n }\n await this.runAfterMiddlewares('deleteMany', middlewareCtx);\n await this.invalidateCachePatterns('deleteMany', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentDeleted: {\n action: meta.softDelete ? 'softDeleteMany' : 'deleteMany',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n result: middlewareCtx.result,\n meta: middlewareCtx.meta\n }\n });\n }));\n }\n /**\n * Populates a single reference field on a document by resolving the related\n * document from another model.\n *\n * This helper performs a follow-up lookup using the referenced field value as\n * the `_id` of the related document. If the target field is empty or\n * undefined, the original document is returned unchanged.\n *\n * @typeParam K - The related model document type.\n * @param doc - The source document containing the reference field.\n * @param field - The field on the source document that stores the related document identifier.\n * @param relatedModel - The model used to resolve the related document.\n * @returns The source document with the populated field replaced by the related\n * document result, or `null` when the input document is invalid.\n */\n async populateOne(doc, field, relatedModel) {\n await this.init();\n if (!doc || typeof doc !== 'object') {\n return null;\n }\n const referenceValue = doc[field];\n if (referenceValue === undefined || referenceValue === null) {\n return doc;\n }\n const relatedDoc = await relatedModel.findOne({\n _id: referenceValue\n });\n return {\n ...doc,\n [field]: relatedDoc\n };\n }\n /**\n * Populates an array reference field on a document by resolving the related\n * documents from another model.\n *\n * This helper performs a follow-up lookup using the referenced field values as\n * `_id` values of the related documents. If the target field is empty,\n * undefined, or not an array, the original document is returned unchanged.\n *\n * @typeParam K - The related model document type.\n * @param doc - The source document containing the reference array field.\n * @param field - The field on the source document that stores related document identifiers.\n * @param relatedModel - The model used to resolve the related documents.\n * @returns The source document with the populated field replaced by the related\n * document results, or `null` when the input document is invalid.\n */\n async populateMany(doc, field, relatedModel) {\n await this.init();\n if (!doc || typeof doc !== 'object') {\n return null;\n }\n const referenceValues = doc[field];\n if (!Array.isArray(referenceValues) || referenceValues.length === 0) {\n return doc;\n }\n const relatedDocs = await relatedModel.find({\n _id: { $in: referenceValues }\n });\n return {\n ...doc,\n [field]: relatedDocs\n };\n }\n /**\n * Creates a new document inside a transaction-aware runtime context.\n *\n * This transactional variant runs within the active Ambiten runtime context,\n * executes registered create middlewares, validates the incoming document,\n * triggers schema create hooks with transactional metadata, invalidates\n * relevant cache patterns, and publishes a database change event after\n * successful insertion.\n *\n * @param doc - The document to insert.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and transaction-aware runtime overrides.\n * @returns The created document as a normalized model result.\n * @throws {Error} When the provided document is missing or invalid.\n */\n async createWithTransaction(doc, ctx) {\n await this.init();\n if (!doc || typeof doc !== 'object') {\n throw new Error('Document must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async () => (0, instrumentation_1.measureQuery)({\n operation: 'create',\n collectionName: this.resolveCollectionName(ctx),\n documentCount: 1\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('create', ctx, {\n doc: doc,\n meta: { transactional: true }\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('create', middlewareCtx);\n const nextDoc = (middlewareCtx.doc ?? doc);\n middlewareCtx.doc = nextDoc;\n const meta = this.buildOperationMeta(middlewareCtx.meta, {\n transactional: true\n });\n this.validate(nextDoc);\n await this.schema.executePre('create', this.buildHookPayload('create', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: nextDoc,\n meta\n }));\n const result = await col.insertOne(nextDoc, session ? { session } : undefined);\n const createdDoc = {\n ...nextDoc,\n _id: result.insertedId\n };\n await this.schema.executePost('create', this.buildHookPayload('create', ctx, {\n operation: 'create',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: createdDoc,\n result: createdDoc,\n meta\n }));\n const payload = this.toModelResult(createdDoc);\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('create', middlewareCtx);\n await this.invalidateCachePatterns('create', middlewareCtx);\n const finalResult = (middlewareCtx.result ?? payload);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentInserted: {\n action: 'create',\n collectionName: middlewareCtx.collectionName,\n doc: finalResult,\n meta\n }\n });\n return finalResult;\n }), ctx));\n }\n /**\n * Executes multiple MongoDB bulk write operations inside a transaction-aware\n * runtime context.\n *\n * This transactional variant runs within the active Ambiten runtime context,\n * executes registered bulk update middlewares, triggers schema bulk update\n * hooks with transactional metadata, invalidates relevant cache patterns, and\n * publishes a database change event after completion.\n *\n * @param operations - MongoDB bulk write operations to execute.\n * @param options - Optional MongoDB bulk write options.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and transaction-aware runtime overrides.\n * @returns The MongoDB bulk write result.\n * @throws {Error} When the operations payload is missing or invalid.\n */\n async bulkWriteWithTransaction(operations, options = {}, ctx) {\n await this.init();\n if (!Array.isArray(operations)) {\n throw new Error('Operations must be a valid array.');\n }\n if (operations.length === 0) {\n throw new Error('Operations array must not be empty.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async () => (0, instrumentation_1.measureQuery)({\n operation: 'bulkWrite',\n collectionName: this.resolveCollectionName(ctx),\n documentCount: operations.length,\n extra: {\n bulkWrite: true\n }\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('bulkUpdate', ctx, {\n bulkOperations: operations,\n meta: {\n transactional: true,\n bulkWrite: true\n }\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('bulkUpdate', middlewareCtx);\n const nextOperations = middlewareCtx.bulkOperations ?? operations;\n middlewareCtx.bulkOperations = nextOperations;\n const meta = this.buildOperationMeta(middlewareCtx.meta, {\n transactional: true,\n bulkWrite: true\n });\n middlewareCtx.meta = meta;\n await this.schema.executePre('bulkUpdate', this.buildHookPayload('bulkUpdate', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n bulkOperations: nextOperations,\n meta\n }));\n const result = await col.bulkWrite(nextOperations, {\n ...options,\n ...(session ? { session } : {})\n });\n const bulkResultSummary = {\n acknowledged: result?.isOk?.() ?? true,\n matchedCount: result?.matchedCount,\n modifiedCount: result?.modifiedCount,\n upsertedCount: result?.upsertedCount,\n insertedCount: result?.insertedCount,\n deletedCount: result?.deletedCount\n };\n await this.schema.executePost('bulkUpdate', this.buildHookPayload('bulkUpdate', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n bulkOperations: nextOperations,\n result: bulkResultSummary,\n meta\n }));\n middlewareCtx.result = bulkResultSummary;\n await this.runAfterMiddlewares('bulkUpdate', middlewareCtx);\n await this.invalidateCachePatterns('bulkWrite', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n bulkWrite: {\n action: 'bulkWrite',\n collectionName: middlewareCtx.collectionName,\n result: bulkResultSummary,\n meta\n }\n });\n return result;\n }), ctx));\n }\n /**\n * Deletes a single document inside a transaction-aware runtime context.\n *\n * This transactional variant runs within the active Ambiten runtime context,\n * executes registered delete middlewares, triggers schema delete hooks with\n * transactional metadata, invalidates relevant cache patterns, and publishes a\n * database change event after completion.\n *\n * @param filter - MongoDB filter used to identify the document to delete.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and transaction-aware runtime overrides.\n * @returns `true` when a document was deleted, otherwise `false`.\n * @throws {Error} When the filter is missing or invalid.\n */\n async deleteWithTransaction(filter, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async () => (0, instrumentation_1.measureQuery)({\n operation: 'deleteOne',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const meta = {\n transactional: true\n };\n const middlewareCtx = this.buildMiddlewareContext('deleteOne', ctx, {\n filter,\n meta\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('deleteOne', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const existingDoc = await col.findOne(effectiveFilter, session ? { session } : undefined);\n if (!existingDoc) {\n middlewareCtx.result = null;\n await this.runAfterMiddlewares('deleteOne', middlewareCtx);\n return false;\n }\n const payload = this.toModelResult(existingDoc);\n middlewareCtx.result = payload;\n await this.schema.triggerMiddleware('pre', 'deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n ...payload\n });\n await this.schema.executePre('deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: existingDoc,\n result: payload,\n meta\n });\n const result = await col.deleteOne(effectiveFilter, session ? { session } : undefined);\n await this.schema.triggerMiddleware('post', 'deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n ...payload\n });\n await this.schema.executePost('deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: existingDoc,\n result: payload,\n meta\n });\n await this.runAfterMiddlewares('deleteOne', middlewareCtx);\n await this.invalidateCachePatterns('deleteOne', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentDeleted: {\n action: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n meta\n }\n });\n return result.deletedCount === 1;\n }), ctx));\n }\n /**\n * Updates a single document inside a transaction-aware runtime context.\n *\n * This transactional variant runs within the active Ambiten runtime context,\n * executes registered update middlewares, validates the projected updated\n * document, triggers schema update hooks with transactional metadata,\n * invalidates relevant cache patterns, and publishes a database change event\n * after completion.\n *\n * @param filter - MongoDB filter used to identify the document to update.\n * @param update - MongoDB update document to apply.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and transaction-aware runtime overrides.\n * @returns The updated document as a normalized model result, or `null` if no\n * document matched the filter.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the update document is missing or invalid.\n */\n async updateWithTransaction(filter, update, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!update || typeof update !== 'object') {\n throw new Error('Update must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async () => (0, instrumentation_1.measureQuery)({\n operation: 'updateOne',\n collectionName: this.resolveCollectionName(ctx),\n filter,\n update\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const meta = {\n transactional: true\n };\n const middlewareCtx = this.buildMiddlewareContext('updateOne', ctx, {\n filter,\n update,\n meta\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('updateOne', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n const effectiveUpdate = (middlewareCtx.update ?? update);\n middlewareCtx.filter = effectiveFilter;\n middlewareCtx.update = effectiveUpdate;\n const existingDoc = await col.findOne(effectiveFilter, session ? { session } : undefined);\n if (!existingDoc) {\n middlewareCtx.result = null;\n await this.runAfterMiddlewares('updateOne', middlewareCtx);\n return null;\n }\n const projectedUpdatedDoc = {\n ...existingDoc,\n ...(effectiveUpdate.$set ?? {})\n };\n this.validate(projectedUpdatedDoc);\n await this.schema.executePre('updateOne', {\n operation: 'updateOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: effectiveUpdate,\n meta\n });\n await col.updateOne(effectiveFilter, effectiveUpdate, session ? { session } : undefined);\n const result = await col.findOne(effectiveFilter, session ? { session } : undefined);\n const payload = result\n ? this.toModelResult(result)\n : null;\n await this.schema.executePost('updateOne', {\n operation: 'updateOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: payload,\n meta\n });\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('updateOne', middlewareCtx);\n await this.invalidateCachePatterns('updateOne', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'updateOne',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: payload,\n meta\n }\n });\n return (middlewareCtx.result ?? payload);\n }), ctx));\n }\n /**\n * Finds a single document matching the provided filter and updates it.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered findOneAndUpdate\n * middlewares, triggers schema update hooks, invalidates relevant cache\n * patterns, and publishes a database change event after completion.\n *\n * The updated document is returned in its post-update state when a matching\n * document is found.\n *\n * @param filter - MongoDB filter used to identify the document to update.\n * @param update - MongoDB update document to apply.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns The updated document as a normalized model result, or `null` if no\n * document matched the filter.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the update document is missing or invalid.\n */\n async findOneAndUpdate(filter, update, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!update || typeof update !== 'object') {\n throw new Error('Update must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'findOneAndUpdate',\n collectionName: this.resolveCollectionName(ctx),\n filter,\n update\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('findOneAndUpdate', ctx, {\n filter,\n update\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('findOneAndUpdate', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n const effectiveUpdate = (middlewareCtx.update ?? update);\n middlewareCtx.filter = effectiveFilter;\n middlewareCtx.update = effectiveUpdate;\n await this.schema.executePre('updateOne', {\n operation: 'findOneAndUpdate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: effectiveUpdate,\n meta: middlewareCtx.meta\n });\n const updateResult = await col.findOneAndUpdate(effectiveFilter, effectiveUpdate, {\n returnDocument: 'after',\n ...(session ? { session } : {})\n });\n const updatedDoc = updateResult &&\n typeof updateResult === 'object' &&\n 'value' in updateResult\n ? updateResult.value\n : updateResult;\n const payload = updatedDoc\n ? this.toModelResult(updatedDoc)\n : null;\n await this.schema.executePost('updateOne', {\n operation: 'findOneAndUpdate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: payload,\n meta: middlewareCtx.meta\n });\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('findOneAndUpdate', middlewareCtx);\n await this.invalidateCachePatterns('findOneAndUpdate', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'findOneAndUpdate',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: payload,\n meta: middlewareCtx.meta\n }\n });\n return (middlewareCtx.result ?? payload);\n }));\n }\n /**\n * Finds a single document matching the provided filter and deletes it.\n *\n * Supports both hard delete and middleware-driven soft delete flows.\n * When soft delete is enabled via middleware metadata, the matched document\n * is updated using the provided soft-delete update operation instead of being\n * physically removed from the collection.\n *\n * The operation:\n * - runs within the active Ambiten runtime context\n * - is instrumented through {@link measureQuery}\n * - executes registered before/after model middlewares\n * - triggers schema delete/update hooks as appropriate\n * - invalidates relevant cache patterns after mutation\n * - publishes a database change event through PubSub\n *\n * @param filter - MongoDB filter used to identify the document to delete.\n * @param ctx - Optional model execution context for tenant, database,\n * session, cache, and collection overrides.\n * @returns The deleted document as a model result, or `null` if no document matched.\n * @throws {Error} When the filter is missing or invalid.\n */\n async findOneAndDelete(filter, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'findOneAndDelete',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('findOneAndDelete', ctx, { filter });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('findOneAndDelete', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const meta = this.buildOperationMeta(middlewareCtx.meta);\n middlewareCtx.meta = meta;\n const existingDoc = await col.findOne(effectiveFilter, session ? { session } : undefined);\n if (!existingDoc) {\n middlewareCtx.result = null;\n await this.runAfterMiddlewares('findOneAndDelete', middlewareCtx);\n return null;\n }\n const existingPayload = this.toModelResult(existingDoc);\n middlewareCtx.result = existingPayload;\n if (meta.softDelete === true) {\n const softDeleteUpdate = middlewareCtx.update ?? this.buildSoftDeleteUpdate();\n middlewareCtx.update = softDeleteUpdate;\n const softDeleteMeta = this.buildOperationMeta(meta, {\n softDelete: true\n });\n await this.schema.executePre('updateOne', this.buildHookPayload('findOneAndDelete', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n result: existingPayload,\n meta: softDeleteMeta\n }));\n await col.updateOne(effectiveFilter, softDeleteUpdate, session ? { session } : undefined);\n await this.schema.executePost('updateOne', this.buildHookPayload('findOneAndDelete', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n result: existingPayload,\n meta: softDeleteMeta\n }));\n await this.runAfterMiddlewares('findOneAndDelete', middlewareCtx);\n await this.invalidateCachePatterns('findOneAndDelete', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentDeleted: {\n action: 'softDeleteOne',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n meta: softDeleteMeta\n }\n });\n return (middlewareCtx.result ?? existingPayload);\n }\n await this.schema.triggerMiddleware('pre', 'deleteOne', {\n operation: 'findOneAndDelete',\n collectionName: middlewareCtx.collectionName,\n ...existingPayload\n });\n await this.schema.executePre('deleteOne', this.buildHookPayload('findOneAndDelete', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: existingDoc,\n result: existingPayload,\n meta\n }));\n const deleteOptions = session ? { session } : {};\n const deleteResult = await col.findOneAndDelete(effectiveFilter, deleteOptions);\n const deletedDoc = deleteResult &&\n typeof deleteResult === 'object' &&\n 'value' in deleteResult\n ? deleteResult.value\n : deleteResult;\n const finalPayload = deletedDoc\n ? this.toModelResult(deletedDoc)\n : existingPayload;\n await this.schema.triggerMiddleware('post', 'deleteOne', {\n operation: 'findOneAndDelete',\n collectionName: middlewareCtx.collectionName,\n ...(finalPayload ?? {})\n });\n await this.schema.executePost('deleteOne', this.buildHookPayload('findOneAndDelete', ctx, {\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n doc: existingDoc,\n result: finalPayload,\n meta\n }));\n middlewareCtx.result = finalPayload;\n await this.runAfterMiddlewares('findOneAndDelete', middlewareCtx);\n await this.invalidateCachePatterns('findOneAndDelete', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentDeleted: {\n action: 'findOneAndDelete',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n result: finalPayload,\n meta\n }\n });\n return (middlewareCtx.result ?? finalPayload);\n }));\n }\n /**\n * Finds a single document matching the provided filter and replaces it with the\n * supplied replacement document.\n *\n * This operation runs inside the active Ambiten runtime context, executes model\n * middlewares, triggers schema update hooks, invalidates relevant cache entries,\n * and publishes a database change event after a successful replacement.\n *\n * The replacement document is fully validated before being persisted.\n *\n * @param filter - MongoDB filter used to identify the document to replace.\n * @param replacement - The full replacement document that will overwrite the matched document.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns The replaced document in its updated form, or `null` if no document matched the filter.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the replacement document fails validation.\n */\n async findOneAndReplace(filter, replacement, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!replacement || typeof replacement !== 'object') {\n throw new Error('Replacement document must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'findOneAndReplace',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('findOneAndReplace', ctx, {\n filter,\n doc: replacement\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('findOneAndReplace', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n const nextReplacement = (middlewareCtx.doc ?? replacement);\n middlewareCtx.filter = effectiveFilter;\n middlewareCtx.doc = nextReplacement;\n this.validate(nextReplacement);\n await this.schema.executePre('updateOne', {\n operation: 'findOneAndReplace',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n doc: nextReplacement\n });\n const replaceResult = await col.findOneAndReplace(effectiveFilter, nextReplacement, {\n returnDocument: 'after',\n ...(session ? { session } : {})\n });\n const replacedDoc = replaceResult &&\n typeof replaceResult === 'object' &&\n 'value' in replaceResult\n ? replaceResult.value\n : replaceResult;\n const payload = replacedDoc\n ? this.toModelResult(replacedDoc)\n : null;\n await this.schema.executePost('updateOne', {\n operation: 'findOneAndReplace',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n doc: nextReplacement,\n result: replacedDoc\n });\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('findOneAndReplace', middlewareCtx);\n await this.invalidateCachePatterns('findOneAndReplace', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'findOneAndReplace',\n filter: effectiveFilter,\n replacement: nextReplacement\n }\n });\n return (middlewareCtx.result ?? payload);\n }));\n }\n /**\n * Finds a single document matching the provided filter and updates it. If no\n * matching document exists, a new one is inserted using MongoDB upsert\n * semantics.\n *\n * This operation runs within the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered model middlewares, triggers\n * schema update hooks, invalidates relevant cache patterns, and publishes a\n * database change event after completion.\n *\n * @param filter - MongoDB filter used to identify the document to update or insert.\n * @param update - MongoDB update document applied to the matched document or to the inserted document during upsert.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns The updated or newly upserted document in its final state, or `null`\n * if no document could be resolved from the operation result.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the update document is missing or invalid.\n */\n async findOneAndUpsert(filter, update, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!update || typeof update !== 'object') {\n throw new Error('Update must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'findOneAndUpsert',\n collectionName: this.resolveCollectionName(ctx),\n filter,\n update\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('findOneAndUpsert', ctx, {\n filter,\n update\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('findOneAndUpsert', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n const effectiveUpdate = (middlewareCtx.update ?? update);\n middlewareCtx.filter = effectiveFilter;\n middlewareCtx.update = effectiveUpdate;\n await this.schema.executePre('updateOne', {\n operation: 'findOneAndUpsert',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate\n });\n const upsertResult = await col.findOneAndUpdate(effectiveFilter, effectiveUpdate, {\n upsert: true,\n returnDocument: 'after',\n ...(session ? { session } : {})\n });\n const updatedDoc = upsertResult &&\n typeof upsertResult === 'object' &&\n 'value' in upsertResult\n ? upsertResult.value\n : upsertResult;\n const payload = updatedDoc\n ? this.toModelResult(updatedDoc)\n : null;\n await this.schema.executePost('updateOne', {\n operation: 'findOneAndUpsert',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: updatedDoc\n });\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('findOneAndUpsert', middlewareCtx);\n await this.invalidateCachePatterns('findOneAndUpsert', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'findOneAndUpsert',\n filter: effectiveFilter,\n update: effectiveUpdate\n }\n });\n return (middlewareCtx.result ?? payload);\n }));\n }\n /**\n * Finds a single document matching the provided filter and updates it inside a\n * transaction. If no document matches, a new one is inserted using MongoDB\n * upsert semantics.\n *\n * This transactional variant runs inside the active Ambiten runtime context,\n * executes registered model middlewares, triggers schema update hooks with\n * transactional metadata, invalidates relevant cache patterns, and publishes a\n * database change event after completion.\n *\n * @param filter - MongoDB filter used to identify the document to update or insert.\n * @param update - MongoDB update document applied to the matched document or inserted document.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and transaction-aware runtime overrides.\n * @returns The updated or newly inserted document in its final state, or `null`\n * if no document could be resolved from the operation result.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the update document is missing or invalid.\n */\n async findOneAndUpsertWithTransaction(filter, update, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!update || typeof update !== 'object') {\n throw new Error('Update must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const col = await this.getCollection(ctx);\n const session = this.resolveSession(ctx);\n const middlewareCtx = this.buildMiddlewareContext('findOneAndUpsert', ctx, {\n filter,\n update,\n meta: {\n transactional: true\n }\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('findOneAndUpsert', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n const effectiveUpdate = (middlewareCtx.update ?? update);\n middlewareCtx.filter = effectiveFilter;\n middlewareCtx.update = effectiveUpdate;\n await this.schema.executePre('updateOne', {\n operation: 'findOneAndUpsert',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n meta: {\n transactional: true\n }\n });\n const upsertResult = await col.findOneAndUpdate(effectiveFilter, effectiveUpdate, {\n upsert: true,\n returnDocument: 'after',\n ...(session ? { session } : {})\n });\n const updatedDoc = upsertResult &&\n typeof upsertResult === 'object' &&\n 'value' in upsertResult\n ? upsertResult.value\n : upsertResult;\n const payload = updatedDoc\n ? this.toModelResult(updatedDoc)\n : null;\n await this.schema.executePost('updateOne', {\n operation: 'findOneAndUpsert',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: updatedDoc,\n meta: {\n transactional: true\n }\n });\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('findOneAndUpsert', middlewareCtx);\n await this.invalidateCachePatterns('findOneAndUpsert', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'findOneAndUpsert',\n filter: effectiveFilter,\n update: effectiveUpdate,\n meta: {\n transactional: true\n }\n }\n });\n return (middlewareCtx.result ?? payload);\n }, ctx));\n }\n /**\n * Finds a single document matching the provided filter and updates it inside a\n * secure transaction. If no document matches, a new one is inserted using\n * MongoDB upsert semantics.\n *\n * This secure transactional variant enforces an admin-only authorization rule\n * before performing the operation. It runs inside the active Ambiten runtime\n * context, executes registered model middlewares, triggers schema update hooks\n * with transactional and security metadata, invalidates relevant cache patterns,\n * and publishes a database change event after completion.\n *\n * @param filter - MongoDB filter used to identify the document to update or insert.\n * @param update - MongoDB update document applied to the matched document or inserted document.\n * @param user - Authenticated user performing the operation. Must have the `admin` role.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and transaction-aware runtime overrides.\n * @returns The updated or newly inserted document in its final state, or `null`\n * if no document could be resolved from the operation result.\n * @throws {Error} When the user is not authorized to perform the operation.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the update document is missing or invalid.\n */\n async findOneAndUpsertWithTransactionSecure(filter, update, user, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!update || typeof update !== 'object') {\n throw new Error('Update must be a valid object.');\n }\n if (!user) {\n throw new Error('User is required.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async () => {\n if (user.role !== 'admin') {\n throw new Error('Unauthorized');\n }\n const meta = {\n transactional: true,\n secure: true,\n userId: user.id,\n userRole: user.role\n };\n const collectionName = this.resolveCollectionName(ctx);\n const col = await this.getCollection(ctx);\n const session = this.resolveSession(ctx);\n const middlewareCtx = this.buildMiddlewareContext('findOneAndUpsert', ctx, {\n filter,\n update,\n meta\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('findOneAndUpsert', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n const effectiveUpdate = (middlewareCtx.update ?? update);\n middlewareCtx.filter = effectiveFilter;\n middlewareCtx.update = effectiveUpdate;\n await this.schema.executePre('updateOne', {\n operation: 'findOneAndUpsert',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n meta\n });\n const upsertResult = await col.findOneAndUpdate(effectiveFilter, effectiveUpdate, {\n upsert: true,\n returnDocument: 'after',\n ...(session ? { session } : {})\n });\n const updatedDoc = upsertResult &&\n typeof upsertResult === 'object' &&\n 'value' in upsertResult\n ? upsertResult.value\n : upsertResult;\n const payload = updatedDoc\n ? this.toModelResult(updatedDoc)\n : null;\n await this.schema.executePost('updateOne', {\n operation: 'findOneAndUpsert',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n update: effectiveUpdate,\n result: updatedDoc,\n meta\n });\n middlewareCtx.result = payload;\n await this.runAfterMiddlewares('findOneAndUpsert', middlewareCtx);\n await this.invalidateCachePatterns('findOneAndUpsert', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentUpdated: {\n action: 'findOneAndUpsert',\n filter: effectiveFilter,\n update: effectiveUpdate,\n meta\n }\n });\n return (middlewareCtx.result ?? payload);\n }, ctx));\n }\n /**\n * Deletes a single document matching the provided filter using an admin-only\n * secure operation.\n *\n * This method enforces authorization before executing the delete flow. It runs\n * inside the active Ambiten runtime context, is instrumented through\n * {@link measureQuery}, executes registered model middlewares, triggers schema\n * delete hooks with security metadata, invalidates relevant cache patterns, and\n * publishes a database change event after a successful deletion.\n *\n * @param filter - MongoDB filter used to identify the document to delete.\n * @param user - Authenticated user performing the operation. Must have the `admin` role.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n * @throws {Error} When the user is not authorized to perform the operation.\n * @throws {Error} When the filter is missing or invalid.\n * @throws {Error} When the user payload is missing.\n */\n async deleteSecure(filter, user, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n if (!user) {\n throw new Error('User is required.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'deleteOne',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n if (user.role !== 'admin') {\n throw new Error('Unauthorized');\n }\n const meta = {\n secure: true,\n userId: user.id,\n userRole: user.role\n };\n const collectionName = this.resolveCollectionName(ctx);\n const col = await this.getCollection(ctx);\n const session = this.resolveSession(ctx);\n const middlewareCtx = this.buildMiddlewareContext('deleteOne', ctx, {\n filter,\n meta\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('deleteOne', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const doc = await col.findOne(effectiveFilter, session ? { session } : undefined);\n if (!doc) {\n middlewareCtx.result = null;\n await this.runAfterMiddlewares('deleteOne', middlewareCtx);\n return;\n }\n const payload = this.toModelResult(doc);\n middlewareCtx.result = payload;\n await this.schema.executePre('deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n ...doc,\n meta\n });\n await col.deleteOne(effectiveFilter, session ? { session } : undefined);\n await this.schema.executePost('deleteOne', {\n operation: 'deleteOne',\n collectionName: middlewareCtx.collectionName,\n ...doc,\n meta\n });\n await this.runAfterMiddlewares('deleteOne', middlewareCtx);\n await this.invalidateCachePatterns('deleteOne', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentDeleted: {\n action: 'deleteOne',\n filter: effectiveFilter,\n meta\n }\n });\n }));\n }\n /**\n * Executes an aggregation pipeline against the model collection.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered aggregate middlewares,\n * supports optional query-result caching, and publishes a database change event\n * after execution.\n *\n * When caching is enabled through {@link QueryOptions}, the aggregation result\n * is stored and reused using a tenant-aware cache key derived from the\n * collection, pipeline, options, and runtime context.\n *\n * @typeParam U - The aggregation result document shape.\n * @param pipeline - MongoDB aggregation pipeline stages.\n * @param options - Optional MongoDB aggregation options.\n * @param externalSession - Optional explicit client session to use for the aggregation.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @param queryOptions - Optional query-level features such as caching.\n * @returns The aggregation result array.\n * @throws {Error} When the pipeline is missing or invalid.\n */\n async aggregate(pipeline, options = {}, externalSession, ctx, queryOptions) {\n await this.init();\n if (!Array.isArray(pipeline)) {\n throw new Error('Pipeline must be a valid array.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'aggregate',\n collectionName: this.resolveCollectionName(ctx),\n pipeline\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const col = await this.getCollection(ctx);\n const resolvedSession = this.resolveSessionStrict(ctx, externalSession);\n const middlewareCtx = this.buildMiddlewareContext('aggregate', ctx, {\n pipeline\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('aggregate', middlewareCtx);\n const effectivePipeline = (middlewareCtx.pipeline ?? pipeline);\n middlewareCtx.pipeline = effectivePipeline;\n const cache = queryOptions?.cache\n ? this.resolveCache(queryOptions)\n : null;\n await this.schema.executePre('aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session: resolvedSession,\n pipeline: effectivePipeline,\n meta: middlewareCtx.meta\n });\n let cacheKey = null;\n if (cache) {\n cacheKey = this.buildCacheKey('aggregate', {\n collectionName: middlewareCtx.collectionName,\n pipeline: effectivePipeline,\n options,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName\n });\n const cached = await cache.get(cacheKey, {\n ttlSeconds: typeof queryOptions?.cache === 'object'\n ? queryOptions.cache.ttl\n : undefined,\n tenantId: middlewareCtx.tenantId,\n namespace: middlewareCtx.collectionName\n });\n if (cached) {\n middlewareCtx.result = cached;\n await this.runAfterMiddlewares('aggregate', middlewareCtx);\n return (middlewareCtx.result ?? cached);\n }\n }\n const cursor = col.aggregate(effectivePipeline, {\n ...options,\n ...(resolvedSession ? { session: resolvedSession } : {})\n });\n const result = await cursor.toArray();\n await this.schema.executePost('aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session: resolvedSession,\n pipeline: effectivePipeline,\n result,\n meta: middlewareCtx.meta\n });\n middlewareCtx.result = result;\n await this.runAfterMiddlewares('aggregate', middlewareCtx);\n const finalResult = (middlewareCtx.result ?? result);\n if (cache && cacheKey) {\n await cache.set(cacheKey, finalResult, {\n ttlSeconds: typeof queryOptions?.cache === 'object'\n ? queryOptions.cache.ttl\n : undefined,\n tenantId: middlewareCtx.tenantId,\n namespace: middlewareCtx.collectionName\n });\n }\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n dbChange: {\n action: 'aggregate',\n pipeline: effectivePipeline\n }\n });\n return finalResult;\n }));\n }\n /**\n * Executes an aggregation pipeline inside a transaction-aware runtime context.\n *\n * This transactional variant runs within the active Ambiten runtime context,\n * executes registered aggregate middlewares, triggers schema aggregate hooks,\n * instruments the query through {@link measureQuery}, and publishes a database\n * change event after execution.\n *\n * @typeParam U - The aggregation result document shape.\n * @param pipeline - MongoDB aggregation pipeline stages.\n * @param options - Optional MongoDB aggregation options.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and transaction-aware runtime overrides.\n * @returns The aggregation result array.\n * @throws {Error} When the pipeline is missing or invalid.\n */\n async aggregateWithTransaction(pipeline, options = {}, ctx) {\n await this.init();\n if (!Array.isArray(pipeline)) {\n throw new Error('Pipeline must be a valid array.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async () => (0, instrumentation_1.measureQuery)({\n operation: 'aggregate',\n collectionName: this.resolveCollectionName(ctx),\n pipeline\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const col = await this.getCollection(ctx);\n const session = this.resolveSession(ctx);\n const middlewareCtx = this.buildMiddlewareContext('aggregate', ctx, {\n pipeline,\n meta: {\n transactional: true\n }\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('aggregate', middlewareCtx);\n const effectivePipeline = (middlewareCtx.pipeline ?? pipeline);\n middlewareCtx.pipeline = effectivePipeline;\n await this.schema.executePre('aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n pipeline: effectivePipeline,\n meta: {\n ...(middlewareCtx.meta ?? {}),\n transactional: true\n }\n });\n const cursor = col.aggregate(effectivePipeline, {\n ...options,\n ...(session ? { session } : {})\n });\n const result = await cursor.toArray();\n await this.schema.executePost('aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n pipeline: effectivePipeline,\n result,\n meta: {\n ...(middlewareCtx.meta ?? {}),\n transactional: true\n }\n });\n middlewareCtx.result = result;\n await this.runAfterMiddlewares('aggregate', middlewareCtx);\n const finalResult = (middlewareCtx.result ?? result);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n dbChange: {\n action: 'aggregate',\n pipeline: effectivePipeline,\n meta: {\n transactional: true\n }\n }\n });\n return finalResult;\n }), ctx));\n }\n /**\n * Executes the provided operation within a transaction-aware runtime context.\n *\n * Resolution order:\n * 1. Reuse an existing session from the merged model context when available.\n * 2. Start a provider-managed session when the active database provider\n * exposes a session factory.\n * 3. Fall back to {@link AmbitenContext.withTransaction} to resolve a client\n * and execute the operation inside a transaction.\n *\n * When an existing session is supplied, the current transaction boundary is\n * reused and no new transaction is started.\n *\n * @typeParam R - The operation result type.\n * @param operation - Callback executed with the resolved MongoDB client session.\n * @param ctx - Optional model execution context used to resolve tenant,\n * database, collection, and session overrides.\n * @returns The resolved operation result.\n */\n async withTransaction(operation, ctx) {\n const baseCtx = this.mergeCtx(ctx) ?? {};\n const collectionName = baseCtx.collectionName ?? this._collectionName;\n const existingSession = baseCtx.session;\n const runtimeBase = {\n tenantId: baseCtx.tenantId,\n dbName: baseCtx.dbName,\n collectionName\n };\n if (existingSession) {\n return context_1.AmbitenContext.run({\n ...runtimeBase,\n session: existingSession\n }, async () => operation(existingSession));\n }\n if (this._provider?.startSession) {\n const session = await this.getSession(baseCtx);\n return await context_1.AmbitenContext.run({\n ...runtimeBase,\n session\n }, async () => (0, context_1.runManualTransaction)(session, operation));\n }\n return context_1.AmbitenContext.run(runtimeBase, async () => context_1.AmbitenContext.withTransaction(operation));\n }\n /**\n * Executes the provided operation inside a transaction-aware Ambiten runtime context.\n *\n * This helper ensures the operation runs with a resolved MongoDB client session\n * and within the active Ambiten runtime context for the current tenant,\n * database, and collection. If a session already exists in the merged model\n * context, that session is reused and no new transaction boundary is created.\n *\n * Use this method when multiple model operations must be executed atomically\n * within a single transactional unit of work.\n *\n * @typeParam R - The operation result type.\n * @param operation - Callback executed with the resolved MongoDB client session.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, and session overrides.\n * @returns The resolved result of the transactional operation.\n */\n async runInTransaction(operation, ctx) {\n await this.init();\n if (typeof operation !== 'function') {\n throw new Error('Operation must be a valid function.');\n }\n return this.runWithModelContext(ctx, async () => this.withTransaction(async (session) => operation(session), ctx));\n }\n async getSession(ctx) {\n if (!this._provider?.startSession) {\n throw new Error('Transaction support is not available. Provider does not implement startSession().');\n }\n return this._provider.startSession(this.mergeCtx(ctx));\n }\n /**\n * Creates a readable stream for an aggregation pipeline.\n *\n * This method runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered aggregate middlewares,\n * triggers schema aggregate hooks, and publishes a database change event after\n * the aggregation stream is created.\n *\n * This method instruments stream creation only. It does not track the full\n * lifecycle of stream consumption unless additional listeners are attached by\n * the caller or by a higher-level observability layer.\n *\n * @typeParam U - The aggregation result document shape.\n * @param pipeline - MongoDB aggregation pipeline stages.\n * @param options - Optional MongoDB aggregation options.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A readable stream for the aggregation result set.\n * @throws {Error} When the pipeline is missing or invalid.\n */\n async streamAggregation(pipeline, options = {}, ctx) {\n await this.init();\n if (!Array.isArray(pipeline)) {\n throw new Error('Pipeline must be a valid array.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'aggregate',\n collectionName: this.resolveCollectionName(ctx),\n pipeline,\n extra: {\n streaming: true\n }\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const middlewareCtx = this.buildMiddlewareContext('aggregate', ctx, {\n pipeline,\n meta: {\n streaming: true\n }\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('aggregate', middlewareCtx);\n const effectivePipeline = (middlewareCtx.pipeline ?? pipeline);\n middlewareCtx.pipeline = effectivePipeline;\n const meta = {\n ...(middlewareCtx.meta ?? {}),\n streaming: true\n };\n await this.schema.triggerMiddleware('pre', 'aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n pipeline: effectivePipeline,\n meta\n });\n await this.schema.executePre('aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n pipeline: effectivePipeline,\n meta\n });\n const stream = col.aggregate(effectivePipeline, {\n ...options,\n ...(session ? { session } : {})\n }).stream();\n await this.schema.triggerMiddleware('post', 'aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n result: stream,\n meta\n });\n await this.schema.executePost('aggregate', {\n operation: 'aggregate',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n pipeline: effectivePipeline,\n result: stream,\n meta\n });\n middlewareCtx.result = stream;\n await this.runAfterMiddlewares('aggregate', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n dbChange: {\n action: 'aggregateStream',\n collectionName: middlewareCtx.collectionName,\n pipeline: effectivePipeline,\n meta\n }\n });\n return stream;\n }));\n }\n /**\n * Aggregates documents in the collection using a pipeline with caching.\n * @param {object[]} pipeline - The aggregation pipeline.\n * @param {string} cacheKey - The cache key.\n * @param {number} [cacheDuration=300] - The cache duration in seconds.\n * @returns {Promise<T[]>} The aggregation result as an array.\n * @throws {Error} If the pipeline is not valid or the cache key is not a string.\n */\n async aggregateWithCache(pipeline, cacheKey, cacheDuration = 300) {\n await this.init();\n if (!Array.isArray(pipeline)) {\n throw new Error('Pipeline must be an array of objects.');\n }\n const cachedResult = await redis_manager_1.redis.get(cacheKey);\n if (cachedResult) {\n console.info(`[info]: Cache hit: ${cacheKey}`);\n return JSON.parse(cachedResult);\n }\n else if (typeof cacheKey !== 'string') {\n throw new Error('Cache key must be a string.');\n }\n else {\n console.info(`[info]: Cache miss: ${cacheKey}`);\n }\n const col = await this.getCollection();\n const result = await col.aggregate(pipeline).toArray();\n await redis_manager_1.redis.set(cacheKey, JSON.stringify(result) || '');\n await redis_manager_1.redis.expire(cacheKey, cacheDuration);\n console.info('Cache set:', cacheKey);\n this.schema.triggerMiddleware('post', 'aggregate', {\n operation: 'aggregate',\n collectionName: this.resolveCollectionName(col),\n result: [result]\n });\n await pubsub.publish(\"DB_CHANGE\", { dbChange: { action: \"aggregate\", result } });\n return result || [];\n }\n /**\n * Cursor-based pagination using _id comparison instead of skip.\n * @param filter - The filter for documents.\n * @param pageSize - Number of documents per page.\n * @param lastId - Last document _id from the previous page.\n * @returns {Promise<T[]>} Array of documents for the current page.\n * This method uses the _id field for pagination, which is more efficient than using skip.\n *\n */\n async paginatedFind(filter, pageSize, lastId) {\n await this.init();\n const query = filter;\n if (lastId) {\n query._id = { $gt: new mongodb_1.ObjectId(lastId) }; // Fetch only newer documents\n }\n const col = await this.getCollection();\n const results = await col.find(query).limit(pageSize).toArray();\n return results.map(({ _id, ...rest }) => rest);\n }\n ;\n /**\n * Opens a MongoDB change stream on the model collection and registers a change\n * callback.\n *\n * This helper initializes the model, resolves the collection within the active\n * Ambiten runtime context, creates a change stream, and subscribes the provided\n * callback to `\"change\"` events.\n *\n * The method is intentionally lightweight: it manages change stream creation,\n * but does not yet instrument the full lifecycle of emitted change events. That\n * can be added later by higher-level observability or evidence collection\n * layers.\n *\n * @param callback - Function invoked whenever a change event is emitted by the collection change stream.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns The active MongoDB change stream.\n * @throws {Error} When the callback is not a valid function.\n */\n async watchChanges(callback, ctx) {\n await this.init();\n if (typeof callback !== 'function') {\n throw new Error('Callback must be a valid function.');\n }\n return this.runWithModelContext(ctx, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const col = await this.getCollection(ctx);\n const changeStream = col.watch();\n changeStream.on('change', callback);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n dbChange: {\n action: 'watchChanges',\n collectionName\n }\n });\n return changeStream;\n });\n }\n /**\n * Creates an index on the model collection.\n *\n * @param fields - Index field specification where each key maps to ascending\n * (`1`) or descending (`-1`) index order.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the index has been created.\n * @throws {Error} When the field specification is missing or invalid.\n */\n async createIndex(fields, ctx) {\n await this.init();\n if (!fields || typeof fields !== 'object') {\n throw new Error('Index fields must be a valid object.');\n }\n const entries = Object.entries(fields);\n if (entries.length === 0) {\n throw new Error('Index fields must contain at least one entry.');\n }\n for (const [, direction] of entries) {\n if (direction !== 1 && direction !== -1) {\n throw new Error('Index direction must be either 1 or -1.');\n }\n }\n return this.runWithModelContext(ctx, async () => {\n const col = await this.getCollection(ctx);\n await col.createIndex(fields);\n });\n }\n /**\n * Drops an index from the collection by its name.\n * @param {string} indexName - The name of the index to drop.\n * @returns {Promise<void>} Resolves when the index is dropped.\n */\n async dropIndex(indexName) {\n await this.init();\n const col = await this.getCollection();\n await col.dropIndex(indexName);\n }\n // ============== Invalidation ==============//\n async invalidateCachePatterns(operation, ctx) {\n const tenantId = ctx.tenantId ?? 'default';\n const dbName = ctx.dbName ?? 'default';\n const collectionName = ctx.collectionName ?? this._collectionName;\n const basePatterns = [\n `Ambiten:${tenantId}:${dbName}:${collectionName}:find:*`,\n `Ambiten:${tenantId}:${dbName}:${collectionName}:findOne:*`\n ];\n const patterns = operation === 'aggregate'\n ? [\n ...basePatterns,\n `Ambiten:${tenantId}:${dbName}:${collectionName}:aggregate:*`\n ]\n : [\n ...basePatterns,\n `Ambiten:${tenantId}:${dbName}:${collectionName}:aggregate:*`\n ];\n await Promise.all([...new Set(patterns)].map((pattern) => AmbitenModel.invalidatePattern(pattern)));\n }\n /**\n * Invalidates all cache entries matching the provided Redis key pattern.\n *\n * This method uses Redis `SCAN` to iterate over matching keys in batches and\n * deletes them using a pipelined multi-operation for better efficiency.\n *\n * @param pattern - Redis key pattern to invalidate.\n * @returns The number of successfully deleted keys.\n * @throws {Error} When the pattern is invalid or cache invalidation fails.\n */\n static async invalidatePattern(pattern) {\n if (typeof pattern !== 'string' || pattern.trim().length === 0) {\n throw new Error('Pattern must be a non-empty string.');\n }\n const normalizedPattern = pattern.trim();\n const scanCount = 100;\n let deletedCount = 0;\n let cursor = 0;\n try {\n do {\n const result = await redis_manager_1.redis.scan(cursor, {\n MATCH: normalizedPattern,\n COUNT: scanCount\n });\n const nextCursor = Array.isArray(result) ? Number(result[0]) : 0;\n const keys = Array.isArray(result) ? result[1] : [];\n if (Array.isArray(keys) && keys.length > 0) {\n const multi = redis_manager_1.redis.multi();\n for (const key of keys) {\n multi.del(key);\n }\n const execResult = await multi.exec();\n if (Array.isArray(execResult)) {\n deletedCount += execResult.filter((entry) => {\n if (Array.isArray(entry)) {\n const [err, value] = entry;\n return !err && value === 1;\n }\n return entry === 1;\n }).length;\n }\n }\n cursor = nextCursor;\n } while (cursor !== 0);\n return deletedCount;\n }\n catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to invalidate cache pattern \"${normalizedPattern}\": ${message}`);\n }\n }\n getContext() {\n return { ctx: {} };\n }\n /**\n * Invalidates cache entries for the current model scope using a pattern.\n *\n * This helper resolves tenant, database, and collection scope from the\n * provided context and applies the pattern within the Ambiten cache namespace.\n *\n * @param pattern - Partial cache pattern (e.g. \"find:*\", \"aggregate:*\").\n * @param ctx - Optional model execution context.\n * @returns Number of deleted cache entries.\n * @throws {Error} When the pattern is invalid.\n */\n async invalidateModelPattern(pattern, ctx) {\n await this.init();\n if (typeof pattern !== 'string' || pattern.trim().length === 0) {\n throw new Error('Pattern must be a non-empty string.');\n }\n return this.runWithModelContext(ctx, async () => {\n const tenantId = ctx?.tenantId ?? 'default';\n const dbName = ctx?.dbName ?? 'default';\n const collectionName = ctx?.collectionName ?? this._collectionName;\n const fullPattern = `Ambiten:${tenantId}:${dbName}:${collectionName}:${pattern.trim()}`;\n return AmbitenModel.invalidatePattern(fullPattern);\n });\n }\n /**\n * Invalidates cache entries related to a specific document within the current\n * model scope.\n *\n * This helper is useful only when document-specific cache keys are part of the\n * active cache strategy.\n *\n * @param doc - The document whose cache entries should be invalidated.\n * @param ctx - Optional model execution context.\n * @returns A promise that resolves when invalidation completes.\n * @throws {Error} When the document is missing a valid `_id`.\n */\n async invalidateDocumentCache(doc, ctx) {\n await this.init();\n if (!doc || typeof doc !== 'object' || !('_id' in doc) || !doc._id) {\n throw new Error('Document must contain a valid _id.');\n }\n return this.runWithModelContext(ctx, async () => {\n const merged = this.mergeCtx(ctx);\n const tenantId = merged?.tenantId ?? 'default';\n const dbName = merged?.dbName ?? 'default';\n const collectionName = merged?.collectionName ?? this._collectionName;\n const pattern = `Ambiten:${tenantId}:${dbName}:${collectionName}:*${String(doc._id)}*`;\n return AmbitenModel.invalidatePattern(pattern);\n });\n }\n /**\n * Returns cache statistics for the active Redis cache backend.\n *\n * This helper retrieves Redis memory and keyspace statistics, along with Ambiten\n * cache hit/miss counters. When a tenant identifier is provided, it also counts\n * cache keys scoped to that tenant within the Ambiten cache namespace.\n *\n * @param tenantId - Optional tenant identifier used to count tenant-scoped cache keys.\n * @returns Cache statistics for the current Redis backend.\n * @throws {Error} When cache statistics cannot be retrieved.\n */\n static async getCacheStats(tenantId) {\n try {\n const memoryInfo = await redis_manager_1.redis.info('memory');\n const keyspaceInfo = await redis_manager_1.redis.info('keyspace');\n const matches = Array.from(keyspaceInfo.matchAll(/db\\d+:keys=(\\d+)/g));\n const totalKeys = matches.reduce((sum, match) => {\n return sum + Number(match[1] ?? 0);\n }, 0);\n const memoryMatch = memoryInfo.match(/used_memory:(\\d+)/);\n const memoryUsageBytes = memoryMatch ? Number(memoryMatch[1]) : 0;\n const hitsRaw = (await redis_manager_1.redis.get('Ambiten:cache:stats:hits')) ?? '0';\n const missesRaw = (await redis_manager_1.redis.get('Ambiten:cache:stats:misses')) ?? '0';\n const totalHits = Number.parseInt(hitsRaw, 10) || 0;\n const totalMisses = Number.parseInt(missesRaw, 10) || 0;\n const totalRequests = totalHits + totalMisses;\n const hitRate = totalRequests > 0\n ? Math.round((totalHits / totalRequests) * 100)\n : 0;\n const missRate = totalRequests > 0\n ? Math.round((totalMisses / totalRequests) * 100)\n : 0;\n let tenantKeys;\n if (tenantId) {\n const pattern = `Ambiten:${tenantId}:*`;\n let cursor = 0;\n let count = 0;\n do {\n const result = await redis_manager_1.redis.scan(cursor, {\n MATCH: pattern,\n COUNT: 100\n });\n const nextCursor = Array.isArray(result) ? Number(result[0]) : 0;\n const keys = Array.isArray(result) ? result[1] : [];\n if (Array.isArray(keys)) {\n count += keys.length;\n }\n cursor = nextCursor;\n } while (cursor !== 0);\n tenantKeys = count;\n }\n return {\n totalKeys,\n tenantKeys,\n memoryUsageMb: Math.round(memoryUsageBytes / 1024 / 1024),\n memoryUsageBytes,\n hitRate,\n missRate,\n totalHits,\n totalMisses,\n totalRequests,\n tenantId: tenantId ?? null,\n timestamp: new Date().toISOString()\n };\n }\n catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to get cache stats: ${message}`);\n }\n }\n /**\n * Runs a custom command on the collection.\n * @param {string} command - The command to run.\n * @param {...any} args - The arguments for the command.\n * @returns {Promise<any>} The result of the command.\n */\n async runCommand(command, ...args) {\n await this.init();\n const dbCommand = { [command]: 1, ...args };\n const col = await this.getCollection();\n return col.db.command(dbCommand);\n }\n /**\n * Runs garbage collection for expired documents in the model collection.\n *\n * This operation uses the model GC configuration to locate expired documents\n * and either soft-delete them or permanently delete them. When configured,\n * expired documents may be archived before deletion.\n *\n * The operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered GC-related middlewares,\n * triggers schema update/delete hooks as appropriate, invalidates relevant\n * cache patterns, and publishes a garbage collection event after completion.\n *\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when garbage collection completes.\n */\n async runGC(ctx) {\n await this.init();\n const config = this.resolveSchemaGCConfig();\n if (!config || !config.ttlField || !config.expiresIn) {\n return;\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'runGC',\n collectionName: this.resolveCollectionName(ctx)\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const meta = {\n gc: true\n };\n const middlewareCtx = this.buildMiddlewareContext('runGC', ctx, { meta });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('runGC', middlewareCtx);\n const expireDate = new Date(Date.now() - Number(config.expiresIn));\n const gcFilter = {\n [config.ttlField]: { $lt: expireDate }\n };\n const effectiveFilter = (middlewareCtx.filter ?? gcFilter);\n middlewareCtx.filter = effectiveFilter;\n const expiredDocs = await col.find(effectiveFilter, session ? { session } : undefined).toArray();\n if (expiredDocs.length === 0) {\n middlewareCtx.result = {\n scanned: 0,\n affected: 0,\n archived: 0,\n deleted: 0,\n softDeleted: 0\n };\n await this.runAfterMiddlewares('runGC', middlewareCtx);\n return;\n }\n let archived = 0;\n let deleted = 0;\n let softDeleted = 0;\n if (config.softDelete) {\n const softDeleteUpdate = {\n $set: {\n deletedAt: new Date(),\n isDeleted: true\n }\n };\n await this.schema.executePre('updateMany', {\n operation: 'runGC',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n docs: expiredDocs,\n meta: {\n ...(middlewareCtx.meta ?? {}),\n gc: true,\n softDelete: true\n }\n });\n const result = await col.updateMany(effectiveFilter, softDeleteUpdate, session ? { session } : undefined);\n softDeleted = result.modifiedCount;\n await this.schema.executePost('updateMany', {\n operation: 'runGC',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: softDeleteUpdate,\n docs: expiredDocs,\n result: {\n scanned: expiredDocs.length,\n affected: softDeleted,\n archived: 0,\n deleted: 0,\n softDeleted\n },\n meta: {\n ...(middlewareCtx.meta ?? {}),\n gc: true,\n softDelete: true\n }\n });\n }\n else {\n if (config.archiveBeforeDelete) {\n const archiveDocs = expiredDocs.map((doc) => ({\n ...doc,\n _archivedAt: new Date(),\n _from: col.collectionName\n }));\n await col.db.collection('Ambiten_archives').insertMany(archiveDocs, session ? { session } : undefined);\n archived = archiveDocs.length;\n }\n await this.schema.triggerMiddleware('pre', 'deleteMany', {\n operation: 'runGC',\n collectionName: middlewareCtx.collectionName,\n docs: expiredDocs\n });\n await this.schema.executePre('deleteMany', {\n operation: 'runGC',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n docs: expiredDocs,\n result: this.toModelResults(expiredDocs),\n meta: {\n ...(middlewareCtx.meta ?? {}),\n gc: true\n }\n });\n const result = await col.deleteMany(effectiveFilter, session ? { session } : undefined);\n deleted = result.deletedCount ?? 0;\n await this.schema.triggerMiddleware('post', 'deleteMany', {\n operation: 'runGC',\n collectionName: middlewareCtx.collectionName,\n docs: expiredDocs\n });\n await this.schema.executePost('deleteMany', {\n operation: 'runGC',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n docs: expiredDocs,\n result: {\n scanned: expiredDocs.length,\n affected: deleted,\n archived,\n deleted,\n softDeleted: 0\n },\n meta: {\n ...(middlewareCtx.meta ?? {}),\n gc: true\n }\n });\n }\n const gcResult = {\n scanned: expiredDocs.length,\n affected: softDeleted || deleted,\n archived,\n deleted,\n softDeleted\n };\n middlewareCtx.result = gcResult;\n await this.runAfterMiddlewares('runGC', middlewareCtx);\n await this.invalidateCachePatterns('runGC', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n garbageCollection: {\n action: 'runGC',\n collectionName: middlewareCtx.collectionName,\n ...gcResult,\n meta: {\n ...(middlewareCtx.meta ?? {}),\n gc: true\n }\n }\n });\n }));\n }\n /**\n * Starts the automatic garbage collection process.\n * @param {number} intervalMs - The interval in milliseconds for the garbage collection to run.\n */\n startAutoGC(intervalMs = 3600000) {\n setInterval(() => this.runGC().catch(console.error), intervalMs);\n }\n /**\n * Resolves instrumentation context for model operations by combining explicit\n * model context with the active runtime context.\n *\n * This helper is used to provide stable metadata for logging, observers,\n * tracing, and query instrumentation.\n *\n * @param ctx - Optional model execution context.\n * @returns Resolved instrumentation metadata for the current operation.\n */\n resolveInstrumentationContext(ctx) {\n const runtimeCtx = context_1.AmbitenContext.get();\n const merged = this.mergeCtx(ctx);\n return {\n tenantId: merged?.tenantId,\n dbName: merged?.dbName,\n collectionName: merged?.collectionName ?? this._collectionName,\n session: merged?.session,\n requestId: runtimeCtx.requestId\n };\n }\n /**\n * Builds normalized operation metadata by merging existing middleware metadata\n * with operation-specific overrides.\n *\n * @param base - Existing operation metadata.\n * @param overrides - Additional metadata flags or values to apply.\n * @returns Normalized operation metadata.\n */\n buildOperationMeta(base, overrides) {\n return {\n ...(base ?? {}),\n ...(overrides ?? {}),\n extra: {\n ...(base?.extra ?? {}),\n ...(overrides?.extra ?? {})\n }\n };\n }\n /**\n * Builds a normalized hook payload for schema middleware and instrumentation.\n *\n * @param operation - Operation name.\n * @param ctx - Optional model execution context.\n * @param payload - Additional hook payload fields.\n * @returns Normalized hook payload.\n */\n buildHookPayload(operation, ctx, payload = {}) {\n const instrumentation = this.resolveInstrumentationContext(ctx);\n return {\n operation,\n collectionName: payload.collectionName ?? instrumentation.collectionName,\n tenantId: payload.tenantId ?? instrumentation.tenantId,\n dbName: payload.dbName ?? instrumentation.dbName,\n session: payload.session ?? instrumentation.session,\n filter: payload.filter,\n update: payload.update,\n doc: payload.doc,\n docs: payload.docs,\n pipeline: payload.pipeline,\n result: payload.result,\n meta: payload.meta\n };\n }\n //=============== Cache ====================//\n /**\n * Resolves a cache adapter for the current query options.\n *\n * This helper returns a lightweight Redis-backed cache interface when caching\n * is enabled in the provided query options. Cache failures are treated as\n * non-fatal so query execution can continue even when Redis is unavailable or\n * a cache payload is invalid.\n *\n * @param options - Optional query options that may enable caching.\n * @returns A cache adapter when caching is enabled, otherwise `null`.\n */\n resolveCache(options) {\n if (!options?.cache) {\n return null;\n }\n return {\n get: async (key, meta) => {\n try {\n const cached = await redis_manager_1.redis.get(key);\n if (!cached) {\n await AmbitenModel.trackCacheMiss();\n return null;\n }\n const parsed = JSON.parse(cached);\n await AmbitenModel.trackCacheHit();\n return parsed;\n }\n catch {\n return null;\n }\n },\n set: async (key, value, meta) => {\n try {\n const ttl = meta?.ttlSeconds ?? 300;\n await redis_manager_1.redis.set(key, JSON.stringify(value), {\n EX: ttl\n });\n }\n catch {\n // Best-effort cache write. Intentionally ignored.\n }\n }\n };\n }\n /**\n * Builds a deterministic cache key for a query operation.\n *\n * The cache key is scoped by tenant, database, collection, and operation, and\n * uses a normalized serialized payload to ensure stable cache identity across\n * semantically equivalent query inputs.\n *\n * @param operation - Query operation name.\n * @param payload - Cache identity payload for the operation.\n * @returns A deterministic tenant-aware cache key.\n */\n buildCacheKey(operation, payload) {\n const tenantId = String(payload.tenantId ?? 'default');\n const dbName = String(payload.dbName ?? 'default');\n const collectionName = String(payload.collectionName ?? this._collectionName);\n const { tenantId: _tenantId, dbName: _dbName, collectionName: _collectionName, ...rest } = payload;\n const normalizedPayload = this.sortObjectDeep(rest);\n const serialized = JSON.stringify(normalizedPayload);\n return `Ambiten:${tenantId}:${dbName}:${collectionName}:${operation}:${serialized}`;\n }\n static async trackCacheMiss() {\n try {\n const today = new Date().toISOString().slice(0, 10);\n const retentionSeconds = 86400 * 7;\n const pipeline = redis_manager_1.redis.multi();\n pipeline.incr('Ambiten:cache:stats:misses');\n pipeline.incr(`Ambiten:cache:stats:misses:${today}`);\n pipeline.expire(`Ambiten:cache:stats:misses:${today}`, retentionSeconds);\n await pipeline.exec();\n }\n catch {\n // Best-effort telemetry. Intentionally ignored.\n }\n }\n static async trackCacheHit() {\n try {\n const today = new Date().toISOString().slice(0, 10);\n const retentionSeconds = 86400 * 7;\n const pipeline = redis_manager_1.redis.multi();\n pipeline.incr('Ambiten:cache:stats:hits');\n pipeline.incr(`Ambiten:cache:stats:hits:${today}`);\n pipeline.expire(`Ambiten:cache:stats:hits:${today}`, retentionSeconds);\n await pipeline.exec();\n }\n catch {\n // Best-effort telemetry. Intentionally ignored.\n }\n }\n static async cacheResult(key, data, ttl = 3600) {\n if (typeof key !== 'string' || key.trim().length === 0) {\n throw new Error('Cache key must be a non-empty string.');\n }\n if (!Number.isFinite(ttl) || ttl <= 0) {\n throw new Error('TTL must be a positive number.');\n }\n try {\n await redis_manager_1.redis.set(key, JSON.stringify(data));\n await redis_manager_1.redis.expire(key, ttl);\n }\n catch {\n // Best-effort cache write. Intentionally ignored.\n }\n }\n /**\n * Clears a cached result by its key.\n * @param {string} key - The cache key.\n * @returns {Promise<void>} Resolves when the cache is cleared.\n */\n static async clearCache(key) {\n if (!key || typeof key !== 'string') {\n throw new Error('Cache key must be a non-empty string');\n }\n try {\n await redis_manager_1.redis.del(key);\n }\n catch (error) {\n console.error('Error clearing cache:', error);\n throw new Error(`Failed to clear cache for key \"${key}\": ${error}`);\n }\n }\n /**\n * Warms cache entries for selected model queries.\n *\n * When query definitions are provided, this helper executes the corresponding\n * `find` operations and stores the results using Ambiten's scoped cache key\n * strategy. When no queries are provided, it warms a default collection-wide\n * `find({})` cache entry, subject to a safety threshold for large collections.\n *\n * This helper is best suited for controlled cache priming scenarios such as\n * startup warmup, scheduled maintenance, or high-traffic query preparation.\n *\n * @param queries - Optional list of query definitions to warm.\n * @param defaultTtl - Default TTL in seconds for warmed entries.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when cache warming completes.\n * @throws {Error} When cache warming fails.\n */\n async warmCache(queries, defaultTtl = 3600, ctx) {\n await this.init();\n if (!Number.isFinite(defaultTtl) || defaultTtl <= 0) {\n throw new Error('Default TTL must be a positive number.');\n }\n return this.runWithModelContext(ctx, async () => {\n const cache = this.resolveCache({ cache: { ttl: defaultTtl } });\n if (!cache) {\n return;\n }\n const instrumentation = this.resolveInstrumentationContext(ctx);\n const col = await this.getCollection(ctx);\n const session = this.resolveSession(ctx);\n const warmQueries = queries && queries.length > 0\n ? queries\n : [{ filter: {}, ttl: defaultTtl }];\n if ((!queries || queries.length === 0)) {\n const totalDocs = await col.countDocuments({}, session ? { session } : undefined);\n if (totalDocs > 1000) {\n return;\n }\n }\n for (const query of warmQueries) {\n const filter = (query.filter ?? {});\n const ttl = query.ttl ?? defaultTtl;\n const docs = await col.find(filter, session ? { session } : undefined).toArray();\n const payload = this.toModelResults(docs);\n const cacheKey = this.buildCacheKey('find', {\n collectionName: instrumentation.collectionName,\n filter,\n tenantId: instrumentation.tenantId,\n dbName: instrumentation.dbName\n });\n await cache.set(cacheKey, payload, {\n ttlSeconds: ttl,\n tenantId: instrumentation.tenantId,\n namespace: instrumentation.collectionName\n });\n }\n });\n }\n // We want to avoids cache-key drift from key ordering.\n sortObjectDeep(value) {\n if (Array.isArray(value)) {\n return value.map((item) => this.sortObjectDeep(item));\n }\n if (value instanceof Date) {\n return value.toISOString();\n }\n if (value && typeof value === 'object') {\n return Object.keys(value)\n .sort()\n .reduce((acc, key) => {\n acc[key] = this.sortObjectDeep(value[key]);\n return acc;\n }, {});\n }\n return value;\n }\n toModelResult(doc) {\n const { _id, ...rest } = doc;\n return {\n ...rest,\n _id: _id.toString()\n };\n }\n toModelResults(docs = []) {\n return docs.map((doc) => this.toModelResult(doc));\n }\n /**\n * Restores a single soft-deleted document matching the provided filter.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered restore middlewares,\n * triggers schema update hooks, invalidates relevant cache patterns, and\n * publishes a document restoration event after completion.\n *\n * The actual restore behavior is driven by the update document returned from\n * {@link buildRestoreUpdate}.\n *\n * @param filter - MongoDB filter used to identify the document to restore.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n * @throws {Error} When the filter is missing or invalid.\n */\n async restoreOne(filter, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'restoreOne',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const meta = {\n restore: true\n };\n const middlewareCtx = this.buildMiddlewareContext('restoreOne', ctx, {\n filter,\n meta\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('restoreOne', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const restoreUpdate = this.buildRestoreUpdate();\n const existingDoc = await col.findOne(effectiveFilter, session ? { session } : undefined);\n if (!existingDoc) {\n middlewareCtx.result = null;\n await this.runAfterMiddlewares('restoreOne', middlewareCtx);\n return;\n }\n await this.schema.executePre('restoreOne', {\n operation: 'restoreOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: restoreUpdate,\n meta\n });\n const result = await col.updateOne(effectiveFilter, restoreUpdate, session ? { session } : undefined);\n const restoredDoc = await col.findOne(effectiveFilter, session ? { session } : undefined);\n const restoreResult = {\n acknowledged: result.acknowledged,\n matchedCount: result.matchedCount,\n modifiedCount: result.modifiedCount,\n upsertedCount: result.upsertedCount,\n upsertedId: result.upsertedId,\n restored: restoredDoc\n ? this.toModelResult(restoredDoc)\n : null\n };\n await this.schema.executePost('restoreOne', {\n operation: 'restoreOne',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: restoreUpdate,\n result: restoreResult,\n meta\n });\n middlewareCtx.result = restoreResult;\n await this.runAfterMiddlewares('restoreOne', middlewareCtx);\n await this.invalidateCachePatterns('restoreOne', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentRestored: {\n action: 'restoreOne',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n result: restoreResult,\n meta\n }\n });\n }));\n }\n /**\n * Restores multiple soft-deleted documents matching the provided filter.\n *\n * This operation runs inside the active Ambiten runtime context, is instrumented\n * through {@link measureQuery}, executes registered restore middlewares,\n * triggers schema update hooks, invalidates relevant cache patterns, and\n * publishes a document restoration event after completion.\n *\n * The actual restore behavior is driven by the update document returned from\n * {@link buildRestoreUpdate}.\n *\n * @param filter - MongoDB filter used to identify the documents to restore.\n * @param ctx - Optional model execution context for tenant, database,\n * collection, session, and related runtime overrides.\n * @returns A promise that resolves when the operation completes.\n * @throws {Error} When the filter is missing or invalid.\n */\n async restoreMany(filter, ctx) {\n await this.init();\n if (!filter || typeof filter !== 'object') {\n throw new Error('Filter must be a valid object.');\n }\n return this.runWithModelContext(ctx, async () => (0, instrumentation_1.measureQuery)({\n operation: 'restoreMany',\n collectionName: this.resolveCollectionName(ctx),\n filter\n }, async () => {\n const collectionName = this.resolveCollectionName(ctx);\n const session = this.resolveSession(ctx);\n const col = await this.getCollection(ctx);\n const meta = {\n restore: true\n };\n const middlewareCtx = this.buildMiddlewareContext('restoreMany', ctx, {\n filter,\n meta\n });\n middlewareCtx.collectionName =\n middlewareCtx.collectionName ?? collectionName;\n await this.runBeforeMiddlewares('restoreMany', middlewareCtx);\n const effectiveFilter = (middlewareCtx.filter ?? filter);\n middlewareCtx.filter = effectiveFilter;\n const restoreUpdate = this.buildRestoreUpdate();\n const existingDocs = await col.find(effectiveFilter, session ? { session } : undefined).toArray();\n if (existingDocs.length === 0) {\n middlewareCtx.result = {\n restoredCount: 0,\n docs: []\n };\n await this.runAfterMiddlewares('restoreMany', middlewareCtx);\n return;\n }\n await this.schema.executePre('updateMany', {\n operation: 'restoreMany',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: restoreUpdate,\n docs: existingDocs,\n meta\n });\n const result = await col.updateMany(effectiveFilter, restoreUpdate, session ? { session } : undefined);\n const restoredDocs = await col.find(effectiveFilter, session ? { session } : undefined).toArray();\n const restoreResult = {\n acknowledged: result.acknowledged,\n matchedCount: existingDocs.length,\n modifiedCount: result.modifiedCount,\n restoredCount: result.modifiedCount,\n docs: this.toModelResults(restoredDocs)\n };\n await this.schema.executePost('updateMany', {\n operation: 'restoreMany',\n collectionName: middlewareCtx.collectionName,\n tenantId: middlewareCtx.tenantId,\n dbName: middlewareCtx.dbName,\n session,\n filter: effectiveFilter,\n update: restoreUpdate,\n docs: restoredDocs,\n result: restoreResult,\n meta\n });\n middlewareCtx.result = restoreResult;\n await this.runAfterMiddlewares('restoreMany', middlewareCtx);\n await this.invalidateCachePatterns('restoreMany', middlewareCtx);\n await pubsub.publish(`${utils_1.DB_CHANGE_EVENT}`, {\n documentRestored: {\n action: 'restoreMany',\n collectionName: middlewareCtx.collectionName,\n filter: effectiveFilter,\n result: restoreResult,\n meta\n }\n });\n }));\n }\n buildRestoreUpdate() {\n const deletedAtField = this._softDeleteConfig?.deletedAtField ?? 'deletedAt';\n const isDeletedField = this._softDeleteConfig?.isDeletedField ?? 'isDeleted';\n return {\n $set: {\n [deletedAtField]: null,\n [isDeletedField]: false\n }\n };\n }\n //================ Middleware Context and Execution =================//\n buildMiddlewareContext(operation, ctx, payload = {}) {\n const merged = this.mergeCtx(ctx);\n return {\n operation,\n modelName: this.constructor.name,\n collectionName: payload.collectionName ??\n merged?.collectionName ??\n this._collectionName,\n tenantId: payload.tenantId ?? merged?.tenantId,\n dbName: payload.dbName ?? merged?.dbName,\n session: payload.session ?? merged?.session,\n withDeleted: payload.withDeleted ?? merged?.withDeleted,\n onlyDeleted: payload.onlyDeleted ?? merged?.onlyDeleted,\n hardDelete: payload.hardDelete ?? merged?.hardDelete,\n filter: payload.filter,\n update: payload.update,\n doc: payload.doc,\n docs: payload.docs,\n pipeline: payload.pipeline,\n bulkUpdates: payload.bulkUpdates,\n bulkOperations: payload.bulkOperations,\n result: payload.result,\n meta: payload.meta\n };\n }\n setSoftDeleteConfig(config) {\n this._softDeleteConfig = config;\n }\n /**\n * Builds the update document used for soft delete operations.\n *\n * The generated update sets the configured deleted timestamp field and\n * deleted-state flag field to mark the document as logically deleted without\n * physically removing it from the collection.\n *\n * @returns MongoDB update document for soft delete flows.\n */\n buildSoftDeleteUpdate() {\n const deletedAtField = this._softDeleteConfig?.deletedAtField ?? 'deletedAt';\n const isDeletedField = this._softDeleteConfig?.isDeletedField ?? 'isDeleted';\n return {\n $set: {\n [deletedAtField]: new Date(),\n [isDeletedField]: true\n }\n };\n }\n // Middleware runners/execution methods\n async runBeforeMiddlewares(operation, ctx) {\n const handlers = this.beforeMiddlewares.get(operation) ?? [];\n for (const handler of handlers) {\n await handler(ctx);\n }\n }\n async runAfterMiddlewares(operation, ctx) {\n const handlers = this.afterMiddlewares.get(operation) ?? [];\n for (const handler of handlers) {\n await handler(ctx);\n }\n }\n // Middleware registration methods\n before(operation, handler) {\n const existing = this.beforeMiddlewares.get(operation) ?? [];\n existing.push(handler);\n this.beforeMiddlewares.set(operation, existing);\n return this;\n }\n after(operation, handler) {\n const existing = this.afterMiddlewares.get(operation) ?? [];\n existing.push(handler);\n this.afterMiddlewares.set(operation, existing);\n return this;\n }\n beforeFind(handler) {\n return this.before('find', handler);\n }\n afterFind(handler) {\n return this.after('find', handler);\n }\n beforeFindOne(handler) {\n return this.before('findOne', handler);\n }\n afterFindOne(handler) {\n return this.after('findOne', handler);\n }\n beforeSave(handler) {\n return this.before('create', handler);\n }\n afterSave(handler) {\n return this.after('create', handler);\n }\n beforeUpdateOne(handler) {\n return this.before('updateOne', handler);\n }\n afterUpdateOne(handler) {\n return this.after('updateOne', handler);\n }\n beforeDeleteOne(handler) {\n return this.before('deleteOne', handler);\n }\n afterDeleteOne(handler) {\n return this.after('deleteOne', handler);\n }\n beforeDeleteMany(handler) {\n return this.before('deleteMany', handler);\n }\n afterDeleteMany(handler) {\n return this.after('deleteMany', handler);\n }\n beforeBulkInsert(handler) {\n return this.before('bulkInsert', handler);\n }\n afterBulkInsert(handler) {\n return this.after('bulkInsert', handler);\n }\n beforeBulkUpdate(handler) {\n return this.before('bulkUpdate', handler);\n }\n afterBulkUpdate(handler) {\n return this.after('bulkUpdate', handler);\n }\n beforeAggregate(handler) {\n return this.before('aggregate', handler);\n }\n afterAggregate(handler) {\n return this.after('aggregate', handler);\n }\n beforeFindOneAndUpdate(handler) {\n return this.before('findOneAndUpdate', handler);\n }\n afterFindOneAndUpdate(handler) {\n return this.after('findOneAndUpdate', handler);\n }\n beforeFindOneAndDelete(handler) {\n return this.before('findOneAndDelete', handler);\n }\n afterFindOneAndDelete(handler) {\n return this.after('findOneAndDelete', handler);\n }\n beforeFindOneAndReplace(handler) {\n return this.before('findOneAndReplace', handler);\n }\n afterFindOneAndReplace(handler) {\n return this.after('findOneAndReplace', handler);\n }\n beforeFindOneAndUpsert(handler) {\n return this.before('findOneAndUpsert', handler);\n }\n afterFindOneAndUpsert(handler) {\n return this.after('findOneAndUpsert', handler);\n }\n}\nexports.AmbitenModel = AmbitenModel;\n;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n;\n","\"use strict\";\n/**\n * @author Emmanuel Nodolomwanyi - Ambiten Team\n * @package - @Ambiten/core\n * @version 1.0.0\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.measureQueryForBrowser = exports.AmbitenBootstrapFactory = exports.AmbitenSchema = exports.AmbitenModel = exports.createAmbitenClientModule = exports.AmbitenClient = void 0;\nconst tslib_1 = require(\"tslib\");\nconst lib_core_1 = require(\"./lib-core\");\n/**\n * Ambiten Core Library for Browser\n * This module provides core functionalities for Ambiten in a browser environment.\n * It includes database operations, configuration, and more.\n * @module Ambiten Core Browser Module\n * @version 1.0.0\n */\nconsole.log('Ambiten Core Library Loaded for (Browser)');\nwindow.AmbitenClient = lib_core_1.AmbitenClient;\nwindow.Buffer = Buffer;\ntslib_1.__exportStar(require(\"./lib-core/index\"), exports);\ntslib_1.__exportStar(require(\"./lib-core/bootstrap/index\"), exports);\ntslib_1.__exportStar(require(\"./config/index\"), exports);\ntslib_1.__exportStar(require(\"./redis-manager/index\"), exports);\ntslib_1.__exportStar(require(\"./tanancy/index\"), exports);\ntslib_1.__exportStar(require(\"./context/index\"), exports);\ntslib_1.__exportStar(require(\"./plugins/index\"), exports);\ntslib_1.__exportStar(require(\"./instrumentation/index\"), exports);\ntslib_1.__exportStar(require(\"./debug/index\"), exports);\ntslib_1.__exportStar(require(\"./ambiten-cache/index\"), exports);\ntslib_1.__exportStar(require(\"./init-cli/generate.project\"), exports);\ntslib_1.__exportStar(require(\"./middleware/index\"), exports);\ntslib_1.__exportStar(require(\"./graphql/index\"), exports);\ntslib_1.__exportStar(require(\"./utils/index\"), exports);\ntslib_1.__exportStar(require(\"./utils/builders/index\"), exports);\ntslib_1.__exportStar(require(\"./gc/index\"), exports);\ntslib_1.__exportStar(require(\"./types/index\"), exports);\nvar ambitenClient_1 = require(\"./lib-core/ambitenClient\");\nObject.defineProperty(exports, \"AmbitenClient\", { enumerable: true, get: function () { return ambitenClient_1.AmbitenClient; } });\nObject.defineProperty(exports, \"createAmbitenClientModule\", { enumerable: true, get: function () { return ambitenClient_1.createAmbitenClientModule; } });\nvar ambitenModelFactory_1 = require(\"./lib-core/ambitenModelFactory\");\nObject.defineProperty(exports, \"AmbitenModel\", { enumerable: true, get: function () { return ambitenModelFactory_1.AmbitenModel; } });\nvar ambitenSchema_1 = require(\"./lib-core/ambitenSchema\");\nObject.defineProperty(exports, \"AmbitenSchema\", { enumerable: true, get: function () { return ambitenSchema_1.AmbitenSchema; } });\nvar ambitenBootstrap_1 = require(\"./lib-core/bootstrap/ambitenBootstrap\");\nObject.defineProperty(exports, \"AmbitenBootstrapFactory\", { enumerable: true, get: function () { return ambitenBootstrap_1.AmbitenBootstrapFactory; } });\nvar instrumentation_1 = require(\"./instrumentation\");\nObject.defineProperty(exports, \"measureQueryForBrowser\", { enumerable: true, get: function () { return instrumentation_1.measureQueryForBrowser; } });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./createModel\"), exports);\ntslib_1.__exportStar(require(\"./schema\"), exports);\ntslib_1.__exportStar(require(\"./getTenantDb\"), exports);\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n;\n;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tslib_1 = require(\"tslib\");\ntslib_1.__exportStar(require(\"./ambitenError-handler\"), exports);\ntslib_1.__exportStar(require(\"./errorTypes\"), exports);\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\nvar __webpack_exports__ = __webpack_require__(9590);\n"],"names":["root","factory","exports","module","require","define","amd","self","__WEBPACK_EXTERNAL_MODULE__2947__","__WEBPACK_EXTERNAL_MODULE__3911__","__WEBPACK_EXTERNAL_MODULE__8535__","Object","defineProperty","value","resolveAmbitenOption","values","undefined","detectPackageManager","getInstallCommand","manager","packages","join","installPackages","async","cwd","process","args","length","Promise","resolve","reject","child","child_process_1","spawn","stdio","shell","platform","on","code","Error","tslib_1","__webpack_require__","fs_1","__importDefault","path_1","default","existsSync","userAgent","env","npm_config_user_agent","includes","objectIdSymbol","schemaTypeSymbol","AmbitenSymbol","Symbol","for","__exportStar","webpackEmptyAsyncContext","req","then","e","keys","id","createBootstrapLogger","config","transportConfigs","enabled","logger_1","setupLogger","level","colorize","loggerConfig","json","transports","formatOptions","hooks","contextProvider","enableMetrics","circuitBreaker","compress","DEFAULT_CONFIG_CONTENT","options","configVersion","projectName","connection","uri","dbName","multiTenant","headerKey","tenants","initOptions","lazy","retryAttempts","logger","type","filename","frequency","maxSize","flushInterval","logInterval","graphql","subscriptions","playground","schemaOutputPath","features","models","schemas","typeDefs","resolvers","useRedisCache","redisUri","advanced","autoInstall","garbageCollector","retentionPeriod","logResults","gcCron","JSON","stringify","Model","lib_core_1","AmbitenModel","provider","AmbitenClient","init","createAmbitenClientModule","mongodb_1","utils_1","tanancy_1","context_1","_opts","_uri","_client","_db","collectionRef","_connected","_defaultDbName","_overrideDbName","static","Map","constructor","this","MONGO_URI","defaultUri","DB_NAME","MongoClient","directConnection","minPoolSize","maxPoolSize","serverSelectionTimeoutMS","db","ensureMongoDependency","opts","key","String","existing","instances","get","client","tenantResolver","set","console","error","exit","ctx","tenantId","resolver","tenantClient","getClient","resolvedTenantDbName","MultiTenantManager","getTenantDbName","message","createAmbitenError","ErrorType","CONNECTION_ERROR","details","operation","validateUri","VALIDATION_ERROR","providedUri","test","connect","useCollection","collectionName","trim","scope","resolveClientScope","collection","getCollection","toString","getClusterInfo","helloResult","admin","command","hello","msg","log","setName","hosts","resolveRuntime","AmbitenContext","tenant","getTenant","resolveDbFromTenant","session","useDatabase","withDatabase","merged","startSession","close","resolveDbName","overrideDbName","input","requestId","withContext","context","callback","run","logWithContext","meta","enrichedMeta","loggerMeta","withTenant","withScope","resetDatabase","dropCollection","providedCollectionName","resolvedCollectionName","drop","dropDatabase","result","disconnect","isConnected","handleTopologyEvent","event","TopologyOpeningEvent","topologyId","TopologyClosedEvent","warn","handleLogBatch","batch","transporter","Array","isArray","remaining","slice","writes","map","eventName","name","eventType","toLowerCase","write","timestamp","Date","toISOString","source","all","DB_CHANGE_EVENT","DOCUMENT_DELETED_EVENT","DOCUMENT_UPDATED_EVENT","DOCUMENT_INSERTED_EVENT","debugLog","isDebug","getLogger","getLoggerMeta","payload","getTenantId","getRequestId","getDbName","getCollectionName","debug","ensureRedis","publisher","subscriber","redis_manager_1","redis","isOpen","duplicate","err","getTenantModel","builders_1","MultiTenantManager_1","tenantModelsCache","params","has","tenantCache","cacheKey","resolvedDbName","createTenantProvider","model","schema","resolveRuntimeConfig","resolveAmbitenOption_1","methodTenantId","modelTenantId","methodDbName","modelDbName","clientDbName","methodCollectionName","modelCollectionName","methodSession","modelSession","checkPermission","getCachedData","setCachedData","invalidateTenantCache","role","exists","del","info","enforceRBAC","permission","wrapped","parent","user","writable","configurable","__originalResolver","__rbacAction","getRBACAction","getOriginalResolver","rbacTypes_1","buildCacheKey","parse","allowedActions","rolePermissions","permissions","cachedData","data","ttl","EX","roleKey","loadAmbitenConfig","configPath","candidates","DEFAULT_CONFIG_FILENAME","finalPath","parsed","candidate","fs_extra_1","pathExists","raw","readFile","rawConfig","cfg","compressLogFiles","normalizeAmbitenConfig","validate","ajv","compile","ambiten_config_schema_json_1","errors","location","instancePath","extra","keyword","additionalProperty","assertValidAmbitenConfig","ajv_1","allErrors","useDefaults","strict","coerceTypes","now","isValidDuration","formatDuration","parseDuration","duration","match","isValid","parseInt","unit","ms","seconds","Math","floor","minutes","hours","days","AmbitenError","cause","super","captureStackTrace","toJSON","AmbitenBootstrapFactory","config_1","index_1","__1","gc_1","invalidateTenantCache_1","AmbitenBootstrap","gc","adapter","onConnectHooks","connectCallbacks","onConnect","push","initialize","configFilePathOrObject","initializeLogger","initializeRedis","initializeMongoProvider","initializeSchema","initializeModel","initializeMultiTenancy","initializeGraphQL","runOnConnectHooks","initializeGarbageCollector","mongoClient","configureAmbitenContext","Schema","registerSchema","gcConfig","registerModel","initMultiTenancy","tenantCount","AmbitenGraphQL","useRedis","customTypeDefs","customResolvers","generateSchema","hook","AmbitenGC","cron","continueOnError","registerMultiTenancy","multiTenantConfig","cache","fetcher","cacheWithRedis","invalidateCache","namespace","getRedisClient","getMongoClient","getModel","getSchema","getGraphQL","getGCRunner","shutdown","create","bootstrap","node_async_hooks_1","runManualTransaction_1","DEFAULT_AMBITEN_BUDGET","maxQueries","Infinity","queriesExecuted","totalTimeMs","storage","AsyncLocalStorage","transactionResolver","getStore","budget","normalizeBudget","hasActiveContext","patch","current","assign","clear","configureTransactionResolver","getSession","getObserver","observer","getBudget","state","normalized","setBudget","assertQueryBudget","incrementQueries","addQueryTime","durationMs","Boolean","AMBITEN_DEBUG","withTransaction","resolveClient","endSession","runManualTransaction","hasTransactionResolver","measureQueryForBrowser","_meta","executor","getTenantDB","dbCache","runGarbageCollectorOnAllModels","ModelRegistry_1","AmbitenModelRegistry","getAllModels","scanned","succeeded","failed","modelContext","getContext","runGC","success","runGarbageCollector","ambiten_cache_1","AmbitenCache","wrap","generateProject","generateProjectWithConfig","templates_1","startedAt","projectRoot","entryFilePath","ensureDir","createScaffoldLogger","resolvedOptions","generateAppStructure","printSummary","files","dirs","normalize","p","relative","replace","addFile","filePath","addDir","dirPath","enabledFeatures","filter","disabledFeatures","toFixed","color_palatte_1","forEach","d","f","feature","SchemaType","Types","ObjectId","applySoftDelete","DEFAULTS","applyReadFilter","withDeleted","onlyDeleted","excludeDeletedByDefault","mergeFilter","buildNotDeletedFilter","buildOnlyDeletedFilter","beforeFind","beforeFindOne","beforeFindOneAndUpdate","beforeFindOneAndReplace","beforeFindOneAndUpsert","beforeAggregate","stage","$match","pipeline","beforeDeleteOne","hardDelete","update","buildSoftDeleteUpdate","softDelete","beforeDeleteMany","beforeFindOneAndDelete","setSoftDeleteConfig","deletedAtField","isDeletedField","field","deletedByField","$and","$or","$exists","$ne","original","$set","transactionSession_1","hasManualTransactionMethods","startTransaction","commitTransaction","abortTransaction","text","hasTenant","registerLazyTenant","validateTenantId","normalizedTenantId","tenantConfig","extractDbNameFromUri","metadata","registerTenant","getConnectedTenant","connected","from","find","getAllConnectedTenants","getAllTenants","isEnabled","size","removeTenant","delete","clearTenants","startsWith","parts","split","lastPart","generateMainTS","createAmbitenCache","buildKey","prefix","namespacedKey","cached","emit","ttlSeconds","invalidate","invalidatePattern","pattern","scan","cursor","deletedCount","MATCH","COUNT","nextCursor","Number","scheduleGarbageCollector","cronExpr","schedule","gcManager_1","__importStar","createSchema","AmbitenSchema","redisClient","RedisService","getInstance","ambitenClient_1","enumerable","ambitenModelFactory_1","ambitenSchema_1","ambitenBootstrap_1","instrumentation_1","TenantContext","tenantStorage","setTenantId","store","connectRedis","url","redis_1","DEFAULT_RECONNECT","retries","min","redisUrl","REDIS_URI","currentClient","createStub","publish","subscribe","multi","incr","expire","exec","createClient","socket","reconnectStrategy","quit","channel","listener","generateGCRunner","getEventOptions","eventOptionMap","getEventType","k","et","describeEvent","logEvent","logDefaultEvent","aggregate","createIndex","dropIndex","findOne","insertOne","insertMany","updateOne","updateMany","deleteOne","deleteMany","transaction","eventDesc","schemaDefinition","indexes","virtuals","validators","relationships","middleware","pre","post","validator","fn","doc","entries","validateAsync","index","fields","applyIndexes","addRelationship","ref","localField","getRelationships","virtual","getter","applyVirtuals","getPreHooks","getPostHooks","getHooks","phase","executePre","executePost","executeMiddleware","triggerMiddleware","setGCConfig","getGCConfig","postCtx","srcDir","coreDir","utilsDir","typesDir","modelsDir","graphqlDir","gcDir","mainPath","writeFile","generateMainEntry_1","initAmbitenPath","helperPath","configTypesPath","schemaPath","resolversPath","gcManagerPath","generateGCManagerFile_1","generateGCManager","gcRunnerPath","generateGCRunnerFile_1","generateDefaultConfigContent_1","packageJsonPath","writeJson","dependencies","mongodb","description","private","version","main","scripts","dev","build","start","license","devDependencies","typescript","buildPackageJson","spaces","tsconfigPath","compilerOptions","target","moduleResolution","rootDir","outDir","sourceMap","declaration","declarationMap","esModuleInterop","resolveJsonModule","noImplicitAny","noImplicitReturns","noUncheckedIndexedAccess","exactOptionalPropertyTypes","forceConsistentCasingInFileNames","skipLibCheck","types","lib","include","exclude","gitignorePath","packageManager","installCommand","viewer","schema_1","graphql_tag_1","toModelContext","publishEvent","defaultTypeDefs","gql","defaultResolvers","Query","_","_id","findAll","toArray","Mutation","col","newDoc","insertedId","documentInserted","action","updatedDoc","documentUpdated","documentDeleted","Subscription","makeExecutableSchema","AuthService","jsonwebtoken_1","SECRET","JWT_SECRET","REFRESH_SECRET","REFRESH_EXPIRATION","JWT_EXPIRATION","generateToken","sign","expiresIn","generateRefreshToken","verifyToken","token","verify","isValidObjectId","isObjectId","castId","inputId","createFromHexString","symbols_1","prototype","toHexString","hasOwnProperty","call","valueOf","ensureModelNameSafe","trimmedName","getModelFilesFromPath","loadModelsFromPath","modelFiles","file","modelModule","readdirSync","fullPath","statSync","isDirectory","authorize","roles","res","next","authHeader","headers","authorization","Authorization","status","decoded","AuthUtils_1","clearModelRegistryForTests","registeredModels","unregisterModel","modelRegistry","Set","add","getRegisteredModel","isModelRegistered","intervalMs","intervalRef","cronTask","interval","parseInterval","runOnce","setInterval","stop","clearInterval","num","eventTypes","startGarbageCollector","measureQuery","ambitenContext_1","budgetAfterIncrement","perf_hooks_1","performance","round","budgetAfterTime","documentCount","totalBudgetUsed","setImmediate","onQuery","errorMessage","errorName","onQueryError","events_1","graphql_subscriptions_1","debug_1","pubsub","PubSub","_provider","_collectionName","_collectionOverride","_schema","_initialized","_defaultCtx","_modelGCConfig","_gcConfig","_gcTimer","eventEmitter","beforeMiddlewares","afterMiddlewares","_softDeleteConfig","NULL_OR_UNDEFINED","providedOptions","typeError","AmbitenModelError","fixedDb","schemaGCConfig","resolveSchemaGCConfig","isGCEnabled","initMiddleware","mergeCtx","runtimeCtx","some","runWithModelContext","enableGC","ensureConfigured","resolveDb","resolveCollectionName","databaseName","getResolvedTenant","resolvedCtx","resolveSession","resolveSessionStrict","externalSession","once","off","removeListener","ensureGCIndex","INITIALIZATION_ERROR","TypeError","bind","clone","updatedAtField","createdAtField","expireAfterSeconds","indexName","background","relatedCollection","dbChange","updateFilter","unshift","$lookup","foreignField","as","middlewareCtx","buildMiddlewareContext","runBeforeMiddlewares","nextDoc","buildHookPayload","insertResult","createdDoc","toModelResult","runAfterMiddlewares","finalResult","invalidateCachePatterns","effectiveFilter","resolveCache","cacheHit","results","toModelResults","effectiveUpdate","updateResult","acknowledged","matchedCount","modifiedCount","upsertedCount","upsertedId","bulkInsert","docs","nextDocs","buildOperationMeta","bulkWrite","ordered","insertedDocs","insertedIds","bulkUpdate","updates","bulkUpdates","nextUpdates","insertedCount","entry","bulkOps","bulkResult","isOk","softDeleteUpdate","existingDocs","softDeleteMeta","softDeleteResult","softDeleted","deleteResult","populateOne","relatedModel","referenceValue","relatedDoc","populateMany","referenceValues","relatedDocs","$in","createWithTransaction","transactional","bulkWriteWithTransaction","operations","bulkOperations","nextOperations","bulkResultSummary","deleteWithTransaction","existingDoc","updateWithTransaction","projectedUpdatedDoc","findOneAndUpdate","returnDocument","findOneAndDelete","existingPayload","deleteOptions","deletedDoc","finalPayload","findOneAndReplace","replacement","nextReplacement","replaceResult","replacedDoc","findOneAndUpsert","upsertResult","upsert","findOneAndUpsertWithTransaction","findOneAndUpsertWithTransactionSecure","secure","userId","userRole","deleteSecure","queryOptions","resolvedSession","effectivePipeline","aggregateWithTransaction","baseCtx","existingSession","runtimeBase","runInTransaction","streamAggregation","streaming","stream","aggregateWithCache","cacheDuration","cachedResult","paginatedFind","pageSize","lastId","query","$gt","limit","rest","watchChanges","changeStream","watch","direction","patterns","normalizedPattern","execResult","invalidateModelPattern","fullPattern","invalidateDocumentCache","getCacheStats","memoryInfo","keyspaceInfo","totalKeys","matchAll","reduce","sum","memoryMatch","memoryUsageBytes","hitsRaw","missesRaw","totalHits","totalMisses","totalRequests","hitRate","missRate","tenantKeys","count","memoryUsageMb","runCommand","dbCommand","ttlField","expireDate","gcFilter","$lt","expiredDocs","affected","archived","deleted","deletedAt","isDeleted","archiveBeforeDelete","archiveDocs","_archivedAt","_from","gcResult","garbageCollection","startAutoGC","catch","resolveInstrumentationContext","base","overrides","instrumentation","trackCacheMiss","trackCacheHit","_tenantId","_dbName","normalizedPayload","sortObjectDeep","today","retentionSeconds","cacheResult","isFinite","clearCache","warmCache","queries","defaultTtl","warmQueries","countDocuments","item","sort","acc","restoreOne","restore","restoreUpdate","buildRestoreUpdate","restoredDoc","restoreResult","restored","documentRestored","restoreMany","restoredCount","restoredDocs","modelName","handlers","handler","before","after","afterFind","afterFindOne","beforeSave","afterSave","beforeUpdateOne","afterUpdateOne","afterDeleteOne","afterDeleteMany","beforeBulkInsert","afterBulkInsert","beforeBulkUpdate","afterBulkUpdate","afterAggregate","afterFindOneAndUpdate","afterFindOneAndDelete","afterFindOneAndReplace","afterFindOneAndUpsert","window","Buffer","__webpack_module_cache__","moduleId","cachedModule","__webpack_modules__","o","obj","prop"],"ignoreList":[],"sourceRoot":""}