@lyxa.ai/core 1.0.130 → 1.0.131
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -3
- package/dist/index.js.map +1 -1
- package/dist/libraries/auth/index.d.ts +3 -1
- package/dist/libraries/auth/index.js +15 -3
- package/dist/libraries/auth/index.js.map +1 -1
- package/dist/libraries/auth/refreshtoken.js.map +1 -1
- package/dist/libraries/auth/repository.js +6 -6
- package/dist/libraries/auth/repository.js.map +1 -1
- package/dist/libraries/dispatcher/index.js.map +1 -1
- package/dist/libraries/mongo/index.d.ts +2 -4
- package/dist/libraries/mongo/index.js +27 -161
- package/dist/libraries/mongo/index.js.map +1 -1
- package/dist/libraries/mongo/models/embedded/order-finance.model.js.map +1 -1
- package/dist/libraries/mongo/models/index.d.ts +11 -10
- package/dist/libraries/mongo/models/index.js +81 -13
- package/dist/libraries/mongo/models/index.js.map +1 -1
- package/dist/libraries/mongo/models/user.model.js +1 -1
- package/dist/libraries/mongo/models/user.model.js.map +1 -1
- package/dist/utilities/enum.d.ts +0 -5
- package/dist/utilities/enum.js +1 -7
- package/dist/utilities/enum.js.map +1 -1
- package/dist/utilities/validation/common-validation.d.ts +7 -7
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { LibraryManager } from './libraries';
|
|
|
2
2
|
import { ConfigurationOptions } from './libraries/configuration';
|
|
3
3
|
export { ConfigurationOptions } from './libraries/configuration';
|
|
4
4
|
export { EnvironmentConfigurationType } from './libraries/configuration/types/EnvironmentConfigurationType';
|
|
5
|
-
export { initGlobalConnection
|
|
5
|
+
export { initGlobalConnection } from './libraries/mongo';
|
|
6
6
|
export declare function bootstrapCore(options?: ConfigurationOptions): Promise<void>;
|
|
7
7
|
export declare function registerLibraries(options?: ConfigurationOptions): Promise<void>;
|
|
8
8
|
export declare function getLibraries(): LibraryManager;
|
package/dist/index.js
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.
|
|
6
|
+
exports.initGlobalConnection = exports.EnvironmentConfigurationType = void 0;
|
|
7
7
|
exports.bootstrapCore = bootstrapCore;
|
|
8
8
|
exports.registerLibraries = registerLibraries;
|
|
9
9
|
exports.getLibraries = getLibraries;
|
|
@@ -28,8 +28,6 @@ var EnvironmentConfigurationType_2 = require("./libraries/configuration/types/En
|
|
|
28
28
|
Object.defineProperty(exports, "EnvironmentConfigurationType", { enumerable: true, get: function () { return EnvironmentConfigurationType_2.EnvironmentConfigurationType; } });
|
|
29
29
|
var mongo_2 = require("./libraries/mongo");
|
|
30
30
|
Object.defineProperty(exports, "initGlobalConnection", { enumerable: true, get: function () { return mongo_2.initGlobalConnection; } });
|
|
31
|
-
Object.defineProperty(exports, "createGlobalModel", { enumerable: true, get: function () { return mongo_2.createGlobalModel; } });
|
|
32
|
-
Object.defineProperty(exports, "createGlobalDiscriminatorModel", { enumerable: true, get: function () { return mongo_2.createGlobalDiscriminatorModel; } });
|
|
33
31
|
async function bootstrapCore(options) {
|
|
34
32
|
try {
|
|
35
33
|
await registerLibraries(options);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"/","sources":["index.ts"],"names":[],"mappings":";;;;;;AAsBA,sCAyBC;AAED,8CAsEC;AAED,oCAEC;AA3HD,2CAA6C;AAC7C,mCAAmC;AACnC,wDAAgC;AAChC,6DAAuF;AACvF,+GAA4G;AAC5G,+CAAgD;AAChD,6CAAiD;AACjD,6CAAyD;AACzD,iDAA2D;AAC3D,uDAAgE;AAChE,+CAAmD;AACnD,mDAAuD;AACvD,6CAAmE;AACnE,0FAAuF;AACvF,yCAAgE;AAChE,yDAAmE;AACnE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AM,gBAAgB,GAAG,2CAAoB,CAAC,mBAAmB,EAAE,CAAC;IAEpE,MAAM,oBAAoB,GAAG,IAAI,GAAG,EAAiB,CAAC;IAEtD,KAAK,MAAM,EAAE,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,IAAI,gBAAgB,EAAE,CAAC;QAC3E,IAAI,QAAQ,GAAG,oBAAoB,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;QAC3D,IAAI,CAAC,QAAQ,EAAE,CAAC;YACf,QAAQ,GAAG,kBAAS,CAAC,GAAG,CAAC,iBAAwB,CAAC,CAAC;YACnD,oBAAoB,CAAC,GAAG,CAAC,iBAAiB,EAAE,QAAQ,CAAC,CAAC;QACvD,CAAC;QAED,MAAM,IAAA,wBAAgB,EAAC,OAAO,EAAE,KAAK,EAAC,OAAO,EAAC,EAAE;YAC/C,OAAO,QAAQ,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;IACJ,CAAC;AACF,CAAC;AAED,SAAgB,YAAY;IAC3B,OAAO,kBAAS,CAAC,GAAG,CAAC,0BAAc,CAAC,CAAC;AACtC,CAAC","sourcesContent":["import { LibraryManager } from './libraries';\nimport { Container } from 'typedi';\nimport mongoose from 'mongoose';\nimport { ConfigurationOptions, ConfigurationService } from './libraries/configuration';\nimport { EnvironmentConfigurationType } from './libraries/configuration/types/EnvironmentConfigurationType';\nimport { LyxaLogger } from './libraries/logger';\nimport { RedisService } from './libraries/redis';\nimport { initGlobalConnection } from './libraries/mongo';\nimport { SecretManagerService } from './libraries/secrets';\nimport { MicroServiceDispatcher } from './libraries/dispatcher';\nimport { TwilioService } from './libraries/twilio';\nimport { FirebaseService } from './libraries/firebase';\nimport { initEventBus, subscribeToEvent } from './libraries/event';\nimport { SubscriptionRegistry } from './libraries/event/registry/SubscriptionRegistry';\nimport { MapService, GoogleMapsService } from './libraries/map';\nimport { CachedSettingsService } from './libraries/cache/settings';\nimport { FCMService } from './libraries/firebase/fcmService';\n\nexport { ConfigurationOptions } from './libraries/configuration';\nexport { EnvironmentConfigurationType } from './libraries/configuration/types/EnvironmentConfigurationType';\nexport { initGlobalConnection } from './libraries/mongo';\n\nexport async function bootstrapCore(options?: ConfigurationOptions) {\n\ttry {\n\t\tawait registerLibraries(options);\n\n\t\tgetLibraries().getLogger().logger.info('Successfully bootstrapped lyxa-core.');\n\n\t\tconst gracefulShutdown = async () => {\n\t\t\tgetLibraries().getLogger().logger.info('Received shutdown signal, shutting down gracefully...');\n\t\t\tprocess.exit();\n\t\t};\n\n\t\tprocess.on('SIGTERM', gracefulShutdown);\n\t\tprocess.on('SIGINT', gracefulShutdown);\n\t\tprocess.on('uncaughtException', err => {\n\t\t\tgetLibraries().getLogger().logger.error('Uncaught exception, shutting down...', err);\n\t\t\tgracefulShutdown();\n\t\t});\n\t\tprocess.on('exit', code => {\n\t\t\tgetLibraries().getLogger().logger.info(`Exiting with code: ${code}`);\n\t\t});\n\n\t\tconsole.log('Created hooks.');\n\t} catch (e) {\n\t\tconsole.error(e);\n\t}\n}\n\nexport async function registerLibraries(options?: ConfigurationOptions) {\n\t// Setup configuration.\n\tconst configurationInstance = new ConfigurationService(options);\n\tContainer.set(ConfigurationService, configurationInstance);\n\n\t// Setup redis.\n\tconst redisInstance = new RedisService(configurationInstance.options.redisURL!);\n\tContainer.set(RedisService, redisInstance);\n\n\t// Setup secret\n\tconst secretInstance = new SecretManagerService(configurationInstance, redisInstance);\n\tContainer.set(SecretManagerService, secretInstance);\n\n\tconst mongoUrl = await getLibraries().getSecretsService().getKey('MONGO_URL');\n\n\tawait mongoose.connect(mongoUrl!, { dbName: `lyxa-${options!.environment}-${options!.tenet}` });\n\tmongoose.set(\n\t\t'debug',\n\t\tgetLibraries().getConfigurationService().options.environment == EnvironmentConfigurationType.DEV\n\t);\n\n\tawait initGlobalConnection(mongoUrl!, options!.environment);\n\n\t// Setup logger\n\tconst loggerInstance = new LyxaLogger(options!.instanceType!, mongoUrl!);\n\tContainer.set(LyxaLogger, loggerInstance);\n\n\t// Setup firebase\n\tconst firebaseInstance = new FirebaseService(configurationInstance!);\n\tContainer.set(FirebaseService, firebaseInstance);\n\n\t// Setup microservice dispatcher\n\tconst microserviceDispatcherInstance = new MicroServiceDispatcher(secretInstance);\n\tContainer.set(MicroServiceDispatcher, microserviceDispatcherInstance);\n\n\t// Setup twilio\n\tconst twilioServiceInstance = new TwilioService();\n\tContainer.set(TwilioService, twilioServiceInstance);\n\n\t// Setup map service\n\tconst googleMapsKey = await getLibraries().getSecretsService().getKey('GOOGLE_MAPS_API_KEY');\n\tconst googleMapService = new GoogleMapsService(googleMapsKey as string);\n\tconst mapServiceInstance = new MapService(googleMapService);\n\tContainer.set(MapService, mapServiceInstance);\n\n\tconst settingsServiceInstance = new CachedSettingsService(redisInstance);\n\tContainer.set(CachedSettingsService, settingsServiceInstance);\n\n\t// Setup fcm service\n\tconst fcmServiceInstance = new FCMService();\n\tContainer.set(FCMService, fcmServiceInstance);\n\n\tconsole.log('Initialized everything');\n\n\tawait initEventBus('amqps://adlvedna:oY_X4qH1AphtB83YNcf9DHMO3UVmX23s@dog.lmq.cloudamqp.com/adlvedna');\n\tconst allSubscriptions = SubscriptionRegistry.getAllSubscriptions();\n\n\tconst instantiatedServices = new Map<Function, any>();\n\n\tfor (const { eventId, targetConstructor, methodName } of allSubscriptions) {\n\t\tlet instance = instantiatedServices.get(targetConstructor);\n\t\tif (!instance) {\n\t\t\tinstance = Container.get(targetConstructor as any);\n\t\t\tinstantiatedServices.set(targetConstructor, instance);\n\t\t}\n\n\t\tawait subscribeToEvent(eventId, async payload => {\n\t\t\treturn instance[methodName](payload);\n\t\t});\n\t}\n}\n\nexport function getLibraries(): LibraryManager {\n\treturn Container.get(LibraryManager);\n}\n"]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { SignOptions } from 'jsonwebtoken';
|
|
2
2
|
import { EntityContext } from '../trpc/context';
|
|
3
3
|
import { RefreshToken } from './refreshtoken';
|
|
4
|
+
import { ReturnModelType } from '@typegoose/typegoose';
|
|
4
5
|
export declare enum AuthEntityType {
|
|
5
6
|
USER = "USER",
|
|
6
7
|
SELLER = "SELLER",
|
|
@@ -19,6 +20,8 @@ export interface RefreshTokenRecord {
|
|
|
19
20
|
isRevoked: boolean;
|
|
20
21
|
metadata?: Record<string, unknown>;
|
|
21
22
|
}
|
|
23
|
+
export declare function getRefreshTokenModel(): ReturnModelType<typeof RefreshToken>;
|
|
24
|
+
export declare function initializeRefreshTokenModel(globalConnection: any): void;
|
|
22
25
|
export declare function signAccessToken(entity: {
|
|
23
26
|
id: string;
|
|
24
27
|
type: AuthEntityType;
|
|
@@ -74,4 +77,3 @@ export declare function handleTokenRenewal(refreshToken: string): Promise<{
|
|
|
74
77
|
refreshToken?: string | null;
|
|
75
78
|
};
|
|
76
79
|
}>;
|
|
77
|
-
export declare const RefreshTokenModel: import("@typegoose/typegoose").ReturnModelType<typeof RefreshToken>;
|
|
@@ -3,7 +3,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.
|
|
6
|
+
exports.TokenType = exports.AuthEntityType = void 0;
|
|
7
|
+
exports.getRefreshTokenModel = getRefreshTokenModel;
|
|
8
|
+
exports.initializeRefreshTokenModel = initializeRefreshTokenModel;
|
|
7
9
|
exports.signAccessToken = signAccessToken;
|
|
8
10
|
exports.generateRefreshToken = generateRefreshToken;
|
|
9
11
|
exports.verifyAccessToken = verifyAccessToken;
|
|
@@ -17,7 +19,7 @@ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
|
|
|
17
19
|
const crypto_1 = require("crypto");
|
|
18
20
|
const refreshtoken_1 = require("./refreshtoken");
|
|
19
21
|
const index_1 = require("../../index");
|
|
20
|
-
const
|
|
22
|
+
const typegoose_1 = require("@typegoose/typegoose");
|
|
21
23
|
var AuthEntityType;
|
|
22
24
|
(function (AuthEntityType) {
|
|
23
25
|
AuthEntityType["USER"] = "USER";
|
|
@@ -30,6 +32,17 @@ var TokenType;
|
|
|
30
32
|
TokenType["ACCESS"] = "ACCESS";
|
|
31
33
|
TokenType["REFRESH"] = "REFRESH";
|
|
32
34
|
})(TokenType || (exports.TokenType = TokenType = {}));
|
|
35
|
+
let actualRefreshTokenModel = null;
|
|
36
|
+
function getRefreshTokenModel() {
|
|
37
|
+
if (!actualRefreshTokenModel) {
|
|
38
|
+
throw new Error('RefreshToken model not initialized yet. Call initGlobalConnection() first.');
|
|
39
|
+
}
|
|
40
|
+
return actualRefreshTokenModel;
|
|
41
|
+
}
|
|
42
|
+
function initializeRefreshTokenModel(globalConnection) {
|
|
43
|
+
actualRefreshTokenModel = (0, typegoose_1.getModelForClass)(refreshtoken_1.RefreshToken, { existingConnection: globalConnection });
|
|
44
|
+
console.log('✅ RefreshToken model initialized');
|
|
45
|
+
}
|
|
33
46
|
async function signAccessToken(entity, options) {
|
|
34
47
|
if (!entity?.type) {
|
|
35
48
|
throw new Error('Entity type is required to sign token');
|
|
@@ -243,5 +256,4 @@ async function handleTokenRenewal(refreshToken) {
|
|
|
243
256
|
},
|
|
244
257
|
};
|
|
245
258
|
}
|
|
246
|
-
exports.RefreshTokenModel = (0, mongo_1.createGlobalModel)(refreshtoken_1.RefreshToken);
|
|
247
259
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/auth/index.ts"],"names":[],"mappings":";;;;;;AAgCA,0CA2BC;AAKD,oDAuDC;AAaD,8CAwBC;AAKD,oDA2BC;AAMD,sCAoCC;AAKD,gDAGC;AAKD,wDAGC;AAKD,sCA6BC;AAOD,gDA2EC;AA1WD,gEAA4D;AAE5D,mCAAqC;AACrC,iDAA8C;AAC9C,uCAA2C;AAC3C,oCAA6C;AAE7C,IAAY,cAKX;AALD,WA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AI;QACb,MAAM,EAAE,UAAU;QAClB,WAAW,EAAE,OAAO;QACpB,SAAS,EAAE;YACV,WAAW,EAAE,cAAc;YAC3B,YAAY,EAAE,IAAI;SAClB;KACD,CAAC;AACH,CAAC;AAEY,QAAA,iBAAiB,GAAG,IAAA,yBAAiB,EAAC,2BAAY,CAAC,CAAC","sourcesContent":["import jwt, { SignOptions, JwtPayload } from 'jsonwebtoken';\nimport { EntityContext } from '../trpc/context';\nimport { randomBytes } from 'crypto';\nimport { RefreshToken } from './refreshtoken';\nimport { getLibraries } from '../../index';\nimport { createGlobalModel } from '../mongo';\n\nexport enum AuthEntityType {\n\tUSER = 'USER',\n\tSELLER = 'SELLER',\n\tDELIVERY_BOY = 'DELIVERY_BOY',\n\tCRM = 'CRM',\n}\n\nexport enum TokenType {\n\tACCESS = 'ACCESS',\n\tREFRESH = 'REFRESH',\n}\n\nexport interface RefreshTokenRecord {\n\ttoken: string;\n\tentityId: string;\n\tentityType: AuthEntityType;\n\texpiresAt: Date;\n\tisRevoked: boolean;\n\tmetadata?: Record<string, unknown>;\n}\n\n/**\n * Sign a JWT access token for the given entity (id + type).\n * It will fetch the secret for that entity type and create a token.\n */\nexport async function signAccessToken(\n\tentity: { id: string; type: AuthEntityType; parameters: Record<string, unknown> },\n\toptions?: SignOptions\n): Promise<string> {\n\tif (!entity?.type) {\n\t\tthrow new Error('Entity type is required to sign token');\n\t}\n\n\tconst secret = await getLibraries().getSecretsService().getKey(`${entity.type.toUpperCase()}_JWT_TOKEN`);\n\n\tif (!secret) {\n\t\tthrow new Error(`No secret found for entity type ${entity.type}`);\n\t}\n\n\tconst payload = {\n\t\tid: entity.id,\n\t\ttype: entity.type,\n\t\tparameters: entity.parameters,\n\t\ttokenType: TokenType.ACCESS,\n\t};\n\n\tconst tokenOptions: SignOptions = {\n\t\t...options,\n\t\texpiresIn: options?.expiresIn || '1d',\n\t};\n\n\treturn jwt.sign(payload, secret, tokenOptions);\n}\n\n/**\n * Generate a refresh token for the given entity\n */\nexport async function generateRefreshToken(\n\tentity: { id: string; type: AuthEntityType; parameters?: Record<string, unknown> },\n\toptions?: { expiresIn?: string | number }\n): Promise<string> {\n\tconst tokenValue = randomBytes(40).toString('hex');\n\n\tconst expiresIn = options?.expiresIn || '7d';\n\tconst expiresAt = new Date();\n\n\tif (typeof expiresIn === 'string') {\n\t\t// Parse duration strings like '7d', '30d', etc.\n\t\tconst match = expiresIn.match(/^(\\d+)([smhdwy])$/);\n\t\tif (match) {\n\t\t\tconst value = parseInt(match[1]);\n\t\t\tconst unit = match[2];\n\n\t\t\tswitch (unit) {\n\t\t\t\tcase 's':\n\t\t\t\t\texpiresAt.setSeconds(expiresAt.getSeconds() + value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'm':\n\t\t\t\t\texpiresAt.setMinutes(expiresAt.getMinutes() + value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'h':\n\t\t\t\t\texpiresAt.setHours(expiresAt.getHours() + value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'd':\n\t\t\t\t\texpiresAt.setDate(expiresAt.getDate() + value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'w':\n\t\t\t\t\texpiresAt.setDate(expiresAt.getDate() + value * 7);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'y':\n\t\t\t\t\texpiresAt.setFullYear(expiresAt.getFullYear() + value);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\t// Default to 7 days if format is invalid\n\t\t\texpiresAt.setDate(expiresAt.getDate() + 7);\n\t\t}\n\t} else if (typeof expiresIn === 'number') {\n\t\t// Interpret number as seconds\n\t\texpiresAt.setSeconds(expiresAt.getSeconds() + expiresIn);\n\t}\n\n\tawait storeRefreshToken({\n\t\ttoken: tokenValue,\n\t\tentityId: entity.id,\n\t\tentityType: entity.type,\n\t\texpiresAt,\n\t\tisRevoked: false,\n\t\tmetadata: entity.parameters,\n\t});\n\n\treturn tokenValue;\n}\n\n/**\n * Store a refresh token in the database\n */\nasync function storeRefreshToken(tokenRecord: RefreshTokenRecord): Promise<void> {\n\tconst tokenRepository = getLibraries().getAuthTokenRepository();\n\tawait tokenRepository.saveRefreshToken(tokenRecord);\n}\n\n/**\n * Verify an access token for the given entity types\n */\nexport async function verifyAccessToken(\n\tentityTypes: AuthEntityType[],\n\ttoken: string\n): Promise<EntityContext | undefined> {\n\tfor (const entityType of entityTypes) {\n\t\tconst secret = await getLibraries()\n\t\t\t.getSecretsService()\n\t\t\t.getKey(entityType.toUpperCase() + '_JWT_TOKEN');\n\n\t\ttry {\n\t\t\tconst decoded = jwt.verify(token, secret!) as EntityContext & { tokenType?: TokenType };\n\n\t\t\t// Verify this is an access token\n\t\t\tif (decoded.tokenType !== TokenType.ACCESS) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\treturn decoded;\n\t\t} catch (err) {\n\t\t\t// Continue to the next entity type\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Validate a refresh token and return the associated entity\n */\nexport async function validateRefreshToken(token: string): Promise<{\n\tvalid: boolean;\n\tentity?: { id: string; type: AuthEntityType; parameters?: Record<string, unknown> };\n}> {\n\tconst tokenRepository = getLibraries().getAuthTokenRepository();\n\tconst storedToken = await tokenRepository.findRefreshToken(token);\n\n\tif (!storedToken) {\n\t\treturn { valid: false };\n\t}\n\n\tif (storedToken.expiresAt && new Date() > storedToken.expiresAt) {\n\t\treturn { valid: false };\n\t}\n\n\tif (storedToken.isRevoked) {\n\t\treturn { valid: false };\n\t}\n\n\treturn {\n\t\tvalid: true,\n\t\tentity: {\n\t\t\tid: storedToken.entityId,\n\t\t\ttype: storedToken.entityType,\n\t\t\tparameters: storedToken.metadata,\n\t\t},\n\t};\n}\n\n/**\n * Refresh authentication tokens\n * Returns new access and refresh tokens\n */\nexport async function refreshTokens(refreshToken: string): Promise<{\n\taccessToken: string;\n\trefreshToken: string;\n\tentity: { id: string; type: AuthEntityType };\n} | null> {\n\t// Validate the refresh token\n\tconst validation = await validateRefreshToken(refreshToken);\n\n\tif (!validation.valid || !validation.entity) {\n\t\treturn null;\n\t}\n\n\tawait revokeRefreshToken(refreshToken);\n\n\t// Create new tokens\n\tconst entity = validation.entity;\n\tconst newAccessToken = await signAccessToken({\n\t\tid: entity.id,\n\t\ttype: entity.type,\n\t\tparameters: entity.parameters || {},\n\t});\n\n\tconst newRefreshToken = await generateRefreshToken({\n\t\tid: entity.id,\n\t\ttype: entity.type,\n\t\tparameters: entity.parameters,\n\t});\n\n\treturn {\n\t\taccessToken: newAccessToken,\n\t\trefreshToken: newRefreshToken,\n\t\tentity: {\n\t\t\tid: entity.id,\n\t\t\ttype: entity.type,\n\t\t},\n\t};\n}\n\n/**\n * Revoke a refresh token\n */\nexport async function revokeRefreshToken(token: string): Promise<boolean> {\n\tconst tokenRepository = getLibraries().getAuthTokenRepository();\n\treturn tokenRepository.revokeRefreshToken(token);\n}\n\n/**\n * Revoke all refresh tokens for a specific entity\n */\nexport async function revokeAllRefreshTokens(entityId: string, entityType: AuthEntityType): Promise<boolean> {\n\tconst tokenRepository = getLibraries().getAuthTokenRepository();\n\treturn tokenRepository.revokeAllRefreshTokensForEntity(entityId, entityType);\n}\n\n/**\n * Sign both access and refresh tokens - utility for initial login/authentication\n */\nexport async function signTokenPair(\n\tentity: { id: string; type: AuthEntityType; parameters?: Record<string, unknown> },\n\toptions?: { accessTokenOptions?: SignOptions; refreshTokenExpiresIn?: string | number }\n): Promise<{\n\taccessToken: string;\n\trefreshToken: string;\n}> {\n\tconst accessToken = await signAccessToken(\n\t\t{\n\t\t\tid: entity.id,\n\t\t\ttype: entity.type,\n\t\t\tparameters: entity.parameters || {},\n\t\t},\n\t\toptions?.accessTokenOptions\n\t);\n\n\tconst refreshToken = await generateRefreshToken(\n\t\t{\n\t\t\tid: entity.id,\n\t\t\ttype: entity.type,\n\t\t\tparameters: entity.parameters,\n\t\t},\n\t\t{ expiresIn: options?.refreshTokenExpiresIn }\n\t);\n\n\treturn {\n\t\taccessToken,\n\t\trefreshToken,\n\t};\n}\n\n/**\n * Handle the refresh token validation and renewal logic\n * @param refreshToken The refresh token to validate or renew\n * @returns Result object with token status and renewal information\n */\nexport async function handleTokenRenewal(refreshToken: string): Promise<{\n\tsuccess: boolean;\n\tentity?: {\n\t\tid: string;\n\t\ttype: AuthEntityType;\n\t\tparameters: Record<string, unknown>;\n\t};\n\ttokenStatus: 'valid' | 'expired' | 'revoked' | 'invalid';\n\tnewTokens?: {\n\t\taccessToken: string;\n\t\trefreshToken?: string | null;\n\t};\n}> {\n\tconst tokenRepository = getLibraries().getAuthTokenRepository();\n\n\tconst storedToken = await tokenRepository.findRefreshToken(refreshToken);\n\n\tif (!storedToken) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\ttokenStatus: 'invalid',\n\t\t};\n\t}\n\n\tconst isRevoked = storedToken.isRevoked;\n\tif (isRevoked) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\ttokenStatus: 'revoked',\n\t\t};\n\t}\n\n\tconst isExpired = storedToken.isExpired();\n\n\tconst entityData = {\n\t\tid: storedToken.entityId,\n\t\ttype: storedToken.entityType,\n\t\tparameters: storedToken.metadata || {},\n\t};\n\n\tif (isExpired) {\n\t\tconst newTokens = await signTokenPair({\n\t\t\tid: storedToken.entityId,\n\t\t\ttype: storedToken.entityType,\n\t\t\tparameters: storedToken.metadata || {},\n\t\t});\n\n\t\tawait tokenRepository.revokeRefreshToken(refreshToken);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tentity: entityData,\n\t\t\ttokenStatus: 'expired',\n\t\t\tnewTokens: {\n\t\t\t\taccessToken: newTokens.accessToken,\n\t\t\t\trefreshToken: newTokens.refreshToken,\n\t\t\t},\n\t\t};\n\t}\n\n\tconst newAccessToken = await signAccessToken({\n\t\tid: storedToken.entityId,\n\t\ttype: storedToken.entityType,\n\t\tparameters: storedToken.metadata || {},\n\t});\n\n\treturn {\n\t\tsuccess: true,\n\t\tentity: entityData,\n\t\ttokenStatus: 'valid',\n\t\tnewTokens: {\n\t\t\taccessToken: newAccessToken,\n\t\t\trefreshToken: null,\n\t\t},\n\t};\n}\n\nexport const RefreshTokenModel = createGlobalModel(RefreshToken);\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/auth/index.ts"],"names":[],"mappings":";;;;;;AAkCA,oDAKC;AAKD,kEAGC;AAMD,0CA2BC;AAKD,oDAuDC;AAaD,8CAwBC;AAKD,oDA2BC;AAMD,sCAoCC;AAKD,gDAGC;AAKD,wDAGC;AAKD,sCA6BC;AAOD,gDA2EC;AA/XD,gEAA4D;AAE5D,mCAAqC;AACrC,iDAA8C;AAC9C,uCAA2C;AAC3C,oDAAyE;AAEzE,IAAY,cAKX;AALD,WAAY,cAAc;IACzB,+BAAa,CAAA;IACb,mCAAiB,CAAA;IACjB,+CAA6B,CAAA;IAC7B,6BAAW,CAAA;AACZ,CAAC,EALW,cAAc,8BAAd,cAAc,QAKzB;AAED,IAAY,SAGX;AAHD,WAAY,SAAS;IACpB,8BAAiB,CAAA;IACjB,gCAAmB,CAAA;AACpB,CAAC,EAHW,SAAS,yBAAT,SAAS,QAGpB;AAYD,IAAI,uBAAuB,GAAgD,IAAI,CAAC;AAKhF,SAAgB,oBAAoB;IACnC,IAAI,CAAC,uBAAuB,EAAE,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;IAC/F,CAAC;IACD,OAAO,uBAAuB,CAAC;AAChC,CAAC;AAKD,SAAgB,2BAA2B,CAAC,gBAAqB;IAChE,uBAAuB,GAAG,IAAA,4BAAgB,EAAC,2BAAY,EAAE,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,CAAC,CAAC;IACnG,OAAO,CAAC,GAAG,CAAC,kCAAkC,CAAC,CAAC;AACjD,CAAC;AAMM,KAAK,UAAU,eAAe,CACpC,MAAiF,EACjF,OAAqB;IAErB,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC;QACnB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AW,CAAC,SAAS,EAAE,CAAC;IAE1C,MAAM,UAAU,GAAG;QAClB,EAAE,EAAE,WAAW,CAAC,QAAQ;QACxB,IAAI,EAAE,WAAW,CAAC,UAAU;QAC5B,UAAU,EAAE,WAAW,CAAC,QAAQ,IAAI,EAAE;KACtC,CAAC;IAEF,IAAI,SAAS,EAAE,CAAC;QACf,MAAM,SAAS,GAAG,MAAM,aAAa,CAAC;YACrC,EAAE,EAAE,WAAW,CAAC,QAAQ;YACxB,IAAI,EAAE,WAAW,CAAC,UAAU;YAC5B,UAAU,EAAE,WAAW,CAAC,QAAQ,IAAI,EAAE;SACtC,CAAC,CAAC;QAEH,MAAM,eAAe,CAAC,kBAAkB,CAAC,YAAY,CAAC,CAAC;QAEvD,OAAO;YACN,OAAO,EAAE,IAAI;YACb,MAAM,EAAE,UAAU;YAClB,WAAW,EAAE,SAAS;YACtB,SAAS,EAAE;gBACV,WAAW,EAAE,SAAS,CAAC,WAAW;gBAClC,YAAY,EAAE,SAAS,CAAC,YAAY;aACpC;SACD,CAAC;IACH,CAAC;IAED,MAAM,cAAc,GAAG,MAAM,eAAe,CAAC;QAC5C,EAAE,EAAE,WAAW,CAAC,QAAQ;QACxB,IAAI,EAAE,WAAW,CAAC,UAAU;QAC5B,UAAU,EAAE,WAAW,CAAC,QAAQ,IAAI,EAAE;KACtC,CAAC,CAAC;IAEH,OAAO;QACN,OAAO,EAAE,IAAI;QACb,MAAM,EAAE,UAAU;QAClB,WAAW,EAAE,OAAO;QACpB,SAAS,EAAE;YACV,WAAW,EAAE,cAAc;YAC3B,YAAY,EAAE,IAAI;SAClB;KACD,CAAC;AACH,CAAC","sourcesContent":["import jwt, { SignOptions, JwtPayload } from 'jsonwebtoken';\nimport { EntityContext } from '../trpc/context';\nimport { randomBytes } from 'crypto';\nimport { RefreshToken } from './refreshtoken';\nimport { getLibraries } from '../../index';\nimport { getModelForClass, ReturnModelType } from '@typegoose/typegoose';\n\nexport enum AuthEntityType {\n\tUSER = 'USER',\n\tSELLER = 'SELLER',\n\tDELIVERY_BOY = 'DELIVERY_BOY',\n\tCRM = 'CRM',\n}\n\nexport enum TokenType {\n\tACCESS = 'ACCESS',\n\tREFRESH = 'REFRESH',\n}\n\nexport interface RefreshTokenRecord {\n\ttoken: string;\n\tentityId: string;\n\tentityType: AuthEntityType;\n\texpiresAt: Date;\n\tisRevoked: boolean;\n\tmetadata?: Record<string, unknown>;\n}\n\n// Global model for RefreshToken - will be set after initGlobalConnection()\nlet actualRefreshTokenModel: ReturnModelType<typeof RefreshToken> | null = null;\n\n/**\n * Get the RefreshToken model (throws if not initialized)\n */\nexport function getRefreshTokenModel(): ReturnModelType<typeof RefreshToken> {\n\tif (!actualRefreshTokenModel) {\n\t\tthrow new Error('RefreshToken model not initialized yet. Call initGlobalConnection() first.');\n\t}\n\treturn actualRefreshTokenModel;\n}\n\n/**\n * Initialize the RefreshToken model (called from initGlobalConnection)\n */\nexport function initializeRefreshTokenModel(globalConnection: any) {\n\tactualRefreshTokenModel = getModelForClass(RefreshToken, { existingConnection: globalConnection });\n\tconsole.log('✅ RefreshToken model initialized');\n}\n\n/**\n * Sign a JWT access token for the given entity (id + type).\n * It will fetch the secret for that entity type and create a token.\n */\nexport async function signAccessToken(\n\tentity: { id: string; type: AuthEntityType; parameters: Record<string, unknown> },\n\toptions?: SignOptions\n): Promise<string> {\n\tif (!entity?.type) {\n\t\tthrow new Error('Entity type is required to sign token');\n\t}\n\n\tconst secret = await getLibraries().getSecretsService().getKey(`${entity.type.toUpperCase()}_JWT_TOKEN`);\n\n\tif (!secret) {\n\t\tthrow new Error(`No secret found for entity type ${entity.type}`);\n\t}\n\n\tconst payload = {\n\t\tid: entity.id,\n\t\ttype: entity.type,\n\t\tparameters: entity.parameters,\n\t\ttokenType: TokenType.ACCESS,\n\t};\n\n\tconst tokenOptions: SignOptions = {\n\t\t...options,\n\t\texpiresIn: options?.expiresIn || '1d',\n\t};\n\n\treturn jwt.sign(payload, secret, tokenOptions);\n}\n\n/**\n * Generate a refresh token for the given entity\n */\nexport async function generateRefreshToken(\n\tentity: { id: string; type: AuthEntityType; parameters?: Record<string, unknown> },\n\toptions?: { expiresIn?: string | number }\n): Promise<string> {\n\tconst tokenValue = randomBytes(40).toString('hex');\n\n\tconst expiresIn = options?.expiresIn || '7d';\n\tconst expiresAt = new Date();\n\n\tif (typeof expiresIn === 'string') {\n\t\t// Parse duration strings like '7d', '30d', etc.\n\t\tconst match = expiresIn.match(/^(\\d+)([smhdwy])$/);\n\t\tif (match) {\n\t\t\tconst value = parseInt(match[1]);\n\t\t\tconst unit = match[2];\n\n\t\t\tswitch (unit) {\n\t\t\t\tcase 's':\n\t\t\t\t\texpiresAt.setSeconds(expiresAt.getSeconds() + value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'm':\n\t\t\t\t\texpiresAt.setMinutes(expiresAt.getMinutes() + value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'h':\n\t\t\t\t\texpiresAt.setHours(expiresAt.getHours() + value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'd':\n\t\t\t\t\texpiresAt.setDate(expiresAt.getDate() + value);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'w':\n\t\t\t\t\texpiresAt.setDate(expiresAt.getDate() + value * 7);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'y':\n\t\t\t\t\texpiresAt.setFullYear(expiresAt.getFullYear() + value);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\t// Default to 7 days if format is invalid\n\t\t\texpiresAt.setDate(expiresAt.getDate() + 7);\n\t\t}\n\t} else if (typeof expiresIn === 'number') {\n\t\t// Interpret number as seconds\n\t\texpiresAt.setSeconds(expiresAt.getSeconds() + expiresIn);\n\t}\n\n\tawait storeRefreshToken({\n\t\ttoken: tokenValue,\n\t\tentityId: entity.id,\n\t\tentityType: entity.type,\n\t\texpiresAt,\n\t\tisRevoked: false,\n\t\tmetadata: entity.parameters,\n\t});\n\n\treturn tokenValue;\n}\n\n/**\n * Store a refresh token in the database\n */\nasync function storeRefreshToken(tokenRecord: RefreshTokenRecord): Promise<void> {\n\tconst tokenRepository = getLibraries().getAuthTokenRepository();\n\tawait tokenRepository.saveRefreshToken(tokenRecord);\n}\n\n/**\n * Verify an access token for the given entity types\n */\nexport async function verifyAccessToken(\n\tentityTypes: AuthEntityType[],\n\ttoken: string\n): Promise<EntityContext | undefined> {\n\tfor (const entityType of entityTypes) {\n\t\tconst secret = await getLibraries()\n\t\t\t.getSecretsService()\n\t\t\t.getKey(entityType.toUpperCase() + '_JWT_TOKEN');\n\n\t\ttry {\n\t\t\tconst decoded = jwt.verify(token, secret!) as EntityContext & { tokenType?: TokenType };\n\n\t\t\t// Verify this is an access token\n\t\t\tif (decoded.tokenType !== TokenType.ACCESS) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\treturn decoded;\n\t\t} catch (err) {\n\t\t\t// Continue to the next entity type\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Validate a refresh token and return the associated entity\n */\nexport async function validateRefreshToken(token: string): Promise<{\n\tvalid: boolean;\n\tentity?: { id: string; type: AuthEntityType; parameters?: Record<string, unknown> };\n}> {\n\tconst tokenRepository = getLibraries().getAuthTokenRepository();\n\tconst storedToken = await tokenRepository.findRefreshToken(token);\n\n\tif (!storedToken) {\n\t\treturn { valid: false };\n\t}\n\n\tif (storedToken.expiresAt && new Date() > storedToken.expiresAt) {\n\t\treturn { valid: false };\n\t}\n\n\tif (storedToken.isRevoked) {\n\t\treturn { valid: false };\n\t}\n\n\treturn {\n\t\tvalid: true,\n\t\tentity: {\n\t\t\tid: storedToken.entityId,\n\t\t\ttype: storedToken.entityType,\n\t\t\tparameters: storedToken.metadata,\n\t\t},\n\t};\n}\n\n/**\n * Refresh authentication tokens\n * Returns new access and refresh tokens\n */\nexport async function refreshTokens(refreshToken: string): Promise<{\n\taccessToken: string;\n\trefreshToken: string;\n\tentity: { id: string; type: AuthEntityType };\n} | null> {\n\t// Validate the refresh token\n\tconst validation = await validateRefreshToken(refreshToken);\n\n\tif (!validation.valid || !validation.entity) {\n\t\treturn null;\n\t}\n\n\tawait revokeRefreshToken(refreshToken);\n\n\t// Create new tokens\n\tconst entity = validation.entity;\n\tconst newAccessToken = await signAccessToken({\n\t\tid: entity.id,\n\t\ttype: entity.type,\n\t\tparameters: entity.parameters || {},\n\t});\n\n\tconst newRefreshToken = await generateRefreshToken({\n\t\tid: entity.id,\n\t\ttype: entity.type,\n\t\tparameters: entity.parameters,\n\t});\n\n\treturn {\n\t\taccessToken: newAccessToken,\n\t\trefreshToken: newRefreshToken,\n\t\tentity: {\n\t\t\tid: entity.id,\n\t\t\ttype: entity.type,\n\t\t},\n\t};\n}\n\n/**\n * Revoke a refresh token\n */\nexport async function revokeRefreshToken(token: string): Promise<boolean> {\n\tconst tokenRepository = getLibraries().getAuthTokenRepository();\n\treturn tokenRepository.revokeRefreshToken(token);\n}\n\n/**\n * Revoke all refresh tokens for a specific entity\n */\nexport async function revokeAllRefreshTokens(entityId: string, entityType: AuthEntityType): Promise<boolean> {\n\tconst tokenRepository = getLibraries().getAuthTokenRepository();\n\treturn tokenRepository.revokeAllRefreshTokensForEntity(entityId, entityType);\n}\n\n/**\n * Sign both access and refresh tokens - utility for initial login/authentication\n */\nexport async function signTokenPair(\n\tentity: { id: string; type: AuthEntityType; parameters?: Record<string, unknown> },\n\toptions?: { accessTokenOptions?: SignOptions; refreshTokenExpiresIn?: string | number }\n): Promise<{\n\taccessToken: string;\n\trefreshToken: string;\n}> {\n\tconst accessToken = await signAccessToken(\n\t\t{\n\t\t\tid: entity.id,\n\t\t\ttype: entity.type,\n\t\t\tparameters: entity.parameters || {},\n\t\t},\n\t\toptions?.accessTokenOptions\n\t);\n\n\tconst refreshToken = await generateRefreshToken(\n\t\t{\n\t\t\tid: entity.id,\n\t\t\ttype: entity.type,\n\t\t\tparameters: entity.parameters,\n\t\t},\n\t\t{ expiresIn: options?.refreshTokenExpiresIn }\n\t);\n\n\treturn {\n\t\taccessToken,\n\t\trefreshToken,\n\t};\n}\n\n/**\n * Handle the refresh token validation and renewal logic\n * @param refreshToken The refresh token to validate or renew\n * @returns Result object with token status and renewal information\n */\nexport async function handleTokenRenewal(refreshToken: string): Promise<{\n\tsuccess: boolean;\n\tentity?: {\n\t\tid: string;\n\t\ttype: AuthEntityType;\n\t\tparameters: Record<string, unknown>;\n\t};\n\ttokenStatus: 'valid' | 'expired' | 'revoked' | 'invalid';\n\tnewTokens?: {\n\t\taccessToken: string;\n\t\trefreshToken?: string | null;\n\t};\n}> {\n\tconst tokenRepository = getLibraries().getAuthTokenRepository();\n\n\tconst storedToken = await tokenRepository.findRefreshToken(refreshToken);\n\n\tif (!storedToken) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\ttokenStatus: 'invalid',\n\t\t};\n\t}\n\n\tconst isRevoked = storedToken.isRevoked;\n\tif (isRevoked) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\ttokenStatus: 'revoked',\n\t\t};\n\t}\n\n\tconst isExpired = storedToken.isExpired();\n\n\tconst entityData = {\n\t\tid: storedToken.entityId,\n\t\ttype: storedToken.entityType,\n\t\tparameters: storedToken.metadata || {},\n\t};\n\n\tif (isExpired) {\n\t\tconst newTokens = await signTokenPair({\n\t\t\tid: storedToken.entityId,\n\t\t\ttype: storedToken.entityType,\n\t\t\tparameters: storedToken.metadata || {},\n\t\t});\n\n\t\tawait tokenRepository.revokeRefreshToken(refreshToken);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tentity: entityData,\n\t\t\ttokenStatus: 'expired',\n\t\t\tnewTokens: {\n\t\t\t\taccessToken: newTokens.accessToken,\n\t\t\t\trefreshToken: newTokens.refreshToken,\n\t\t\t},\n\t\t};\n\t}\n\n\tconst newAccessToken = await signAccessToken({\n\t\tid: storedToken.entityId,\n\t\ttype: storedToken.entityType,\n\t\tparameters: storedToken.metadata || {},\n\t});\n\n\treturn {\n\t\tsuccess: true,\n\t\tentity: entityData,\n\t\ttokenStatus: 'valid',\n\t\tnewTokens: {\n\t\t\taccessToken: newAccessToken,\n\t\t\trefreshToken: null,\n\t\t},\n\t};\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"refreshtoken.js","sourceRoot":"/","sources":["libraries/auth/refreshtoken.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,oDAQ8B;AAC9B,4EAAqE;AAErE,
|
|
1
|
+
{"version":3,"file":"refreshtoken.js","sourceRoot":"/","sources":["libraries/auth/refreshtoken.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,oDAQ8B;AAC9B,4EAAqE;AAErE,mCAAyC;AAelC,IAAM,YAAY,oBAAlB,MAAM,YAAa,SAAQ,2BAAU;IAEpC,KAAK,CAAU;IAGf,QAAQ,CAAU;IAOlB,UAAU,CAAkB;IAG5B,SAAS,CAAe;IAGxB,SAAS,CAAW;IAGpB,QAAQ,CAA2B;IAKnC,MAAM,CAAC,KAAK,CAAC,cAAc,CAEjC,KAAa;QAEb,MAAM,KAAK,GAAQ,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;QAG/C,KAAK,CAAC,GAAG,GAAG,CAAC,EAAE,SAAS,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,GAAG,EAAE,IAAI,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;QAEzG,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IAC5B,CAAC;IAKM,MAAM,CAAC,KAAK,CAAC,kBAAkB,CAErC,QAAgB,EAChB,UAA0B;QAE1B,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,SAAS,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAEtG,O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EAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC;;8CACJ;uBArB9B,YAAY;IAbxB,IAAA,wBAAY,EAAC;QACb,aAAa,EAAE;YACd,UAAU,EAAE,gBAAgB;YAC5B,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE;YAC1B,QAAQ,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE;SAC5B;QACD,OAAO,EAAE;YACR,UAAU,EAAE,oBAAQ,CAAC,KAAK;SAC1B;KACD,CAAC;IACD,IAAA,iBAAK,EAAC,EAAE,QAAQ,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,CAAC;IACrC,IAAA,iBAAK,EAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC;GACX,YAAY,CA4ExB","sourcesContent":["import {\n\tprop,\n\tgetModelForClass,\n\tmodelOptions,\n\tindex,\n\tSeverity,\n\tDocumentType,\n\tReturnModelType,\n} from '@typegoose/typegoose';\nimport { TimeStamps } from '@typegoose/typegoose/lib/defaultClasses';\nimport { getLibraries } from '../../index';\nimport { AuthEntityType } from './index';\n\n@modelOptions({\n\tschemaOptions: {\n\t\tcollection: 'refresh_tokens',\n\t\tautoCreate: true,\n\t\ttoJSON: { virtuals: true },\n\t\ttoObject: { virtuals: true },\n\t},\n\toptions: {\n\t\tallowMixed: Severity.ALLOW, // Allow mixed types for metadata\n\t},\n})\n@index({ entityId: 1, entityType: 1 })\n@index({ isRevoked: 1 })\nexport class RefreshToken extends TimeStamps {\n\t@prop({ required: true, type: () => String, unique: true })\n\tpublic token!: string;\n\n\t@prop({ required: true, type: () => String })\n\tpublic entityId!: string;\n\n\t@prop({\n\t\trequired: true,\n\t\ttype: () => String,\n\t\tenum: AuthEntityType,\n\t})\n\tpublic entityType!: AuthEntityType;\n\n\t@prop({ required: false, type: () => Date })\n\tpublic expiresAt?: Date | null;\n\n\t@prop({ required: true, type: () => Boolean, default: false })\n\tpublic isRevoked!: boolean;\n\n\t@prop({ required: false, type: () => Object })\n\tpublic metadata?: Record<string, unknown>;\n\n\t/**\n\t * Static method to find a valid token\n\t */\n\tpublic static async findValidToken(\n\t\tthis: ReturnModelType<typeof RefreshToken>,\n\t\ttoken: string\n\t): Promise<DocumentType<RefreshToken> | null> {\n\t\tconst query: any = { token, isRevoked: false };\n\n\t\t// Only check expiration if token has an expiration date\n\t\tquery.$or = [{ expiresAt: { $exists: false } }, { expiresAt: null }, { expiresAt: { $gt: new Date() } }];\n\n\t\treturn this.findOne(query);\n\t}\n\n\t/**\n\t * Static method to revoke all tokens for an entity\n\t */\n\tpublic static async revokeAllForEntity(\n\t\tthis: ReturnModelType<typeof RefreshToken>,\n\t\tentityId: string,\n\t\tentityType: AuthEntityType\n\t): Promise<number> {\n\t\tconst result = await this.updateMany({ entityId, entityType, isRevoked: false }, { isRevoked: true });\n\n\t\treturn result.modifiedCount;\n\t}\n\n\t/**\n\t * Check if this token is expired\n\t */\n\tpublic isExpired(): boolean {\n\t\tif (!this.expiresAt) return false;\n\t\treturn new Date() > this.expiresAt;\n\t}\n\n\t/**\n\t * Static method to clean up old expired tokens\n\t * Call this periodically to keep your database clean\n\t */\n\tpublic static async cleanupExpiredTokens(\n\t\tthis: ReturnModelType<typeof RefreshToken>,\n\t\tolderThan?: Date\n\t): Promise<number> {\n\t\tconst cutoffDate = olderThan || new Date();\n\n\t\tconst result = await this.deleteMany({\n\t\t\texpiresAt: { $ne: null, $lt: cutoffDate },\n\t\t\tisRevoked: true, // Only delete tokens that are both expired and already revoked\n\t\t});\n\n\t\treturn result.deletedCount;\n\t}\n}\n"]}
|
|
@@ -11,21 +11,21 @@ const index_1 = require("./index");
|
|
|
11
11
|
const typedi_1 = require("typedi");
|
|
12
12
|
let TokenRepository = class TokenRepository {
|
|
13
13
|
async saveRefreshToken(token) {
|
|
14
|
-
return index_1.
|
|
14
|
+
return (0, index_1.getRefreshTokenModel)().create(token);
|
|
15
15
|
}
|
|
16
16
|
async findRefreshToken(token) {
|
|
17
|
-
return index_1.
|
|
17
|
+
return (0, index_1.getRefreshTokenModel)().findValidToken(token);
|
|
18
18
|
}
|
|
19
19
|
async revokeRefreshToken(token) {
|
|
20
|
-
const result = await index_1.
|
|
20
|
+
const result = await (0, index_1.getRefreshTokenModel)().updateOne({ token }, { isRevoked: true });
|
|
21
21
|
return result.modifiedCount > 0;
|
|
22
22
|
}
|
|
23
23
|
async revokeAllRefreshTokensForEntity(entityId, entityType) {
|
|
24
|
-
const count = await index_1.
|
|
24
|
+
const count = await (0, index_1.getRefreshTokenModel)().revokeAllForEntity(entityId, entityType);
|
|
25
25
|
return count > 0;
|
|
26
26
|
}
|
|
27
27
|
async getActiveTokensForEntity(entityId, entityType) {
|
|
28
|
-
return index_1.
|
|
28
|
+
return (0, index_1.getRefreshTokenModel)().find({
|
|
29
29
|
entityId,
|
|
30
30
|
entityType,
|
|
31
31
|
isRevoked: false,
|
|
@@ -33,7 +33,7 @@ let TokenRepository = class TokenRepository {
|
|
|
33
33
|
});
|
|
34
34
|
}
|
|
35
35
|
async cleanupExpiredTokens(olderThan) {
|
|
36
|
-
return index_1.
|
|
36
|
+
return (0, index_1.getRefreshTokenModel)().cleanupExpiredTokens(olderThan);
|
|
37
37
|
}
|
|
38
38
|
};
|
|
39
39
|
exports.TokenRepository = TokenRepository;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"repository.js","sourceRoot":"/","sources":["libraries/auth/repository.ts"],"names":[],"mappings":";;;;;;;;;AAAA,
|
|
1
|
+
{"version":3,"file":"repository.js","sourceRoot":"/","sources":["libraries/auth/repository.ts"],"names":[],"mappings":";;;;;;;;;AAAA,mCAA6D;AAG7D,mCAAiC;AAG1B,IAAM,eAAe,GAArB,MAAM,eAAe;IAI3B,KAAK,CAAC,gBAAgB,CAAC,KAOtB;QACA,OAAO,IAAA,4BAAoB,GAAE,CAAC,MAAM,CAAC,KAAK,CAA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\nimport { RefreshToken } from './refreshtoken';\nimport { Service } from 'typedi';\n\n@Service()\nexport class TokenRepository {\n\t/**\n\t * Save a refresh token\n\t */\n\tasync saveRefreshToken(token: {\n\t\ttoken: string;\n\t\tentityId: string;\n\t\tentityType: AuthEntityType;\n\t\texpiresAt?: Date | null;\n\t\tisRevoked?: boolean;\n\t\tmetadata?: Record<string, unknown>;\n\t}): Promise<DocumentType<RefreshToken>> {\n\t\treturn getRefreshTokenModel().create(token);\n\t}\n\n\t/**\n\t * Find a refresh token by its value\n\t */\n\tasync findRefreshToken(token: string): Promise<DocumentType<RefreshToken> | null> {\n\t\treturn getRefreshTokenModel().findValidToken(token);\n\t}\n\n\t/**\n\t * Revoke a specific refresh token\n\t */\n\tasync revokeRefreshToken(token: string): Promise<boolean> {\n\t\tconst result = await getRefreshTokenModel().updateOne({ token }, { isRevoked: true });\n\n\t\treturn result.modifiedCount > 0;\n\t}\n\n\t/**\n\t * Revoke all refresh tokens for a specific entity\n\t */\n\tasync revokeAllRefreshTokensForEntity(entityId: string, entityType: AuthEntityType): Promise<boolean> {\n\t\tconst count = await getRefreshTokenModel().revokeAllForEntity(entityId, entityType);\n\t\treturn count > 0;\n\t}\n\n\t/**\n\t * Get all active tokens for an entity\n\t */\n\tasync getActiveTokensForEntity(\n\t\tentityId: string,\n\t\tentityType: AuthEntityType\n\t): Promise<DocumentType<RefreshToken>[]> {\n\t\treturn getRefreshTokenModel().find({\n\t\t\tentityId,\n\t\t\tentityType,\n\t\t\tisRevoked: false,\n\t\t\t$or: [{ expiresAt: { $exists: false } }, { expiresAt: null }, { expiresAt: { $gt: new Date() } }],\n\t\t});\n\t}\n\n\t/**\n\t * Clean up expired tokens (can be called periodically if needed)\n\t * Note: MongoDB TTL index will also handle this automatically for tokens with expiresAt\n\t */\n\tasync cleanupExpiredTokens(olderThan?: Date): Promise<number> {\n\t\treturn getRefreshTokenModel().cleanupExpiredTokens(olderThan);\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/dispatcher/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mCAAiC;AACjC,yCAAoE;AAEpE,wCAAkD;AAG3C,IAAM,sBAAsB,GAA5B,MAAM,sBAAsB;IAC1B,cAAc,CAAuB;IAE7C,YAAY,aAAmC;QAC9C,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;IACrC,CAAC;IAEM,KAAK,CAAC,eAAe,CAC3B,WAAmB,EACnB,SAAkB,EAClB,OAEC;QAED,MAAM,aAAa,GAClB,SAAS;YACT,CAAC,MAAM,IAAI,CAAC,cAAc,CAAC,MAAM,CAChC,2BAA2B,GAAG,WAAW,CAAC,WAAW,EAAE,GAAG,WAAW,CACrE,CAAC,CAAC;QAEJ,OAAO,CAAC,GAAG,CAAC,aAAa,EAAE,iBAAiB,CAAC,CAAC;QAE9C,IAAI,CAAC,aAAa,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CAAC,6DAA6D,CAAC,CAAC;QAChF,CAAC;QAGD,OAAO,IAAA,8BAAqB,EAAI;YAC/B,KAAK,EAAE;gBACN,IAAA,sBAAa,EAAC;oBACb,GAAG,EAAE,aAAa;oBAClB,OAAO,EAAE,KAAK,IAAI,EAAE,CAAC,OAAO,EAAE,OAAO,IAAI,EAAE;iBAC3C,CAAC;aACF;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/dispatcher/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,mCAAiC;AACjC,yCAAoE;AAEpE,wCAAkD;AAG3C,IAAM,sBAAsB,GAA5B,MAAM,sBAAsB;IAC1B,cAAc,CAAuB;IAE7C,YAAY,aAAmC;QAC9C,IAAI,CAAC,cAAc,GAAG,aAAa,CAAC;IACrC,CAAC;IAEM,KAAK,CAAC,eAAe,CAC3B,WAAmB,EACnB,SAAkB,EAClB,OAEC;QAED,MAAM,aAAa,GAClB,SAAS;YACT,CAAC,MAAM,IAAI,CAAC,cAAc,CAAC,MAAM,CAChC,2BAA2B,GAAG,WAAW,CAAC,WAAW,EAAE,GAAG,WAAW,CACrE,CAAC,CAAC;QAEJ,OAAO,CAAC,GAAG,CAAC,aAAa,EAAE,iBAAiB,CAAC,CAAC;QAE9C,IAAI,CAAC,aAAa,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CAAC,6DAA6D,CAAC,CAAC;QAChF,CAAC;QAGD,OAAO,IAAA,8BAAqB,EAAI;YAC/B,KAAK,EAAE;gBACN,IAAA,sBAAa,EAAC;oBACb,GAAG,EAAE,aAAa;oBAClB,OAAO,EAAE,KAAK,IAAI,EAAE,CAAC,OAAO,EAAE,OAAO,IAAI,EAAE;iBAC3C,CAAC;aACF;SAED,CAAC,CAAC;IACJ,CAAC;CACD,CAAA;AArCY,wDAAsB;iCAAtB,sBAAsB;IADlC,IAAA,gBAAO,GAAE;qCAIkB,8BAAoB;GAHnC,sBAAsB,CAqClC","sourcesContent":["import { Service } from 'typedi';\nimport { createTRPCProxyClient, httpBatchLink } from '@trpc/client';\nimport { AnyRouter } from '@trpc/server';\nimport { SecretManagerService } from '../secrets';\n\n@Service()\nexport class MicroServiceDispatcher {\n\tprivate _secretService: SecretManagerService;\n\n\tconstructor(secretService: SecretManagerService) {\n\t\tthis._secretService = secretService;\n\t}\n\n\tpublic async getMicroService<T extends AnyRouter>(\n\t\tserviceName: string,\n\t\tcustomURL?: string,\n\t\toptions?: {\n\t\t\theaders?: Record<string, string>;\n\t\t}\n\t) {\n\t\tconst deploymentURL =\n\t\t\tcustomURL ??\n\t\t\t(await this._secretService.getKey(\n\t\t\t\t'DEPLOYMENTS_MICROSERVICE_' + serviceName.toUpperCase() + '_ENDPOINT'\n\t\t\t));\n\n\t\tconsole.log(deploymentURL, 'deploymentURL--');\n\n\t\tif (!deploymentURL) {\n\t\t\tthrow new Error('The requested service does not have a configured secret URL');\n\t\t}\n\n\t\t// @ts-ignore\n\t\treturn createTRPCProxyClient<T>({\n\t\t\tlinks: [\n\t\t\t\thttpBatchLink({\n\t\t\t\t\turl: deploymentURL,\n\t\t\t\t\theaders: async () => options?.headers ?? {},\n\t\t\t\t}),\n\t\t\t],\n\t\t\t//special http request header that has a token\n\t\t});\n\t}\n}\n"]}
|
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
import { Connection } from 'mongoose';
|
|
2
|
-
import { ReturnModelType } from '@typegoose/typegoose';
|
|
3
|
-
import { AnyParamConstructor, IModelOptions } from '@typegoose/typegoose/lib/types';
|
|
4
2
|
export declare function initGlobalConnection(uri: string, environment: string): Promise<Connection>;
|
|
5
|
-
export declare function
|
|
6
|
-
export declare function
|
|
3
|
+
export declare function isGlobalConnectionInitialized(): boolean;
|
|
4
|
+
export declare function getGlobalConnection(): Connection;
|
|
@@ -1,181 +1,47 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.initGlobalConnection = initGlobalConnection;
|
|
4
|
-
exports.
|
|
5
|
-
exports.
|
|
4
|
+
exports.isGlobalConnectionInitialized = isGlobalConnectionInitialized;
|
|
5
|
+
exports.getGlobalConnection = getGlobalConnection;
|
|
6
6
|
const mongoose_1 = require("mongoose");
|
|
7
|
-
const typegoose_1 = require("@typegoose/typegoose");
|
|
8
7
|
const soft_delete_plugin_1 = require("./plugins/soft-delete-plugin");
|
|
8
|
+
const models_1 = require("./models");
|
|
9
9
|
(0, soft_delete_plugin_1.applySoftDeletePlugin)();
|
|
10
10
|
let globalConnection;
|
|
11
11
|
let connectionPromise = null;
|
|
12
|
-
let pendingModels = new Map();
|
|
13
|
-
let pendingDiscriminatorModels = new Map();
|
|
14
12
|
async function initGlobalConnection(uri, environment) {
|
|
15
13
|
if (!connectionPromise) {
|
|
16
|
-
connectionPromise = new Promise(resolve => {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
...options,
|
|
14
|
+
connectionPromise = new Promise(async (resolve, reject) => {
|
|
15
|
+
try {
|
|
16
|
+
console.log(`Initializing global connection for environment: ${environment}`);
|
|
17
|
+
const connection = (0, mongoose_1.createConnection)(uri, {
|
|
18
|
+
dbName: `lyxa-${environment}-global`,
|
|
19
|
+
});
|
|
20
|
+
await new Promise((connectResolve, connectReject) => {
|
|
21
|
+
connection.once('connected', () => {
|
|
22
|
+
console.log('Global connection successfully established');
|
|
23
|
+
globalConnection = connection;
|
|
24
|
+
connectResolve();
|
|
28
25
|
});
|
|
29
|
-
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
for (const [modelName, { baseModelPromise, subClass, discriminatorName, options, resolve },] of pendingDiscriminatorModels.entries()) {
|
|
33
|
-
try {
|
|
34
|
-
const actualBaseModel = await baseModelPromise;
|
|
35
|
-
const model = (0, typegoose_1.getDiscriminatorModelForClass)(actualBaseModel, subClass, discriminatorName, {
|
|
36
|
-
existingConnection: globalConnection,
|
|
37
|
-
...options,
|
|
38
|
-
});
|
|
39
|
-
resolve(model);
|
|
40
|
-
}
|
|
41
|
-
catch (error) {
|
|
42
|
-
console.error(`Failed to create discriminator model ${modelName}:`, error);
|
|
43
|
-
resolve(Promise.reject(error));
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
pendingDiscriminatorModels.clear();
|
|
26
|
+
connection.once('error', connectReject);
|
|
27
|
+
});
|
|
28
|
+
(0, models_1.initializeGlobalModels)(globalConnection);
|
|
47
29
|
resolve(connection);
|
|
48
|
-
}
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
reject(error);
|
|
33
|
+
}
|
|
49
34
|
});
|
|
50
35
|
}
|
|
51
36
|
return connectionPromise;
|
|
52
37
|
}
|
|
53
|
-
function
|
|
54
|
-
|
|
55
|
-
if (globalConnection) {
|
|
56
|
-
return (0, typegoose_1.getModelForClass)(Class, {
|
|
57
|
-
existingConnection: globalConnection,
|
|
58
|
-
...options,
|
|
59
|
-
});
|
|
60
|
-
}
|
|
61
|
-
console.log(`Registering model ${modelName} to be initialized when global connection is ready`);
|
|
62
|
-
let actualModel = null;
|
|
63
|
-
let modelReadyPromise;
|
|
64
|
-
modelReadyPromise = new Promise(resolve => {
|
|
65
|
-
pendingModels.set(modelName, { Class, options, resolve });
|
|
66
|
-
});
|
|
67
|
-
const modelProxy = new Proxy({}, {
|
|
68
|
-
get(target, prop, receiver) {
|
|
69
|
-
if (prop === 'then') {
|
|
70
|
-
return modelReadyPromise.then.bind(modelReadyPromise);
|
|
71
|
-
}
|
|
72
|
-
if (typeof prop === 'symbol' || typeof prop === 'number') {
|
|
73
|
-
return async function (...args) {
|
|
74
|
-
if (!actualModel) {
|
|
75
|
-
actualModel = await modelReadyPromise;
|
|
76
|
-
}
|
|
77
|
-
return actualModel[prop];
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
return function (...args) {
|
|
81
|
-
return (async () => {
|
|
82
|
-
if (!actualModel) {
|
|
83
|
-
actualModel = await modelReadyPromise;
|
|
84
|
-
}
|
|
85
|
-
const propValue = actualModel[prop];
|
|
86
|
-
if (typeof propValue === 'function') {
|
|
87
|
-
const result = propValue.apply(actualModel, args);
|
|
88
|
-
if (result && typeof result === 'object' && typeof result.then !== 'function') {
|
|
89
|
-
const queryMethods = ['sort', 'limit', 'skip', 'populate', 'select', 'lean', 'exec'];
|
|
90
|
-
const isQueryLike = queryMethods.some(method => typeof result[method] === 'function');
|
|
91
|
-
if (isQueryLike) {
|
|
92
|
-
return result;
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
return result;
|
|
96
|
-
}
|
|
97
|
-
return propValue;
|
|
98
|
-
})();
|
|
99
|
-
};
|
|
100
|
-
},
|
|
101
|
-
});
|
|
102
|
-
return modelProxy;
|
|
38
|
+
function isGlobalConnectionInitialized() {
|
|
39
|
+
return !!globalConnection;
|
|
103
40
|
}
|
|
104
|
-
function
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
if (baseModel instanceof Promise || baseModel.then) {
|
|
108
|
-
const discriminatorPromise = (async () => {
|
|
109
|
-
const resolvedBaseModel = await baseModel;
|
|
110
|
-
return (0, typegoose_1.getDiscriminatorModelForClass)(resolvedBaseModel, subClass, discriminatorName, {
|
|
111
|
-
existingConnection: globalConnection,
|
|
112
|
-
...options,
|
|
113
|
-
});
|
|
114
|
-
})();
|
|
115
|
-
return createProxyForPromise(discriminatorPromise);
|
|
116
|
-
}
|
|
117
|
-
return (0, typegoose_1.getDiscriminatorModelForClass)(baseModel, subClass, discriminatorName, {
|
|
118
|
-
existingConnection: globalConnection,
|
|
119
|
-
...options,
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
console.log(`Registering discriminator model ${modelName} to be initialized when global connection is ready`);
|
|
123
|
-
let actualModel = null;
|
|
124
|
-
let modelReadyPromise;
|
|
125
|
-
let baseModelPromise;
|
|
126
|
-
if (baseModel instanceof Promise || baseModel.then) {
|
|
127
|
-
baseModelPromise = Promise.resolve(baseModel);
|
|
128
|
-
}
|
|
129
|
-
else {
|
|
130
|
-
baseModelPromise = Promise.resolve(baseModel);
|
|
41
|
+
function getGlobalConnection() {
|
|
42
|
+
if (!globalConnection) {
|
|
43
|
+
throw new Error('Global connection not initialized. Call initGlobalConnection() first.');
|
|
131
44
|
}
|
|
132
|
-
|
|
133
|
-
pendingDiscriminatorModels.set(modelName, {
|
|
134
|
-
baseModelPromise,
|
|
135
|
-
subClass,
|
|
136
|
-
discriminatorName,
|
|
137
|
-
options,
|
|
138
|
-
resolve,
|
|
139
|
-
});
|
|
140
|
-
});
|
|
141
|
-
return createProxyForPromise(modelReadyPromise);
|
|
142
|
-
}
|
|
143
|
-
function createProxyForPromise(promise) {
|
|
144
|
-
let resolvedValue = null;
|
|
145
|
-
return new Proxy({}, {
|
|
146
|
-
get(target, prop, receiver) {
|
|
147
|
-
if (prop === 'then') {
|
|
148
|
-
return promise.then.bind(promise);
|
|
149
|
-
}
|
|
150
|
-
if (typeof prop === 'symbol' || typeof prop === 'number') {
|
|
151
|
-
return async function (...args) {
|
|
152
|
-
if (!resolvedValue) {
|
|
153
|
-
resolvedValue = await promise;
|
|
154
|
-
}
|
|
155
|
-
return resolvedValue[prop];
|
|
156
|
-
};
|
|
157
|
-
}
|
|
158
|
-
return function (...args) {
|
|
159
|
-
return (async () => {
|
|
160
|
-
if (!resolvedValue) {
|
|
161
|
-
resolvedValue = await promise;
|
|
162
|
-
}
|
|
163
|
-
const propValue = resolvedValue[prop];
|
|
164
|
-
if (typeof propValue === 'function') {
|
|
165
|
-
const result = propValue.apply(resolvedValue, args);
|
|
166
|
-
if (result && typeof result === 'object' && typeof result.then !== 'function') {
|
|
167
|
-
const queryMethods = ['sort', 'limit', 'skip', 'populate', 'select', 'lean', 'exec'];
|
|
168
|
-
const isQueryLike = queryMethods.some(method => typeof result[method] === 'function');
|
|
169
|
-
if (isQueryLike) {
|
|
170
|
-
return result;
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
return result;
|
|
174
|
-
}
|
|
175
|
-
return propValue;
|
|
176
|
-
})();
|
|
177
|
-
};
|
|
178
|
-
},
|
|
179
|
-
});
|
|
45
|
+
return globalConnection;
|
|
180
46
|
}
|
|
181
47
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/mongo/index.ts"],"names":[],"mappings":";;AAkCA,oDAmDC;AAMD,8CA8EC;AAMD,wEAgEC;AA/OD,uCAAkE;AAClE,oDAAwG;AAExG,qEAAqE;AAGrE,IAAA,0CAAqB,GAAE,CAAC;AAGxB,IAAI,gBAAwC,CAAC;AAC7C,IAAI,iBAAiB,GAA+B,IAAI,CAAC;AACzD,IAAI,aAAa,GAAG,IAAI,GAAG,EAOxB,CAAC;AAEJ,IAAI,0BAA0B,GAAG,IAAI,GAAG,EASrC,CAAC;AAKG,KAAK,UAAU,oBAAoB,CAA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,CAAC,CAAC;4BACrF,MAAM,WAAW,GAAG,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,OAAO,MAAM,CAAC,MAAM,CAAC,KAAK,UAAU,CAAC,CAAC;4BAEtF,IAAI,WAAW,EAAE,CAAC;gCACjB,OAAO,MAAM,CAAC;4BACf,CAAC;wBACF,CAAC;wBAED,OAAO,MAAM,CAAC;oBACf,CAAC;oBACD,OAAO,SAAS,CAAC;gBAClB,CAAC,CAAC,EAAE,CAAC;YACN,CAAC,CAAC;QACH,CAAC;KACD,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import mongoose, { Connection, createConnection } from 'mongoose';\nimport { getDiscriminatorModelForClass, getModelForClass, ReturnModelType } from '@typegoose/typegoose';\nimport { AnyParamConstructor, IModelOptions } from '@typegoose/typegoose/lib/types';\nimport { applySoftDeletePlugin } from './plugins/soft-delete-plugin';\n\n// Apply the soft delete plugin globally before any connections or models\napplySoftDeletePlugin();\n\n// Track connection status\nlet globalConnection: Connection | undefined;\nlet connectionPromise: Promise<Connection> | null = null;\nlet pendingModels = new Map<\n\tstring,\n\t{\n\t\tClass: AnyParamConstructor<any>;\n\t\toptions?: IModelOptions;\n\t\tresolve: (model: any) => void;\n\t}\n>();\n\nlet pendingDiscriminatorModels = new Map<\n\tstring,\n\t{\n\t\tbaseModelPromise: Promise<any>; // Store the promise for the base model\n\t\tsubClass: AnyParamConstructor<any>;\n\t\tdiscriminatorName?: string;\n\t\toptions?: IModelOptions;\n\t\tresolve: (model: any) => void;\n\t}\n>();\n\n/**\n * Initialize the global database connection\n */\nexport async function initGlobalConnection(uri: string, environment: string): Promise<Connection> {\n\tif (!connectionPromise) {\n\t\tconnectionPromise = new Promise<Connection>(resolve => {\n\t\t\tconsole.log(`Initializing global connection for environment: ${environment}`);\n\t\t\tconst connection = createConnection(uri, {\n\t\t\t\tdbName: `lyxa-${environment}-global`,\n\t\t\t});\n\n\t\t\tconnection.once('connected', async () => {\n\t\t\t\tconsole.log('Global connection successfully established');\n\t\t\t\tglobalConnection = connection;\n\n\t\t\t\t// Initialize any pending models with the real connection\n\t\t\t\tfor (const [modelName, { Class, options, resolve }] of pendingModels.entries()) {\n\t\t\t\t\tconst model = getModelForClass(Class, {\n\t\t\t\t\t\texistingConnection: globalConnection,\n\t\t\t\t\t\t...options,\n\t\t\t\t\t});\n\t\t\t\t\tresolve(model);\n\t\t\t\t}\n\t\t\t\tpendingModels.clear();\n\n\t\t\t\t// Initialize any pending discriminator models\n\t\t\t\t// Process discriminators sequentially to ensure dependencies are resolved\n\t\t\t\tfor (const [\n\t\t\t\t\tmodelName,\n\t\t\t\t\t{ baseModelPromise, subClass, discriminatorName, options, resolve },\n\t\t\t\t] of pendingDiscriminatorModels.entries()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// Await the base model to be fully resolved\n\t\t\t\t\t\tconst actualBaseModel = await baseModelPromise;\n\n\t\t\t\t\t\t// Create the discriminator model with the actual base model\n\t\t\t\t\t\tconst model = getDiscriminatorModelForClass(actualBaseModel, subClass, discriminatorName, {\n\t\t\t\t\t\t\texistingConnection: globalConnection,\n\t\t\t\t\t\t\t...options,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tresolve(model);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconsole.error(`Failed to create discriminator model ${modelName}:`, error);\n\t\t\t\t\t\t// Resolve with error to unblock the promise chain\n\t\t\t\t\t\tresolve(Promise.reject(error));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpendingDiscriminatorModels.clear();\n\n\t\t\t\tresolve(connection);\n\t\t\t});\n\t\t});\n\t}\n\treturn connectionPromise;\n}\n\n/**\n * Creates a Typegoose model that will use the global connection when it's ready.\n * Safe to call during module initialization before initGlobalConnection.\n */\nexport function createGlobalModel<T extends AnyParamConstructor<any>>(\n\tClass: T,\n\toptions?: IModelOptions\n): ReturnModelType<T> {\n\tconst modelName = options?.schemaOptions?.collection || Class.name;\n\n\t// If the connection is already initialized, create the model directly\n\tif (globalConnection) {\n\t\treturn getModelForClass(Class, {\n\t\t\texistingConnection: globalConnection,\n\t\t\t...options,\n\t\t});\n\t}\n\n\tconsole.log(`Registering model ${modelName} to be initialized when global connection is ready`);\n\n\t// Create a lazy-loaded model instance that will initialize once the connection is ready\n\tlet actualModel: ReturnModelType<T> | null = null;\n\tlet modelReadyPromise: Promise<ReturnModelType<T>>;\n\n\t// Setup the promise that will resolve once the model is ready\n\tmodelReadyPromise = new Promise<ReturnModelType<T>>(resolve => {\n\t\t// Register this model to be initialized when connection is ready\n\t\tpendingModels.set(modelName, { Class, options, resolve });\n\t});\n\n\t// Create a proxy that forwards operations to the real model once it's available\n\tconst modelProxy = new Proxy({} as ReturnModelType<T>, {\n\t\tget(target, prop, receiver) {\n\t\t\t// Handle special case for 'then' to make the proxy thenable\n\t\t\tif (prop === 'then') {\n\t\t\t\treturn modelReadyPromise.then.bind(modelReadyPromise);\n\t\t\t}\n\n\t\t\t// Handle Symbol properties and other non-string properties\n\t\t\tif (typeof prop === 'symbol' || typeof prop === 'number') {\n\t\t\t\treturn async function (...args: any[]) {\n\t\t\t\t\tif (!actualModel) {\n\t\t\t\t\t\tactualModel = await modelReadyPromise;\n\t\t\t\t\t}\n\t\t\t\t\treturn (actualModel as any)[prop];\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// For method calls, we need to preserve the context and chaining\n\t\t\treturn function (this: any, ...args: any[]) {\n\t\t\t\t// Return a promise that resolves to the method call result\n\t\t\t\treturn (async () => {\n\t\t\t\t\tif (!actualModel) {\n\t\t\t\t\t\tactualModel = await modelReadyPromise;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst propValue = (actualModel as any)[prop];\n\t\t\t\t\tif (typeof propValue === 'function') {\n\t\t\t\t\t\tconst result = propValue.apply(actualModel, args);\n\n\t\t\t\t\t\t// If the result is a Mongoose Query or similar chainable object,\n\t\t\t\t\t\t// we need to wrap it in a proxy to handle further chaining\n\t\t\t\t\t\tif (result && typeof result === 'object' && typeof result.then !== 'function') {\n\t\t\t\t\t\t\t// Check if it's a Mongoose Query-like object (has common query methods)\n\t\t\t\t\t\t\tconst queryMethods = ['sort', 'limit', 'skip', 'populate', 'select', 'lean', 'exec'];\n\t\t\t\t\t\t\tconst isQueryLike = queryMethods.some(method => typeof result[method] === 'function');\n\n\t\t\t\t\t\t\tif (isQueryLike) {\n\t\t\t\t\t\t\t\t// Return the query object directly - no need to proxy it\n\t\t\t\t\t\t\t\treturn result;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t\treturn propValue;\n\t\t\t\t})();\n\t\t\t};\n\t\t},\n\t});\n\n\treturn modelProxy;\n}\n\n/**\n * Creates a Typegoose discriminator model that will use the global connection when it's ready.\n * Safe to call during module initialization before initGlobalConnection.\n */\nexport function createGlobalDiscriminatorModel<\n\tBase extends AnyParamConstructor<any>,\n\tSub extends AnyParamConstructor<any>,\n>(\n\tbaseModel: ReturnModelType<Base>,\n\tsubClass: Sub,\n\tdiscriminatorName?: string,\n\toptions?: IModelOptions\n): ReturnModelType<Sub> {\n\tconst modelName = discriminatorName || subClass.name;\n\n\t// If the connection is already initialized, create the model directly\n\tif (globalConnection) {\n\t\t// Ensure baseModel is fully resolved if it's a promise or proxy\n\t\tif (baseModel instanceof Promise || (baseModel as any).then) {\n\t\t\t// Create a new promise that will resolve with the discriminator model\n\t\t\tconst discriminatorPromise = (async () => {\n\t\t\t\tconst resolvedBaseModel = await baseModel;\n\t\t\t\treturn getDiscriminatorModelForClass(resolvedBaseModel, subClass, discriminatorName, {\n\t\t\t\t\texistingConnection: globalConnection,\n\t\t\t\t\t...options,\n\t\t\t\t});\n\t\t\t})();\n\n\t\t\t// Return a proxy that will await the discriminator model\n\t\t\treturn createProxyForPromise(discriminatorPromise);\n\t\t}\n\n\t\t// If baseModel is not a promise, create the discriminator directly\n\t\treturn getDiscriminatorModelForClass(baseModel, subClass, discriminatorName, {\n\t\t\texistingConnection: globalConnection,\n\t\t\t...options,\n\t\t});\n\t}\n\n\tconsole.log(\n\t\t`Registering discriminator model ${modelName} to be initialized when global connection is ready`\n\t);\n\n\t// Create a lazy-loaded model instance that will initialize once the connection is ready\n\tlet actualModel: ReturnModelType<Sub> | null = null;\n\tlet modelReadyPromise: Promise<ReturnModelType<Sub>>;\n\n\t// Handle the case where baseModel might be a proxy or promise\n\tlet baseModelPromise: Promise<any>;\n\tif (baseModel instanceof Promise || (baseModel as any).then) {\n\t\tbaseModelPromise = Promise.resolve(baseModel);\n\t} else {\n\t\tbaseModelPromise = Promise.resolve(baseModel);\n\t}\n\n\t// Setup the promise that will resolve once the model is ready\n\tmodelReadyPromise = new Promise<ReturnModelType<Sub>>(resolve => {\n\t\t// Register this discriminator model to be initialized when connection is ready\n\t\tpendingDiscriminatorModels.set(modelName, {\n\t\t\tbaseModelPromise,\n\t\t\tsubClass,\n\t\t\tdiscriminatorName,\n\t\t\toptions,\n\t\t\tresolve,\n\t\t});\n\t});\n\n\treturn createProxyForPromise(modelReadyPromise);\n}\n\n/**\n * Helper function to create a proxy for a promise that will resolve to a model\n */\nfunction createProxyForPromise<T extends object>(promise: Promise<T>): T {\n\tlet resolvedValue: T | null = null;\n\n\treturn new Proxy({} as T, {\n\t\tget(target, prop, receiver) {\n\t\t\t// Handle special case for 'then' to make the proxy thenable\n\t\t\tif (prop === 'then') {\n\t\t\t\treturn promise.then.bind(promise);\n\t\t\t}\n\n\t\t\t// Handle Symbol properties and other non-string properties\n\t\t\tif (typeof prop === 'symbol' || typeof prop === 'number') {\n\t\t\t\treturn async function (...args: any[]) {\n\t\t\t\t\tif (!resolvedValue) {\n\t\t\t\t\t\tresolvedValue = await promise;\n\t\t\t\t\t}\n\t\t\t\t\treturn (resolvedValue as any)[prop];\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn function (this: any, ...args: any[]) {\n\t\t\t\treturn (async () => {\n\t\t\t\t\tif (!resolvedValue) {\n\t\t\t\t\t\tresolvedValue = await promise;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst propValue = (resolvedValue as any)[prop];\n\t\t\t\t\tif (typeof propValue === 'function') {\n\t\t\t\t\t\tconst result = propValue.apply(resolvedValue, args);\n\n\t\t\t\t\t\t// If the result is a Mongoose Query or similar chainable object,\n\t\t\t\t\t\t// return it directly to preserve chaining\n\t\t\t\t\t\tif (result && typeof result === 'object' && typeof result.then !== 'function') {\n\t\t\t\t\t\t\tconst queryMethods = ['sort', 'limit', 'skip', 'populate', 'select', 'lean', 'exec'];\n\t\t\t\t\t\t\tconst isQueryLike = queryMethods.some(method => typeof result[method] === 'function');\n\n\t\t\t\t\t\t\tif (isQueryLike) {\n\t\t\t\t\t\t\t\treturn result;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t\treturn propValue;\n\t\t\t\t})();\n\t\t\t};\n\t\t},\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"/","sources":["libraries/mongo/index.ts"],"names":[],"mappings":";;AAcA,oDA2BC;AAKD,sEAEC;AAKD,kDAKC;AA1DD,uCAAkE;AAClE,qEAAqE;AACrE,qCAAgD;AAGhD,IAAA,0CAAqB,GAAE,CAAC;AAGxB,IAAI,gBAAwC,CAAC;AAC7C,IAAI,iBAAiB,GAA+B,IAAI,CAAC;AAKlD,KAAK,UAAU,oBAAoB,CAAC,GAAW,EAAE,WAAmB;IAC1E,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACxB,iBAAiB,GAAG,IAAI,OAAO,CAAa,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE;YACrE,IAAI,CAAC;gBACJ,OAAO,CAAC,GAAG,CAAC,mDAAmD,WAAW,EAAE,CAAC,CAAC;gBAC9E,MAAM,UAAU,GAAG,IAAA,2BAAgB,EAAC,GAAG,EAAE;oBACxC,MAAM,EAAE,QAAQ,WAAW,SAAS;iBACpC,CAAC,CAAC;gBAEH,MAAM,IAAI,OAAO,CAAO,CAAC,cAAc,EAAE,aAAa,EAAE,EAAE;oBACzD,UAAU,CAAC,IAAI,CAAC,WAAW,EAAE,GAAG,EAAE;wBACjC,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC,CAAC;wBAC1D,gBAAgB,GAAG,UAAU,CAAC;wBAC9B,cAAc,EAAE,CAAC;oBAClB,CAAC,CAAC,CAAC;oBACH,UAAU,CAAC,IAAI,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;gBACzC,CAAC,CAAC,CAAC;gBAEH,IAAA,+BAAsB,EAAC,gBAAgB,CAAC,CAAC;gBAEzC,OAAO,CAAC,UAAU,CAAC,CAAC;YACrB,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,MAAM,CAAC,KAAK,CAAC,CAAC;YACf,CAAC;QACF,CAAC,CAAC,CAAC;IACJ,CAAC;IACD,OAAO,iBAAiB,CAAC;AAC1B,CAAC;AAKD,SAAgB,6BAA6B;IAC5C,OAAO,CAAC,CAAC,gBAAgB,CAAC;AAC3B,CAAC;AAKD,SAAgB,mBAAmB;IAClC,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAC;IAC1F,CAAC;IACD,OAAO,gBAAgB,CAAC;AACzB,CAAC","sourcesContent":["import mongoose, { Connection, createConnection } from 'mongoose';\nimport { applySoftDeletePlugin } from './plugins/soft-delete-plugin';\nimport {initializeGlobalModels} from \"./models\";\n\n// Apply the soft delete plugin globally before any connections or models\napplySoftDeletePlugin();\n\n// Track connection status\nlet globalConnection: Connection | undefined;\nlet connectionPromise: Promise<Connection> | null = null;\n\n/**\n * Initialize the global database connection and create all global models\n */\nexport async function initGlobalConnection(uri: string, environment: string): Promise<Connection> {\n\tif (!connectionPromise) {\n\t\tconnectionPromise = new Promise<Connection>(async (resolve, reject) => {\n\t\t\ttry {\n\t\t\t\tconsole.log(`Initializing global connection for environment: ${environment}`);\n\t\t\t\tconst connection = createConnection(uri, {\n\t\t\t\t\tdbName: `lyxa-${environment}-global`,\n\t\t\t\t});\n\n\t\t\t\tawait new Promise<void>((connectResolve, connectReject) => {\n\t\t\t\t\tconnection.once('connected', () => {\n\t\t\t\t\t\tconsole.log('Global connection successfully established');\n\t\t\t\t\t\tglobalConnection = connection;\n\t\t\t\t\t\tconnectResolve();\n\t\t\t\t\t});\n\t\t\t\t\tconnection.once('error', connectReject);\n\t\t\t\t});\n\n\t\t\t\tinitializeGlobalModels(globalConnection);\n\n\t\t\t\tresolve(connection);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t});\n\t}\n\treturn connectionPromise;\n}\n\n/**\n * Check if the global connection is initialized\n */\nexport function isGlobalConnectionInitialized(): boolean {\n\treturn !!globalConnection;\n}\n\n/**\n * Get the global connection (throws if not initialized)\n */\nexport function getGlobalConnection(): Connection {\n\tif (!globalConnection) {\n\t\tthrow new Error('Global connection not initialized. Call initGlobalConnection() first.');\n\t}\n\treturn globalConnection;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"order-finance.model.js","sourceRoot":"/","sources":["libraries/mongo/models/embedded/order-finance.model.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oDAA4C;AAC5C,4EAAqE;AACrE,2EAAiE;AACjE,qDAA2D;AAC3D,iDAA6C;AAC7C,mEAAyD;AAEzD,MAAa,YAAa,SAAQ,2BAAU;IAEpC,YAAY,CAAU;IAGtB,aAAa,CAAiB;
|
|
1
|
+
{"version":3,"file":"order-finance.model.js","sourceRoot":"/","sources":["libraries/mongo/models/embedded/order-finance.model.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oDAA4C;AAC5C,4EAAqE;AACrE,2EAAiE;AACjE,qDAA2D;AAC3D,iDAA6C;AAC7C,mEAAyD;AAEzD,MAAa,YAAa,SAAQ,2BAAU;IAEpC,YAAY,CAAU;IAGtB,aAAa,CAAiB;IAG9B,kBAAkB,CAAsB;IAGxC,WAAW,CAAe;IAG1B,cAAc,CAAkB;CACvC;AAfD,oCAeC;AAbO;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC;;kDACN;AAGtB;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,oBAAa,EAAE,OAAO,EAAE,oBAAa,CAAC,IAAI,EAAE,CAAC;;mDACpC;AAG9B;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,8CAAkB,EAAE,CAAC;8BACb,8CAAkB;wDAAC;AAGxC;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,0BAAW,EAAE,CAAC;8BACb,0BAAW;iDAAC;AAG1B;IADN,IAAA,gBAAI,EAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,sCAAc,EAAE,CAAC;8BACb,sCAAc;oDAAC","sourcesContent":["import { prop } from '@typegoose/typegoose';\nimport { TimeStamps } from '@typegoose/typegoose/lib/defaultClasses';\nimport { PaymentInformation } from './payment-infromation.model';\nimport { PaymentMethod } from '../../../../utilities/enum';\nimport { RiderProfit } from './profit.model';\nimport { CashSettlement } from './cash-settlement.model';\n\nexport class OrderFinance extends TimeStamps {\n\t@prop({ type: Number, default: 1 })\n\tpublic exchangeRate?: number;\n\n\t@prop({ type: String, enum: PaymentMethod, default: PaymentMethod.CASH })\n\tpublic paymentMethod?: PaymentMethod;\n\n\t@prop({ type: () => PaymentInformation })\n\tpublic paymentInformation?: PaymentInformation;\n\n\t@prop({ type: () => RiderProfit })\n\tpublic riderProfit?: RiderProfit;\n\n\t@prop({ type: () => CashSettlement })\n\tpublic cashSettlement?: CashSettlement;\n}\n"]}
|