getpatter 0.5.1 → 0.5.3

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.
@@ -0,0 +1,1348 @@
1
+ import {
2
+ __commonJS,
3
+ __require
4
+ } from "./chunk-QHHBUCMT.mjs";
5
+
6
+ // node_modules/node-cron/dist/esm/create-id.js
7
+ var require_create_id = __commonJS({
8
+ "node_modules/node-cron/dist/esm/create-id.js"(exports) {
9
+ "use strict";
10
+ var __importDefault = exports && exports.__importDefault || function(mod) {
11
+ return mod && mod.__esModule ? mod : { "default": mod };
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.createID = createID;
15
+ var node_crypto_1 = __importDefault(__require("crypto"));
16
+ function createID(prefix = "", length = 16) {
17
+ const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
18
+ const values = node_crypto_1.default.randomBytes(length);
19
+ const id = Array.from(values, (v) => charset[v % charset.length]).join("");
20
+ return prefix ? `${prefix}-${id}` : id;
21
+ }
22
+ }
23
+ });
24
+
25
+ // node_modules/node-cron/dist/esm/logger.js
26
+ var require_logger = __commonJS({
27
+ "node_modules/node-cron/dist/esm/logger.js"(exports) {
28
+ "use strict";
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ var levelColors = {
31
+ INFO: "\x1B[36m",
32
+ WARN: "\x1B[33m",
33
+ ERROR: "\x1B[31m",
34
+ DEBUG: "\x1B[35m"
35
+ };
36
+ var GREEN = "\x1B[32m";
37
+ var RESET = "\x1B[0m";
38
+ function log(level, message, extra) {
39
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
40
+ const color = levelColors[level] ?? "";
41
+ const prefix = `[${timestamp}] [PID: ${process.pid}] ${GREEN}[NODE-CRON]${GREEN} ${color}[${level}]${RESET}`;
42
+ const output = `${prefix} ${message}`;
43
+ switch (level) {
44
+ case "ERROR":
45
+ console.error(output, extra ?? "");
46
+ break;
47
+ case "DEBUG":
48
+ console.debug(output, extra ?? "");
49
+ break;
50
+ case "WARN":
51
+ console.warn(output);
52
+ break;
53
+ case "INFO":
54
+ default:
55
+ console.info(output);
56
+ break;
57
+ }
58
+ }
59
+ var logger = {
60
+ info(message) {
61
+ log("INFO", message);
62
+ },
63
+ warn(message) {
64
+ log("WARN", message);
65
+ },
66
+ error(message, err) {
67
+ if (message instanceof Error) {
68
+ log("ERROR", message.message, message);
69
+ } else {
70
+ log("ERROR", message, err);
71
+ }
72
+ },
73
+ debug(message, err) {
74
+ if (message instanceof Error) {
75
+ log("DEBUG", message.message, message);
76
+ } else {
77
+ log("DEBUG", message, err);
78
+ }
79
+ }
80
+ };
81
+ exports.default = logger;
82
+ }
83
+ });
84
+
85
+ // node_modules/node-cron/dist/esm/promise/tracked-promise.js
86
+ var require_tracked_promise = __commonJS({
87
+ "node_modules/node-cron/dist/esm/promise/tracked-promise.js"(exports) {
88
+ "use strict";
89
+ Object.defineProperty(exports, "__esModule", { value: true });
90
+ exports.TrackedPromise = void 0;
91
+ var TrackedPromise = class {
92
+ promise;
93
+ error;
94
+ state;
95
+ value;
96
+ constructor(executor) {
97
+ this.state = "pending";
98
+ this.promise = new Promise((resolve, reject) => {
99
+ executor((value) => {
100
+ this.state = "fulfilled";
101
+ this.value = value;
102
+ resolve(value);
103
+ }, (error) => {
104
+ this.state = "rejected";
105
+ this.error = error;
106
+ reject(error);
107
+ });
108
+ });
109
+ }
110
+ getPromise() {
111
+ return this.promise;
112
+ }
113
+ getState() {
114
+ return this.state;
115
+ }
116
+ isPending() {
117
+ return this.state === "pending";
118
+ }
119
+ isFulfilled() {
120
+ return this.state === "fulfilled";
121
+ }
122
+ isRejected() {
123
+ return this.state === "rejected";
124
+ }
125
+ getValue() {
126
+ return this.value;
127
+ }
128
+ getError() {
129
+ return this.error;
130
+ }
131
+ then(onfulfilled, onrejected) {
132
+ return this.promise.then(onfulfilled, onrejected);
133
+ }
134
+ catch(onrejected) {
135
+ return this.promise.catch(onrejected);
136
+ }
137
+ finally(onfinally) {
138
+ return this.promise.finally(onfinally);
139
+ }
140
+ };
141
+ exports.TrackedPromise = TrackedPromise;
142
+ }
143
+ });
144
+
145
+ // node_modules/node-cron/dist/esm/scheduler/runner.js
146
+ var require_runner = __commonJS({
147
+ "node_modules/node-cron/dist/esm/scheduler/runner.js"(exports) {
148
+ "use strict";
149
+ var __importDefault = exports && exports.__importDefault || function(mod) {
150
+ return mod && mod.__esModule ? mod : { "default": mod };
151
+ };
152
+ Object.defineProperty(exports, "__esModule", { value: true });
153
+ exports.Runner = void 0;
154
+ var create_id_1 = require_create_id();
155
+ var logger_1 = __importDefault(require_logger());
156
+ var tracked_promise_1 = require_tracked_promise();
157
+ function emptyOnFn() {
158
+ }
159
+ function emptyHookFn() {
160
+ return true;
161
+ }
162
+ function defaultOnError(date, error) {
163
+ logger_1.default.error("Task failed with error!", error);
164
+ }
165
+ var Runner = class {
166
+ timeMatcher;
167
+ onMatch;
168
+ noOverlap;
169
+ maxExecutions;
170
+ maxRandomDelay;
171
+ runCount;
172
+ running;
173
+ heartBeatTimeout;
174
+ onMissedExecution;
175
+ onOverlap;
176
+ onError;
177
+ beforeRun;
178
+ onFinished;
179
+ onMaxExecutions;
180
+ constructor(timeMatcher, onMatch, options) {
181
+ this.timeMatcher = timeMatcher;
182
+ this.onMatch = onMatch;
183
+ this.noOverlap = options == void 0 || options.noOverlap === void 0 ? false : options.noOverlap;
184
+ this.maxExecutions = options?.maxExecutions;
185
+ this.maxRandomDelay = options?.maxRandomDelay || 0;
186
+ this.onMissedExecution = options?.onMissedExecution || emptyOnFn;
187
+ this.onOverlap = options?.onOverlap || emptyOnFn;
188
+ this.onError = options?.onError || defaultOnError;
189
+ this.onFinished = options?.onFinished || emptyHookFn;
190
+ this.beforeRun = options?.beforeRun || emptyHookFn;
191
+ this.onMaxExecutions = options?.onMaxExecutions || emptyOnFn;
192
+ this.runCount = 0;
193
+ this.running = false;
194
+ }
195
+ start() {
196
+ this.running = true;
197
+ let lastExecution;
198
+ let expectedNextExecution;
199
+ const scheduleNextHeartBeat = (currentDate) => {
200
+ if (this.running) {
201
+ clearTimeout(this.heartBeatTimeout);
202
+ this.heartBeatTimeout = setTimeout(heartBeat, getDelay(this.timeMatcher, currentDate));
203
+ }
204
+ };
205
+ const runTask = (date) => {
206
+ return new Promise(async (resolve) => {
207
+ const execution = {
208
+ id: (0, create_id_1.createID)("exec"),
209
+ reason: "scheduled"
210
+ };
211
+ const shouldExecute = await this.beforeRun(date, execution);
212
+ const randomDelay = Math.floor(Math.random() * this.maxRandomDelay);
213
+ if (shouldExecute) {
214
+ setTimeout(async () => {
215
+ try {
216
+ this.runCount++;
217
+ execution.startedAt = /* @__PURE__ */ new Date();
218
+ const result = await this.onMatch(date, execution);
219
+ execution.finishedAt = /* @__PURE__ */ new Date();
220
+ execution.result = result;
221
+ this.onFinished(date, execution);
222
+ if (this.maxExecutions && this.runCount >= this.maxExecutions) {
223
+ this.onMaxExecutions(date);
224
+ this.stop();
225
+ }
226
+ } catch (error) {
227
+ execution.finishedAt = /* @__PURE__ */ new Date();
228
+ execution.error = error;
229
+ this.onError(date, error, execution);
230
+ }
231
+ resolve(true);
232
+ }, randomDelay);
233
+ }
234
+ });
235
+ };
236
+ const checkAndRun = (date) => {
237
+ return new tracked_promise_1.TrackedPromise(async (resolve, reject) => {
238
+ try {
239
+ if (this.timeMatcher.match(date)) {
240
+ await runTask(date);
241
+ }
242
+ resolve(true);
243
+ } catch (err) {
244
+ reject(err);
245
+ }
246
+ });
247
+ };
248
+ const heartBeat = async () => {
249
+ const currentDate = nowWithoutMs();
250
+ if (expectedNextExecution && expectedNextExecution.getTime() < currentDate.getTime()) {
251
+ while (expectedNextExecution.getTime() < currentDate.getTime()) {
252
+ logger_1.default.warn(`missed execution at ${expectedNextExecution}! Possible blocking IO or high CPU user at the same process used by node-cron.`);
253
+ expectedNextExecution = this.timeMatcher.getNextMatch(expectedNextExecution);
254
+ runAsync(this.onMissedExecution, expectedNextExecution, defaultOnError);
255
+ }
256
+ }
257
+ if (lastExecution && lastExecution.getState() === "pending") {
258
+ runAsync(this.onOverlap, currentDate, defaultOnError);
259
+ if (this.noOverlap) {
260
+ logger_1.default.warn("task still running, new execution blocked by overlap prevention!");
261
+ expectedNextExecution = this.timeMatcher.getNextMatch(currentDate);
262
+ scheduleNextHeartBeat(currentDate);
263
+ return;
264
+ }
265
+ }
266
+ lastExecution = checkAndRun(currentDate);
267
+ expectedNextExecution = this.timeMatcher.getNextMatch(currentDate);
268
+ scheduleNextHeartBeat(currentDate);
269
+ };
270
+ this.heartBeatTimeout = setTimeout(() => {
271
+ heartBeat();
272
+ }, getDelay(this.timeMatcher, nowWithoutMs()));
273
+ }
274
+ nextRun() {
275
+ return this.timeMatcher.getNextMatch(/* @__PURE__ */ new Date());
276
+ }
277
+ stop() {
278
+ this.running = false;
279
+ if (this.heartBeatTimeout) {
280
+ clearTimeout(this.heartBeatTimeout);
281
+ this.heartBeatTimeout = void 0;
282
+ }
283
+ }
284
+ isStarted() {
285
+ return !!this.heartBeatTimeout && this.running;
286
+ }
287
+ isStopped() {
288
+ return !this.isStarted();
289
+ }
290
+ async execute() {
291
+ const date = /* @__PURE__ */ new Date();
292
+ const execution = {
293
+ id: (0, create_id_1.createID)("exec"),
294
+ reason: "invoked"
295
+ };
296
+ try {
297
+ const shouldExecute = await this.beforeRun(date, execution);
298
+ if (shouldExecute) {
299
+ this.runCount++;
300
+ execution.startedAt = /* @__PURE__ */ new Date();
301
+ const result = await this.onMatch(date, execution);
302
+ execution.finishedAt = /* @__PURE__ */ new Date();
303
+ execution.result = result;
304
+ this.onFinished(date, execution);
305
+ }
306
+ } catch (error) {
307
+ execution.finishedAt = /* @__PURE__ */ new Date();
308
+ execution.error = error;
309
+ this.onError(date, error, execution);
310
+ }
311
+ }
312
+ };
313
+ exports.Runner = Runner;
314
+ async function runAsync(fn, date, onError) {
315
+ try {
316
+ await fn(date);
317
+ } catch (error) {
318
+ onError(date, error);
319
+ }
320
+ }
321
+ function getDelay(timeMatcher, currentDate) {
322
+ const maxDelay = 864e5;
323
+ const nextRun = timeMatcher.getNextMatch(currentDate);
324
+ const now = /* @__PURE__ */ new Date();
325
+ const delay = nextRun.getTime() - now.getTime();
326
+ if (delay > maxDelay) {
327
+ return maxDelay;
328
+ }
329
+ return Math.max(0, delay);
330
+ }
331
+ function nowWithoutMs() {
332
+ const date = /* @__PURE__ */ new Date();
333
+ date.setMilliseconds(0);
334
+ return date;
335
+ }
336
+ }
337
+ });
338
+
339
+ // node_modules/node-cron/dist/esm/pattern/convertion/month-names-conversion.js
340
+ var require_month_names_conversion = __commonJS({
341
+ "node_modules/node-cron/dist/esm/pattern/convertion/month-names-conversion.js"(exports) {
342
+ "use strict";
343
+ Object.defineProperty(exports, "__esModule", { value: true });
344
+ exports.default = /* @__PURE__ */ (() => {
345
+ const months = [
346
+ "january",
347
+ "february",
348
+ "march",
349
+ "april",
350
+ "may",
351
+ "june",
352
+ "july",
353
+ "august",
354
+ "september",
355
+ "october",
356
+ "november",
357
+ "december"
358
+ ];
359
+ const shortMonths = [
360
+ "jan",
361
+ "feb",
362
+ "mar",
363
+ "apr",
364
+ "may",
365
+ "jun",
366
+ "jul",
367
+ "aug",
368
+ "sep",
369
+ "oct",
370
+ "nov",
371
+ "dec"
372
+ ];
373
+ function convertMonthName(expression, items) {
374
+ for (let i = 0; i < items.length; i++) {
375
+ expression = expression.replace(new RegExp(items[i], "gi"), i + 1);
376
+ }
377
+ return expression;
378
+ }
379
+ function interprete(monthExpression) {
380
+ monthExpression = convertMonthName(monthExpression, months);
381
+ monthExpression = convertMonthName(monthExpression, shortMonths);
382
+ return monthExpression;
383
+ }
384
+ return interprete;
385
+ })();
386
+ }
387
+ });
388
+
389
+ // node_modules/node-cron/dist/esm/pattern/convertion/week-day-names-conversion.js
390
+ var require_week_day_names_conversion = __commonJS({
391
+ "node_modules/node-cron/dist/esm/pattern/convertion/week-day-names-conversion.js"(exports) {
392
+ "use strict";
393
+ Object.defineProperty(exports, "__esModule", { value: true });
394
+ exports.default = /* @__PURE__ */ (() => {
395
+ const weekDays = [
396
+ "sunday",
397
+ "monday",
398
+ "tuesday",
399
+ "wednesday",
400
+ "thursday",
401
+ "friday",
402
+ "saturday"
403
+ ];
404
+ const shortWeekDays = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
405
+ function convertWeekDayName(expression, items) {
406
+ for (let i = 0; i < items.length; i++) {
407
+ expression = expression.replace(new RegExp(items[i], "gi"), i);
408
+ }
409
+ return expression;
410
+ }
411
+ function convertWeekDays(expression) {
412
+ expression = expression.replace("7", "0");
413
+ expression = convertWeekDayName(expression, weekDays);
414
+ return convertWeekDayName(expression, shortWeekDays);
415
+ }
416
+ return convertWeekDays;
417
+ })();
418
+ }
419
+ });
420
+
421
+ // node_modules/node-cron/dist/esm/pattern/convertion/asterisk-to-range-conversion.js
422
+ var require_asterisk_to_range_conversion = __commonJS({
423
+ "node_modules/node-cron/dist/esm/pattern/convertion/asterisk-to-range-conversion.js"(exports) {
424
+ "use strict";
425
+ Object.defineProperty(exports, "__esModule", { value: true });
426
+ exports.default = /* @__PURE__ */ (() => {
427
+ function convertAsterisk(expression, replecement) {
428
+ if (expression.indexOf("*") !== -1) {
429
+ return expression.replace("*", replecement);
430
+ }
431
+ return expression;
432
+ }
433
+ function convertAsterisksToRanges(expressions) {
434
+ expressions[0] = convertAsterisk(expressions[0], "0-59");
435
+ expressions[1] = convertAsterisk(expressions[1], "0-59");
436
+ expressions[2] = convertAsterisk(expressions[2], "0-23");
437
+ expressions[3] = convertAsterisk(expressions[3], "1-31");
438
+ expressions[4] = convertAsterisk(expressions[4], "1-12");
439
+ expressions[5] = convertAsterisk(expressions[5], "0-6");
440
+ return expressions;
441
+ }
442
+ return convertAsterisksToRanges;
443
+ })();
444
+ }
445
+ });
446
+
447
+ // node_modules/node-cron/dist/esm/pattern/convertion/range-conversion.js
448
+ var require_range_conversion = __commonJS({
449
+ "node_modules/node-cron/dist/esm/pattern/convertion/range-conversion.js"(exports) {
450
+ "use strict";
451
+ Object.defineProperty(exports, "__esModule", { value: true });
452
+ exports.default = /* @__PURE__ */ (() => {
453
+ function replaceWithRange(expression, text, init, end, stepTxt) {
454
+ const step = parseInt(stepTxt);
455
+ const numbers = [];
456
+ let last = parseInt(end);
457
+ let first = parseInt(init);
458
+ if (first > last) {
459
+ last = parseInt(init);
460
+ first = parseInt(end);
461
+ }
462
+ for (let i = first; i <= last; i += step) {
463
+ numbers.push(i);
464
+ }
465
+ return expression.replace(new RegExp(text, "i"), numbers.join());
466
+ }
467
+ function convertRange(expression) {
468
+ const rangeRegEx = /(\d+)-(\d+)(\/(\d+)|)/;
469
+ let match = rangeRegEx.exec(expression);
470
+ while (match !== null && match.length > 0) {
471
+ expression = replaceWithRange(expression, match[0], match[1], match[2], match[4] || "1");
472
+ match = rangeRegEx.exec(expression);
473
+ }
474
+ return expression;
475
+ }
476
+ function convertAllRanges(expressions) {
477
+ for (let i = 0; i < expressions.length; i++) {
478
+ expressions[i] = convertRange(expressions[i]);
479
+ }
480
+ return expressions;
481
+ }
482
+ return convertAllRanges;
483
+ })();
484
+ }
485
+ });
486
+
487
+ // node_modules/node-cron/dist/esm/pattern/convertion/index.js
488
+ var require_convertion = __commonJS({
489
+ "node_modules/node-cron/dist/esm/pattern/convertion/index.js"(exports) {
490
+ "use strict";
491
+ var __importDefault = exports && exports.__importDefault || function(mod) {
492
+ return mod && mod.__esModule ? mod : { "default": mod };
493
+ };
494
+ Object.defineProperty(exports, "__esModule", { value: true });
495
+ var month_names_conversion_1 = __importDefault(require_month_names_conversion());
496
+ var week_day_names_conversion_1 = __importDefault(require_week_day_names_conversion());
497
+ var asterisk_to_range_conversion_1 = __importDefault(require_asterisk_to_range_conversion());
498
+ var range_conversion_1 = __importDefault(require_range_conversion());
499
+ exports.default = /* @__PURE__ */ (() => {
500
+ function appendSeccondExpression(expressions) {
501
+ if (expressions.length === 5) {
502
+ return ["0"].concat(expressions);
503
+ }
504
+ return expressions;
505
+ }
506
+ function removeSpaces(str) {
507
+ return str.replace(/\s{2,}/g, " ").trim();
508
+ }
509
+ function normalizeIntegers(expressions) {
510
+ for (let i = 0; i < expressions.length; i++) {
511
+ const numbers = expressions[i].split(",");
512
+ for (let j = 0; j < numbers.length; j++) {
513
+ numbers[j] = parseInt(numbers[j]);
514
+ }
515
+ expressions[i] = numbers;
516
+ }
517
+ return expressions;
518
+ }
519
+ function interprete(expression) {
520
+ let expressions = removeSpaces(`${expression}`).split(" ");
521
+ expressions = appendSeccondExpression(expressions);
522
+ expressions[4] = (0, month_names_conversion_1.default)(expressions[4]);
523
+ expressions[5] = (0, week_day_names_conversion_1.default)(expressions[5]);
524
+ expressions = (0, asterisk_to_range_conversion_1.default)(expressions);
525
+ expressions = (0, range_conversion_1.default)(expressions);
526
+ expressions = normalizeIntegers(expressions);
527
+ return expressions;
528
+ }
529
+ return interprete;
530
+ })();
531
+ }
532
+ });
533
+
534
+ // node_modules/node-cron/dist/esm/time/localized-time.js
535
+ var require_localized_time = __commonJS({
536
+ "node_modules/node-cron/dist/esm/time/localized-time.js"(exports) {
537
+ "use strict";
538
+ Object.defineProperty(exports, "__esModule", { value: true });
539
+ exports.LocalizedTime = void 0;
540
+ var LocalizedTime = class {
541
+ timestamp;
542
+ parts;
543
+ timezone;
544
+ constructor(date, timezone) {
545
+ this.timestamp = date.getTime();
546
+ this.timezone = timezone;
547
+ this.parts = buildDateParts(date, timezone);
548
+ }
549
+ toDate() {
550
+ return new Date(this.timestamp);
551
+ }
552
+ toISO() {
553
+ const gmt = this.parts.gmt.replace(/^GMT/, "");
554
+ const offset = gmt ? gmt : "Z";
555
+ const pad = (n) => String(n).padStart(2, "0");
556
+ return `${this.parts.year}-${pad(this.parts.month)}-${pad(this.parts.day)}T${pad(this.parts.hour)}:${pad(this.parts.minute)}:${pad(this.parts.second)}.${String(this.parts.milisecond).padStart(3, "0")}` + offset;
557
+ }
558
+ getParts() {
559
+ return this.parts;
560
+ }
561
+ set(field, value) {
562
+ this.parts[field] = value;
563
+ const newDate = new Date(this.toISO());
564
+ this.timestamp = newDate.getTime();
565
+ this.parts = buildDateParts(newDate, this.timezone);
566
+ }
567
+ };
568
+ exports.LocalizedTime = LocalizedTime;
569
+ function buildDateParts(date, timezone) {
570
+ const dftOptions = {
571
+ year: "numeric",
572
+ month: "2-digit",
573
+ day: "2-digit",
574
+ hour: "2-digit",
575
+ minute: "2-digit",
576
+ second: "2-digit",
577
+ weekday: "short",
578
+ hour12: false
579
+ };
580
+ if (timezone) {
581
+ dftOptions.timeZone = timezone;
582
+ }
583
+ const dateFormat = new Intl.DateTimeFormat("en-US", dftOptions);
584
+ const parts = dateFormat.formatToParts(date).filter((part) => {
585
+ return part.type !== "literal";
586
+ }).reduce((acc, part) => {
587
+ acc[part.type] = part.value;
588
+ return acc;
589
+ }, {});
590
+ return {
591
+ day: parseInt(parts.day),
592
+ month: parseInt(parts.month),
593
+ year: parseInt(parts.year),
594
+ hour: parts.hour === "24" ? 0 : parseInt(parts.hour),
595
+ minute: parseInt(parts.minute),
596
+ second: parseInt(parts.second),
597
+ milisecond: date.getMilliseconds(),
598
+ weekday: parts.weekday,
599
+ gmt: getTimezoneGMT(date, timezone)
600
+ };
601
+ }
602
+ function getTimezoneGMT(date, timezone) {
603
+ const utcDate = new Date(date.toLocaleString("en-US", { timeZone: "UTC" }));
604
+ const tzDate = new Date(date.toLocaleString("en-US", { timeZone: timezone }));
605
+ let offsetInMinutes = (utcDate.getTime() - tzDate.getTime()) / 6e4;
606
+ const sign = offsetInMinutes <= 0 ? "+" : "-";
607
+ offsetInMinutes = Math.abs(offsetInMinutes);
608
+ if (offsetInMinutes === 0)
609
+ return "Z";
610
+ const hours = Math.floor(offsetInMinutes / 60).toString().padStart(2, "0");
611
+ const minutes = Math.floor(offsetInMinutes % 60).toString().padStart(2, "0");
612
+ return `GMT${sign}${hours}:${minutes}`;
613
+ }
614
+ }
615
+ });
616
+
617
+ // node_modules/node-cron/dist/esm/time/matcher-walker.js
618
+ var require_matcher_walker = __commonJS({
619
+ "node_modules/node-cron/dist/esm/time/matcher-walker.js"(exports) {
620
+ "use strict";
621
+ var __importDefault = exports && exports.__importDefault || function(mod) {
622
+ return mod && mod.__esModule ? mod : { "default": mod };
623
+ };
624
+ Object.defineProperty(exports, "__esModule", { value: true });
625
+ exports.MatcherWalker = void 0;
626
+ var convertion_1 = __importDefault(require_convertion());
627
+ var localized_time_1 = require_localized_time();
628
+ var time_matcher_1 = require_time_matcher();
629
+ var week_day_names_conversion_1 = __importDefault(require_week_day_names_conversion());
630
+ var MatcherWalker = class {
631
+ cronExpression;
632
+ baseDate;
633
+ pattern;
634
+ expressions;
635
+ timeMatcher;
636
+ timezone;
637
+ constructor(cronExpression, baseDate, timezone) {
638
+ this.cronExpression = cronExpression;
639
+ this.baseDate = baseDate;
640
+ this.timeMatcher = new time_matcher_1.TimeMatcher(cronExpression, timezone);
641
+ this.timezone = timezone;
642
+ this.expressions = (0, convertion_1.default)(cronExpression);
643
+ }
644
+ isMatching() {
645
+ return this.timeMatcher.match(this.baseDate);
646
+ }
647
+ matchNext() {
648
+ const findNextDateIgnoringWeekday = () => {
649
+ const baseDate = new Date(this.baseDate.getTime());
650
+ baseDate.setMilliseconds(0);
651
+ const localTime = new localized_time_1.LocalizedTime(baseDate, this.timezone);
652
+ const dateParts = localTime.getParts();
653
+ const date2 = new localized_time_1.LocalizedTime(localTime.toDate(), this.timezone);
654
+ const seconds = this.expressions[0];
655
+ const nextSecond = availableValue(seconds, dateParts.second);
656
+ if (nextSecond) {
657
+ date2.set("second", nextSecond);
658
+ if (this.timeMatcher.match(date2.toDate())) {
659
+ return date2;
660
+ }
661
+ }
662
+ date2.set("second", seconds[0]);
663
+ const minutes = this.expressions[1];
664
+ const nextMinute = availableValue(minutes, dateParts.minute);
665
+ if (nextMinute) {
666
+ date2.set("minute", nextMinute);
667
+ if (this.timeMatcher.match(date2.toDate())) {
668
+ return date2;
669
+ }
670
+ }
671
+ date2.set("minute", minutes[0]);
672
+ const hours = this.expressions[2];
673
+ const nextHour = availableValue(hours, dateParts.hour);
674
+ if (nextHour) {
675
+ date2.set("hour", nextHour);
676
+ if (this.timeMatcher.match(date2.toDate())) {
677
+ return date2;
678
+ }
679
+ }
680
+ date2.set("hour", hours[0]);
681
+ const days = this.expressions[3];
682
+ const nextDay = availableValue(days, dateParts.day);
683
+ if (nextDay) {
684
+ date2.set("day", nextDay);
685
+ if (this.timeMatcher.match(date2.toDate())) {
686
+ return date2;
687
+ }
688
+ }
689
+ date2.set("day", days[0]);
690
+ const months = this.expressions[4];
691
+ const nextMonth = availableValue(months, dateParts.month);
692
+ if (nextMonth) {
693
+ date2.set("month", nextMonth);
694
+ if (this.timeMatcher.match(date2.toDate())) {
695
+ return date2;
696
+ }
697
+ }
698
+ date2.set("year", date2.getParts().year + 1);
699
+ date2.set("month", months[0]);
700
+ return date2;
701
+ };
702
+ const date = findNextDateIgnoringWeekday();
703
+ const weekdays = this.expressions[5];
704
+ let currentWeekday = parseInt((0, week_day_names_conversion_1.default)(date.getParts().weekday));
705
+ while (!(weekdays.indexOf(currentWeekday) > -1)) {
706
+ date.set("year", date.getParts().year + 1);
707
+ currentWeekday = parseInt((0, week_day_names_conversion_1.default)(date.getParts().weekday));
708
+ }
709
+ return date;
710
+ }
711
+ };
712
+ exports.MatcherWalker = MatcherWalker;
713
+ function availableValue(values, currentValue) {
714
+ const availableValues = values.sort((a, b) => a - b).filter((s) => s > currentValue);
715
+ if (availableValues.length > 0)
716
+ return availableValues[0];
717
+ return false;
718
+ }
719
+ }
720
+ });
721
+
722
+ // node_modules/node-cron/dist/esm/time/time-matcher.js
723
+ var require_time_matcher = __commonJS({
724
+ "node_modules/node-cron/dist/esm/time/time-matcher.js"(exports) {
725
+ "use strict";
726
+ var __importDefault = exports && exports.__importDefault || function(mod) {
727
+ return mod && mod.__esModule ? mod : { "default": mod };
728
+ };
729
+ Object.defineProperty(exports, "__esModule", { value: true });
730
+ exports.TimeMatcher = void 0;
731
+ var index_1 = __importDefault(require_convertion());
732
+ var week_day_names_conversion_1 = __importDefault(require_week_day_names_conversion());
733
+ var localized_time_1 = require_localized_time();
734
+ var matcher_walker_1 = require_matcher_walker();
735
+ function matchValue(allowedValues, value) {
736
+ return allowedValues.indexOf(value) !== -1;
737
+ }
738
+ var TimeMatcher = class {
739
+ timezone;
740
+ pattern;
741
+ expressions;
742
+ constructor(pattern, timezone) {
743
+ this.timezone = timezone;
744
+ this.pattern = pattern;
745
+ this.expressions = (0, index_1.default)(pattern);
746
+ }
747
+ match(date) {
748
+ const localizedTime = new localized_time_1.LocalizedTime(date, this.timezone);
749
+ const parts = localizedTime.getParts();
750
+ const runOnSecond = matchValue(this.expressions[0], parts.second);
751
+ const runOnMinute = matchValue(this.expressions[1], parts.minute);
752
+ const runOnHour = matchValue(this.expressions[2], parts.hour);
753
+ const runOnDay = matchValue(this.expressions[3], parts.day);
754
+ const runOnMonth = matchValue(this.expressions[4], parts.month);
755
+ const runOnWeekDay = matchValue(this.expressions[5], parseInt((0, week_day_names_conversion_1.default)(parts.weekday)));
756
+ return runOnSecond && runOnMinute && runOnHour && runOnDay && runOnMonth && runOnWeekDay;
757
+ }
758
+ getNextMatch(date) {
759
+ const walker = new matcher_walker_1.MatcherWalker(this.pattern, date, this.timezone);
760
+ const next = walker.matchNext();
761
+ return next.toDate();
762
+ }
763
+ };
764
+ exports.TimeMatcher = TimeMatcher;
765
+ }
766
+ });
767
+
768
+ // node_modules/node-cron/dist/esm/tasks/state-machine.js
769
+ var require_state_machine = __commonJS({
770
+ "node_modules/node-cron/dist/esm/tasks/state-machine.js"(exports) {
771
+ "use strict";
772
+ Object.defineProperty(exports, "__esModule", { value: true });
773
+ exports.StateMachine = void 0;
774
+ var allowedTransitions = {
775
+ "stopped": ["stopped", "idle", "destroyed"],
776
+ "idle": ["idle", "running", "stopped", "destroyed"],
777
+ "running": ["running", "idle", "stopped", "destroyed"],
778
+ "destroyed": ["destroyed"]
779
+ };
780
+ var StateMachine = class {
781
+ state;
782
+ constructor(initial = "stopped") {
783
+ this.state = initial;
784
+ }
785
+ changeState(state) {
786
+ if (allowedTransitions[this.state].includes(state)) {
787
+ this.state = state;
788
+ } else {
789
+ throw new Error(`invalid transition from ${this.state} to ${state}`);
790
+ }
791
+ }
792
+ };
793
+ exports.StateMachine = StateMachine;
794
+ }
795
+ });
796
+
797
+ // node_modules/node-cron/dist/esm/tasks/inline-scheduled-task.js
798
+ var require_inline_scheduled_task = __commonJS({
799
+ "node_modules/node-cron/dist/esm/tasks/inline-scheduled-task.js"(exports) {
800
+ "use strict";
801
+ var __importDefault = exports && exports.__importDefault || function(mod) {
802
+ return mod && mod.__esModule ? mod : { "default": mod };
803
+ };
804
+ Object.defineProperty(exports, "__esModule", { value: true });
805
+ exports.InlineScheduledTask = void 0;
806
+ var events_1 = __importDefault(__require("events"));
807
+ var runner_1 = require_runner();
808
+ var time_matcher_1 = require_time_matcher();
809
+ var create_id_1 = require_create_id();
810
+ var state_machine_1 = require_state_machine();
811
+ var logger_1 = __importDefault(require_logger());
812
+ var localized_time_1 = require_localized_time();
813
+ var TaskEmitter = class extends events_1.default {
814
+ };
815
+ var InlineScheduledTask = class {
816
+ emitter;
817
+ cronExpression;
818
+ timeMatcher;
819
+ runner;
820
+ id;
821
+ name;
822
+ stateMachine;
823
+ timezone;
824
+ constructor(cronExpression, taskFn, options) {
825
+ this.emitter = new TaskEmitter();
826
+ this.cronExpression = cronExpression;
827
+ this.id = (0, create_id_1.createID)("task", 12);
828
+ this.name = options?.name || this.id;
829
+ this.timezone = options?.timezone;
830
+ this.timeMatcher = new time_matcher_1.TimeMatcher(cronExpression, options?.timezone);
831
+ this.stateMachine = new state_machine_1.StateMachine();
832
+ const runnerOptions = {
833
+ timezone: options?.timezone,
834
+ noOverlap: options?.noOverlap,
835
+ maxExecutions: options?.maxExecutions,
836
+ maxRandomDelay: options?.maxRandomDelay,
837
+ beforeRun: (date, execution) => {
838
+ if (execution.reason === "scheduled") {
839
+ this.changeState("running");
840
+ }
841
+ this.emitter.emit("execution:started", this.createContext(date, execution));
842
+ return true;
843
+ },
844
+ onFinished: (date, execution) => {
845
+ if (execution.reason === "scheduled") {
846
+ this.changeState("idle");
847
+ }
848
+ this.emitter.emit("execution:finished", this.createContext(date, execution));
849
+ return true;
850
+ },
851
+ onError: (date, error, execution) => {
852
+ logger_1.default.error(error);
853
+ this.emitter.emit("execution:failed", this.createContext(date, execution));
854
+ this.changeState("idle");
855
+ },
856
+ onOverlap: (date) => {
857
+ this.emitter.emit("execution:overlap", this.createContext(date));
858
+ },
859
+ onMissedExecution: (date) => {
860
+ this.emitter.emit("execution:missed", this.createContext(date));
861
+ },
862
+ onMaxExecutions: (date) => {
863
+ this.emitter.emit("execution:maxReached", this.createContext(date));
864
+ this.destroy();
865
+ }
866
+ };
867
+ this.runner = new runner_1.Runner(this.timeMatcher, (date, execution) => {
868
+ return taskFn(this.createContext(date, execution));
869
+ }, runnerOptions);
870
+ }
871
+ getNextRun() {
872
+ if (this.stateMachine.state !== "stopped") {
873
+ return this.runner.nextRun();
874
+ }
875
+ return null;
876
+ }
877
+ changeState(state) {
878
+ if (this.runner.isStarted()) {
879
+ this.stateMachine.changeState(state);
880
+ }
881
+ }
882
+ start() {
883
+ if (this.runner.isStopped()) {
884
+ this.runner.start();
885
+ this.stateMachine.changeState("idle");
886
+ this.emitter.emit("task:started", this.createContext(/* @__PURE__ */ new Date()));
887
+ }
888
+ }
889
+ stop() {
890
+ if (this.runner.isStarted()) {
891
+ this.runner.stop();
892
+ this.stateMachine.changeState("stopped");
893
+ this.emitter.emit("task:stopped", this.createContext(/* @__PURE__ */ new Date()));
894
+ }
895
+ }
896
+ getStatus() {
897
+ return this.stateMachine.state;
898
+ }
899
+ destroy() {
900
+ if (this.stateMachine.state === "destroyed")
901
+ return;
902
+ this.stop();
903
+ this.stateMachine.changeState("destroyed");
904
+ this.emitter.emit("task:destroyed", this.createContext(/* @__PURE__ */ new Date()));
905
+ }
906
+ execute() {
907
+ return new Promise((resolve, reject) => {
908
+ const onFail = (context) => {
909
+ this.off("execution:finished", onFail);
910
+ reject(context.execution?.error);
911
+ };
912
+ const onFinished = (context) => {
913
+ this.off("execution:failed", onFail);
914
+ resolve(context.execution?.result);
915
+ };
916
+ this.once("execution:finished", onFinished);
917
+ this.once("execution:failed", onFail);
918
+ this.runner.execute();
919
+ });
920
+ }
921
+ on(event, fun) {
922
+ this.emitter.on(event, fun);
923
+ }
924
+ off(event, fun) {
925
+ this.emitter.off(event, fun);
926
+ }
927
+ once(event, fun) {
928
+ this.emitter.once(event, fun);
929
+ }
930
+ createContext(executionDate, execution) {
931
+ const localTime = new localized_time_1.LocalizedTime(executionDate, this.timezone);
932
+ const ctx = {
933
+ date: localTime.toDate(),
934
+ dateLocalIso: localTime.toISO(),
935
+ triggeredAt: /* @__PURE__ */ new Date(),
936
+ task: this,
937
+ execution
938
+ };
939
+ return ctx;
940
+ }
941
+ };
942
+ exports.InlineScheduledTask = InlineScheduledTask;
943
+ }
944
+ });
945
+
946
+ // node_modules/node-cron/dist/esm/task-registry.js
947
+ var require_task_registry = __commonJS({
948
+ "node_modules/node-cron/dist/esm/task-registry.js"(exports) {
949
+ "use strict";
950
+ Object.defineProperty(exports, "__esModule", { value: true });
951
+ exports.TaskRegistry = void 0;
952
+ var tasks = /* @__PURE__ */ new Map();
953
+ var TaskRegistry = class {
954
+ add(task) {
955
+ if (this.has(task.id)) {
956
+ throw Error(`task ${task.id} already registred!`);
957
+ }
958
+ tasks.set(task.id, task);
959
+ task.on("task:destroyed", () => {
960
+ this.remove(task);
961
+ });
962
+ }
963
+ get(taskId) {
964
+ return tasks.get(taskId);
965
+ }
966
+ remove(task) {
967
+ if (this.has(task.id)) {
968
+ task?.destroy();
969
+ tasks.delete(task.id);
970
+ }
971
+ }
972
+ all() {
973
+ return tasks;
974
+ }
975
+ has(taskId) {
976
+ return tasks.has(taskId);
977
+ }
978
+ killAll() {
979
+ tasks.forEach((id) => this.remove(id));
980
+ }
981
+ };
982
+ exports.TaskRegistry = TaskRegistry;
983
+ }
984
+ });
985
+
986
+ // node_modules/node-cron/dist/esm/pattern/validation/pattern-validation.js
987
+ var require_pattern_validation = __commonJS({
988
+ "node_modules/node-cron/dist/esm/pattern/validation/pattern-validation.js"(exports) {
989
+ "use strict";
990
+ var __importDefault = exports && exports.__importDefault || function(mod) {
991
+ return mod && mod.__esModule ? mod : { "default": mod };
992
+ };
993
+ Object.defineProperty(exports, "__esModule", { value: true });
994
+ var index_1 = __importDefault(require_convertion());
995
+ var validationRegex = /^(?:\d+|\*|\*\/\d+)$/;
996
+ function isValidExpression(expression, min, max) {
997
+ const options = expression;
998
+ for (const option of options) {
999
+ const optionAsInt = parseInt(option, 10);
1000
+ if (!Number.isNaN(optionAsInt) && (optionAsInt < min || optionAsInt > max) || !validationRegex.test(option))
1001
+ return false;
1002
+ }
1003
+ return true;
1004
+ }
1005
+ function isInvalidSecond(expression) {
1006
+ return !isValidExpression(expression, 0, 59);
1007
+ }
1008
+ function isInvalidMinute(expression) {
1009
+ return !isValidExpression(expression, 0, 59);
1010
+ }
1011
+ function isInvalidHour(expression) {
1012
+ return !isValidExpression(expression, 0, 23);
1013
+ }
1014
+ function isInvalidDayOfMonth(expression) {
1015
+ return !isValidExpression(expression, 1, 31);
1016
+ }
1017
+ function isInvalidMonth(expression) {
1018
+ return !isValidExpression(expression, 1, 12);
1019
+ }
1020
+ function isInvalidWeekDay(expression) {
1021
+ return !isValidExpression(expression, 0, 7);
1022
+ }
1023
+ function validateFields(patterns, executablePatterns) {
1024
+ if (isInvalidSecond(executablePatterns[0]))
1025
+ throw new Error(`${patterns[0]} is a invalid expression for second`);
1026
+ if (isInvalidMinute(executablePatterns[1]))
1027
+ throw new Error(`${patterns[1]} is a invalid expression for minute`);
1028
+ if (isInvalidHour(executablePatterns[2]))
1029
+ throw new Error(`${patterns[2]} is a invalid expression for hour`);
1030
+ if (isInvalidDayOfMonth(executablePatterns[3]))
1031
+ throw new Error(`${patterns[3]} is a invalid expression for day of month`);
1032
+ if (isInvalidMonth(executablePatterns[4]))
1033
+ throw new Error(`${patterns[4]} is a invalid expression for month`);
1034
+ if (isInvalidWeekDay(executablePatterns[5]))
1035
+ throw new Error(`${patterns[5]} is a invalid expression for week day`);
1036
+ }
1037
+ function validate(pattern) {
1038
+ if (typeof pattern !== "string")
1039
+ throw new TypeError("pattern must be a string!");
1040
+ const patterns = pattern.split(" ");
1041
+ const executablePatterns = (0, index_1.default)(pattern);
1042
+ if (patterns.length === 5)
1043
+ patterns.unshift("0");
1044
+ validateFields(patterns, executablePatterns);
1045
+ }
1046
+ exports.default = validate;
1047
+ }
1048
+ });
1049
+
1050
+ // node_modules/node-cron/dist/esm/tasks/background-scheduled-task/background-scheduled-task.js
1051
+ var require_background_scheduled_task = __commonJS({
1052
+ "node_modules/node-cron/dist/esm/tasks/background-scheduled-task/background-scheduled-task.js"(exports) {
1053
+ "use strict";
1054
+ var __importDefault = exports && exports.__importDefault || function(mod) {
1055
+ return mod && mod.__esModule ? mod : { "default": mod };
1056
+ };
1057
+ Object.defineProperty(exports, "__esModule", { value: true });
1058
+ var path_1 = __require("path");
1059
+ var child_process_1 = __require("child_process");
1060
+ var create_id_1 = require_create_id();
1061
+ var stream_1 = __require("stream");
1062
+ var state_machine_1 = require_state_machine();
1063
+ var localized_time_1 = require_localized_time();
1064
+ var logger_1 = __importDefault(require_logger());
1065
+ var time_matcher_1 = require_time_matcher();
1066
+ var daemonPath = (0, path_1.resolve)(__dirname, "daemon.js");
1067
+ var TaskEmitter = class extends stream_1.EventEmitter {
1068
+ };
1069
+ var BackgroundScheduledTask = class {
1070
+ emitter;
1071
+ id;
1072
+ name;
1073
+ cronExpression;
1074
+ taskPath;
1075
+ options;
1076
+ forkProcess;
1077
+ stateMachine;
1078
+ constructor(cronExpression, taskPath, options) {
1079
+ this.cronExpression = cronExpression;
1080
+ this.taskPath = taskPath;
1081
+ this.options = options;
1082
+ this.id = (0, create_id_1.createID)("task");
1083
+ this.name = options?.name || this.id;
1084
+ this.emitter = new TaskEmitter();
1085
+ this.stateMachine = new state_machine_1.StateMachine("stopped");
1086
+ this.on("task:stopped", () => {
1087
+ this.forkProcess?.kill();
1088
+ this.forkProcess = void 0;
1089
+ this.stateMachine.changeState("stopped");
1090
+ });
1091
+ this.on("task:destroyed", () => {
1092
+ this.forkProcess?.kill();
1093
+ this.forkProcess = void 0;
1094
+ this.stateMachine.changeState("destroyed");
1095
+ });
1096
+ }
1097
+ getNextRun() {
1098
+ if (this.stateMachine.state !== "stopped") {
1099
+ const timeMatcher = new time_matcher_1.TimeMatcher(this.cronExpression, this.options?.timezone);
1100
+ return timeMatcher.getNextMatch(/* @__PURE__ */ new Date());
1101
+ }
1102
+ return null;
1103
+ }
1104
+ start() {
1105
+ return new Promise((resolve, reject) => {
1106
+ if (this.forkProcess) {
1107
+ return resolve(void 0);
1108
+ }
1109
+ const timeout = setTimeout(() => {
1110
+ reject(new Error("Start operation timed out"));
1111
+ }, 5e3);
1112
+ try {
1113
+ this.forkProcess = (0, child_process_1.fork)(daemonPath);
1114
+ this.forkProcess.on("error", (err) => {
1115
+ clearTimeout(timeout);
1116
+ reject(new Error(`Error on daemon: ${err.message}`));
1117
+ });
1118
+ this.forkProcess.on("exit", (code, signal) => {
1119
+ if (code !== 0 && signal !== "SIGTERM") {
1120
+ const erro = new Error(`node-cron daemon exited with code ${code || signal}`);
1121
+ logger_1.default.error(erro);
1122
+ clearTimeout(timeout);
1123
+ reject(erro);
1124
+ }
1125
+ });
1126
+ this.forkProcess.on("message", (message) => {
1127
+ if (message.jsonError) {
1128
+ if (message.context?.execution) {
1129
+ message.context.execution.error = deserializeError(message.jsonError);
1130
+ delete message.jsonError;
1131
+ }
1132
+ }
1133
+ if (message.context?.task?.state) {
1134
+ this.stateMachine.changeState(message.context?.task?.state);
1135
+ }
1136
+ if (message.context) {
1137
+ const execution = message.context?.execution;
1138
+ delete execution?.hasError;
1139
+ const context = this.createContext(new Date(message.context.date), execution);
1140
+ this.emitter.emit(message.event, context);
1141
+ }
1142
+ });
1143
+ this.once("task:started", () => {
1144
+ this.stateMachine.changeState("idle");
1145
+ clearTimeout(timeout);
1146
+ resolve(void 0);
1147
+ });
1148
+ this.forkProcess.send({
1149
+ command: "task:start",
1150
+ path: this.taskPath,
1151
+ cron: this.cronExpression,
1152
+ options: this.options
1153
+ });
1154
+ } catch (error) {
1155
+ reject(error);
1156
+ }
1157
+ });
1158
+ }
1159
+ stop() {
1160
+ return new Promise((resolve, reject) => {
1161
+ if (!this.forkProcess) {
1162
+ return resolve(void 0);
1163
+ }
1164
+ const timeoutId = setTimeout(() => {
1165
+ clearTimeout(timeoutId);
1166
+ reject(new Error("Stop operation timed out"));
1167
+ }, 5e3);
1168
+ const cleanupAndResolve = () => {
1169
+ clearTimeout(timeoutId);
1170
+ this.off("task:stopped", onStopped);
1171
+ this.forkProcess = void 0;
1172
+ resolve(void 0);
1173
+ };
1174
+ const onStopped = () => {
1175
+ cleanupAndResolve();
1176
+ };
1177
+ this.once("task:stopped", onStopped);
1178
+ this.forkProcess.send({
1179
+ command: "task:stop"
1180
+ });
1181
+ });
1182
+ }
1183
+ getStatus() {
1184
+ return this.stateMachine.state;
1185
+ }
1186
+ destroy() {
1187
+ return new Promise((resolve, reject) => {
1188
+ if (!this.forkProcess) {
1189
+ return resolve(void 0);
1190
+ }
1191
+ const timeoutId = setTimeout(() => {
1192
+ clearTimeout(timeoutId);
1193
+ reject(new Error("Destroy operation timed out"));
1194
+ }, 5e3);
1195
+ const onDestroy = () => {
1196
+ clearTimeout(timeoutId);
1197
+ this.off("task:destroyed", onDestroy);
1198
+ resolve(void 0);
1199
+ };
1200
+ this.once("task:destroyed", onDestroy);
1201
+ this.forkProcess.send({
1202
+ command: "task:destroy"
1203
+ });
1204
+ });
1205
+ }
1206
+ execute() {
1207
+ return new Promise((resolve, reject) => {
1208
+ if (!this.forkProcess) {
1209
+ return reject(new Error("Cannot execute background task because it hasn't been started yet. Please initialize the task using the start() method before attempting to execute it."));
1210
+ }
1211
+ const timeoutId = setTimeout(() => {
1212
+ cleanupListeners();
1213
+ reject(new Error("Execution timeout exceeded"));
1214
+ }, 5e3);
1215
+ const cleanupListeners = () => {
1216
+ clearTimeout(timeoutId);
1217
+ this.off("execution:finished", onFinished);
1218
+ this.off("execution:failed", onFail);
1219
+ };
1220
+ const onFinished = (context) => {
1221
+ cleanupListeners();
1222
+ resolve(context.execution?.result);
1223
+ };
1224
+ const onFail = (context) => {
1225
+ cleanupListeners();
1226
+ reject(context.execution?.error || new Error("Execution failed without specific error"));
1227
+ };
1228
+ this.once("execution:finished", onFinished);
1229
+ this.once("execution:failed", onFail);
1230
+ this.forkProcess.send({
1231
+ command: "task:execute"
1232
+ });
1233
+ });
1234
+ }
1235
+ on(event, fun) {
1236
+ this.emitter.on(event, fun);
1237
+ }
1238
+ off(event, fun) {
1239
+ this.emitter.off(event, fun);
1240
+ }
1241
+ once(event, fun) {
1242
+ this.emitter.once(event, fun);
1243
+ }
1244
+ createContext(executionDate, execution) {
1245
+ const localTime = new localized_time_1.LocalizedTime(executionDate, this.options?.timezone);
1246
+ const ctx = {
1247
+ date: localTime.toDate(),
1248
+ dateLocalIso: localTime.toISO(),
1249
+ triggeredAt: /* @__PURE__ */ new Date(),
1250
+ task: this,
1251
+ execution
1252
+ };
1253
+ return ctx;
1254
+ }
1255
+ };
1256
+ function deserializeError(str) {
1257
+ const data = JSON.parse(str);
1258
+ const Err = globalThis[data.name] || Error;
1259
+ const err = new Err(data.message);
1260
+ if (data.stack) {
1261
+ err.stack = data.stack;
1262
+ }
1263
+ Object.keys(data).forEach((key) => {
1264
+ if (!["name", "message", "stack"].includes(key)) {
1265
+ err[key] = data[key];
1266
+ }
1267
+ });
1268
+ return err;
1269
+ }
1270
+ exports.default = BackgroundScheduledTask;
1271
+ }
1272
+ });
1273
+
1274
+ // node_modules/node-cron/dist/esm/node-cron.js
1275
+ var require_node_cron = __commonJS({
1276
+ "node_modules/node-cron/dist/esm/node-cron.js"(exports) {
1277
+ var __importDefault = exports && exports.__importDefault || function(mod) {
1278
+ return mod && mod.__esModule ? mod : { "default": mod };
1279
+ };
1280
+ Object.defineProperty(exports, "__esModule", { value: true });
1281
+ exports.nodeCron = exports.getTask = exports.getTasks = void 0;
1282
+ exports.schedule = schedule;
1283
+ exports.createTask = createTask;
1284
+ exports.solvePath = solvePath;
1285
+ exports.validate = validate;
1286
+ var inline_scheduled_task_1 = require_inline_scheduled_task();
1287
+ var task_registry_1 = require_task_registry();
1288
+ var pattern_validation_1 = __importDefault(require_pattern_validation());
1289
+ var background_scheduled_task_1 = __importDefault(require_background_scheduled_task());
1290
+ var path_1 = __importDefault(__require("path"));
1291
+ var url_1 = __require("url");
1292
+ var registry = new task_registry_1.TaskRegistry();
1293
+ function schedule(expression, func, options) {
1294
+ const task = createTask(expression, func, options);
1295
+ task.start();
1296
+ return task;
1297
+ }
1298
+ function createTask(expression, func, options) {
1299
+ let task;
1300
+ if (func instanceof Function) {
1301
+ task = new inline_scheduled_task_1.InlineScheduledTask(expression, func, options);
1302
+ } else {
1303
+ const taskPath = solvePath(func);
1304
+ task = new background_scheduled_task_1.default(expression, taskPath, options);
1305
+ }
1306
+ registry.add(task);
1307
+ return task;
1308
+ }
1309
+ function solvePath(filePath) {
1310
+ if (path_1.default.isAbsolute(filePath))
1311
+ return (0, url_1.pathToFileURL)(filePath).href;
1312
+ if (filePath.startsWith("file://"))
1313
+ return filePath;
1314
+ const stackLines = new Error().stack?.split("\n");
1315
+ if (stackLines) {
1316
+ stackLines?.shift();
1317
+ const callerLine = stackLines?.find((line) => {
1318
+ return line.indexOf(__filename) === -1;
1319
+ });
1320
+ const match = callerLine?.match(/(file:\/\/)?(((\/?)(\w:))?([/\\].+)):\d+:\d+/);
1321
+ if (match) {
1322
+ const dir = `${match[5] ?? ""}${path_1.default.dirname(match[6])}`;
1323
+ return (0, url_1.pathToFileURL)(path_1.default.resolve(dir, filePath)).href;
1324
+ }
1325
+ }
1326
+ throw new Error(`Could not locate task file ${filePath}`);
1327
+ }
1328
+ function validate(expression) {
1329
+ try {
1330
+ (0, pattern_validation_1.default)(expression);
1331
+ return true;
1332
+ } catch (e) {
1333
+ return false;
1334
+ }
1335
+ }
1336
+ exports.getTasks = registry.all;
1337
+ exports.getTask = registry.get;
1338
+ exports.nodeCron = {
1339
+ schedule,
1340
+ createTask,
1341
+ validate,
1342
+ getTasks: exports.getTasks,
1343
+ getTask: exports.getTask
1344
+ };
1345
+ exports.default = exports.nodeCron;
1346
+ }
1347
+ });
1348
+ export default require_node_cron();