@monque/tsed 0.1.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -22
- package/dist/CHANGELOG.md +31 -0
- package/dist/README.md +22 -22
- package/dist/index.cjs +105 -91
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +77 -63
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +78 -64
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +101 -88
- package/dist/index.mjs.map +1 -1
- package/package.json +16 -16
- package/src/config/config.ts +4 -2
- package/src/config/types.ts +35 -2
- package/src/constants/constants.ts +1 -1
- package/src/constants/types.ts +3 -3
- package/src/decorators/cron.ts +5 -5
- package/src/decorators/index.ts +5 -5
- package/src/decorators/{worker-controller.ts → job-controller.ts} +14 -14
- package/src/decorators/{worker.ts → job.ts} +14 -14
- package/src/decorators/types.ts +18 -18
- package/src/index.ts +7 -7
- package/src/monque-module.ts +23 -18
- package/src/utils/build-job-name.ts +2 -2
- package/src/utils/collect-job-metadata.ts +95 -0
- package/src/utils/get-job-token.ts +29 -0
- package/src/utils/index.ts +4 -4
- package/src/utils/resolve-database.ts +6 -5
- package/src/utils/collect-worker-metadata.ts +0 -95
- package/src/utils/get-worker-token.ts +0 -27
package/dist/index.mjs
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
|
+
import { ConnectionError, Monque, MonqueError, WorkerRegistrationError } from "@monque/core";
|
|
1
2
|
import { Store, useDecorators } from "@tsed/core";
|
|
2
3
|
import { Configuration, DIContext, Inject, Injectable, InjectorService, LOGGER, Module, ProviderScope, runInContext } from "@tsed/di";
|
|
3
|
-
import { Monque, MonqueError } from "@monque/core";
|
|
4
4
|
import { ObjectId } from "mongodb";
|
|
5
5
|
|
|
6
6
|
//#region src/config/config.ts
|
|
7
7
|
/**
|
|
8
|
+
* @monque/tsed - Configuration
|
|
9
|
+
*
|
|
10
|
+
* Defines the configuration interface and TsED module augmentation.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
8
13
|
* Validate that exactly one database resolution strategy is provided.
|
|
9
14
|
*
|
|
10
15
|
* @param config - The configuration to validate.
|
|
@@ -23,8 +28,8 @@ function validateDatabaseConfig(config) {
|
|
|
23
28
|
config.dbFactory,
|
|
24
29
|
config.dbToken
|
|
25
30
|
].filter(Boolean);
|
|
26
|
-
if (strategies.length === 0) throw new
|
|
27
|
-
if (strategies.length > 1) throw new
|
|
31
|
+
if (strategies.length === 0) throw new MonqueError("MonqueTsedConfig requires exactly one of 'db', 'dbFactory', or 'dbToken' to be set");
|
|
32
|
+
if (strategies.length > 1) throw new MonqueError("MonqueTsedConfig accepts only one of 'db', 'dbFactory', or 'dbToken' - multiple were provided");
|
|
28
33
|
}
|
|
29
34
|
|
|
30
35
|
//#endregion
|
|
@@ -32,7 +37,7 @@ function validateDatabaseConfig(config) {
|
|
|
32
37
|
/**
|
|
33
38
|
* Symbol used to store decorator metadata on class constructors.
|
|
34
39
|
*
|
|
35
|
-
* Used by @
|
|
40
|
+
* Used by @JobController, @Job, and @Cron decorators to attach
|
|
36
41
|
* metadata that is later collected by MonqueModule during initialization.
|
|
37
42
|
*
|
|
38
43
|
* @example
|
|
@@ -49,13 +54,13 @@ const MONQUE = Symbol.for("monque");
|
|
|
49
54
|
*
|
|
50
55
|
* These constants are used to categorize providers registered with Ts.ED's
|
|
51
56
|
* dependency injection container, enabling MonqueModule to discover and
|
|
52
|
-
* register
|
|
57
|
+
* register jobs automatically.
|
|
53
58
|
*
|
|
54
59
|
* Note: Using string constants with `as const` instead of enums per
|
|
55
60
|
* Constitution guidelines.
|
|
56
61
|
*/
|
|
57
62
|
const ProviderTypes = {
|
|
58
|
-
|
|
63
|
+
JOB_CONTROLLER: "monque:job-controller",
|
|
59
64
|
CRON: "monque:cron"
|
|
60
65
|
};
|
|
61
66
|
|
|
@@ -69,8 +74,8 @@ const ProviderTypes = {
|
|
|
69
74
|
*
|
|
70
75
|
* @example
|
|
71
76
|
* ```typescript
|
|
72
|
-
* @
|
|
73
|
-
* class
|
|
77
|
+
* @JobController()
|
|
78
|
+
* class ReportJobs {
|
|
74
79
|
* @Cron("@daily", { timezone: "UTC" })
|
|
75
80
|
* async generateDailyReport() {
|
|
76
81
|
* // ...
|
|
@@ -91,7 +96,7 @@ function Cron(pattern, options) {
|
|
|
91
96
|
const store = Store.from(targetConstructor);
|
|
92
97
|
const existing = store.get(MONQUE) || {
|
|
93
98
|
type: "controller",
|
|
94
|
-
|
|
99
|
+
jobs: [],
|
|
95
100
|
cronJobs: []
|
|
96
101
|
};
|
|
97
102
|
const cronJobs = [...existing.cronJobs || [], cronMetadata];
|
|
@@ -103,21 +108,21 @@ function Cron(pattern, options) {
|
|
|
103
108
|
}
|
|
104
109
|
|
|
105
110
|
//#endregion
|
|
106
|
-
//#region src/decorators/
|
|
111
|
+
//#region src/decorators/job.ts
|
|
107
112
|
/**
|
|
108
|
-
* @
|
|
113
|
+
* @Job method decorator
|
|
109
114
|
*
|
|
110
115
|
* Registers a method as a job handler. The method will be called when a job
|
|
111
116
|
* with the matching name is picked up for processing.
|
|
112
117
|
*
|
|
113
118
|
* @param name - Job name (combined with controller namespace if present).
|
|
114
|
-
* @param options -
|
|
119
|
+
* @param options - Job configuration options.
|
|
115
120
|
*
|
|
116
121
|
* @example
|
|
117
122
|
* ```typescript
|
|
118
|
-
* @
|
|
119
|
-
* export class
|
|
120
|
-
* @
|
|
123
|
+
* @JobController("notifications")
|
|
124
|
+
* export class NotificationJobs {
|
|
125
|
+
* @Job("push", { concurrency: 10 })
|
|
121
126
|
* async sendPush(job: Job<PushPayload>) {
|
|
122
127
|
* await pushService.send(job.data);
|
|
123
128
|
* }
|
|
@@ -128,11 +133,11 @@ function Cron(pattern, options) {
|
|
|
128
133
|
* Method decorator that registers a method as a job handler.
|
|
129
134
|
*
|
|
130
135
|
* @param name - The job name (will be prefixed with controller namespace if present)
|
|
131
|
-
* @param options - Optional
|
|
136
|
+
* @param options - Optional job configuration (concurrency, replace, etc.)
|
|
132
137
|
*/
|
|
133
|
-
function
|
|
138
|
+
function Job(name, options) {
|
|
134
139
|
return (target, propertyKey, _descriptor) => {
|
|
135
|
-
const
|
|
140
|
+
const jobMetadata = {
|
|
136
141
|
name,
|
|
137
142
|
method: String(propertyKey),
|
|
138
143
|
opts: options || {}
|
|
@@ -141,58 +146,58 @@ function Worker(name, options) {
|
|
|
141
146
|
const store = Store.from(targetConstructor);
|
|
142
147
|
const existing = store.get(MONQUE) || {
|
|
143
148
|
type: "controller",
|
|
144
|
-
|
|
149
|
+
jobs: [],
|
|
145
150
|
cronJobs: []
|
|
146
151
|
};
|
|
147
|
-
const
|
|
152
|
+
const jobs = [...existing.jobs || [], jobMetadata];
|
|
148
153
|
store.set(MONQUE, {
|
|
149
154
|
...existing,
|
|
150
|
-
|
|
155
|
+
jobs
|
|
151
156
|
});
|
|
152
157
|
};
|
|
153
158
|
}
|
|
154
159
|
|
|
155
160
|
//#endregion
|
|
156
|
-
//#region src/decorators/
|
|
161
|
+
//#region src/decorators/job-controller.ts
|
|
157
162
|
/**
|
|
158
|
-
* @
|
|
163
|
+
* @JobController class decorator
|
|
159
164
|
*
|
|
160
|
-
* Marks a class as containing
|
|
161
|
-
*
|
|
165
|
+
* Marks a class as containing job methods and registers it with the Ts.ED DI container.
|
|
166
|
+
* Jobs in the class will have their job names prefixed with the namespace.
|
|
162
167
|
*
|
|
163
168
|
* @param namespace - Optional prefix for all job names in this controller.
|
|
164
169
|
* When set, job names become "{namespace}.{name}".
|
|
165
170
|
*
|
|
166
171
|
* @example
|
|
167
172
|
* ```typescript
|
|
168
|
-
* @
|
|
169
|
-
* export class
|
|
170
|
-
* @
|
|
173
|
+
* @JobController("email")
|
|
174
|
+
* export class EmailJobs {
|
|
175
|
+
* @Job("send") // Registered as "email.send"
|
|
171
176
|
* async send(job: Job<EmailPayload>) { }
|
|
172
177
|
* }
|
|
173
178
|
* ```
|
|
174
179
|
*/
|
|
175
180
|
/**
|
|
176
|
-
* Class decorator that registers a class as a
|
|
181
|
+
* Class decorator that registers a class as a job controller.
|
|
177
182
|
*
|
|
178
183
|
* @param namespace - Optional namespace prefix for job names
|
|
179
184
|
*/
|
|
180
|
-
function
|
|
181
|
-
return useDecorators(Injectable({ type: ProviderTypes.
|
|
185
|
+
function JobController(namespace) {
|
|
186
|
+
return useDecorators(Injectable({ type: ProviderTypes.JOB_CONTROLLER }), (target) => {
|
|
182
187
|
const store = Store.from(target);
|
|
183
188
|
const existing = store.get(MONQUE) || {};
|
|
184
|
-
const
|
|
189
|
+
const jobStore = {
|
|
185
190
|
type: "controller",
|
|
186
191
|
...namespace !== void 0 && { namespace },
|
|
187
|
-
|
|
192
|
+
jobs: existing.jobs || [],
|
|
188
193
|
cronJobs: existing.cronJobs || []
|
|
189
194
|
};
|
|
190
|
-
store.set(MONQUE,
|
|
195
|
+
store.set(MONQUE, jobStore);
|
|
191
196
|
});
|
|
192
197
|
}
|
|
193
198
|
|
|
194
199
|
//#endregion
|
|
195
|
-
//#region \0@oxc-project+runtime@0.
|
|
200
|
+
//#region \0@oxc-project+runtime@0.112.0/helpers/decorate.js
|
|
196
201
|
function __decorate(decorators, target, key, desc) {
|
|
197
202
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
198
203
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
@@ -379,8 +384,8 @@ MonqueService = __decorate([Injectable()], MonqueService);
|
|
|
379
384
|
/**
|
|
380
385
|
* Build the full job name by combining namespace and name.
|
|
381
386
|
*
|
|
382
|
-
* @param namespace - Optional namespace from @
|
|
383
|
-
* @param name - Job name from @
|
|
387
|
+
* @param namespace - Optional namespace from @JobController
|
|
388
|
+
* @param name - Job name from @Job or @Cron
|
|
384
389
|
* @returns Full job name (e.g., "email.send" or just "send")
|
|
385
390
|
*
|
|
386
391
|
* @example
|
|
@@ -395,22 +400,22 @@ function buildJobName(namespace, name) {
|
|
|
395
400
|
}
|
|
396
401
|
|
|
397
402
|
//#endregion
|
|
398
|
-
//#region src/utils/collect-
|
|
403
|
+
//#region src/utils/collect-job-metadata.ts
|
|
399
404
|
/**
|
|
400
|
-
* Collect
|
|
405
|
+
* Collect job metadata utility
|
|
401
406
|
*
|
|
402
|
-
* Collects all
|
|
403
|
-
* Used by MonqueModule to discover and register all
|
|
407
|
+
* Collects all job metadata from a class decorated with @JobController.
|
|
408
|
+
* Used by MonqueModule to discover and register all jobs.
|
|
404
409
|
*/
|
|
405
410
|
/**
|
|
406
|
-
* Collect all
|
|
411
|
+
* Collect all job metadata from a class.
|
|
407
412
|
*
|
|
408
|
-
* @param target - The class constructor (decorated with @
|
|
409
|
-
* @returns Array of collected
|
|
413
|
+
* @param target - The class constructor (decorated with @JobController)
|
|
414
|
+
* @returns Array of collected job metadata ready for registration
|
|
410
415
|
*
|
|
411
416
|
* @example
|
|
412
417
|
* ```typescript
|
|
413
|
-
* const metadata =
|
|
418
|
+
* const metadata = collectJobMetadata(EmailJobs);
|
|
414
419
|
* // Returns:
|
|
415
420
|
* // [
|
|
416
421
|
* // { fullName: "email.send", method: "sendEmail", opts: {}, isCron: false },
|
|
@@ -418,18 +423,18 @@ function buildJobName(namespace, name) {
|
|
|
418
423
|
* // ]
|
|
419
424
|
* ```
|
|
420
425
|
*/
|
|
421
|
-
function
|
|
422
|
-
const
|
|
423
|
-
if (!
|
|
426
|
+
function collectJobMetadata(target) {
|
|
427
|
+
const jobStore = Store.from(target).get(MONQUE);
|
|
428
|
+
if (!jobStore) return [];
|
|
424
429
|
const results = [];
|
|
425
|
-
const namespace =
|
|
426
|
-
for (const
|
|
427
|
-
fullName: buildJobName(namespace,
|
|
428
|
-
method:
|
|
429
|
-
opts:
|
|
430
|
+
const namespace = jobStore.namespace;
|
|
431
|
+
for (const job of jobStore.jobs) results.push({
|
|
432
|
+
fullName: buildJobName(namespace, job.name),
|
|
433
|
+
method: job.method,
|
|
434
|
+
opts: job.opts,
|
|
430
435
|
isCron: false
|
|
431
436
|
});
|
|
432
|
-
for (const cron of
|
|
437
|
+
for (const cron of jobStore.cronJobs) results.push({
|
|
433
438
|
fullName: buildJobName(namespace, cron.name),
|
|
434
439
|
method: cron.method,
|
|
435
440
|
opts: cron.opts,
|
|
@@ -440,29 +445,29 @@ function collectWorkerMetadata(target) {
|
|
|
440
445
|
}
|
|
441
446
|
|
|
442
447
|
//#endregion
|
|
443
|
-
//#region src/utils/get-
|
|
448
|
+
//#region src/utils/get-job-token.ts
|
|
444
449
|
/**
|
|
445
|
-
* Generate a unique token for a
|
|
450
|
+
* Generate a unique token for a job controller.
|
|
446
451
|
*
|
|
447
|
-
* Used internally by Ts.ED DI to identify
|
|
452
|
+
* Used internally by Ts.ED DI to identify job controller providers.
|
|
448
453
|
* The token is based on the class name for debugging purposes.
|
|
449
454
|
*
|
|
450
455
|
* @param target - The class constructor
|
|
451
|
-
* @returns A Symbol token unique to this
|
|
456
|
+
* @returns A Symbol token unique to this job controller
|
|
452
457
|
*
|
|
453
458
|
* @example
|
|
454
459
|
* ```typescript
|
|
455
|
-
* @
|
|
456
|
-
* class
|
|
460
|
+
* @JobController("email")
|
|
461
|
+
* class EmailJobs {}
|
|
457
462
|
*
|
|
458
|
-
* const token =
|
|
459
|
-
* // Symbol("monque:
|
|
463
|
+
* const token = getJobToken(EmailJobs);
|
|
464
|
+
* // Symbol("monque:job:EmailJobs")
|
|
460
465
|
* ```
|
|
461
466
|
*/
|
|
462
|
-
function
|
|
467
|
+
function getJobToken(target) {
|
|
463
468
|
const name = target.name?.trim();
|
|
464
|
-
if (!name) throw new
|
|
465
|
-
return Symbol.for(`monque:
|
|
469
|
+
if (!name) throw new MonqueError("Job class must have a non-empty name");
|
|
470
|
+
return Symbol.for(`monque:job:${name}`);
|
|
466
471
|
}
|
|
467
472
|
|
|
468
473
|
//#endregion
|
|
@@ -491,6 +496,11 @@ function isMongooseConnection(value) {
|
|
|
491
496
|
//#endregion
|
|
492
497
|
//#region src/utils/resolve-database.ts
|
|
493
498
|
/**
|
|
499
|
+
* @monque/tsed - Database Resolution Utility
|
|
500
|
+
*
|
|
501
|
+
* Multi-strategy database resolution for flexible MongoDB connection handling.
|
|
502
|
+
*/
|
|
503
|
+
/**
|
|
494
504
|
* Resolve the MongoDB database instance from the configuration.
|
|
495
505
|
*
|
|
496
506
|
* Supports three resolution strategies:
|
|
@@ -527,30 +537,30 @@ async function resolveDatabase(config, injectorFn) {
|
|
|
527
537
|
if (config.db) return config.db;
|
|
528
538
|
if (config.dbFactory) return config.dbFactory();
|
|
529
539
|
if (config.dbToken) {
|
|
530
|
-
if (!injectorFn) throw new
|
|
540
|
+
if (!injectorFn) throw new ConnectionError("MonqueTsedConfig.dbToken requires an injector function to resolve the database");
|
|
531
541
|
const resolved = injectorFn(config.dbToken);
|
|
532
|
-
if (!resolved) throw new
|
|
542
|
+
if (!resolved) throw new ConnectionError(`Could not resolve database from token: ${String(config.dbToken)}. Make sure the provider is registered in the DI container.`);
|
|
533
543
|
if (isMongooseService(resolved)) {
|
|
534
544
|
const connectionId = config.mongooseConnectionId || "default";
|
|
535
545
|
const connection = resolved.get(connectionId);
|
|
536
|
-
if (!connection) throw new
|
|
546
|
+
if (!connection) throw new ConnectionError(`MongooseService resolved from token "${String(config.dbToken)}" returned no connection for ID "${connectionId}". Ensure the connection ID is correct and the connection is established.`);
|
|
537
547
|
if ("db" in connection && connection.db) return connection.db;
|
|
538
548
|
}
|
|
539
549
|
if (isMongooseConnection(resolved)) return resolved.db;
|
|
540
|
-
if (typeof resolved !== "object" || resolved === null || !("collection" in resolved)) throw new
|
|
550
|
+
if (typeof resolved !== "object" || resolved === null || !("collection" in resolved)) throw new ConnectionError(`Resolved value from token "${String(config.dbToken)}" does not appear to be a valid MongoDB Db instance.`);
|
|
541
551
|
return resolved;
|
|
542
552
|
}
|
|
543
|
-
throw new
|
|
553
|
+
throw new ConnectionError("MonqueTsedConfig requires 'db', 'dbFactory', or 'dbToken' to be set");
|
|
544
554
|
}
|
|
545
555
|
|
|
546
556
|
//#endregion
|
|
547
|
-
//#region \0@oxc-project+runtime@0.
|
|
557
|
+
//#region \0@oxc-project+runtime@0.112.0/helpers/decorateMetadata.js
|
|
548
558
|
function __decorateMetadata(k, v) {
|
|
549
559
|
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
550
560
|
}
|
|
551
561
|
|
|
552
562
|
//#endregion
|
|
553
|
-
//#region \0@oxc-project+runtime@0.
|
|
563
|
+
//#region \0@oxc-project+runtime@0.112.0/helpers/decorateParam.js
|
|
554
564
|
function __decorateParam(paramIndex, decorator) {
|
|
555
565
|
return function(target, key) {
|
|
556
566
|
decorator(target, key, paramIndex);
|
|
@@ -563,7 +573,7 @@ function __decorateParam(paramIndex, decorator) {
|
|
|
563
573
|
* MonqueModule - Main Integration Module
|
|
564
574
|
*
|
|
565
575
|
* Orchestrates the integration between Monque and Ts.ED.
|
|
566
|
-
* Handles lifecycle hooks, configuration resolution, and
|
|
576
|
+
* Handles lifecycle hooks, configuration resolution, and job registration.
|
|
567
577
|
*/
|
|
568
578
|
var _ref, _ref2, _ref3, _ref4;
|
|
569
579
|
let MonqueModule = class MonqueModule {
|
|
@@ -592,9 +602,12 @@ let MonqueModule = class MonqueModule {
|
|
|
592
602
|
this.monqueService._setMonque(this.monque);
|
|
593
603
|
this.logger.info("Monque: Connecting to MongoDB...");
|
|
594
604
|
await this.monque.initialize();
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
605
|
+
if (config.disableJobProcessing) this.logger.info("Monque: Job processing is disabled for this instance");
|
|
606
|
+
else {
|
|
607
|
+
await this.registerJobs();
|
|
608
|
+
await this.monque.start();
|
|
609
|
+
this.logger.info("Monque: Started successfully");
|
|
610
|
+
}
|
|
598
611
|
} catch (error) {
|
|
599
612
|
this.logger.error({
|
|
600
613
|
event: "MONQUE_INIT_ERROR",
|
|
@@ -612,25 +625,25 @@ let MonqueModule = class MonqueModule {
|
|
|
612
625
|
}
|
|
613
626
|
}
|
|
614
627
|
/**
|
|
615
|
-
* Discover and register all
|
|
628
|
+
* Discover and register all jobs from @JobController providers
|
|
616
629
|
*/
|
|
617
|
-
async
|
|
618
|
-
if (!this.monque) throw new
|
|
630
|
+
async registerJobs() {
|
|
631
|
+
if (!this.monque) throw new MonqueError("Monque instance not initialized");
|
|
619
632
|
const monque = this.monque;
|
|
620
|
-
const
|
|
633
|
+
const jobControllers = this.injector.getProviders(ProviderTypes.JOB_CONTROLLER);
|
|
621
634
|
const registeredJobs = /* @__PURE__ */ new Set();
|
|
622
|
-
this.logger.info(`Monque: Found ${
|
|
623
|
-
for (const provider of
|
|
635
|
+
this.logger.info(`Monque: Found ${jobControllers.length} job controllers`);
|
|
636
|
+
for (const provider of jobControllers) {
|
|
624
637
|
const useClass = provider.useClass;
|
|
625
|
-
const
|
|
638
|
+
const jobs = collectJobMetadata(useClass);
|
|
626
639
|
const instance = this.injector.get(provider.token);
|
|
627
640
|
if (!instance && provider.scope !== ProviderScope.REQUEST) {
|
|
628
641
|
this.logger.warn(`Monque: Could not resolve instance for controller ${provider.name}. Skipping.`);
|
|
629
642
|
continue;
|
|
630
643
|
}
|
|
631
|
-
for (const
|
|
632
|
-
const { fullName, method, opts, isCron, cronPattern } =
|
|
633
|
-
if (registeredJobs.has(fullName)) throw new
|
|
644
|
+
for (const job of jobs) {
|
|
645
|
+
const { fullName, method, opts, isCron, cronPattern } = job;
|
|
646
|
+
if (registeredJobs.has(fullName)) throw new WorkerRegistrationError(`Monque: Duplicate job registration detected. Job "${fullName}" is already registered.`, fullName);
|
|
634
647
|
registeredJobs.add(fullName);
|
|
635
648
|
const handler = async (job) => {
|
|
636
649
|
const $ctx = new DIContext({
|
|
@@ -664,7 +677,7 @@ let MonqueModule = class MonqueModule {
|
|
|
664
677
|
monque.register(fullName, handler, opts);
|
|
665
678
|
await monque.schedule(cronPattern, fullName, {}, opts);
|
|
666
679
|
} else {
|
|
667
|
-
this.logger.debug(`Monque: Registering
|
|
680
|
+
this.logger.debug(`Monque: Registering job "${fullName}"`);
|
|
668
681
|
monque.register(fullName, handler, opts);
|
|
669
682
|
}
|
|
670
683
|
}
|
|
@@ -687,5 +700,5 @@ MonqueModule = __decorate([
|
|
|
687
700
|
], MonqueModule);
|
|
688
701
|
|
|
689
702
|
//#endregion
|
|
690
|
-
export { Cron, MONQUE, MonqueModule, MonqueService, ProviderTypes,
|
|
703
|
+
export { Cron, Job, JobController, MONQUE, MonqueModule, MonqueService, ProviderTypes, buildJobName, collectJobMetadata, getJobToken, resolveDatabase, validateDatabaseConfig };
|
|
691
704
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/config/config.ts","../src/constants/constants.ts","../src/constants/types.ts","../src/decorators/cron.ts","../src/decorators/worker.ts","../src/decorators/worker-controller.ts","../src/services/monque-service.ts","../src/utils/build-job-name.ts","../src/utils/collect-worker-metadata.ts","../src/utils/get-worker-token.ts","../src/utils/guards.ts","../src/utils/resolve-database.ts","../src/monque-module.ts"],"sourcesContent":["/**\n * @monque/tsed - Configuration\n *\n * Defines the configuration interface and TsED module augmentation.\n */\n\nimport type { MonqueTsedConfig } from './types.js';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// TsED Module Augmentation\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Augment TsED's Configuration interface to include monque settings.\n *\n * This allows type-safe configuration via @Configuration decorator.\n */\ndeclare global {\n\tnamespace TsED {\n\t\tinterface Configuration {\n\t\t\t/**\n\t\t\t * Monque job queue configuration.\n\t\t\t */\n\t\t\tmonque?: MonqueTsedConfig;\n\t\t}\n\t}\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Validation\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Validate that exactly one database resolution strategy is provided.\n *\n * @param config - The configuration to validate.\n * @throws Error if zero or multiple strategies are provided.\n *\n * @example\n * ```typescript\n * validateDatabaseConfig({ db: mongoDb }); // OK\n * validateDatabaseConfig({}); // throws\n * validateDatabaseConfig({ db: mongoDb, dbFactory: fn }); // throws\n * ```\n */\nexport function validateDatabaseConfig(config: MonqueTsedConfig): void {\n\tconst strategies = [config.db, config.dbFactory, config.dbToken].filter(Boolean);\n\n\tif (strategies.length === 0) {\n\t\tthrow new Error(\n\t\t\t\"MonqueTsedConfig requires exactly one of 'db', 'dbFactory', or 'dbToken' to be set\",\n\t\t);\n\t}\n\n\tif (strategies.length > 1) {\n\t\tthrow new Error(\n\t\t\t\"MonqueTsedConfig accepts only one of 'db', 'dbFactory', or 'dbToken' - multiple were provided\",\n\t\t);\n\t}\n}\n","/**\n * Symbol used to store decorator metadata on class constructors.\n *\n * Used by @WorkerController, @Worker, and @Cron decorators to attach\n * metadata that is later collected by MonqueModule during initialization.\n *\n * @example\n * ```typescript\n * Store.from(Class).set(MONQUE, metadata);\n * ```\n */\nexport const MONQUE = Symbol.for('monque');\n","/**\n * Provider type constants for DI scanning.\n *\n * These constants are used to categorize providers registered with Ts.ED's\n * dependency injection container, enabling MonqueModule to discover and\n * register workers automatically.\n *\n * Note: Using string constants with `as const` instead of enums per\n * Constitution guidelines.\n */\nexport const ProviderTypes = {\n\t/** Provider type for @WorkerController decorated classes */\n\tWORKER_CONTROLLER: 'monque:worker-controller',\n\t/** Provider type for cron job handlers */\n\tCRON: 'monque:cron',\n} as const;\n\n/**\n * Union type of all provider type values.\n */\nexport type ProviderType = (typeof ProviderTypes)[keyof typeof ProviderTypes];\n","import { Store } from '@tsed/core';\n\nimport { MONQUE } from '@/constants';\nimport type { CronDecoratorOptions, CronMetadata, WorkerStore } from '@/decorators/types.js';\n\n/**\n * Method decorator that registers a method as a scheduled cron job.\n *\n * @param pattern - Cron expression (e.g., \"* * * * *\", \"@daily\")\n * @param options - Optional cron configuration (name, timezone, etc.)\n *\n * @example\n * ```typescript\n * @WorkerController()\n * class ReportWorkers {\n * @Cron(\"@daily\", { timezone: \"UTC\" })\n * async generateDailyReport() {\n * // ...\n * }\n * }\n * ```\n */\nexport function Cron(pattern: string, options?: CronDecoratorOptions): MethodDecorator {\n\treturn <T>(\n\t\ttarget: object,\n\t\tpropertyKey: string | symbol,\n\t\t_descriptor: TypedPropertyDescriptor<T>,\n\t): void => {\n\t\tconst methodName = String(propertyKey);\n\n\t\tconst cronMetadata: CronMetadata = {\n\t\t\tpattern,\n\t\t\t// Default name to method name if not provided\n\t\t\tname: options?.name || methodName,\n\t\t\tmethod: methodName,\n\t\t\topts: options || {},\n\t\t};\n\n\t\t// Get the class constructor (target is the prototype for instance methods)\n\t\tconst targetConstructor = target.constructor;\n\t\tconst store = Store.from(targetConstructor);\n\n\t\t// Get or initialize the MONQUE store\n\t\tconst existing = store.get<Partial<WorkerStore>>(MONQUE) || {\n\t\t\ttype: 'controller',\n\t\t\tworkers: [],\n\t\t\tcronJobs: [],\n\t\t};\n\n\t\t// Add this cron job to the list\n\t\tconst cronJobs = [...(existing.cronJobs || []), cronMetadata];\n\n\t\tstore.set(MONQUE, {\n\t\t\t...existing,\n\t\t\tcronJobs,\n\t\t});\n\t};\n}\n","/**\n * @Worker method decorator\n *\n * Registers a method as a job handler. The method will be called when a job\n * with the matching name is picked up for processing.\n *\n * @param name - Job name (combined with controller namespace if present).\n * @param options - Worker configuration options.\n *\n * @example\n * ```typescript\n * @WorkerController(\"notifications\")\n * export class NotificationWorkers {\n * @Worker(\"push\", { concurrency: 10 })\n * async sendPush(job: Job<PushPayload>) {\n * await pushService.send(job.data);\n * }\n * }\n * ```\n */\nimport { Store } from '@tsed/core';\n\nimport { MONQUE } from '@/constants';\n\nimport type { WorkerDecoratorOptions, WorkerMetadata, WorkerStore } from './types.js';\n\n/**\n * Method decorator that registers a method as a job handler.\n *\n * @param name - The job name (will be prefixed with controller namespace if present)\n * @param options - Optional worker configuration (concurrency, replace, etc.)\n */\nexport function Worker(name: string, options?: WorkerDecoratorOptions): MethodDecorator {\n\treturn <T>(\n\t\ttarget: object,\n\t\tpropertyKey: string | symbol,\n\t\t_descriptor: TypedPropertyDescriptor<T>,\n\t): void => {\n\t\tconst methodName = String(propertyKey);\n\n\t\tconst workerMetadata: WorkerMetadata = {\n\t\t\tname,\n\t\t\tmethod: methodName,\n\t\t\topts: options || {},\n\t\t};\n\n\t\t// Get the class constructor (target is the prototype for instance methods)\n\t\tconst targetConstructor = target.constructor;\n\t\tconst store = Store.from(targetConstructor);\n\n\t\t// Get or initialize the MONQUE store\n\t\tconst existing = store.get<Partial<WorkerStore>>(MONQUE) || {\n\t\t\ttype: 'controller',\n\t\t\tworkers: [],\n\t\t\tcronJobs: [],\n\t\t};\n\n\t\t// Add this worker to the list\n\t\tconst workers = [...(existing.workers || []), workerMetadata];\n\n\t\tstore.set(MONQUE, {\n\t\t\t...existing,\n\t\t\tworkers,\n\t\t});\n\t};\n}\n","/**\n * @WorkerController class decorator\n *\n * Marks a class as containing worker methods and registers it with the Ts.ED DI container.\n * Workers in the class will have their job names prefixed with the namespace.\n *\n * @param namespace - Optional prefix for all job names in this controller.\n * When set, job names become \"{namespace}.{name}\".\n *\n * @example\n * ```typescript\n * @WorkerController(\"email\")\n * export class EmailWorkers {\n * @Worker(\"send\") // Registered as \"email.send\"\n * async send(job: Job<EmailPayload>) { }\n * }\n * ```\n */\nimport { Store, useDecorators } from '@tsed/core';\nimport { Injectable } from '@tsed/di';\n\nimport { MONQUE, ProviderTypes } from '@/constants';\n\nimport type { WorkerStore } from './types.js';\n\n/**\n * Class decorator that registers a class as a worker controller.\n *\n * @param namespace - Optional namespace prefix for job names\n */\nexport function WorkerController(namespace?: string): ClassDecorator {\n\treturn useDecorators(\n\t\t// Register as injectable with custom provider type\n\t\tInjectable({\n\t\t\ttype: ProviderTypes.WORKER_CONTROLLER,\n\t\t}),\n\t\t// Apply custom decorator to store metadata\n\t\t(target: object) => {\n\t\t\tconst store = Store.from(target);\n\n\t\t\t// Get existing store or create new one\n\t\t\tconst existing = store.get<Partial<WorkerStore>>(MONQUE) || {};\n\n\t\t\t// Merge with new metadata, only include namespace if defined\n\t\t\tconst workerStore: WorkerStore = {\n\t\t\t\ttype: 'controller',\n\t\t\t\t...(namespace !== undefined && { namespace }),\n\t\t\t\tworkers: existing.workers || [],\n\t\t\t\tcronJobs: existing.cronJobs || [],\n\t\t\t};\n\n\t\t\tstore.set(MONQUE, workerStore);\n\t\t},\n\t);\n}\n","/**\n * MonqueService - Injectable wrapper for Monque\n *\n * Provides a DI-friendly interface to the Monque job queue.\n * All methods delegate to the underlying Monque instance.\n *\n * @example\n * ```typescript\n * @Service()\n * export class OrderService {\n * @Inject()\n * private monque: MonqueService;\n *\n * async createOrder(data: CreateOrderDto) {\n * const order = await this.save(data);\n * await this.monque.enqueue(\"order.process\", { orderId: order.id });\n * return order;\n * }\n * }\n * ```\n */\n\nimport type {\n\tBulkOperationResult,\n\tCursorOptions,\n\tCursorPage,\n\tEnqueueOptions,\n\tGetJobsFilter,\n\tJobSelector,\n\tMonque,\n\tPersistedJob,\n\tQueueStats,\n\tScheduleOptions,\n} from '@monque/core';\nimport { MonqueError } from '@monque/core';\nimport { Injectable } from '@tsed/di';\nimport { ObjectId } from 'mongodb';\n\n/**\n * Injectable service that wraps the Monque instance.\n *\n * Exposes the full Monque public API through dependency injection.\n */\n@Injectable()\nexport class MonqueService {\n\t/**\n\t * Internal Monque instance (set by MonqueModule)\n\t * @internal\n\t */\n\tprivate _monque: Monque | null = null;\n\n\t/**\n\t * Set the internal Monque instance.\n\t * Called by MonqueModule during initialization.\n\t * @internal\n\t */\n\t_setMonque(monque: Monque): void {\n\t\tthis._monque = monque;\n\t}\n\n\t/**\n\t * Access the underlying Monque instance.\n\t * @throws Error if MonqueModule is not initialized\n\t */\n\tget monque(): Monque {\n\t\tif (!this._monque) {\n\t\t\tthrow new MonqueError(\n\t\t\t\t'MonqueService is not initialized. Ensure MonqueModule is imported and enabled.',\n\t\t\t);\n\t\t}\n\n\t\treturn this._monque;\n\t}\n\n\t// ─────────────────────────────────────────────────────────────────────────────\n\t// Job Scheduling\n\t// ─────────────────────────────────────────────────────────────────────────────\n\n\t/**\n\t * Enqueue a job for processing.\n\t *\n\t * @param name - Job type identifier (use full namespaced name, e.g., \"email.send\")\n\t * @param data - Job payload\n\t * @param options - Scheduling and deduplication options\n\t * @returns The created or existing job document\n\t */\n\tasync enqueue<T>(name: string, data: T, options?: EnqueueOptions): Promise<PersistedJob<T>> {\n\t\treturn this.monque.enqueue(name, data, options);\n\t}\n\n\t/**\n\t * Enqueue a job for immediate processing.\n\t *\n\t * @param name - Job type identifier\n\t * @param data - Job payload\n\t * @returns The created job document\n\t */\n\tasync now<T>(name: string, data: T): Promise<PersistedJob<T>> {\n\t\treturn this.monque.now(name, data);\n\t}\n\n\t/**\n\t * Schedule a recurring job with a cron expression.\n\t *\n\t * @param cron - Cron expression (5-field standard or predefined like @daily)\n\t * @param name - Job type identifier\n\t * @param data - Job payload\n\t * @param options - Scheduling options\n\t * @returns The created job document\n\t */\n\tasync schedule<T>(\n\t\tcron: string,\n\t\tname: string,\n\t\tdata: T,\n\t\toptions?: ScheduleOptions,\n\t): Promise<PersistedJob<T>> {\n\t\treturn this.monque.schedule(cron, name, data, options);\n\t}\n\n\t// ─────────────────────────────────────────────────────────────────────────────\n\t// Job Management (Single Job Operations)\n\t// ─────────────────────────────────────────────────────────────────────────────\n\n\t/**\n\t * Cancel a pending or scheduled job.\n\t *\n\t * @param jobId - The ID of the job to cancel\n\t * @returns The cancelled job, or null if not found\n\t */\n\tasync cancelJob(jobId: string): Promise<PersistedJob<unknown> | null> {\n\t\treturn this.monque.cancelJob(jobId);\n\t}\n\n\t/**\n\t * Retry a failed or cancelled job.\n\t *\n\t * @param jobId - The ID of the job to retry\n\t * @returns The updated job, or null if not found\n\t */\n\tasync retryJob(jobId: string): Promise<PersistedJob<unknown> | null> {\n\t\treturn this.monque.retryJob(jobId);\n\t}\n\n\t/**\n\t * Reschedule a pending job to run at a different time.\n\t *\n\t * @param jobId - The ID of the job to reschedule\n\t * @param runAt - The new Date when the job should run\n\t * @returns The updated job, or null if not found\n\t */\n\tasync rescheduleJob(jobId: string, runAt: Date): Promise<PersistedJob<unknown> | null> {\n\t\treturn this.monque.rescheduleJob(jobId, runAt);\n\t}\n\n\t/**\n\t * Permanently delete a job.\n\t *\n\t * @param jobId - The ID of the job to delete\n\t * @returns true if deleted, false if job not found\n\t */\n\tasync deleteJob(jobId: string): Promise<boolean> {\n\t\treturn this.monque.deleteJob(jobId);\n\t}\n\n\t// ─────────────────────────────────────────────────────────────────────────────\n\t// Job Management (Bulk Operations)\n\t// ─────────────────────────────────────────────────────────────────────────────\n\n\t/**\n\t * Cancel multiple jobs matching the given filter.\n\t *\n\t * @param filter - Selector for which jobs to cancel\n\t * @returns Result with count of cancelled jobs\n\t */\n\tasync cancelJobs(filter: JobSelector): Promise<BulkOperationResult> {\n\t\treturn this.monque.cancelJobs(filter);\n\t}\n\n\t/**\n\t * Retry multiple jobs matching the given filter.\n\t *\n\t * @param filter - Selector for which jobs to retry\n\t * @returns Result with count of retried jobs\n\t */\n\tasync retryJobs(filter: JobSelector): Promise<BulkOperationResult> {\n\t\treturn this.monque.retryJobs(filter);\n\t}\n\n\t/**\n\t * Delete multiple jobs matching the given filter.\n\t *\n\t * @param filter - Selector for which jobs to delete\n\t * @returns Result with count of deleted jobs\n\t */\n\tasync deleteJobs(filter: JobSelector): Promise<BulkOperationResult> {\n\t\treturn this.monque.deleteJobs(filter);\n\t}\n\n\t// ─────────────────────────────────────────────────────────────────────────────\n\t// Job Queries\n\t// ─────────────────────────────────────────────────────────────────────────────\n\n\t/**\n\t * Get a job by its ID.\n\t *\n\t * @param jobId - The job's ObjectId (as string or ObjectId)\n\t * @returns The job document, or null if not found\n\t * @throws MonqueError if jobId is an invalid hex string\n\t */\n\tasync getJob<T>(jobId: string | ObjectId): Promise<PersistedJob<T> | null> {\n\t\tlet id: ObjectId;\n\n\t\tif (typeof jobId === 'string') {\n\t\t\tif (!ObjectId.isValid(jobId)) {\n\t\t\t\tthrow new MonqueError(`Invalid job ID format: ${jobId}`);\n\t\t\t}\n\t\t\tid = ObjectId.createFromHexString(jobId);\n\t\t} else {\n\t\t\tid = jobId;\n\t\t}\n\n\t\treturn this.monque.getJob(id);\n\t}\n\n\t/**\n\t * Query jobs from the queue with optional filters.\n\t *\n\t * @param filter - Optional filter criteria (name, status, limit, skip)\n\t * @returns Array of matching jobs\n\t */\n\tasync getJobs<T>(filter?: GetJobsFilter): Promise<PersistedJob<T>[]> {\n\t\treturn this.monque.getJobs(filter);\n\t}\n\n\t/**\n\t * Get a paginated list of jobs using opaque cursors.\n\t *\n\t * @param options - Pagination options (cursor, limit, direction, filter)\n\t * @returns Page of jobs with next/prev cursors\n\t */\n\tasync getJobsWithCursor<T>(options?: CursorOptions): Promise<CursorPage<T>> {\n\t\treturn this.monque.getJobsWithCursor(options);\n\t}\n\n\t/**\n\t * Get aggregate statistics for the job queue.\n\t *\n\t * @param filter - Optional filter to scope statistics by job name\n\t * @returns Queue statistics\n\t */\n\tasync getQueueStats(filter?: Pick<JobSelector, 'name'>): Promise<QueueStats> {\n\t\treturn this.monque.getQueueStats(filter);\n\t}\n\n\t// ─────────────────────────────────────────────────────────────────────────────\n\t// Health Check\n\t// ─────────────────────────────────────────────────────────────────────────────\n\n\t/**\n\t * Check if the scheduler is healthy and running.\n\t *\n\t * @returns true if running and connected\n\t */\n\tisHealthy(): boolean {\n\t\treturn this.monque.isHealthy();\n\t}\n}\n","/**\n * Build the full job name by combining namespace and name.\n *\n * @param namespace - Optional namespace from @WorkerController\n * @param name - Job name from @Worker or @Cron\n * @returns Full job name (e.g., \"email.send\" or just \"send\")\n *\n * @example\n * ```typescript\n * buildJobName(\"email\", \"send\"); // \"email.send\"\n * buildJobName(undefined, \"send\"); // \"send\"\n * buildJobName(\"\", \"send\"); // \"send\"\n * ```\n */\nexport function buildJobName(namespace: string | undefined, name: string): string {\n\treturn namespace ? `${namespace}.${name}` : name;\n}\n","/**\n * Collect worker metadata utility\n *\n * Collects all worker metadata from a class decorated with @WorkerController.\n * Used by MonqueModule to discover and register all workers.\n */\nimport { Store } from '@tsed/core';\n\nimport { MONQUE } from '@/constants';\nimport type { CronDecoratorOptions, WorkerDecoratorOptions, WorkerStore } from '@/decorators';\n\nimport { buildJobName } from './build-job-name.js';\n\n/**\n * Collected worker registration info ready for Monque.register()\n */\nexport interface CollectedWorkerMetadata {\n\t/**\n\t * Full job name (with namespace prefix if applicable)\n\t */\n\tfullName: string;\n\n\t/**\n\t * Method name on the controller class\n\t */\n\tmethod: string;\n\n\t/**\n\t * Worker options to pass to Monque.register()\n\t */\n\topts: WorkerDecoratorOptions | CronDecoratorOptions;\n\n\t/**\n\t * Whether this is a cron job\n\t */\n\tisCron: boolean;\n\n\t/**\n\t * Cron pattern (only for cron jobs)\n\t */\n\tcronPattern?: string;\n}\n\n/**\n * Collect all worker metadata from a class.\n *\n * @param target - The class constructor (decorated with @WorkerController)\n * @returns Array of collected worker metadata ready for registration\n *\n * @example\n * ```typescript\n * const metadata = collectWorkerMetadata(EmailWorkers);\n * // Returns:\n * // [\n * // { fullName: \"email.send\", method: \"sendEmail\", opts: {}, isCron: false },\n * // { fullName: \"email.daily-digest\", method: \"sendDailyDigest\", opts: {}, isCron: true, cronPattern: \"0 9 * * *\" }\n * // ]\n * ```\n */\nexport function collectWorkerMetadata(\n\ttarget: new (...args: unknown[]) => unknown,\n): CollectedWorkerMetadata[] {\n\tconst store = Store.from(target);\n\tconst workerStore = store.get<WorkerStore>(MONQUE);\n\n\tif (!workerStore) {\n\t\treturn [];\n\t}\n\n\tconst results: CollectedWorkerMetadata[] = [];\n\tconst namespace = workerStore.namespace;\n\n\t// Collect regular workers\n\tfor (const worker of workerStore.workers) {\n\t\tresults.push({\n\t\t\tfullName: buildJobName(namespace, worker.name),\n\t\t\tmethod: worker.method,\n\t\t\topts: worker.opts,\n\t\t\tisCron: false,\n\t\t});\n\t}\n\n\t// Collect cron jobs\n\tfor (const cron of workerStore.cronJobs) {\n\t\tresults.push({\n\t\t\tfullName: buildJobName(namespace, cron.name),\n\t\t\tmethod: cron.method,\n\t\t\topts: cron.opts,\n\t\t\tisCron: true,\n\t\t\tcronPattern: cron.pattern,\n\t\t});\n\t}\n\n\treturn results;\n}\n","/**\n * Generate a unique token for a worker controller.\n *\n * Used internally by Ts.ED DI to identify worker controller providers.\n * The token is based on the class name for debugging purposes.\n *\n * @param target - The class constructor\n * @returns A Symbol token unique to this worker controller\n *\n * @example\n * ```typescript\n * @WorkerController(\"email\")\n * class EmailWorkers {}\n *\n * const token = getWorkerToken(EmailWorkers);\n * // Symbol(\"monque:worker:EmailWorkers\")\n * ```\n */\nexport function getWorkerToken(target: new (...args: unknown[]) => unknown): symbol {\n\tconst name = target.name?.trim();\n\n\tif (!name) {\n\t\tthrow new Error('Worker class must have a non-empty name');\n\t}\n\n\treturn Symbol.for(`monque:worker:${name}`);\n}\n","/**\n * @monque/tsed - Type Guards\n *\n * Utilities for duck-typing Mongoose and MongoDB related objects\n * to avoid hard dependencies on @tsed/mongoose.\n */\n\nimport type { Db } from 'mongodb';\n\n/**\n * Interface representing a Mongoose Connection object.\n * We only care that it has a `db` property which is a MongoDB Db instance.\n */\nexport interface MongooseConnection {\n\tdb: Db;\n}\n\n/**\n * Interface representing the @tsed/mongoose MongooseService.\n * It acts as a registry/factory for connections.\n */\nexport interface MongooseService {\n\t/**\n\t * Get a connection by its ID (configuration key).\n\t * @param id The connection ID (default: \"default\")\n\t */\n\tget(id?: string): MongooseConnection | undefined;\n}\n\n/**\n * Type guard to check if an object acts like a Mongoose Service.\n *\n * Checks if the object has a `get` method.\n *\n * @param value The value to check\n */\nexport function isMongooseService(value: unknown): value is MongooseService {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'get' in value &&\n\t\ttypeof (value as MongooseService).get === 'function'\n\t);\n}\n\n/**\n * Type guard to check if an object acts like a Mongoose Connection.\n *\n * Checks if the object has a `db` property.\n *\n * @param value The value to check\n */\nexport function isMongooseConnection(value: unknown): value is MongooseConnection {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'db' in value &&\n\t\ttypeof (value as MongooseConnection).db === 'object' &&\n\t\t(value as MongooseConnection).db !== null &&\n\t\ttypeof (value as MongooseConnection).db.collection === 'function'\n\t);\n}\n","/**\n * @monque/tsed - Database Resolution Utility\n *\n * Multi-strategy database resolution for flexible MongoDB connection handling.\n */\n\nimport type { TokenProvider } from '@tsed/di';\nimport type { Db } from 'mongodb';\n\nimport type { MonqueTsedConfig } from '@/config';\n\nimport { isMongooseConnection, isMongooseService } from './guards.js';\n\n/**\n * Type for the injector function used to resolve DI tokens.\n */\nexport type InjectorFn = <T>(token: TokenProvider<T>) => T | undefined;\n\n/**\n * Resolve the MongoDB database instance from the configuration.\n *\n * Supports three resolution strategies:\n * 1. **Direct `db`**: Returns the provided Db instance directly\n * 2. **Factory `dbFactory`**: Calls the factory function (supports async)\n * 3. **DI Token `dbToken`**: Resolves the Db from the DI container\n *\n * @param config - The Monque configuration containing database settings\n * @param injectorFn - Optional function to resolve DI tokens (required for dbToken strategy)\n * @returns The resolved MongoDB Db instance\n * @throws Error if no database strategy is provided or if DI resolution fails\n *\n * @example\n * ```typescript\n * // Direct Db instance\n * const db = await resolveDatabase({ db: mongoDb });\n *\n * // Factory function\n * const db = await resolveDatabase({\n * dbFactory: async () => {\n * const client = await MongoClient.connect(uri);\n * return client.db(\"myapp\");\n * }\n * });\n *\n * // DI token\n * const db = await resolveDatabase(\n * { dbToken: \"MONGODB_DATABASE\" },\n * (token) => injector.get(token)\n * );\n * ```\n */\nexport async function resolveDatabase(\n\tconfig: MonqueTsedConfig,\n\tinjectorFn?: InjectorFn,\n): Promise<Db> {\n\t// Strategy 1: Direct Db instance\n\tif (config.db) {\n\t\treturn config.db;\n\t}\n\n\t// Strategy 2: Factory function (sync or async)\n\tif (config.dbFactory) {\n\t\treturn config.dbFactory();\n\t}\n\n\t// Strategy 3: DI token resolution\n\tif (config.dbToken) {\n\t\tif (!injectorFn) {\n\t\t\tthrow new Error(\n\t\t\t\t'MonqueTsedConfig.dbToken requires an injector function to resolve the database',\n\t\t\t);\n\t\t}\n\n\t\tconst resolved = injectorFn(config.dbToken);\n\n\t\tif (!resolved) {\n\t\t\tthrow new Error(\n\t\t\t\t`Could not resolve database from token: ${String(config.dbToken)}. ` +\n\t\t\t\t\t'Make sure the provider is registered in the DI container.',\n\t\t\t);\n\t\t}\n\n\t\tif (isMongooseService(resolved)) {\n\t\t\t// Check for Mongoose Service (duck typing)\n\t\t\t// It has a get() method that returns a connection\n\t\t\tconst connectionId = config.mongooseConnectionId || 'default';\n\t\t\tconst connection = resolved.get(connectionId);\n\n\t\t\tif (!connection) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`MongooseService resolved from token \"${String(config.dbToken)}\" returned no connection for ID \"${connectionId}\". ` +\n\t\t\t\t\t\t'Ensure the connection ID is correct and the connection is established.',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif ('db' in connection && connection.db) {\n\t\t\t\treturn connection.db as Db;\n\t\t\t}\n\t\t}\n\n\t\tif (isMongooseConnection(resolved)) {\n\t\t\t// Check for Mongoose Connection (duck typing)\n\t\t\t// It has a db property that is the native Db instance\n\t\t\treturn resolved.db as Db;\n\t\t}\n\n\t\t// Default: Assume it is a native Db instance\n\t\tif (typeof resolved !== 'object' || resolved === null || !('collection' in resolved)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Resolved value from token \"${String(config.dbToken)}\" does not appear to be a valid MongoDB Db instance.`,\n\t\t\t);\n\t\t}\n\n\t\treturn resolved as Db;\n\t}\n\n\t// No strategy provided\n\tthrow new Error(\"MonqueTsedConfig requires 'db', 'dbFactory', or 'dbToken' to be set\");\n}\n","/**\n * MonqueModule - Main Integration Module\n *\n * Orchestrates the integration between Monque and Ts.ED.\n * Handles lifecycle hooks, configuration resolution, and worker registration.\n */\n\nimport {\n\ttype Job,\n\tMonque,\n\ttype MonqueOptions,\n\ttype ScheduleOptions,\n\ttype WorkerOptions,\n} from '@monque/core';\nimport {\n\tConfiguration,\n\tDIContext,\n\tInject,\n\tInjectorService,\n\tLOGGER,\n\tModule,\n\ttype OnDestroy,\n\ttype OnInit,\n\tProviderScope,\n\trunInContext,\n\ttype TokenProvider,\n} from '@tsed/di';\n\nimport { type MonqueTsedConfig, validateDatabaseConfig } from '@/config';\nimport { ProviderTypes } from '@/constants';\nimport { MonqueService } from '@/services';\nimport { collectWorkerMetadata, resolveDatabase } from '@/utils';\n\n@Module({\n\timports: [MonqueService],\n})\nexport class MonqueModule implements OnInit, OnDestroy {\n\tprotected injector: InjectorService;\n\tprotected monqueService: MonqueService;\n\tprotected logger: LOGGER;\n\tprotected monqueConfig: MonqueTsedConfig;\n\n\tprotected monque: Monque | null = null;\n\n\tconstructor(\n\t\t@Inject(InjectorService) injector: InjectorService,\n\t\t@Inject(MonqueService) monqueService: MonqueService,\n\t\t@Inject(LOGGER) logger: LOGGER,\n\t\t@Inject(Configuration) configuration: Configuration,\n\t) {\n\t\tthis.injector = injector;\n\t\tthis.monqueService = monqueService;\n\t\tthis.logger = logger;\n\t\tthis.monqueConfig = configuration.get<MonqueTsedConfig>('monque') || {};\n\t}\n\n\tasync $onInit(): Promise<void> {\n\t\tconst config = this.monqueConfig;\n\n\t\tif (config?.enabled === false) {\n\t\t\tthis.logger.info('Monque integration is disabled');\n\n\t\t\treturn;\n\t\t}\n\n\t\tvalidateDatabaseConfig(config);\n\n\t\ttry {\n\t\t\tconst db = await resolveDatabase(config, (token) =>\n\t\t\t\tthis.injector.get(token as TokenProvider),\n\t\t\t);\n\n\t\t\t// We construct the options object carefully to match MonqueOptions\n\t\t\tconst { db: _db, ...restConfig } = config;\n\t\t\tconst options: MonqueOptions = restConfig;\n\n\t\t\tthis.monque = new Monque(db, options);\n\t\t\tthis.monqueService._setMonque(this.monque);\n\n\t\t\tthis.logger.info('Monque: Connecting to MongoDB...');\n\t\t\tawait this.monque.initialize();\n\n\t\t\tawait this.registerWorkers();\n\n\t\t\tawait this.monque.start();\n\n\t\t\tthis.logger.info('Monque: Started successfully');\n\t\t} catch (error) {\n\t\t\tthis.logger.error({\n\t\t\t\tevent: 'MONQUE_INIT_ERROR',\n\t\t\t\tmessage: 'Failed to initialize Monque',\n\t\t\t\terror,\n\t\t\t});\n\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync $onDestroy(): Promise<void> {\n\t\tif (this.monque) {\n\t\t\tthis.logger.info('Monque: Stopping...');\n\n\t\t\tawait this.monque.stop();\n\n\t\t\tthis.logger.info('Monque: Stopped');\n\t\t}\n\t}\n\n\t/**\n\t * Discover and register all workers from @WorkerController providers\n\t */\n\tprotected async registerWorkers(): Promise<void> {\n\t\tif (!this.monque) {\n\t\t\tthrow new Error('Monque instance not initialized');\n\t\t}\n\n\t\tconst monque = this.monque;\n\t\tconst workerControllers = this.injector.getProviders(ProviderTypes.WORKER_CONTROLLER);\n\t\tconst registeredJobs = new Set<string>();\n\n\t\tthis.logger.info(`Monque: Found ${workerControllers.length} worker controllers`);\n\n\t\tfor (const provider of workerControllers) {\n\t\t\tconst useClass = provider.useClass;\n\t\t\tconst workers = collectWorkerMetadata(useClass);\n\t\t\t// Try to resolve singleton instance immediately\n\t\t\tconst instance = this.injector.get(provider.token);\n\n\t\t\tif (!instance && provider.scope !== ProviderScope.REQUEST) {\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t`Monque: Could not resolve instance for controller ${provider.name}. Skipping.`,\n\t\t\t\t);\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (const worker of workers) {\n\t\t\t\tconst { fullName, method, opts, isCron, cronPattern } = worker;\n\n\t\t\t\tif (registeredJobs.has(fullName)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Monque: Duplicate job registration detected. Job \"${fullName}\" is already registered.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tregisteredJobs.add(fullName);\n\n\t\t\t\tconst handler = async (job: Job) => {\n\t\t\t\t\tconst $ctx = new DIContext({\n\t\t\t\t\t\tinjector: this.injector,\n\t\t\t\t\t\tid: job._id?.toString() || 'unknown',\n\t\t\t\t\t});\n\t\t\t\t\t$ctx.set('MONQUE_JOB', job);\n\t\t\t\t\t$ctx.container.set(DIContext, $ctx);\n\n\t\t\t\t\tawait runInContext($ctx, async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tlet targetInstance = instance;\n\t\t\t\t\t\t\tif (provider.scope === ProviderScope.REQUEST || !targetInstance) {\n\t\t\t\t\t\t\t\ttargetInstance = await this.injector.invoke(provider.token, {\n\t\t\t\t\t\t\t\t\tlocals: $ctx.container,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst typedInstance = targetInstance as Record<string, (job: Job) => unknown>;\n\n\t\t\t\t\t\t\tif (typedInstance && typeof typedInstance[method] === 'function') {\n\t\t\t\t\t\t\t\tawait typedInstance[method](job);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tthis.logger.error({\n\t\t\t\t\t\t\t\tevent: 'MONQUE_JOB_ERROR',\n\t\t\t\t\t\t\t\tjobName: fullName,\n\t\t\t\t\t\t\t\tjobId: job._id,\n\t\t\t\t\t\t\t\tmessage: `Error processing job ${fullName}`,\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tawait $ctx.destroy();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t};\n\n\t\t\t\tif (isCron && cronPattern) {\n\t\t\t\t\tthis.logger.debug(`Monque: Registering cron job \"${fullName}\" (${cronPattern})`);\n\n\t\t\t\t\tmonque.register(fullName, handler, opts as WorkerOptions);\n\t\t\t\t\tawait monque.schedule(cronPattern, fullName, {}, opts as ScheduleOptions);\n\t\t\t\t} else {\n\t\t\t\t\tthis.logger.debug(`Monque: Registering worker \"${fullName}\"`);\n\t\t\t\t\tmonque.register(fullName, handler, opts as WorkerOptions);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.logger.info(`Monque: Registered ${registeredJobs.size} jobs`);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,uBAAuB,QAAgC;CACtE,MAAM,aAAa;EAAC,OAAO;EAAI,OAAO;EAAW,OAAO;EAAQ,CAAC,OAAO,QAAQ;AAEhF,KAAI,WAAW,WAAW,EACzB,OAAM,IAAI,MACT,qFACA;AAGF,KAAI,WAAW,SAAS,EACvB,OAAM,IAAI,MACT,gGACA;;;;;;;;;;;;;;;;AC9CH,MAAa,SAAS,OAAO,IAAI,SAAS;;;;;;;;;;;;;;ACD1C,MAAa,gBAAgB;CAE5B,mBAAmB;CAEnB,MAAM;CACN;;;;;;;;;;;;;;;;;;;;;ACOD,SAAgB,KAAK,SAAiB,SAAiD;AACtF,SACC,QACA,aACA,gBACU;EACV,MAAM,aAAa,OAAO,YAAY;EAEtC,MAAM,eAA6B;GAClC;GAEA,MAAM,SAAS,QAAQ;GACvB,QAAQ;GACR,MAAM,WAAW,EAAE;GACnB;EAGD,MAAM,oBAAoB,OAAO;EACjC,MAAM,QAAQ,MAAM,KAAK,kBAAkB;EAG3C,MAAM,WAAW,MAAM,IAA0B,OAAO,IAAI;GAC3D,MAAM;GACN,SAAS,EAAE;GACX,UAAU,EAAE;GACZ;EAGD,MAAM,WAAW,CAAC,GAAI,SAAS,YAAY,EAAE,EAAG,aAAa;AAE7D,QAAM,IAAI,QAAQ;GACjB,GAAG;GACH;GACA,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACvBJ,SAAgB,OAAO,MAAc,SAAmD;AACvF,SACC,QACA,aACA,gBACU;EAGV,MAAM,iBAAiC;GACtC;GACA,QAJkB,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,MAAM,KAAK,SAAS,OAAO,SAAS,OAAO,EAC3D,QAAQ,KAAK,WACb,CAAC;OAGH,MAAM,gBAAgB;AAEtB,WAAI,iBAAiB,OAAO,cAAc,YAAY,WACrD,OAAM,cAAc,QAAQ,IAAI;eAEzB,OAAO;AACf,YAAK,OAAO,MAAM;QACjB,OAAO;QACP,SAAS;QACT,OAAO,IAAI;QACX,SAAS,wBAAwB;QACjC;QACA,CAAC;AACF,aAAM;gBACG;AACT,aAAM,KAAK,SAAS;;OAEpB;;AAGH,QAAI,UAAU,aAAa;AAC1B,UAAK,OAAO,MAAM,iCAAiC,SAAS,KAAK,YAAY,GAAG;AAEhF,YAAO,SAAS,UAAU,SAAS,KAAsB;AACzD,WAAM,OAAO,SAAS,aAAa,UAAU,EAAE,EAAE,KAAwB;WACnE;AACN,UAAK,OAAO,MAAM,+BAA+B,SAAS,GAAG;AAC7D,YAAO,SAAS,UAAU,SAAS,KAAsB;;;;AAK5D,OAAK,OAAO,KAAK,sBAAsB,eAAe,KAAK,OAAO;;;;CAnKnE,OAAO,EACP,SAAS,CAAC,cAAc,EACxB,CAAC;oBAUC,OAAO,gBAAgB;oBACvB,OAAO,cAAc;oBACrB,OAAO,OAAO;oBACd,OAAO,cAAc"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/config/config.ts","../src/constants/constants.ts","../src/constants/types.ts","../src/decorators/cron.ts","../src/decorators/job.ts","../src/decorators/job-controller.ts","../src/services/monque-service.ts","../src/utils/build-job-name.ts","../src/utils/collect-job-metadata.ts","../src/utils/get-job-token.ts","../src/utils/guards.ts","../src/utils/resolve-database.ts","../src/monque-module.ts"],"sourcesContent":["/**\n * @monque/tsed - Configuration\n *\n * Defines the configuration interface and TsED module augmentation.\n */\n\nimport { MonqueError } from '@monque/core';\n\nimport type { MonqueTsedConfig } from './types.js';\n\n// ─────────────────────────────────────────────────────────────────────────────\n// TsED Module Augmentation\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Augment TsED's Configuration interface to include monque settings.\n *\n * This allows type-safe configuration via @Configuration decorator.\n */\ndeclare global {\n\tnamespace TsED {\n\t\tinterface Configuration {\n\t\t\t/**\n\t\t\t * Monque job queue configuration.\n\t\t\t */\n\t\t\tmonque?: MonqueTsedConfig;\n\t\t}\n\t}\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Validation\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Validate that exactly one database resolution strategy is provided.\n *\n * @param config - The configuration to validate.\n * @throws Error if zero or multiple strategies are provided.\n *\n * @example\n * ```typescript\n * validateDatabaseConfig({ db: mongoDb }); // OK\n * validateDatabaseConfig({}); // throws\n * validateDatabaseConfig({ db: mongoDb, dbFactory: fn }); // throws\n * ```\n */\nexport function validateDatabaseConfig(config: MonqueTsedConfig): void {\n\tconst strategies = [config.db, config.dbFactory, config.dbToken].filter(Boolean);\n\n\tif (strategies.length === 0) {\n\t\tthrow new MonqueError(\n\t\t\t\"MonqueTsedConfig requires exactly one of 'db', 'dbFactory', or 'dbToken' to be set\",\n\t\t);\n\t}\n\n\tif (strategies.length > 1) {\n\t\tthrow new MonqueError(\n\t\t\t\"MonqueTsedConfig accepts only one of 'db', 'dbFactory', or 'dbToken' - multiple were provided\",\n\t\t);\n\t}\n}\n","/**\n * Symbol used to store decorator metadata on class constructors.\n *\n * Used by @JobController, @Job, and @Cron decorators to attach\n * metadata that is later collected by MonqueModule during initialization.\n *\n * @example\n * ```typescript\n * Store.from(Class).set(MONQUE, metadata);\n * ```\n */\nexport const MONQUE = Symbol.for('monque');\n","/**\n * Provider type constants for DI scanning.\n *\n * These constants are used to categorize providers registered with Ts.ED's\n * dependency injection container, enabling MonqueModule to discover and\n * register jobs automatically.\n *\n * Note: Using string constants with `as const` instead of enums per\n * Constitution guidelines.\n */\nexport const ProviderTypes = {\n\t/** Provider type for @JobController decorated classes */\n\tJOB_CONTROLLER: 'monque:job-controller',\n\t/** Provider type for cron job handlers */\n\tCRON: 'monque:cron',\n} as const;\n\n/**\n * Union type of all provider type values.\n */\nexport type ProviderType = (typeof ProviderTypes)[keyof typeof ProviderTypes];\n","import { Store } from '@tsed/core';\n\nimport { MONQUE } from '@/constants';\nimport type { CronDecoratorOptions, CronMetadata, JobStore } from '@/decorators/types.js';\n\n/**\n * Method decorator that registers a method as a scheduled cron job.\n *\n * @param pattern - Cron expression (e.g., \"* * * * *\", \"@daily\")\n * @param options - Optional cron configuration (name, timezone, etc.)\n *\n * @example\n * ```typescript\n * @JobController()\n * class ReportJobs {\n * @Cron(\"@daily\", { timezone: \"UTC\" })\n * async generateDailyReport() {\n * // ...\n * }\n * }\n * ```\n */\nexport function Cron(pattern: string, options?: CronDecoratorOptions): MethodDecorator {\n\treturn <T>(\n\t\ttarget: object,\n\t\tpropertyKey: string | symbol,\n\t\t_descriptor: TypedPropertyDescriptor<T>,\n\t): void => {\n\t\tconst methodName = String(propertyKey);\n\n\t\tconst cronMetadata: CronMetadata = {\n\t\t\tpattern,\n\t\t\t// Default name to method name if not provided\n\t\t\tname: options?.name || methodName,\n\t\t\tmethod: methodName,\n\t\t\topts: options || {},\n\t\t};\n\n\t\t// Get the class constructor (target is the prototype for instance methods)\n\t\tconst targetConstructor = target.constructor;\n\t\tconst store = Store.from(targetConstructor);\n\n\t\t// Get or initialize the MONQUE store\n\t\tconst existing = store.get<Partial<JobStore>>(MONQUE) || {\n\t\t\ttype: 'controller',\n\t\t\tjobs: [],\n\t\t\tcronJobs: [],\n\t\t};\n\n\t\t// Add this cron job to the list\n\t\tconst cronJobs = [...(existing.cronJobs || []), cronMetadata];\n\n\t\tstore.set(MONQUE, {\n\t\t\t...existing,\n\t\t\tcronJobs,\n\t\t});\n\t};\n}\n","/**\n * @Job method decorator\n *\n * Registers a method as a job handler. The method will be called when a job\n * with the matching name is picked up for processing.\n *\n * @param name - Job name (combined with controller namespace if present).\n * @param options - Job configuration options.\n *\n * @example\n * ```typescript\n * @JobController(\"notifications\")\n * export class NotificationJobs {\n * @Job(\"push\", { concurrency: 10 })\n * async sendPush(job: Job<PushPayload>) {\n * await pushService.send(job.data);\n * }\n * }\n * ```\n */\nimport { Store } from '@tsed/core';\n\nimport { MONQUE } from '@/constants';\n\nimport type { JobDecoratorOptions, JobMetadata, JobStore } from './types.js';\n\n/**\n * Method decorator that registers a method as a job handler.\n *\n * @param name - The job name (will be prefixed with controller namespace if present)\n * @param options - Optional job configuration (concurrency, replace, etc.)\n */\nexport function Job(name: string, options?: JobDecoratorOptions): MethodDecorator {\n\treturn <T>(\n\t\ttarget: object,\n\t\tpropertyKey: string | symbol,\n\t\t_descriptor: TypedPropertyDescriptor<T>,\n\t): void => {\n\t\tconst methodName = String(propertyKey);\n\n\t\tconst jobMetadata: JobMetadata = {\n\t\t\tname,\n\t\t\tmethod: methodName,\n\t\t\topts: options || {},\n\t\t};\n\n\t\t// Get the class constructor (target is the prototype for instance methods)\n\t\tconst targetConstructor = target.constructor;\n\t\tconst store = Store.from(targetConstructor);\n\n\t\t// Get or initialize the MONQUE store\n\t\tconst existing = store.get<Partial<JobStore>>(MONQUE) || {\n\t\t\ttype: 'controller',\n\t\t\tjobs: [],\n\t\t\tcronJobs: [],\n\t\t};\n\n\t\t// Add this job to the list\n\t\tconst jobs = [...(existing.jobs || []), jobMetadata];\n\n\t\tstore.set(MONQUE, {\n\t\t\t...existing,\n\t\t\tjobs,\n\t\t});\n\t};\n}\n","/**\n * @JobController class decorator\n *\n * Marks a class as containing job methods and registers it with the Ts.ED DI container.\n * Jobs in the class will have their job names prefixed with the namespace.\n *\n * @param namespace - Optional prefix for all job names in this controller.\n * When set, job names become \"{namespace}.{name}\".\n *\n * @example\n * ```typescript\n * @JobController(\"email\")\n * export class EmailJobs {\n * @Job(\"send\") // Registered as \"email.send\"\n * async send(job: Job<EmailPayload>) { }\n * }\n * ```\n */\nimport { Store, useDecorators } from '@tsed/core';\nimport { Injectable } from '@tsed/di';\n\nimport { MONQUE, ProviderTypes } from '@/constants';\n\nimport type { JobStore } from './types.js';\n\n/**\n * Class decorator that registers a class as a job controller.\n *\n * @param namespace - Optional namespace prefix for job names\n */\nexport function JobController(namespace?: string): ClassDecorator {\n\treturn useDecorators(\n\t\t// Register as injectable with custom provider type\n\t\tInjectable({\n\t\t\ttype: ProviderTypes.JOB_CONTROLLER,\n\t\t}),\n\t\t// Apply custom decorator to store metadata\n\t\t(target: object) => {\n\t\t\tconst store = Store.from(target);\n\n\t\t\t// Get existing store or create new one\n\t\t\tconst existing = store.get<Partial<JobStore>>(MONQUE) || {};\n\n\t\t\t// Merge with new metadata, only include namespace if defined\n\t\t\tconst jobStore: JobStore = {\n\t\t\t\ttype: 'controller',\n\t\t\t\t...(namespace !== undefined && { namespace }),\n\t\t\t\tjobs: existing.jobs || [],\n\t\t\t\tcronJobs: existing.cronJobs || [],\n\t\t\t};\n\n\t\t\tstore.set(MONQUE, jobStore);\n\t\t},\n\t);\n}\n","/**\n * MonqueService - Injectable wrapper for Monque\n *\n * Provides a DI-friendly interface to the Monque job queue.\n * All methods delegate to the underlying Monque instance.\n *\n * @example\n * ```typescript\n * @Service()\n * export class OrderService {\n * @Inject()\n * private monque: MonqueService;\n *\n * async createOrder(data: CreateOrderDto) {\n * const order = await this.save(data);\n * await this.monque.enqueue(\"order.process\", { orderId: order.id });\n * return order;\n * }\n * }\n * ```\n */\n\nimport type {\n\tBulkOperationResult,\n\tCursorOptions,\n\tCursorPage,\n\tEnqueueOptions,\n\tGetJobsFilter,\n\tJobSelector,\n\tMonque,\n\tPersistedJob,\n\tQueueStats,\n\tScheduleOptions,\n} from '@monque/core';\nimport { MonqueError } from '@monque/core';\nimport { Injectable } from '@tsed/di';\nimport { ObjectId } from 'mongodb';\n\n/**\n * Injectable service that wraps the Monque instance.\n *\n * Exposes the full Monque public API through dependency injection.\n */\n@Injectable()\nexport class MonqueService {\n\t/**\n\t * Internal Monque instance (set by MonqueModule)\n\t * @internal\n\t */\n\tprivate _monque: Monque | null = null;\n\n\t/**\n\t * Set the internal Monque instance.\n\t * Called by MonqueModule during initialization.\n\t * @internal\n\t */\n\t_setMonque(monque: Monque): void {\n\t\tthis._monque = monque;\n\t}\n\n\t/**\n\t * Access the underlying Monque instance.\n\t * @throws Error if MonqueModule is not initialized\n\t */\n\tget monque(): Monque {\n\t\tif (!this._monque) {\n\t\t\tthrow new MonqueError(\n\t\t\t\t'MonqueService is not initialized. Ensure MonqueModule is imported and enabled.',\n\t\t\t);\n\t\t}\n\n\t\treturn this._monque;\n\t}\n\n\t// ─────────────────────────────────────────────────────────────────────────────\n\t// Job Scheduling\n\t// ─────────────────────────────────────────────────────────────────────────────\n\n\t/**\n\t * Enqueue a job for processing.\n\t *\n\t * @param name - Job type identifier (use full namespaced name, e.g., \"email.send\")\n\t * @param data - Job payload\n\t * @param options - Scheduling and deduplication options\n\t * @returns The created or existing job document\n\t */\n\tasync enqueue<T>(name: string, data: T, options?: EnqueueOptions): Promise<PersistedJob<T>> {\n\t\treturn this.monque.enqueue(name, data, options);\n\t}\n\n\t/**\n\t * Enqueue a job for immediate processing.\n\t *\n\t * @param name - Job type identifier\n\t * @param data - Job payload\n\t * @returns The created job document\n\t */\n\tasync now<T>(name: string, data: T): Promise<PersistedJob<T>> {\n\t\treturn this.monque.now(name, data);\n\t}\n\n\t/**\n\t * Schedule a recurring job with a cron expression.\n\t *\n\t * @param cron - Cron expression (5-field standard or predefined like @daily)\n\t * @param name - Job type identifier\n\t * @param data - Job payload\n\t * @param options - Scheduling options\n\t * @returns The created job document\n\t */\n\tasync schedule<T>(\n\t\tcron: string,\n\t\tname: string,\n\t\tdata: T,\n\t\toptions?: ScheduleOptions,\n\t): Promise<PersistedJob<T>> {\n\t\treturn this.monque.schedule(cron, name, data, options);\n\t}\n\n\t// ─────────────────────────────────────────────────────────────────────────────\n\t// Job Management (Single Job Operations)\n\t// ─────────────────────────────────────────────────────────────────────────────\n\n\t/**\n\t * Cancel a pending or scheduled job.\n\t *\n\t * @param jobId - The ID of the job to cancel\n\t * @returns The cancelled job, or null if not found\n\t */\n\tasync cancelJob(jobId: string): Promise<PersistedJob<unknown> | null> {\n\t\treturn this.monque.cancelJob(jobId);\n\t}\n\n\t/**\n\t * Retry a failed or cancelled job.\n\t *\n\t * @param jobId - The ID of the job to retry\n\t * @returns The updated job, or null if not found\n\t */\n\tasync retryJob(jobId: string): Promise<PersistedJob<unknown> | null> {\n\t\treturn this.monque.retryJob(jobId);\n\t}\n\n\t/**\n\t * Reschedule a pending job to run at a different time.\n\t *\n\t * @param jobId - The ID of the job to reschedule\n\t * @param runAt - The new Date when the job should run\n\t * @returns The updated job, or null if not found\n\t */\n\tasync rescheduleJob(jobId: string, runAt: Date): Promise<PersistedJob<unknown> | null> {\n\t\treturn this.monque.rescheduleJob(jobId, runAt);\n\t}\n\n\t/**\n\t * Permanently delete a job.\n\t *\n\t * @param jobId - The ID of the job to delete\n\t * @returns true if deleted, false if job not found\n\t */\n\tasync deleteJob(jobId: string): Promise<boolean> {\n\t\treturn this.monque.deleteJob(jobId);\n\t}\n\n\t// ─────────────────────────────────────────────────────────────────────────────\n\t// Job Management (Bulk Operations)\n\t// ─────────────────────────────────────────────────────────────────────────────\n\n\t/**\n\t * Cancel multiple jobs matching the given filter.\n\t *\n\t * @param filter - Selector for which jobs to cancel\n\t * @returns Result with count of cancelled jobs\n\t */\n\tasync cancelJobs(filter: JobSelector): Promise<BulkOperationResult> {\n\t\treturn this.monque.cancelJobs(filter);\n\t}\n\n\t/**\n\t * Retry multiple jobs matching the given filter.\n\t *\n\t * @param filter - Selector for which jobs to retry\n\t * @returns Result with count of retried jobs\n\t */\n\tasync retryJobs(filter: JobSelector): Promise<BulkOperationResult> {\n\t\treturn this.monque.retryJobs(filter);\n\t}\n\n\t/**\n\t * Delete multiple jobs matching the given filter.\n\t *\n\t * @param filter - Selector for which jobs to delete\n\t * @returns Result with count of deleted jobs\n\t */\n\tasync deleteJobs(filter: JobSelector): Promise<BulkOperationResult> {\n\t\treturn this.monque.deleteJobs(filter);\n\t}\n\n\t// ─────────────────────────────────────────────────────────────────────────────\n\t// Job Queries\n\t// ─────────────────────────────────────────────────────────────────────────────\n\n\t/**\n\t * Get a job by its ID.\n\t *\n\t * @param jobId - The job's ObjectId (as string or ObjectId)\n\t * @returns The job document, or null if not found\n\t * @throws MonqueError if jobId is an invalid hex string\n\t */\n\tasync getJob<T>(jobId: string | ObjectId): Promise<PersistedJob<T> | null> {\n\t\tlet id: ObjectId;\n\n\t\tif (typeof jobId === 'string') {\n\t\t\tif (!ObjectId.isValid(jobId)) {\n\t\t\t\tthrow new MonqueError(`Invalid job ID format: ${jobId}`);\n\t\t\t}\n\t\t\tid = ObjectId.createFromHexString(jobId);\n\t\t} else {\n\t\t\tid = jobId;\n\t\t}\n\n\t\treturn this.monque.getJob(id);\n\t}\n\n\t/**\n\t * Query jobs from the queue with optional filters.\n\t *\n\t * @param filter - Optional filter criteria (name, status, limit, skip)\n\t * @returns Array of matching jobs\n\t */\n\tasync getJobs<T>(filter?: GetJobsFilter): Promise<PersistedJob<T>[]> {\n\t\treturn this.monque.getJobs(filter);\n\t}\n\n\t/**\n\t * Get a paginated list of jobs using opaque cursors.\n\t *\n\t * @param options - Pagination options (cursor, limit, direction, filter)\n\t * @returns Page of jobs with next/prev cursors\n\t */\n\tasync getJobsWithCursor<T>(options?: CursorOptions): Promise<CursorPage<T>> {\n\t\treturn this.monque.getJobsWithCursor(options);\n\t}\n\n\t/**\n\t * Get aggregate statistics for the job queue.\n\t *\n\t * @param filter - Optional filter to scope statistics by job name\n\t * @returns Queue statistics\n\t */\n\tasync getQueueStats(filter?: Pick<JobSelector, 'name'>): Promise<QueueStats> {\n\t\treturn this.monque.getQueueStats(filter);\n\t}\n\n\t// ─────────────────────────────────────────────────────────────────────────────\n\t// Health Check\n\t// ─────────────────────────────────────────────────────────────────────────────\n\n\t/**\n\t * Check if the scheduler is healthy and running.\n\t *\n\t * @returns true if running and connected\n\t */\n\tisHealthy(): boolean {\n\t\treturn this.monque.isHealthy();\n\t}\n}\n","/**\n * Build the full job name by combining namespace and name.\n *\n * @param namespace - Optional namespace from @JobController\n * @param name - Job name from @Job or @Cron\n * @returns Full job name (e.g., \"email.send\" or just \"send\")\n *\n * @example\n * ```typescript\n * buildJobName(\"email\", \"send\"); // \"email.send\"\n * buildJobName(undefined, \"send\"); // \"send\"\n * buildJobName(\"\", \"send\"); // \"send\"\n * ```\n */\nexport function buildJobName(namespace: string | undefined, name: string): string {\n\treturn namespace ? `${namespace}.${name}` : name;\n}\n","/**\n * Collect job metadata utility\n *\n * Collects all job metadata from a class decorated with @JobController.\n * Used by MonqueModule to discover and register all jobs.\n */\nimport { Store } from '@tsed/core';\n\nimport { MONQUE } from '@/constants';\nimport type { CronDecoratorOptions, JobDecoratorOptions, JobStore } from '@/decorators';\n\nimport { buildJobName } from './build-job-name.js';\n\n/**\n * Collected job registration info ready for Monque.register()\n */\nexport interface CollectedJobMetadata {\n\t/**\n\t * Full job name (with namespace prefix if applicable)\n\t */\n\tfullName: string;\n\n\t/**\n\t * Method name on the controller class\n\t */\n\tmethod: string;\n\n\t/**\n\t * Job options to pass to Monque.register()\n\t */\n\topts: JobDecoratorOptions | CronDecoratorOptions;\n\n\t/**\n\t * Whether this is a cron job\n\t */\n\tisCron: boolean;\n\n\t/**\n\t * Cron pattern (only for cron jobs)\n\t */\n\tcronPattern?: string;\n}\n\n/**\n * Collect all job metadata from a class.\n *\n * @param target - The class constructor (decorated with @JobController)\n * @returns Array of collected job metadata ready for registration\n *\n * @example\n * ```typescript\n * const metadata = collectJobMetadata(EmailJobs);\n * // Returns:\n * // [\n * // { fullName: \"email.send\", method: \"sendEmail\", opts: {}, isCron: false },\n * // { fullName: \"email.daily-digest\", method: \"sendDailyDigest\", opts: {}, isCron: true, cronPattern: \"0 9 * * *\" }\n * // ]\n * ```\n */\nexport function collectJobMetadata(\n\ttarget: new (...args: unknown[]) => unknown,\n): CollectedJobMetadata[] {\n\tconst store = Store.from(target);\n\tconst jobStore = store.get<JobStore>(MONQUE);\n\n\tif (!jobStore) {\n\t\treturn [];\n\t}\n\n\tconst results: CollectedJobMetadata[] = [];\n\tconst namespace = jobStore.namespace;\n\n\t// Collect regular jobs\n\tfor (const job of jobStore.jobs) {\n\t\tresults.push({\n\t\t\tfullName: buildJobName(namespace, job.name),\n\t\t\tmethod: job.method,\n\t\t\topts: job.opts,\n\t\t\tisCron: false,\n\t\t});\n\t}\n\n\t// Collect cron jobs\n\tfor (const cron of jobStore.cronJobs) {\n\t\tresults.push({\n\t\t\tfullName: buildJobName(namespace, cron.name),\n\t\t\tmethod: cron.method,\n\t\t\topts: cron.opts,\n\t\t\tisCron: true,\n\t\t\tcronPattern: cron.pattern,\n\t\t});\n\t}\n\n\treturn results;\n}\n","/**\n * Generate a unique token for a job controller.\n *\n * Used internally by Ts.ED DI to identify job controller providers.\n * The token is based on the class name for debugging purposes.\n *\n * @param target - The class constructor\n * @returns A Symbol token unique to this job controller\n *\n * @example\n * ```typescript\n * @JobController(\"email\")\n * class EmailJobs {}\n *\n * const token = getJobToken(EmailJobs);\n * // Symbol(\"monque:job:EmailJobs\")\n * ```\n */\nimport { MonqueError } from '@monque/core';\n\nexport function getJobToken(target: new (...args: unknown[]) => unknown): symbol {\n\tconst name = target.name?.trim();\n\n\tif (!name) {\n\t\tthrow new MonqueError('Job class must have a non-empty name');\n\t}\n\n\treturn Symbol.for(`monque:job:${name}`);\n}\n","/**\n * @monque/tsed - Type Guards\n *\n * Utilities for duck-typing Mongoose and MongoDB related objects\n * to avoid hard dependencies on @tsed/mongoose.\n */\n\nimport type { Db } from 'mongodb';\n\n/**\n * Interface representing a Mongoose Connection object.\n * We only care that it has a `db` property which is a MongoDB Db instance.\n */\nexport interface MongooseConnection {\n\tdb: Db;\n}\n\n/**\n * Interface representing the @tsed/mongoose MongooseService.\n * It acts as a registry/factory for connections.\n */\nexport interface MongooseService {\n\t/**\n\t * Get a connection by its ID (configuration key).\n\t * @param id The connection ID (default: \"default\")\n\t */\n\tget(id?: string): MongooseConnection | undefined;\n}\n\n/**\n * Type guard to check if an object acts like a Mongoose Service.\n *\n * Checks if the object has a `get` method.\n *\n * @param value The value to check\n */\nexport function isMongooseService(value: unknown): value is MongooseService {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'get' in value &&\n\t\ttypeof (value as MongooseService).get === 'function'\n\t);\n}\n\n/**\n * Type guard to check if an object acts like a Mongoose Connection.\n *\n * Checks if the object has a `db` property.\n *\n * @param value The value to check\n */\nexport function isMongooseConnection(value: unknown): value is MongooseConnection {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'db' in value &&\n\t\ttypeof (value as MongooseConnection).db === 'object' &&\n\t\t(value as MongooseConnection).db !== null &&\n\t\ttypeof (value as MongooseConnection).db.collection === 'function'\n\t);\n}\n","/**\n * @monque/tsed - Database Resolution Utility\n *\n * Multi-strategy database resolution for flexible MongoDB connection handling.\n */\n\nimport { ConnectionError } from '@monque/core';\nimport type { TokenProvider } from '@tsed/di';\nimport type { Db } from 'mongodb';\n\nimport type { MonqueTsedConfig } from '@/config';\n\nimport { isMongooseConnection, isMongooseService } from './guards.js';\n\n/**\n * Type for the injector function used to resolve DI tokens.\n */\nexport type InjectorFn = <T>(token: TokenProvider<T>) => T | undefined;\n\n/**\n * Resolve the MongoDB database instance from the configuration.\n *\n * Supports three resolution strategies:\n * 1. **Direct `db`**: Returns the provided Db instance directly\n * 2. **Factory `dbFactory`**: Calls the factory function (supports async)\n * 3. **DI Token `dbToken`**: Resolves the Db from the DI container\n *\n * @param config - The Monque configuration containing database settings\n * @param injectorFn - Optional function to resolve DI tokens (required for dbToken strategy)\n * @returns The resolved MongoDB Db instance\n * @throws Error if no database strategy is provided or if DI resolution fails\n *\n * @example\n * ```typescript\n * // Direct Db instance\n * const db = await resolveDatabase({ db: mongoDb });\n *\n * // Factory function\n * const db = await resolveDatabase({\n * dbFactory: async () => {\n * const client = await MongoClient.connect(uri);\n * return client.db(\"myapp\");\n * }\n * });\n *\n * // DI token\n * const db = await resolveDatabase(\n * { dbToken: \"MONGODB_DATABASE\" },\n * (token) => injector.get(token)\n * );\n * ```\n */\nexport async function resolveDatabase(\n\tconfig: MonqueTsedConfig,\n\tinjectorFn?: InjectorFn,\n): Promise<Db> {\n\t// Strategy 1: Direct Db instance\n\tif (config.db) {\n\t\treturn config.db;\n\t}\n\n\t// Strategy 2: Factory function (sync or async)\n\tif (config.dbFactory) {\n\t\treturn config.dbFactory();\n\t}\n\n\t// Strategy 3: DI token resolution\n\tif (config.dbToken) {\n\t\tif (!injectorFn) {\n\t\t\tthrow new ConnectionError(\n\t\t\t\t'MonqueTsedConfig.dbToken requires an injector function to resolve the database',\n\t\t\t);\n\t\t}\n\n\t\tconst resolved = injectorFn(config.dbToken);\n\n\t\tif (!resolved) {\n\t\t\tthrow new ConnectionError(\n\t\t\t\t`Could not resolve database from token: ${String(config.dbToken)}. ` +\n\t\t\t\t\t'Make sure the provider is registered in the DI container.',\n\t\t\t);\n\t\t}\n\n\t\tif (isMongooseService(resolved)) {\n\t\t\t// Check for Mongoose Service (duck typing)\n\t\t\t// It has a get() method that returns a connection\n\t\t\tconst connectionId = config.mongooseConnectionId || 'default';\n\t\t\tconst connection = resolved.get(connectionId);\n\n\t\t\tif (!connection) {\n\t\t\t\tthrow new ConnectionError(\n\t\t\t\t\t`MongooseService resolved from token \"${String(config.dbToken)}\" returned no connection for ID \"${connectionId}\". ` +\n\t\t\t\t\t\t'Ensure the connection ID is correct and the connection is established.',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif ('db' in connection && connection.db) {\n\t\t\t\treturn connection.db as Db;\n\t\t\t}\n\t\t}\n\n\t\tif (isMongooseConnection(resolved)) {\n\t\t\t// Check for Mongoose Connection (duck typing)\n\t\t\t// It has a db property that is the native Db instance\n\t\t\treturn resolved.db as Db;\n\t\t}\n\n\t\t// Default: Assume it is a native Db instance\n\t\tif (typeof resolved !== 'object' || resolved === null || !('collection' in resolved)) {\n\t\t\tthrow new ConnectionError(\n\t\t\t\t`Resolved value from token \"${String(config.dbToken)}\" does not appear to be a valid MongoDB Db instance.`,\n\t\t\t);\n\t\t}\n\n\t\treturn resolved as Db;\n\t}\n\n\t// No strategy provided\n\tthrow new ConnectionError(\"MonqueTsedConfig requires 'db', 'dbFactory', or 'dbToken' to be set\");\n}\n","/**\n * MonqueModule - Main Integration Module\n *\n * Orchestrates the integration between Monque and Ts.ED.\n * Handles lifecycle hooks, configuration resolution, and job registration.\n */\n\nimport {\n\ttype Job,\n\tMonque,\n\tMonqueError,\n\ttype MonqueOptions,\n\ttype ScheduleOptions,\n\ttype WorkerOptions,\n\tWorkerRegistrationError,\n} from '@monque/core';\nimport {\n\tConfiguration,\n\tDIContext,\n\tInject,\n\tInjectorService,\n\tLOGGER,\n\tModule,\n\ttype OnDestroy,\n\ttype OnInit,\n\tProviderScope,\n\trunInContext,\n\ttype TokenProvider,\n} from '@tsed/di';\n\nimport { type MonqueTsedConfig, validateDatabaseConfig } from '@/config';\nimport { ProviderTypes } from '@/constants';\nimport { MonqueService } from '@/services';\nimport { collectJobMetadata, resolveDatabase } from '@/utils';\n\n@Module({\n\timports: [MonqueService],\n})\nexport class MonqueModule implements OnInit, OnDestroy {\n\tprotected injector: InjectorService;\n\tprotected monqueService: MonqueService;\n\tprotected logger: LOGGER;\n\tprotected monqueConfig: MonqueTsedConfig;\n\n\tprotected monque: Monque | null = null;\n\n\tconstructor(\n\t\t@Inject(InjectorService) injector: InjectorService,\n\t\t@Inject(MonqueService) monqueService: MonqueService,\n\t\t@Inject(LOGGER) logger: LOGGER,\n\t\t@Inject(Configuration) configuration: Configuration,\n\t) {\n\t\tthis.injector = injector;\n\t\tthis.monqueService = monqueService;\n\t\tthis.logger = logger;\n\t\tthis.monqueConfig = configuration.get<MonqueTsedConfig>('monque') || {};\n\t}\n\n\tasync $onInit(): Promise<void> {\n\t\tconst config = this.monqueConfig;\n\n\t\tif (config?.enabled === false) {\n\t\t\tthis.logger.info('Monque integration is disabled');\n\n\t\t\treturn;\n\t\t}\n\n\t\tvalidateDatabaseConfig(config);\n\n\t\ttry {\n\t\t\tconst db = await resolveDatabase(config, (token) =>\n\t\t\t\tthis.injector.get(token as TokenProvider),\n\t\t\t);\n\n\t\t\t// We construct the options object carefully to match MonqueOptions\n\t\t\tconst { db: _db, ...restConfig } = config;\n\t\t\tconst options: MonqueOptions = restConfig;\n\n\t\t\tthis.monque = new Monque(db, options);\n\t\t\tthis.monqueService._setMonque(this.monque);\n\n\t\t\tthis.logger.info('Monque: Connecting to MongoDB...');\n\t\t\tawait this.monque.initialize();\n\n\t\t\tif (config.disableJobProcessing) {\n\t\t\t\tthis.logger.info('Monque: Job processing is disabled for this instance');\n\t\t\t} else {\n\t\t\t\tawait this.registerJobs();\n\t\t\t\tawait this.monque.start();\n\t\t\t\tthis.logger.info('Monque: Started successfully');\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.logger.error({\n\t\t\t\tevent: 'MONQUE_INIT_ERROR',\n\t\t\t\tmessage: 'Failed to initialize Monque',\n\t\t\t\terror,\n\t\t\t});\n\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync $onDestroy(): Promise<void> {\n\t\tif (this.monque) {\n\t\t\tthis.logger.info('Monque: Stopping...');\n\n\t\t\tawait this.monque.stop();\n\n\t\t\tthis.logger.info('Monque: Stopped');\n\t\t}\n\t}\n\n\t/**\n\t * Discover and register all jobs from @JobController providers\n\t */\n\tprotected async registerJobs(): Promise<void> {\n\t\tif (!this.monque) {\n\t\t\tthrow new MonqueError('Monque instance not initialized');\n\t\t}\n\n\t\tconst monque = this.monque;\n\t\tconst jobControllers = this.injector.getProviders(ProviderTypes.JOB_CONTROLLER);\n\t\tconst registeredJobs = new Set<string>();\n\n\t\tthis.logger.info(`Monque: Found ${jobControllers.length} job controllers`);\n\n\t\tfor (const provider of jobControllers) {\n\t\t\tconst useClass = provider.useClass;\n\t\t\tconst jobs = collectJobMetadata(useClass);\n\t\t\t// Try to resolve singleton instance immediately\n\t\t\tconst instance = this.injector.get(provider.token);\n\n\t\t\tif (!instance && provider.scope !== ProviderScope.REQUEST) {\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t`Monque: Could not resolve instance for controller ${provider.name}. Skipping.`,\n\t\t\t\t);\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (const job of jobs) {\n\t\t\t\tconst { fullName, method, opts, isCron, cronPattern } = job;\n\n\t\t\t\tif (registeredJobs.has(fullName)) {\n\t\t\t\t\tthrow new WorkerRegistrationError(\n\t\t\t\t\t\t`Monque: Duplicate job registration detected. Job \"${fullName}\" is already registered.`,\n\t\t\t\t\t\tfullName,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tregisteredJobs.add(fullName);\n\n\t\t\t\tconst handler = async (job: Job) => {\n\t\t\t\t\tconst $ctx = new DIContext({\n\t\t\t\t\t\tinjector: this.injector,\n\t\t\t\t\t\tid: job._id?.toString() || 'unknown',\n\t\t\t\t\t});\n\t\t\t\t\t$ctx.set('MONQUE_JOB', job);\n\t\t\t\t\t$ctx.container.set(DIContext, $ctx);\n\n\t\t\t\t\tawait runInContext($ctx, async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tlet targetInstance = instance;\n\t\t\t\t\t\t\tif (provider.scope === ProviderScope.REQUEST || !targetInstance) {\n\t\t\t\t\t\t\t\ttargetInstance = await this.injector.invoke(provider.token, {\n\t\t\t\t\t\t\t\t\tlocals: $ctx.container,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst typedInstance = targetInstance as Record<string, (job: Job) => unknown>;\n\n\t\t\t\t\t\t\tif (typedInstance && typeof typedInstance[method] === 'function') {\n\t\t\t\t\t\t\t\tawait typedInstance[method](job);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tthis.logger.error({\n\t\t\t\t\t\t\t\tevent: 'MONQUE_JOB_ERROR',\n\t\t\t\t\t\t\t\tjobName: fullName,\n\t\t\t\t\t\t\t\tjobId: job._id,\n\t\t\t\t\t\t\t\tmessage: `Error processing job ${fullName}`,\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tawait $ctx.destroy();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t};\n\n\t\t\t\tif (isCron && cronPattern) {\n\t\t\t\t\tthis.logger.debug(`Monque: Registering cron job \"${fullName}\" (${cronPattern})`);\n\n\t\t\t\t\tmonque.register(fullName, handler, opts as WorkerOptions);\n\t\t\t\t\tawait monque.schedule(cronPattern, fullName, {}, opts as ScheduleOptions);\n\t\t\t\t} else {\n\t\t\t\t\tthis.logger.debug(`Monque: Registering job \"${fullName}\"`);\n\t\t\t\t\tmonque.register(fullName, handler, opts as WorkerOptions);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.logger.info(`Monque: Registered ${registeredJobs.size} jobs`);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA+CA,SAAgB,uBAAuB,QAAgC;CACtE,MAAM,aAAa;EAAC,OAAO;EAAI,OAAO;EAAW,OAAO;EAAQ,CAAC,OAAO,QAAQ;AAEhF,KAAI,WAAW,WAAW,EACzB,OAAM,IAAI,YACT,qFACA;AAGF,KAAI,WAAW,SAAS,EACvB,OAAM,IAAI,YACT,gGACA;;;;;;;;;;;;;;;;AChDH,MAAa,SAAS,OAAO,IAAI,SAAS;;;;;;;;;;;;;;ACD1C,MAAa,gBAAgB;CAE5B,gBAAgB;CAEhB,MAAM;CACN;;;;;;;;;;;;;;;;;;;;;ACOD,SAAgB,KAAK,SAAiB,SAAiD;AACtF,SACC,QACA,aACA,gBACU;EACV,MAAM,aAAa,OAAO,YAAY;EAEtC,MAAM,eAA6B;GAClC;GAEA,MAAM,SAAS,QAAQ;GACvB,QAAQ;GACR,MAAM,WAAW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