@navios/schedule 0.5.0 → 0.7.1

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/lib/index.cjs ADDED
@@ -0,0 +1,626 @@
1
+ let _navios_core = require("@navios/core");
2
+ let cron = require("cron");
3
+
4
+ //#region src/metadata/cron.metadata.mts
5
+ const CronMetadataKey = Symbol("CronMetadataKey");
6
+ function getAllCronMetadata(context) {
7
+ if (context.metadata) {
8
+ const metadata = context.metadata[CronMetadataKey];
9
+ if (metadata) return metadata;
10
+ else {
11
+ context.metadata[CronMetadataKey] = /* @__PURE__ */ new Set();
12
+ return context.metadata[CronMetadataKey];
13
+ }
14
+ }
15
+ throw new Error("[Navios-Schedule] Wrong environment.");
16
+ }
17
+ function getCronMetadata(target, context) {
18
+ if (context.metadata) {
19
+ const metadata = getAllCronMetadata(context);
20
+ if (metadata) {
21
+ const endpointMetadata = Array.from(metadata).find((item) => item.classMethod === target.name);
22
+ if (endpointMetadata) return endpointMetadata;
23
+ else {
24
+ const newMetadata = {
25
+ classMethod: target.name,
26
+ cronTime: null,
27
+ disabled: false
28
+ };
29
+ metadata.add(newMetadata);
30
+ return newMetadata;
31
+ }
32
+ }
33
+ }
34
+ throw new Error("[Navios-Schedule] Wrong environment.");
35
+ }
36
+
37
+ //#endregion
38
+ //#region src/metadata/schedule.metadata.mts
39
+ const ScheduleMetadataKey = Symbol("ControllerMetadataKey");
40
+ function getScheduleMetadata(target, context) {
41
+ if (context.metadata) {
42
+ const metadata = context.metadata[ScheduleMetadataKey];
43
+ if (metadata) return metadata;
44
+ else {
45
+ const jobsMetadata = getAllCronMetadata(context);
46
+ const newMetadata = {
47
+ name: target.name,
48
+ jobs: jobsMetadata
49
+ };
50
+ context.metadata[ScheduleMetadataKey] = newMetadata;
51
+ target[ScheduleMetadataKey] = newMetadata;
52
+ return newMetadata;
53
+ }
54
+ }
55
+ throw new Error("[Navios-Schedule] Wrong environment.");
56
+ }
57
+ function extractScheduleMetadata(target) {
58
+ const metadata = target[ScheduleMetadataKey];
59
+ if (!metadata) throw new Error("[Navios-Schedule] Controller metadata not found. Make sure to use @Controller decorator.");
60
+ return metadata;
61
+ }
62
+ function hasScheduleMetadata(target) {
63
+ return !!target[ScheduleMetadataKey];
64
+ }
65
+
66
+ //#endregion
67
+ //#region src/decorators/cron.decorator.mts
68
+ /**
69
+ * Decorator that marks a method to run on a cron schedule.
70
+ *
71
+ * The method must be in a class decorated with `@Schedulable()`.
72
+ * The method will be automatically executed according to the provided cron expression.
73
+ *
74
+ * @param cronTime - Cron expression (5 or 6 fields) or a pre-defined Schedule constant
75
+ * @param options - Optional configuration for the cron job
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * @Schedulable()
80
+ * class TaskService {
81
+ * // Run daily at midnight
82
+ * @Cron('0 0 * * *')
83
+ * async dailyTask() {
84
+ * console.log('Running daily task')
85
+ * }
86
+ *
87
+ * // Use pre-defined schedule
88
+ * @Cron(Schedule.EveryFiveMinutes)
89
+ * async frequentTask() {
90
+ * console.log('Running every 5 minutes')
91
+ * }
92
+ *
93
+ * // Disabled job (won't start automatically)
94
+ * @Cron('0 2 * * *', { disabled: true })
95
+ * async maintenanceTask() {
96
+ * console.log('Maintenance task')
97
+ * }
98
+ * }
99
+ * ```
100
+ *
101
+ * @throws {Error} If applied to something other than a method
102
+ *
103
+ * @public
104
+ */ function Cron(cronTime, options) {
105
+ return (target, context) => {
106
+ if (context.kind !== "method") throw new Error(`Cron can only be applied to methods, not ${context.kind}`);
107
+ if (context.metadata) {
108
+ const metadata = getCronMetadata(target, context);
109
+ metadata.cronTime = cronTime;
110
+ metadata.disabled = options?.disabled ?? false;
111
+ }
112
+ return target;
113
+ };
114
+ }
115
+
116
+ //#endregion
117
+ //#region src/decorators/schedulable.decorator.mts
118
+ /**
119
+ * Decorator that marks a class as schedulable and makes it injectable.
120
+ *
121
+ * Classes decorated with `@Schedulable()` can contain methods decorated with `@Cron()`
122
+ * that will be automatically scheduled and executed. This decorator also applies
123
+ * the `@Injectable()` decorator, making the class available for dependency injection.
124
+ *
125
+ * @example
126
+ * ```typescript
127
+ * @Schedulable()
128
+ * class TaskService {
129
+ * @Cron('0 0 * * *')
130
+ * async dailyTask() {
131
+ * // This will run daily at midnight
132
+ * }
133
+ * }
134
+ *
135
+ * // Register the service
136
+ * schedulerService.register(TaskService)
137
+ * ```
138
+ *
139
+ * @throws {Error} If applied to something other than a class
140
+ *
141
+ * @public
142
+ */ function Schedulable() {
143
+ return (target, context) => {
144
+ if (context.kind !== "class") throw new Error(`SchedulableDecorator can only be applied to classes, not ${context.kind}`);
145
+ if (context.metadata) getScheduleMetadata(target, context);
146
+ return (0, _navios_core.Injectable)()(target, context);
147
+ };
148
+ }
149
+
150
+ //#endregion
151
+ //#region src/cron.constants.mts
152
+ /**
153
+ * Pre-defined cron schedule constants for common scheduling patterns.
154
+ *
155
+ * These constants provide convenient shortcuts for frequently used cron expressions,
156
+ * making it easier to schedule jobs without manually writing cron expressions.
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * import { Schedule } from '@navios/schedule'
161
+ *
162
+ * @Schedulable()
163
+ * class TaskService {
164
+ * @Cron(Schedule.EveryMinute)
165
+ * async everyMinute() {}
166
+ *
167
+ * @Cron(Schedule.EveryHour)
168
+ * async hourly() {}
169
+ *
170
+ * @Cron(Schedule.EveryDay)
171
+ * async daily() {}
172
+ * }
173
+ * ```
174
+ *
175
+ * @public
176
+ */ var Schedule = /* @__PURE__ */ function(Schedule$1) {
177
+ Schedule$1["EveryMinute"] = "*/1 * * * *";
178
+ Schedule$1["EveryFiveMinutes"] = "*/5 * * * *";
179
+ Schedule$1["EveryTenMinutes"] = "*/10 * * * *";
180
+ Schedule$1["EveryFifteenMinutes"] = "*/15 * * * *";
181
+ Schedule$1["EveryThirtyMinutes"] = "*/30 * * * *";
182
+ Schedule$1["EveryHour"] = "0 * * * *";
183
+ Schedule$1["EveryTwoHours"] = "0 */2 * * *";
184
+ Schedule$1["EveryThreeHours"] = "0 */3 * * *";
185
+ Schedule$1["EveryFourHours"] = "0 */4 * * *";
186
+ Schedule$1["EverySixHours"] = "0 */6 * * *";
187
+ Schedule$1["EveryTwelveHours"] = "0 */12 * * *";
188
+ Schedule$1["EveryDay"] = "0 0 * * *";
189
+ Schedule$1["EveryWeek"] = "0 0 * * 0";
190
+ Schedule$1["EveryMonth"] = "0 0 1 * *";
191
+ return Schedule$1;
192
+ }({});
193
+
194
+ //#endregion
195
+ //#region src/scheduler.service.mts
196
+ function applyDecs2203RFactory() {
197
+ function createAddInitializerMethod(initializers, decoratorFinishedRef) {
198
+ return function addInitializer(initializer) {
199
+ assertNotFinished(decoratorFinishedRef, "addInitializer");
200
+ assertCallable(initializer, "An initializer");
201
+ initializers.push(initializer);
202
+ };
203
+ }
204
+ function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
205
+ var kindStr;
206
+ switch (kind) {
207
+ case 1:
208
+ kindStr = "accessor";
209
+ break;
210
+ case 2:
211
+ kindStr = "method";
212
+ break;
213
+ case 3:
214
+ kindStr = "getter";
215
+ break;
216
+ case 4:
217
+ kindStr = "setter";
218
+ break;
219
+ default: kindStr = "field";
220
+ }
221
+ var ctx = {
222
+ kind: kindStr,
223
+ name: isPrivate ? "#" + name : name,
224
+ static: isStatic,
225
+ private: isPrivate,
226
+ metadata
227
+ };
228
+ var decoratorFinishedRef = { v: false };
229
+ ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
230
+ var get, set;
231
+ if (kind === 0) if (isPrivate) {
232
+ get = desc.get;
233
+ set = desc.set;
234
+ } else {
235
+ get = function() {
236
+ return this[name];
237
+ };
238
+ set = function(v) {
239
+ this[name] = v;
240
+ };
241
+ }
242
+ else if (kind === 2) get = function() {
243
+ return desc.value;
244
+ };
245
+ else {
246
+ if (kind === 1 || kind === 3) get = function() {
247
+ return desc.get.call(this);
248
+ };
249
+ if (kind === 1 || kind === 4) set = function(v) {
250
+ desc.set.call(this, v);
251
+ };
252
+ }
253
+ ctx.access = get && set ? {
254
+ get,
255
+ set
256
+ } : get ? { get } : { set };
257
+ try {
258
+ return dec(value, ctx);
259
+ } finally {
260
+ decoratorFinishedRef.v = true;
261
+ }
262
+ }
263
+ function assertNotFinished(decoratorFinishedRef, fnName) {
264
+ if (decoratorFinishedRef.v) throw new Error("attempted to call " + fnName + " after decoration was finished");
265
+ }
266
+ function assertCallable(fn, hint) {
267
+ if (typeof fn !== "function") throw new TypeError(hint + " must be a function");
268
+ }
269
+ function assertValidReturnValue(kind, value) {
270
+ var type = typeof value;
271
+ if (kind === 1) {
272
+ if (type !== "object" || value === null) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
273
+ if (value.get !== void 0) assertCallable(value.get, "accessor.get");
274
+ if (value.set !== void 0) assertCallable(value.set, "accessor.set");
275
+ if (value.init !== void 0) assertCallable(value.init, "accessor.init");
276
+ } else if (type !== "function") {
277
+ var hint;
278
+ if (kind === 0) hint = "field";
279
+ else if (kind === 10) hint = "class";
280
+ else hint = "method";
281
+ throw new TypeError(hint + " decorators must return a function or void 0");
282
+ }
283
+ }
284
+ function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
285
+ var decs = decInfo[0];
286
+ var desc, init, value;
287
+ if (isPrivate) if (kind === 0 || kind === 1) desc = {
288
+ get: decInfo[3],
289
+ set: decInfo[4]
290
+ };
291
+ else if (kind === 3) desc = { get: decInfo[3] };
292
+ else if (kind === 4) desc = { set: decInfo[3] };
293
+ else desc = { value: decInfo[3] };
294
+ else if (kind !== 0) desc = Object.getOwnPropertyDescriptor(base, name);
295
+ if (kind === 1) value = {
296
+ get: desc.get,
297
+ set: desc.set
298
+ };
299
+ else if (kind === 2) value = desc.value;
300
+ else if (kind === 3) value = desc.get;
301
+ else if (kind === 4) value = desc.set;
302
+ var newValue, get, set;
303
+ if (typeof decs === "function") {
304
+ newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
305
+ if (newValue !== void 0) {
306
+ assertValidReturnValue(kind, newValue);
307
+ if (kind === 0) init = newValue;
308
+ else if (kind === 1) {
309
+ init = newValue.init;
310
+ get = newValue.get || value.get;
311
+ set = newValue.set || value.set;
312
+ value = {
313
+ get,
314
+ set
315
+ };
316
+ } else value = newValue;
317
+ }
318
+ } else for (var i = decs.length - 1; i >= 0; i--) {
319
+ var dec = decs[i];
320
+ newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
321
+ if (newValue !== void 0) {
322
+ assertValidReturnValue(kind, newValue);
323
+ var newInit;
324
+ if (kind === 0) newInit = newValue;
325
+ else if (kind === 1) {
326
+ newInit = newValue.init;
327
+ get = newValue.get || value.get;
328
+ set = newValue.set || value.set;
329
+ value = {
330
+ get,
331
+ set
332
+ };
333
+ } else value = newValue;
334
+ if (newInit !== void 0) if (init === void 0) init = newInit;
335
+ else if (typeof init === "function") init = [init, newInit];
336
+ else init.push(newInit);
337
+ }
338
+ }
339
+ if (kind === 0 || kind === 1) {
340
+ if (init === void 0) init = function(instance, init$1) {
341
+ return init$1;
342
+ };
343
+ else if (typeof init !== "function") {
344
+ var ownInitializers = init;
345
+ init = function(instance, init$1) {
346
+ var value$1 = init$1;
347
+ for (var i$1 = 0; i$1 < ownInitializers.length; i$1++) value$1 = ownInitializers[i$1].call(instance, value$1);
348
+ return value$1;
349
+ };
350
+ } else {
351
+ var originalInitializer = init;
352
+ init = function(instance, init$1) {
353
+ return originalInitializer.call(instance, init$1);
354
+ };
355
+ }
356
+ ret.push(init);
357
+ }
358
+ if (kind !== 0) {
359
+ if (kind === 1) {
360
+ desc.get = value.get;
361
+ desc.set = value.set;
362
+ } else if (kind === 2) desc.value = value;
363
+ else if (kind === 3) desc.get = value;
364
+ else if (kind === 4) desc.set = value;
365
+ if (isPrivate) if (kind === 1) {
366
+ ret.push(function(instance, args) {
367
+ return value.get.call(instance, args);
368
+ });
369
+ ret.push(function(instance, args) {
370
+ return value.set.call(instance, args);
371
+ });
372
+ } else if (kind === 2) ret.push(value);
373
+ else ret.push(function(instance, args) {
374
+ return value.call(instance, args);
375
+ });
376
+ else Object.defineProperty(base, name, desc);
377
+ }
378
+ }
379
+ function applyMemberDecs(Class, decInfos, metadata) {
380
+ var ret = [];
381
+ var protoInitializers;
382
+ var staticInitializers;
383
+ var existingProtoNonFields = /* @__PURE__ */ new Map();
384
+ var existingStaticNonFields = /* @__PURE__ */ new Map();
385
+ for (var i = 0; i < decInfos.length; i++) {
386
+ var decInfo = decInfos[i];
387
+ if (!Array.isArray(decInfo)) continue;
388
+ var kind = decInfo[1];
389
+ var name = decInfo[2];
390
+ var isPrivate = decInfo.length > 3;
391
+ var isStatic = kind >= 5;
392
+ var base;
393
+ var initializers;
394
+ if (isStatic) {
395
+ base = Class;
396
+ kind = kind - 5;
397
+ staticInitializers = staticInitializers || [];
398
+ initializers = staticInitializers;
399
+ } else {
400
+ base = Class.prototype;
401
+ protoInitializers = protoInitializers || [];
402
+ initializers = protoInitializers;
403
+ }
404
+ if (kind !== 0 && !isPrivate) {
405
+ var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
406
+ var existingKind = existingNonFields.get(name) || 0;
407
+ if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
408
+ else if (!existingKind && kind > 2) existingNonFields.set(name, kind);
409
+ else existingNonFields.set(name, true);
410
+ }
411
+ applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
412
+ }
413
+ pushInitializers(ret, protoInitializers);
414
+ pushInitializers(ret, staticInitializers);
415
+ return ret;
416
+ }
417
+ function pushInitializers(ret, initializers) {
418
+ if (initializers) ret.push(function(instance) {
419
+ for (var i = 0; i < initializers.length; i++) initializers[i].call(instance);
420
+ return instance;
421
+ });
422
+ }
423
+ function applyClassDecs(targetClass, classDecs, metadata) {
424
+ if (classDecs.length > 0) {
425
+ var initializers = [];
426
+ var newClass = targetClass;
427
+ var name = targetClass.name;
428
+ for (var i = classDecs.length - 1; i >= 0; i--) {
429
+ var decoratorFinishedRef = { v: false };
430
+ try {
431
+ var nextNewClass = classDecs[i](newClass, {
432
+ kind: "class",
433
+ name,
434
+ addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
435
+ metadata
436
+ });
437
+ } finally {
438
+ decoratorFinishedRef.v = true;
439
+ }
440
+ if (nextNewClass !== void 0) {
441
+ assertValidReturnValue(10, nextNewClass);
442
+ newClass = nextNewClass;
443
+ }
444
+ }
445
+ return [defineMetadata(newClass, metadata), function() {
446
+ for (var i$1 = 0; i$1 < initializers.length; i$1++) initializers[i$1].call(newClass);
447
+ }];
448
+ }
449
+ }
450
+ function defineMetadata(Class, metadata) {
451
+ return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
452
+ configurable: true,
453
+ enumerable: true,
454
+ value: metadata
455
+ });
456
+ }
457
+ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
458
+ if (parentClass !== void 0) var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
459
+ var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
460
+ var e = applyMemberDecs(targetClass, memberDecs, metadata);
461
+ if (!classDecs.length) defineMetadata(targetClass, metadata);
462
+ return {
463
+ e,
464
+ get c() {
465
+ return applyClassDecs(targetClass, classDecs, metadata);
466
+ }
467
+ };
468
+ };
469
+ }
470
+ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
471
+ return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
472
+ }
473
+ var _dec, _initClass;
474
+ let _SchedulerService;
475
+ _dec = (0, _navios_core.Injectable)();
476
+ var SchedulerService = class {
477
+ static {
478
+ ({c: [_SchedulerService, _initClass]} = _apply_decs_2203_r(this, [], [_dec]));
479
+ }
480
+ logger = (0, _navios_core.inject)(_navios_core.Logger, { context: _SchedulerService.name });
481
+ container = (0, _navios_core.inject)(_navios_core.Container);
482
+ jobs = /* @__PURE__ */ new Map();
483
+ /**
484
+ * Registers a schedulable service and starts all its cron jobs.
485
+ *
486
+ * The service must be decorated with `@Schedulable()` and contain methods
487
+ * decorated with `@Cron()` to be registered successfully.
488
+ *
489
+ * @param service - The schedulable service class to register
490
+ * @throws {Error} If the service is not decorated with `@Schedulable()`
491
+ *
492
+ * @example
493
+ * ```typescript
494
+ * @Schedulable()
495
+ * class TaskService {
496
+ * @Cron('0 0 * * *')
497
+ * async dailyTask() {
498
+ * // Runs daily at midnight
499
+ * }
500
+ * }
501
+ *
502
+ * schedulerService.register(TaskService)
503
+ * ```
504
+ *
505
+ * @public
506
+ */ register(service) {
507
+ if (!hasScheduleMetadata(service)) throw new Error(`[Navios-Schedule] Service ${service.name} is not schedulable. Make sure to use @Schedulable decorator.`);
508
+ const metadata = extractScheduleMetadata(service);
509
+ this.logger.debug("Scheduling service", metadata.name);
510
+ this.registerJobs(service, metadata);
511
+ }
512
+ /**
513
+ * Retrieves a specific cron job instance for a method in a schedulable service.
514
+ *
515
+ * @param service - The schedulable service class
516
+ * @param method - The name of the method decorated with `@Cron()`
517
+ * @returns The CronJob instance if found, undefined otherwise
518
+ *
519
+ * @example
520
+ * ```typescript
521
+ * const job = schedulerService.getJob(TaskService, 'dailyTask')
522
+ * if (job) {
523
+ * console.log('Job is active:', job.isActive)
524
+ * job.start() // Manually start the job
525
+ * job.stop() // Manually stop the job
526
+ * }
527
+ * ```
528
+ *
529
+ * @public
530
+ */ getJob(service, method) {
531
+ const jobName = `${extractScheduleMetadata(service).name}.${method}()`;
532
+ return this.jobs.get(jobName);
533
+ }
534
+ registerJobs(service, metadata) {
535
+ const jobs = metadata.jobs;
536
+ for (const job of jobs) {
537
+ if (!job.cronTime) {
538
+ this.logger.debug("Skipping job", job.classMethod);
539
+ continue;
540
+ }
541
+ const name = `${metadata.name}.${job.classMethod}()`;
542
+ const self = this;
543
+ const cronJob = cron.CronJob.from({
544
+ cronTime: job.cronTime,
545
+ name,
546
+ async onTick() {
547
+ try {
548
+ self.logger.debug("Executing job", name);
549
+ await (await self.container.get(service))[job.classMethod]();
550
+ } catch (error) {
551
+ self.logger.error("Error executing job", name, error);
552
+ }
553
+ },
554
+ start: !job.disabled
555
+ });
556
+ this.jobs.set(name, cronJob);
557
+ }
558
+ }
559
+ /**
560
+ * Starts all registered cron jobs that are currently inactive.
561
+ *
562
+ * Only jobs that are not already active will be started. This method
563
+ * is useful for resuming all jobs after calling `stopAll()`.
564
+ *
565
+ * @example
566
+ * ```typescript
567
+ * // Stop all jobs
568
+ * schedulerService.stopAll()
569
+ *
570
+ * // Later, resume all jobs
571
+ * schedulerService.startAll()
572
+ * ```
573
+ *
574
+ * @public
575
+ */ startAll() {
576
+ for (const job of this.jobs.values()) {
577
+ if (job.isActive) continue;
578
+ job.start();
579
+ }
580
+ }
581
+ /**
582
+ * Stops all registered cron jobs that are currently active.
583
+ *
584
+ * Only jobs that are currently active will be stopped. This method
585
+ * is useful for pausing all scheduled tasks, for example during
586
+ * application shutdown or maintenance.
587
+ *
588
+ * @example
589
+ * ```typescript
590
+ * // Pause all scheduled jobs
591
+ * schedulerService.stopAll()
592
+ *
593
+ * // Jobs can be resumed later with startAll()
594
+ * schedulerService.startAll()
595
+ * ```
596
+ *
597
+ * @public
598
+ */ stopAll() {
599
+ for (const job of this.jobs.values()) {
600
+ if (!job.isActive) continue;
601
+ job.stop();
602
+ }
603
+ }
604
+ static {
605
+ _initClass();
606
+ }
607
+ };
608
+
609
+ //#endregion
610
+ exports.Cron = Cron;
611
+ exports.CronMetadataKey = CronMetadataKey;
612
+ exports.Schedulable = Schedulable;
613
+ exports.Schedule = Schedule;
614
+ exports.ScheduleMetadataKey = ScheduleMetadataKey;
615
+ Object.defineProperty(exports, 'SchedulerService', {
616
+ enumerable: true,
617
+ get: function () {
618
+ return _SchedulerService;
619
+ }
620
+ });
621
+ exports.extractScheduleMetadata = extractScheduleMetadata;
622
+ exports.getAllCronMetadata = getAllCronMetadata;
623
+ exports.getCronMetadata = getCronMetadata;
624
+ exports.getScheduleMetadata = getScheduleMetadata;
625
+ exports.hasScheduleMetadata = hasScheduleMetadata;
626
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["newMetadata: CronMetadata","getAllCronMetadata","ScheduleMetadataKey","Symbol","getScheduleMetadata","target","context","metadata","jobsMetadata","newMetadata","name","jobs","Error","extractScheduleMetadata","hasScheduleMetadata","getCronMetadata","Cron","cronTime","options","target","context","kind","Error","metadata","disabled","Injectable","getScheduleMetadata","Schedulable","target","context","kind","Error","metadata","Schedule","Container","inject","Injectable","Logger","CronJob","extractScheduleMetadata","hasScheduleMetadata","SchedulerService","logger","context","name","container","jobs","Map","register","service","Error","metadata","debug","registerJobs","getJob","method","jobName","get","job","cronTime","classMethod","self","defaultDisabled","cronJob","from","onTick","instance","error","start","disabled","set","startAll","values","isActive","stopAll","stop"],"sources":["../src/metadata/cron.metadata.mts","../src/metadata/schedule.metadata.mts","../src/decorators/cron.decorator.mts","../src/decorators/schedulable.decorator.mts","../src/cron.constants.mts","../src/scheduler.service.mts"],"sourcesContent":["import type { CronJobParams } from 'cron'\n\nexport const CronMetadataKey = Symbol('CronMetadataKey')\n\nexport interface CronMetadata {\n classMethod: string\n cronTime: CronJobParams['cronTime'] | null\n disabled: boolean\n}\n\nexport function getAllCronMetadata(\n context: ClassMethodDecoratorContext | ClassDecoratorContext,\n): Set<CronMetadata> {\n if (context.metadata) {\n const metadata = context.metadata[CronMetadataKey] as\n | Set<CronMetadata>\n | undefined\n if (metadata) {\n return metadata\n } else {\n context.metadata[CronMetadataKey] = new Set<CronMetadata>()\n return context.metadata[CronMetadataKey] as Set<CronMetadata>\n }\n }\n throw new Error('[Navios-Schedule] Wrong environment.')\n}\n\nexport function getCronMetadata(\n target: Function,\n context: ClassMethodDecoratorContext,\n): CronMetadata {\n if (context.metadata) {\n const metadata = getAllCronMetadata(context)\n if (metadata) {\n const endpointMetadata = Array.from(metadata).find(\n (item) => item.classMethod === target.name,\n )\n if (endpointMetadata) {\n return endpointMetadata\n } else {\n const newMetadata: CronMetadata = {\n classMethod: target.name,\n cronTime: null,\n disabled: false,\n }\n metadata.add(newMetadata)\n return newMetadata\n }\n }\n }\n throw new Error('[Navios-Schedule] Wrong environment.')\n}\n","import type { ClassType } from '@navios/core'\n\nimport type { CronMetadata } from './cron.metadata.mjs'\n\nimport { getAllCronMetadata } from './cron.metadata.mjs'\n\nexport const ScheduleMetadataKey = Symbol('ControllerMetadataKey')\n\nexport interface ScheduleMetadata {\n name: string\n jobs: Set<CronMetadata>\n}\n\nexport function getScheduleMetadata(\n target: ClassType,\n context: ClassDecoratorContext,\n): ScheduleMetadata {\n if (context.metadata) {\n const metadata = context.metadata[ScheduleMetadataKey] as\n | ScheduleMetadata\n | undefined\n if (metadata) {\n return metadata\n } else {\n const jobsMetadata = getAllCronMetadata(context)\n const newMetadata: ScheduleMetadata = {\n name: target.name,\n jobs: jobsMetadata,\n }\n context.metadata[ScheduleMetadataKey] = newMetadata\n // @ts-expect-error We add a custom metadata key to the target\n target[ScheduleMetadataKey] = newMetadata\n return newMetadata\n }\n }\n throw new Error('[Navios-Schedule] Wrong environment.')\n}\n\nexport function extractScheduleMetadata(target: ClassType): ScheduleMetadata {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[ScheduleMetadataKey] as ScheduleMetadata | undefined\n if (!metadata) {\n throw new Error(\n '[Navios-Schedule] Controller metadata not found. Make sure to use @Controller decorator.',\n )\n }\n return metadata\n}\n\nexport function hasScheduleMetadata(target: ClassType): boolean {\n // @ts-expect-error We add a custom metadata key to the target\n const metadata = target[ScheduleMetadataKey] as ScheduleMetadata | undefined\n\n return !!metadata\n}\n","import type { CronJobParams } from 'cron'\n\nimport { getCronMetadata } from '../metadata/index.mjs'\n\n/**\n * Options for configuring a cron job.\n * \n * @public\n */\nexport interface CronOptions {\n /**\n * Whether the job should be disabled by default.\n * Disabled jobs won't start automatically but can be manually started later.\n * \n * @default false\n */\n disabled?: boolean\n}\n\n/**\n * Decorator that marks a method to run on a cron schedule.\n * \n * The method must be in a class decorated with `@Schedulable()`.\n * The method will be automatically executed according to the provided cron expression.\n * \n * @param cronTime - Cron expression (5 or 6 fields) or a pre-defined Schedule constant\n * @param options - Optional configuration for the cron job\n * \n * @example\n * ```typescript\n * @Schedulable()\n * class TaskService {\n * // Run daily at midnight\n * @Cron('0 0 * * *')\n * async dailyTask() {\n * console.log('Running daily task')\n * }\n * \n * // Use pre-defined schedule\n * @Cron(Schedule.EveryFiveMinutes)\n * async frequentTask() {\n * console.log('Running every 5 minutes')\n * }\n * \n * // Disabled job (won't start automatically)\n * @Cron('0 2 * * *', { disabled: true })\n * async maintenanceTask() {\n * console.log('Maintenance task')\n * }\n * }\n * ```\n * \n * @throws {Error} If applied to something other than a method\n * \n * @public\n */\nexport function Cron(\n cronTime: CronJobParams['cronTime'],\n options?: CronOptions,\n) {\n return (\n target: () => Promise<void>,\n context: ClassMethodDecoratorContext,\n ) => {\n if (context.kind !== 'method') {\n throw new Error(\n `Cron can only be applied to methods, not ${context.kind}`,\n )\n }\n if (context.metadata) {\n const metadata = getCronMetadata(target, context)\n metadata.cronTime = cronTime\n metadata.disabled = options?.disabled ?? false\n }\n return target\n }\n}\n","import type { ClassType } from '@navios/core'\n\nimport { Injectable } from '@navios/core'\n\nimport { getScheduleMetadata } from '../metadata/index.mjs'\n\n/**\n * Decorator that marks a class as schedulable and makes it injectable.\n * \n * Classes decorated with `@Schedulable()` can contain methods decorated with `@Cron()`\n * that will be automatically scheduled and executed. This decorator also applies\n * the `@Injectable()` decorator, making the class available for dependency injection.\n * \n * @example\n * ```typescript\n * @Schedulable()\n * class TaskService {\n * @Cron('0 0 * * *')\n * async dailyTask() {\n * // This will run daily at midnight\n * }\n * }\n * \n * // Register the service\n * schedulerService.register(TaskService)\n * ```\n * \n * @throws {Error} If applied to something other than a class\n * \n * @public\n */\nexport function Schedulable() {\n return (target: ClassType, context: ClassDecoratorContext) => {\n if (context.kind !== 'class') {\n throw new Error(\n `SchedulableDecorator can only be applied to classes, not ${context.kind}`,\n )\n }\n if (context.metadata) {\n getScheduleMetadata(target, context)\n }\n return Injectable()(target, context)\n }\n}\n","/**\n * Pre-defined cron schedule constants for common scheduling patterns.\n *\n * These constants provide convenient shortcuts for frequently used cron expressions,\n * making it easier to schedule jobs without manually writing cron expressions.\n *\n * @example\n * ```typescript\n * import { Schedule } from '@navios/schedule'\n *\n * @Schedulable()\n * class TaskService {\n * @Cron(Schedule.EveryMinute)\n * async everyMinute() {}\n *\n * @Cron(Schedule.EveryHour)\n * async hourly() {}\n *\n * @Cron(Schedule.EveryDay)\n * async daily() {}\n * }\n * ```\n *\n * @public\n */\nexport enum Schedule {\n EveryMinute = '*/1 * * * *',\n EveryFiveMinutes = '*/5 * * * *',\n EveryTenMinutes = '*/10 * * * *',\n EveryFifteenMinutes = '*/15 * * * *',\n EveryThirtyMinutes = '*/30 * * * *',\n EveryHour = '0 * * * *',\n EveryTwoHours = '0 */2 * * *',\n EveryThreeHours = '0 */3 * * *',\n EveryFourHours = '0 */4 * * *',\n EverySixHours = '0 */6 * * *',\n EveryTwelveHours = '0 */12 * * *',\n EveryDay = '0 0 * * *',\n EveryWeek = '0 0 * * 0',\n EveryMonth = '0 0 1 * *',\n}\n","import type { ClassType } from '@navios/core'\n\nimport { Container, inject, Injectable, Logger } from '@navios/core'\n\nimport { CronJob } from 'cron'\n\nimport type { ScheduleMetadata } from './metadata/index.mjs'\n\nimport {\n extractScheduleMetadata,\n hasScheduleMetadata,\n} from './metadata/index.mjs'\n\n/**\n * Service responsible for managing and executing scheduled cron jobs.\n * \n * The SchedulerService registers schedulable services decorated with `@Schedulable()`\n * and automatically starts their cron jobs based on the `@Cron()` decorator configuration.\n * \n * @example\n * ```typescript\n * import { inject, Injectable } from '@navios/core'\n * import { SchedulerService } from '@navios/schedule'\n * \n * @Injectable()\n * class AppModule {\n * private readonly scheduler = inject(SchedulerService)\n * \n * async onModuleInit() {\n * this.scheduler.register(MySchedulableService)\n * }\n * }\n * ```\n * \n * @public\n */\n@Injectable()\nexport class SchedulerService {\n private readonly logger = inject(Logger, {\n context: SchedulerService.name,\n })\n private readonly container = inject(Container)\n private readonly jobs: Map<string, CronJob> = new Map()\n\n /**\n * Registers a schedulable service and starts all its cron jobs.\n * \n * The service must be decorated with `@Schedulable()` and contain methods\n * decorated with `@Cron()` to be registered successfully.\n * \n * @param service - The schedulable service class to register\n * @throws {Error} If the service is not decorated with `@Schedulable()`\n * \n * @example\n * ```typescript\n * @Schedulable()\n * class TaskService {\n * @Cron('0 0 * * *')\n * async dailyTask() {\n * // Runs daily at midnight\n * }\n * }\n * \n * schedulerService.register(TaskService)\n * ```\n * \n * @public\n */\n register(service: ClassType) {\n if (!hasScheduleMetadata(service)) {\n throw new Error(\n `[Navios-Schedule] Service ${service.name} is not schedulable. Make sure to use @Schedulable decorator.`,\n )\n }\n const metadata = extractScheduleMetadata(service)\n this.logger.debug('Scheduling service', metadata.name)\n this.registerJobs(service, metadata)\n }\n\n /**\n * Retrieves a specific cron job instance for a method in a schedulable service.\n * \n * @param service - The schedulable service class\n * @param method - The name of the method decorated with `@Cron()`\n * @returns The CronJob instance if found, undefined otherwise\n * \n * @example\n * ```typescript\n * const job = schedulerService.getJob(TaskService, 'dailyTask')\n * if (job) {\n * console.log('Job is active:', job.isActive)\n * job.start() // Manually start the job\n * job.stop() // Manually stop the job\n * }\n * ```\n * \n * @public\n */\n getJob<T extends ClassType>(\n service: T,\n method: keyof InstanceType<T>,\n ): CronJob | undefined {\n const metadata = extractScheduleMetadata(service)\n const jobName = `${metadata.name}.${method as string}()`\n return this.jobs.get(jobName)\n }\n\n private registerJobs(service: ClassType, metadata: ScheduleMetadata) {\n const jobs = metadata.jobs\n for (const job of jobs) {\n if (!job.cronTime) {\n this.logger.debug('Skipping job', job.classMethod)\n continue\n }\n const name = `${metadata.name}.${job.classMethod}()`\n const self = this\n const defaultDisabled = false\n const cronJob = CronJob.from({\n cronTime: job.cronTime,\n name,\n async onTick() {\n try {\n self.logger.debug('Executing job', name)\n const instance = await self.container.get(service)\n await instance[job.classMethod]()\n } catch (error) {\n self.logger.error('Error executing job', name, error)\n }\n },\n start: !(defaultDisabled || job.disabled),\n })\n this.jobs.set(name, cronJob)\n }\n }\n\n /**\n * Starts all registered cron jobs that are currently inactive.\n * \n * Only jobs that are not already active will be started. This method\n * is useful for resuming all jobs after calling `stopAll()`.\n * \n * @example\n * ```typescript\n * // Stop all jobs\n * schedulerService.stopAll()\n * \n * // Later, resume all jobs\n * schedulerService.startAll()\n * ```\n * \n * @public\n */\n startAll() {\n for (const job of this.jobs.values()) {\n if (job.isActive) {\n continue\n }\n job.start()\n }\n }\n\n /**\n * Stops all registered cron jobs that are currently active.\n * \n * Only jobs that are currently active will be stopped. This method\n * is useful for pausing all scheduled tasks, for example during\n * application shutdown or maintenance.\n * \n * @example\n * ```typescript\n * // Pause all scheduled jobs\n * schedulerService.stopAll()\n * \n * // Jobs can be resumed later with startAll()\n * schedulerService.startAll()\n * ```\n * \n * @public\n */\n stopAll() {\n for (const job of this.jobs.values()) {\n if (!job.isActive) {\n continue\n }\n job.stop()\n }\n }\n}\n"],"mappings":";;;;AAEA,MAAa,kBAAkB,OAAO,kBAAkB;AAQxD,SAAgB,mBACd,SACmB;AACnB,KAAI,QAAQ,UAAU;EACpB,MAAM,WAAW,QAAQ,SAAS;AAGlC,MAAI,SACF,QAAO;OACF;AACL,WAAQ,SAAS,mCAAmB,IAAI,KAAmB;AAC3D,UAAO,QAAQ,SAAS;;;AAG5B,OAAM,IAAI,MAAM,uCAAuC;;AAGzD,SAAgB,gBACd,QACA,SACc;AACd,KAAI,QAAQ,UAAU;EACpB,MAAM,WAAW,mBAAmB,QAAQ;AAC5C,MAAI,UAAU;GACZ,MAAM,mBAAmB,MAAM,KAAK,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