cron 3.1.4 → 3.1.5

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/CHANGELOG.md CHANGED
@@ -1,3 +1,29 @@
1
+ ## [3.1.5](https://github.com/kelektiv/node-cron/compare/v3.1.4...v3.1.5) (2023-10-26)
2
+
3
+
4
+ ### 🐛 Bug Fixes
5
+
6
+ * detect multiple zeros as an invalid step ([#743](https://github.com/kelektiv/node-cron/issues/743)) [skip ci] ([b0bf677](https://github.com/kelektiv/node-cron/commit/b0bf677ee7b7c322dbe2c9feb13257787edc4fb8))
7
+ * re-add runOnce property to CronJob ([#751](https://github.com/kelektiv/node-cron/issues/751)) ([a61d8c9](https://github.com/kelektiv/node-cron/commit/a61d8c95057b6055a2fe0f18896a098f5d0266e0))
8
+
9
+
10
+ ### 📚 Documentation
11
+
12
+ * **readme:** API documentation overhaul ([#716](https://github.com/kelektiv/node-cron/issues/716)) [skip ci] ([23fb0a3](https://github.com/kelektiv/node-cron/commit/23fb0a383fc5dea2f677d69638a1c34ec49b6425))
13
+
14
+
15
+ ### ⚙️ Continuous Integrations
16
+
17
+ * **action:** update actions/setup-node action to v4 ([#749](https://github.com/kelektiv/node-cron/issues/749)) ([ef850f3](https://github.com/kelektiv/node-cron/commit/ef850f32f0b429825e2bea59fedbf53fa0053894))
18
+
19
+
20
+ ### ♻️ Chores
21
+
22
+ * **deps:** update dependency [@commitlint](https://github.com/commitlint)/cli to v18 ([#747](https://github.com/kelektiv/node-cron/issues/747)) ([5ff1cf8](https://github.com/kelektiv/node-cron/commit/5ff1cf826b376b1c3a03003b771ce8ca96edfaf5))
23
+ * **deps:** update dependency sinon to v17 ([#748](https://github.com/kelektiv/node-cron/issues/748)) ([9d61ff9](https://github.com/kelektiv/node-cron/commit/9d61ff976371ebf93bcfedf8386ba4fe426dcac5))
24
+ * **deps:** update linters ([7bdc726](https://github.com/kelektiv/node-cron/commit/7bdc726e8960d89b489a648eb5918090c7ee01c9))
25
+ * improve ossf scorecard's score ([#715](https://github.com/kelektiv/node-cron/issues/715)) [skip ci] ([1284df4](https://github.com/kelektiv/node-cron/commit/1284df476ec7bbcbc6493ab38af4cb4d3542580b))
26
+
1
27
  ## [3.1.4](https://github.com/kelektiv/node-cron/compare/v3.1.3...v3.1.4) (2023-10-24)
2
28
 
3
29
 
package/README.md CHANGED
@@ -1,94 +1,132 @@
1
1
  <p align="center">
2
- <img src="logo.svg" alt="Node Cron Alarm Clock Star Logo" width="100" />
2
+ <img src="logo.svg" alt="cron for Node.js logo" height="150">
3
+ <br />
4
+ <b>cron</b> is a robust tool for running jobs (functions or commands) on schedules defined using the cron syntax.
5
+ <br />
6
+ Perfect for tasks like data backups, notifications, and many more!
3
7
  </p>
4
8
 
5
- # node-cron
9
+ # Cron for Node.js
6
10
 
7
- [![Version](https://badgen.net/npm/v/cron?icon=npm)](https://badgen.net/npm/v/cron)
8
- [![Build Status](https://badgen.net/github/status/kelektiv/node-cron?icon=github)](https://badgen.net/github/status/kelektiv/node-cron)
9
- [![Build Checks](https://badgen.net/github/checks/kelektiv/node-cron?icon=github)](https://badgen.net/github/checks/kelektiv/node-cron)
10
- [![Dependency Status](https://badgen.net/david/dep/kelektiv/node-cron)](https://badgen.net/david/dev/kelektiv/node-cron)
11
- [![Code Coverage](https://badgen.net/codecov/c/github/kelektiv/node-cron?icon=codecov)](https://badgen.net/codecov/c/github/kelektiv/node-cron)
12
- [![Known Vulnerabilities](https://snyk.io/test/github/kelektiv/node-cron/badge.svg)](https://snyk.io/test/github/kelektiv/node-cron)
13
- [![Minified size](https://badgen.net/bundlephobia/min/cron)](https://badgen.net/bundlephobia/min/cron)
14
- [![Minzipped size](https://badgen.net/bundlephobia/minzip/cron)](https://badgen.net/bundlephobia/minzip/cron)
15
- [![monthly downloads](https://badgen.net/npm/dm/cron?icon=npm)](https://badgen.net/npm/dm/cron)
11
+ [![Version](https://img.shields.io/npm/v/cron?label=version&logo=npm)](https://www.npmjs.com/package/cron)
12
+ [![Monthly Downloads](https://img.shields.io/npm/dm/cron?logo=npm)](https://www.npmjs.com/package/cron)
13
+ [![Build Status](https://img.shields.io/github/actions/workflow/status/kelektiv/node-cron/release.yml?logo=github)](https://github.com/kelektiv/node-cron/actions/workflows/release.yml)
14
+ [![CodeQL Status](https://img.shields.io/github/actions/workflow/status/kelektiv/node-cron/codeql.yml?logo=github&label=CodeQL)](https://github.com/kelektiv/node-cron/actions/workflows/codeql.yml)
15
+ [![Coverage](https://img.shields.io/codecov/c/gh/kelektiv/node-cron?logo=codecov)](https://app.codecov.io/gh/kelektiv/node-cron)
16
+ [![Renovate](https://img.shields.io/badge/renovate-enabled-dark_green)](https://github.com/kelektiv/node-cron/issues/718)
17
+ [![OpenSSF Scorecard](https://img.shields.io/ossf-scorecard/github.com/kelektiv/node-cron?label=openssf%20scorecard)](https://securityscorecards.dev/viewer/?uri=github.com/kelektiv/node-cron)
18
+ [![Discord](https://img.shields.io/discord/1075597081017851934?logo=discord)](https://discord.gg/yyKns29zch)
16
19
 
17
- Cron is a tool that allows you to execute _something_ on a schedule. This is typically done using the cron syntax. We allow you to:
20
+ ## 🌟 Features
18
21
 
19
22
  - execute a function whenever your scheduled job triggers
20
23
  - execute a job external to the javascript process (like a system command) using `child_process`
21
24
  - use a Date or Luxon DateTime object instead of cron syntax as the trigger for your callback
22
25
  - use an additional slot for seconds (leaving it off will default to 0 and match the Unix behavior)
23
26
 
24
- ## Installation
27
+ ## 🚀 Installation
25
28
 
26
29
  ```bash
27
30
  npm install cron
28
31
  ```
29
32
 
30
- ## Migrating from v2 to v3
31
-
32
- In version 3 of this library, we migrated to TypeScript, aligned our cron patterns format with the UNIX standard, and released some other breaking changes. See below for the changes you need to make when upgrading:
33
+ ## Table of Contents
34
+
35
+ 1. [Features](#-features)
36
+ 2. [Installation](#-installation)
37
+ 3. [Migrating from v2 to v3](#-migrating-from-v2-to-v3)
38
+ 4. [Basic Usage](#-basic-usage)
39
+ 5. [Cron Patterns](#cron-patterns)
40
+ - [Cron Syntax Overview](#cron-patterns)
41
+ - [Supported Ranges](#supported-ranges)
42
+ 6. [Gotchas](#gotchas)
43
+ 7. [API](#api)
44
+ - [Standalone Functions](#standalone-functions)
45
+ - [CronJob Class](#cronjob-class)
46
+ - [CronTime Class](#crontime-class)
47
+ 8. [Community](#-community)
48
+ - [Join the Community](#-community)
49
+ 9. [Contributing](#-contributing)
50
+ - [General Contribution](#-contributing)
51
+ - [Submitting Bugs/Issues](#-submitting-bugsissues)
52
+ 10. [Acknowledgements](#-acknowledgements)
53
+ 11. [License](#license)
54
+
55
+ ## 🔄 Migrating from v2 to v3
56
+
57
+ With the introduction of TypeScript in version 3 and alignment with UNIX cron patterns, a few changes have been made:
33
58
 
34
59
  <details>
35
60
  <summary>Migrating from v2 to v3</summary>
36
61
 
37
62
  ### Month & day-of-week indexing changes
38
63
 
39
- **Month indexing went from `0-11` to `1-12`. So you need to increment all numeric months by 1.**
64
+ - **Month Indexing:** Changed from `0-11` to `1-12`. So you need to increment all numeric months by 1.
40
65
 
41
- For day-of-week indexing, we only added support for `7` as Sunday, so you don't need to change anything!
66
+ - **Day-of-Week Indexing:** Support added for `7` as Sunday.
42
67
 
43
- ### CronJob changes
68
+ ### Adjustments in `CronJob`
44
69
 
45
- - **constructor no longer accepts an object as its first and only params. Use `CronJob.from(argsObject)` instead.**
46
- - **callbacks are now called in the order they were registered.**
47
- - **`nextDates(count?: number)` now always returns an array (empty if no argument is provided). Use `nextDate()` instead for a single date.**
70
+ - The constructor no longer accepts an object as its first and only params. Use `CronJob.from(argsObject)` instead.
71
+ - Callbacks are now called in the order they were registered.
72
+ - `nextDates(count?: number)` now always returns an array (empty if no argument is provided). Use `nextDate()` instead for a single date.
48
73
 
49
74
  ### Removed methods
50
75
 
51
- - **removed `job()` method in favor of `new CronJob(...args)` / `CronJob.from(argsObject)`**
76
+ - removed `job()` method in favor of `new CronJob(...args)` / `CronJob.from(argsObject)`
52
77
 
53
- - **removed `time()` method in favor of `new CronTime()`**
78
+ - removed `time()` method in favor of `new CronTime()`
54
79
 
55
80
  </details>
56
81
 
57
- ## Usage (basic cron usage)
82
+ ## 🛠 Basic Usage
58
83
 
59
84
  ```javascript
60
85
  import { CronJob } from 'cron';
86
+
61
87
  const job = new CronJob(
62
- '* * * * * *',
88
+ '* * * * * *', // cronTime
63
89
  function () {
64
90
  console.log('You will see this message every second');
65
- },
66
- null,
67
- true,
68
- 'America/Los_Angeles'
91
+ }, // onTick
92
+ null, // onComplete
93
+ true, // start
94
+ 'America/Los_Angeles' // timeZone
69
95
  );
70
- // job.start() - See note below when to use this
96
+ // job.start() is optional here because of the fourth parameter set to true.
97
+ ```
98
+
99
+ ```javascript
100
+ // equivalent job using the "from" static method, providing parameters as an object
101
+ const job = CronJob.from({
102
+ cronTime: '* * * * * *',
103
+ onTick: function () {
104
+ console.log('You will see this message every second');
105
+ },
106
+ start: true,
107
+ timeZone: 'America/Los_Angeles'
108
+ });
71
109
  ```
72
110
 
73
- Note - In the example above, the 4th parameter of `CronJob()` automatically starts the job on initialization. If this parameter is falsy or not provided, the job needs to be explicitly started using `job.start()`.
111
+ > **Note:** In the first example above, the fourth parameter to `CronJob()` starts the job automatically. If not provided or set to falsy, you must explicitly start the job using `job.start()`.
112
+
113
+ For more advanced examples, check the [examples directory](https://github.com/kelektiv/node-cron/tree/main/examples).
74
114
 
75
- There are more examples available in this repository at: [/examples](https://github.com/kelektiv/node-cron/tree/main/examples)
115
+ ## Cron Patterns
76
116
 
77
- ## Available Cron patterns
117
+ Cron patterns are the backbone of this library. Familiarize yourself with the syntax:
78
118
 
79
119
  ```
80
- Asterisks e.g. *
81
- Ranges e.g. 1-3,5
82
- Steps e.g. */2
120
+ - `*` Asterisks: Any value
121
+ - `1-3,5` Ranges: Ranges and individual values
122
+ - `*/2` Steps: Every two units
83
123
  ```
84
124
 
85
- [Read up on cron patterns here](http://crontab.org). Note the examples in the link have five fields, and 1 minute as the finest granularity, but this library has six fields, with 1 second as the finest granularity.
125
+ Detailed patterns and explanations are available at [crontab.org](http://crontab.org). The examples in the link have five fields, and 1 minute as the finest granularity, but our cron scheduling supports an enhanced format with six fields, allowing for second-level precision. Tools like [crontab.guru](https://crontab.guru/) can help in constructing patterns but remember to account for the seconds field.
86
126
 
87
- There are tools that help when constructing your cronjobs. You might find something like https://crontab.guru/ or https://cronjob.xyz/ helpful. But, note that these don't necessarily accept the exact same syntax as this library, for instance, it doesn't accept the `seconds` field, so keep that in mind.
127
+ ### Supported Ranges
88
128
 
89
- ### Cron Ranges
90
-
91
- This library follows the [UNIX Cron format](https://man7.org/linux/man-pages/man5/crontab.5.html), with an added field at the beginning for second granularity.
129
+ Here's a quick reference to the UNIX Cron format this library uses, plus an added second field:
92
130
 
93
131
  ```
94
132
  field allowed values
@@ -106,55 +144,101 @@ day of week 0-7 (0 or 7 is Sunday, or use names)
106
144
 
107
145
  ## Gotchas
108
146
 
109
- - Millisecond level granularity in JS `Date` or Luxon `DateTime` objects: Because computers take time to do things, there may be some delay in execution. This should be on the order of milliseconds. This module doesn't allow MS level granularity for the regular cron syntax, but _does_ allow you to specify a real date of execution in either a javascript `Date` object or a Luxon `DateTime` object. When this happens you may find that you aren't able to execute a job that _should_ run in the future like with `new Date().setMilliseconds(new Date().getMilliseconds() + 1)`. This is due to those cycles of execution above. This wont be the same for everyone because of compute speed. When we tried it locally we saw that somewhere around the 4-5 ms mark was where we got consistent ticks using real dates, but anything less than that would result in an exception. This could be really confusing. We could restrict the granularity for all dates to seconds, but felt that it wasn't a huge problem so long as you were made aware. If this becomes more of an issue, We can revisit it.
110
- - Arrow Functions for `onTick`: Arrow functions get their `this` context from their parent scope. Thus, if you use them, you will not get the `this` context of the cronjob. You can read a little more in issue [GH-47](https://github.com/kelektiv/node-cron/issues/47#issuecomment-459762775)
147
+ - Both JS `Date` and Luxon `DateTime` objects don't guarantee millisecond precision due to computation delays. This module excludes millisecond precision for standard cron syntax but allows execution date specification through JS `Date` or Luxon `DateTime` objects. However, specifying a precise future execution time, such as adding a millisecond to the current time, may not always work due to these computation delays. It's observed that delays less than 4-5 ms might lead to inconsistencies. While we could limit all date granularity to seconds, we've chosen to allow greater precision but advise users of potential issues.
148
+
149
+ - Using arrow functions for `onTick` binds them to the parent's `this` context. As a result, they won't have access to the cronjob's `this` context. You can read a little more in issue [#47 (comment)](https://github.com/kelektiv/node-cron/issues/47#issuecomment-459762775).
111
150
 
112
151
  ## API
113
152
 
114
- Parameter Based
115
-
116
- - `sendAt` - tells you when a `CronTime` will be run.
117
- - `timeout` - tells you when the next timeout is.
118
- - `CronJob`
119
- - `constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout)`
120
- - `cronTime` - [REQUIRED] - The time to fire off your job. This can be in the form of cron syntax or a JS [Date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) object.
121
- - `onTick` - [REQUIRED] - The function to fire at the specified time. If an `onComplete` callback was provided, `onTick` will receive it as an argument. `onTick` may call `onComplete` when it has finished its work.
122
- - `onComplete` - [OPTIONAL] - A function that will fire when the job is stopped with `job.stop()`, and may also be called by `onTick` at the end of each run. **Note for TS users**: This should either be an arrow function, or a regular function cast to `() => void` (bug with generic type inference).
123
- - `start` - [OPTIONAL] - Specifies whether to start the job just before exiting the constructor. By default this is set to false. If left at default you will need to call `job.start()` in order to start the job (assuming `job` is the variable you set the cronjob to). This does not immediately fire your `onTick` function, it just gives you more control over the behavior of your jobs.
124
- - `timeZone` - [OPTIONAL] - Specify the time zone for the execution. This will modify the actual time relative to your time zone. If the time zone is invalid, an error is thrown. By default (if this is omitted) the local time zone will be used. You can check the various time zones format accepted in the [Luxon documentation](https://github.com/moment/luxon/blob/master/docs/zones.md#specifying-a-zone). Note: This parameter supports minutes offsets, e.g. `UTC+5:30`. **Note**: Cannot be used together with `utcOffset`.
125
- - `context` - [OPTIONAL] - The context within which to execute the onTick method. This defaults to the cronjob itself allowing you to call `this.stop()`. However, if you change this you'll have access to the functions and values within your context object.
126
- - `runOnInit` - [OPTIONAL] - This will immediately fire your `onTick` function as soon as the requisite initialization has happened. This option is set to `false` by default for backwards compatibility.
127
- - `utcOffset` - [OPTIONAL] - This allows you to specify the offset of your time zone rather than using the `timeZone` param. This should be an integer representing the number of minutes offset (like `120` for +2 hours or `-90` for -1.5 hours). **Note**: Cannot be used together with `timeZone`.
128
- - `unrefTimeout` - [OPTIONAL] - If you have code that keeps the event loop running and want to stop the node process when that finishes regardless of the state of your cronjob, you can do so making use of this parameter. This is off by default and cron will run as if it needs to control the event loop. For more information take a look at [timers#timers_timeout_unref](https://nodejs.org/api/timers.html#timers_timeout_unref) from the NodeJS docs.
129
- - `from` (static) - Create a new CronJob object providing arguments as an object. See argument names and descriptions above.
130
- - `start` - Runs your job.
131
- - `stop` - Stops your job.
132
- - `setTime` - Stops and changes the time for the `CronJob`. Param must be a `CronTime`.
133
- - `lastDate` - Tells you the last execution date.
134
- - `nextDate` - Provides the next date that will trigger an `onTick`.
135
- - `nextDates(count)` - Provides an array of the next set of dates that will trigger an `onTick`.
136
- - `count` - [OPTIONAL] - The number of next dates to return. Defaults to 0, returning an empty array.
137
- - `fireOnTick` - Allows you to override the `onTick` calling behavior. This matters so only do this if you have a really good reason to do so.
138
- - `addCallback` - Allows you to add `onTick` callbacks. Callbacks are run in the order they are registered.
139
- - `CronTime`
140
- - `constructor(time, zone, utcOffset)`
141
- - `time` - [REQUIRED] - The time to fire off your job. This can be in the form of cron syntax or a JS [Date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) object.
142
- - `zone` - [OPTIONAL] - Same as `timeZone` from `CronJob` parameters.
143
- - `utcOffset` - [OPTIONAL] - Same as `utcOffset` from `CronJob` parameters.
144
-
145
- ## Community
153
+ ### Standalone Functions
154
+
155
+ - `sendAt`: Indicates when a `CronTime` will execute (returns a Luxon `DateTime` object).
156
+
157
+ ```javascript
158
+ import * as cron from 'cron';
159
+
160
+ const dt = cron.sendAt('0 0 * * *');
161
+ console.log(`The job would run at: ${dt.toISO()}`);
162
+ ```
163
+
164
+ - `timeout`: Indicates the number of milliseconds in the future at which a `CronTime` will execute (returns a number).
165
+
166
+ ```javascript
167
+ import * as cron from 'cron';
168
+
169
+ const timeout = cron.timeout('0 0 * * *');
170
+ console.log(`The job would run in ${timeout}ms`);
171
+ ```
172
+
173
+ ### CronJob Class
174
+
175
+ #### Constructor
176
+
177
+ `constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout)`:
178
+
179
+ - `cronTime`: [REQUIRED] - The time to fire off your job. Can be cron syntax, a JS [`Date`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) object or a Luxon [`DateTime`](https://moment.github.io/luxon/api-docs/index.html#datetime) object.
180
+
181
+ - `onTick`: [REQUIRED] - Function to execute at the specified time. If an `onComplete` callback was provided, `onTick` will receive it as an argument.
182
+
183
+ - `onComplete`: [OPTIONAL] - Invoked when the job is halted with `job.stop()`. It might also be triggered by `onTick` post its run.
184
+
185
+ - `start`: [OPTIONAL] - Determines if the job should commence before constructor exit. Default is `false`.
186
+
187
+ - `timeZone`: [OPTIONAL] - Sets the execution time zone. Default is local time. Check valid formats in the [Luxon documentation](https://github.com/moment/luxon/blob/master/docs/zones.md#specifying-a-zone).
188
+
189
+ - `context`: [OPTIONAL] - Execution context for the onTick method.
190
+
191
+ - `runOnInit`: [OPTIONAL] - Instantly triggers the `onTick` function post initialization. Default is `false`.
192
+
193
+ - `utcOffset`: [OPTIONAL] - Specifies time zone offset in minutes. Cannot co-exist with `timeZone`.
194
+
195
+ - `unrefTimeout`: [OPTIONAL] - Useful for controlling event loop behavior. More details [here](https://nodejs.org/api/timers.html#timers_timeout_unref).
196
+
197
+ #### Methods
198
+
199
+ - `from` (static): Create a new CronJob object providing arguments as an object. See argument names and descriptions above.
200
+
201
+ - `start`: Initiates the job.
202
+
203
+ - `stop`: Halts the job.
204
+
205
+ - `setTime`: Modifies the time for the `CronJob`. Parameter must be a `CronTime`.
206
+
207
+ - `lastDate`: Provides the last execution date.
208
+
209
+ - `nextDate`: Indicates the subsequent date that will activate an `onTick`.
210
+
211
+ - `nextDates(count)`: Supplies an array of upcoming dates that will initiate an `onTick`.
212
+
213
+ - `fireOnTick`: Allows modification of the `onTick` calling behavior.
214
+
215
+ - `addCallback`: Permits addition of `onTick` callbacks.
216
+
217
+ ### CronTime Class
218
+
219
+ #### Constructor
220
+
221
+ `constructor(time, zone, utcOffset)`:
222
+
223
+ - `time`: [REQUIRED] - The time to initiate your job. Accepts cron syntax or a JS [Date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) object.
224
+
225
+ - `zone`: [OPTIONAL] - Equivalent to `timeZone` from `CronJob` parameters.
226
+
227
+ - `utcOffset`: [OPTIONAL] - Analogous to `utcOffset` from `CronJob` parameters.
228
+
229
+ ## 🤝 Community
146
230
 
147
231
  Join the [Discord server](https://discord.gg/yyKns29zch)! Here you can discuss issues and get help in a more casual forum than GitHub.
148
232
 
149
- ## Contributing
233
+ ## 🌍 Contributing
150
234
 
151
235
  This project is looking for help! If you're interested in helping with the project, please take a look at our [contributing documentation](https://github.com/kelektiv/node-cron/blob/main/CONTRIBUTING.md).
152
236
 
153
- ### Submitting Bugs/Issues
237
+ ### 🐛 Submitting Bugs/Issues
154
238
 
155
239
  Please have a look at our [contributing documentation](https://github.com/kelektiv/node-cron/blob/main/CONTRIBUTING.md), it contains all the information you need to know before submitting an issue.
156
240
 
157
- ## Acknowledgements
241
+ ## 🙏 Acknowledgements
158
242
 
159
243
  This is a community effort project. In the truest sense, this project started as an open source project from [cron.js](http://github.com/padolsey/cron.js) and grew into something else. Other people have contributed code, time, and oversight to the project. At this point there are too many to name here so we'll just say thanks.
160
244
 
package/dist/errors.d.ts CHANGED
@@ -1,3 +1,5 @@
1
- export declare class ExclusiveParametersError extends Error {
1
+ export declare class CronError extends Error {
2
+ }
3
+ export declare class ExclusiveParametersError extends CronError {
2
4
  constructor(param1: string, param2: string);
3
5
  }
package/dist/errors.js CHANGED
@@ -1,7 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ExclusiveParametersError = void 0;
4
- class ExclusiveParametersError extends Error {
3
+ exports.ExclusiveParametersError = exports.CronError = void 0;
4
+ class CronError extends Error {
5
+ }
6
+ exports.CronError = CronError;
7
+ class ExclusiveParametersError extends CronError {
5
8
  constructor(param1, param2) {
6
9
  super(`You can't specify both ${param1} and ${param2}`);
7
10
  }
package/dist/job.d.ts CHANGED
@@ -7,6 +7,7 @@ export declare class CronJob<OC extends CronOnCompleteCommand | null = null, C =
7
7
  lastExecution: Date | null;
8
8
  context: CronContext<C>;
9
9
  onComplete?: WithOnComplete<OC> extends true ? CronOnCompleteCallback : undefined;
10
+ get runOnce(): boolean;
10
11
  private _timeout?;
11
12
  private _callbacks;
12
13
  constructor(cronTime: CronJobParams<OC, C>['cronTime'], onTick: CronJobParams<OC, C>['onTick'], onComplete?: CronJobParams<OC, C>['onComplete'], start?: CronJobParams<OC, C>['start'], timeZone?: CronJobParams<OC, C>['timeZone'], context?: CronJobParams<OC, C>['context'], runOnInit?: CronJobParams<OC, C>['runOnInit'], utcOffset?: null, unrefTimeout?: CronJobParams<OC, C>['unrefTimeout']);
package/dist/job.js CHANGED
@@ -5,6 +5,9 @@ const child_process_1 = require("child_process");
5
5
  const errors_1 = require("./errors");
6
6
  const time_1 = require("./time");
7
7
  class CronJob {
8
+ get runOnce() {
9
+ return this.cronTime.realDate;
10
+ }
8
11
  constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout) {
9
12
  this.running = false;
10
13
  this.unrefTimeout = false;
@@ -73,7 +76,7 @@ class CronJob {
73
76
  }
74
77
  setTime(time) {
75
78
  if (!(time instanceof time_1.CronTime)) {
76
- throw new Error('time must be an instance of CronTime.');
79
+ throw new errors_1.CronError('time must be an instance of CronTime.');
77
80
  }
78
81
  const wasRunning = this.running;
79
82
  this.stop();
@@ -130,7 +133,7 @@ class CronJob {
130
133
  else {
131
134
  this.lastExecution = new Date();
132
135
  this.running = false;
133
- if (!this.cronTime.realDate) {
136
+ if (!this.runOnce) {
134
137
  this.start();
135
138
  }
136
139
  this.fireOnTick();
package/dist/time.js CHANGED
@@ -20,7 +20,7 @@ class CronTime {
20
20
  if (timeZone) {
21
21
  const dt = luxon_1.DateTime.fromObject({}, { zone: timeZone });
22
22
  if (!dt.isValid) {
23
- throw new Error('Invalid timezone.');
23
+ throw new errors_1.CronError('Invalid timezone.');
24
24
  }
25
25
  this.timeZone = timeZone;
26
26
  }
@@ -85,12 +85,12 @@ class CronTime {
85
85
  const utcZone = `UTC${sign}${offsetHoursStr}:${offsetMinsStr}`;
86
86
  date = date.setZone(utcZone);
87
87
  if (!date.isValid) {
88
- throw new Error('ERROR: You specified an invalid UTC offset.');
88
+ throw new errors_1.CronError('ERROR: You specified an invalid UTC offset.');
89
89
  }
90
90
  }
91
91
  if (this.realDate) {
92
92
  if (luxon_1.DateTime.local() > date) {
93
- throw new Error('WARNING: Date in past. Will never be fired.');
93
+ throw new errors_1.CronError('WARNING: Date in past. Will never be fired.');
94
94
  }
95
95
  return date;
96
96
  }
@@ -133,13 +133,13 @@ class CronTime {
133
133
  }
134
134
  }
135
135
  if (!date.isValid) {
136
- throw new Error('ERROR: You specified an invalid date.');
136
+ throw new errors_1.CronError('ERROR: You specified an invalid date.');
137
137
  }
138
138
  const maxMatch = luxon_1.DateTime.now().plus({ years: 8 });
139
139
  while (true) {
140
140
  const diff = date.toMillis() - start.toMillis();
141
141
  if (date > maxMatch) {
142
- throw new Error(`Something went wrong. No execution date was found in the next 8 years.
142
+ throw new errors_1.CronError(`Something went wrong. No execution date was found in the next 8 years.
143
143
  Please provide the following string if you would like to help debug:
144
144
  Time Zone: ${(_a = timeZone === null || timeZone === void 0 ? void 0 : timeZone.toString()) !== null && _a !== void 0 ? _a : '""'} - Cron String: ${this.source.toString()} - UTC offset: ${date.offset} - current Date: ${luxon_1.DateTime.local().toString()}`);
145
145
  }
@@ -249,7 +249,7 @@ class CronTime {
249
249
  let iteration = 0;
250
250
  do {
251
251
  if (++iteration > iterationLimit) {
252
- throw new Error(`ERROR: This DST checking related function assumes the input DateTime (${(_a = date.toISO()) !== null && _a !== void 0 ? _a : date.toMillis()}) is within 24 hours of a DST jump.`);
252
+ throw new errors_1.CronError(`ERROR: This DST checking related function assumes the input DateTime (${(_a = date.toISO()) !== null && _a !== void 0 ? _a : date.toMillis()}) is within 24 hours of a DST jump.`);
253
253
  }
254
254
  expectedMinute = maybeJumpingPoint.minute - 1;
255
255
  expectedHour = maybeJumpingPoint.hour;
@@ -300,7 +300,7 @@ class CronTime {
300
300
  }
301
301
  _checkTimeInSkippedRangeMultiHour(startHour, startMinute, endHour, endMinute) {
302
302
  if (startHour >= endHour) {
303
- throw new Error(`ERROR: This DST checking related function assumes the forward jump starting hour (${startHour}) is less than the end hour (${endHour})`);
303
+ throw new errors_1.CronError(`ERROR: This DST checking related function assumes the forward jump starting hour (${startHour}) is less than the end hour (${endHour})`);
304
304
  }
305
305
  const firstHourMinuteRange = Array.from({ length: 60 - startMinute }, (_, k) => startMinute + k);
306
306
  const lastHourMinuteRange = Array.from({ length: endMinute }, (_, k) => k);
@@ -365,14 +365,14 @@ class CronTime {
365
365
  if (Object.keys(constants_1.ALIASES).includes(alias)) {
366
366
  return constants_1.ALIASES[alias].toString();
367
367
  }
368
- throw new Error(`Unknown alias: ${alias}`);
368
+ throw new errors_1.CronError(`Unknown alias: ${alias}`);
369
369
  });
370
370
  const units = source.trim().split(/\s+/);
371
371
  if (units.length < constants_1.TIME_UNITS_LEN - 1) {
372
- throw new Error('Too few fields');
372
+ throw new errors_1.CronError('Too few fields');
373
373
  }
374
374
  if (units.length > constants_1.TIME_UNITS_LEN) {
375
- throw new Error('Too many fields');
375
+ throw new errors_1.CronError('Too many fields');
376
376
  }
377
377
  const unitsLen = units.length;
378
378
  for (const unit of constants_1.TIME_UNITS) {
@@ -391,7 +391,7 @@ class CronTime {
391
391
  fields.forEach(field => {
392
392
  const wildcardIndex = field.indexOf('*');
393
393
  if (wildcardIndex !== -1 && wildcardIndex !== 0) {
394
- throw new Error(`Field (${field}) has an invalid wildcard expression`);
394
+ throw new errors_1.CronError(`Field (${field}) has an invalid wildcard expression`);
395
395
  }
396
396
  });
397
397
  value = value.replace(constants_1.RE_WILDCARDS, `${low}-${high}`);
@@ -403,18 +403,18 @@ class CronTime {
403
403
  let lower = parseInt(mLower, 10);
404
404
  let upper = mUpper !== undefined ? parseInt(mUpper, 10) : undefined;
405
405
  const wasStepDefined = mStep !== undefined;
406
- if (mStep === '0') {
407
- throw new Error(`Field (${unit}) has a step of zero`);
408
- }
409
406
  const step = parseInt(mStep !== null && mStep !== void 0 ? mStep : '1', 10);
407
+ if (step === 0) {
408
+ throw new errors_1.CronError(`Field (${unit}) has a step of zero`);
409
+ }
410
410
  if (upper !== undefined && lower > upper) {
411
- throw new Error(`Field (${unit}) has an invalid range`);
411
+ throw new errors_1.CronError(`Field (${unit}) has an invalid range`);
412
412
  }
413
413
  const isOutOfRange = lower < low ||
414
414
  (upper !== undefined && upper > high) ||
415
415
  (upper === undefined && lower > high);
416
416
  if (isOutOfRange) {
417
- throw new Error(`Field value (${value}) is out of range`);
417
+ throw new errors_1.CronError(`Field value (${value}) is out of range`);
418
418
  }
419
419
  lower = Math.min(Math.max(low, ~~Math.abs(lower)), high);
420
420
  if (upper !== undefined) {
@@ -435,7 +435,7 @@ class CronTime {
435
435
  }
436
436
  }
437
437
  else {
438
- throw new Error(`Field (${unit}) cannot be parsed`);
438
+ throw new errors_1.CronError(`Field (${unit}) cannot be parsed`);
439
439
  }
440
440
  }
441
441
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "cron",
3
3
  "description": "Cron jobs for your node",
4
- "version": "3.1.4",
4
+ "version": "3.1.5",
5
5
  "author": "Nick Campbell <nicholas.j.campbell@gmail.com> (https://github.com/ncb000gt)",
6
6
  "bugs": {
7
7
  "url": "https://github.com/kelektiv/node-cron/issues"
@@ -19,6 +19,7 @@
19
19
  "lint:fix": "npm run lint:eslint -- --fix && npm run lint:prettier -- --write",
20
20
  "test": "jest --coverage",
21
21
  "test:watch": "jest --watch --coverage",
22
+ "test:fuzz": "jest --testMatch='**/*.fuzz.ts' --coverage=false --testTimeout=120000",
22
23
  "prepare": "husky install",
23
24
  "release": "semantic-release"
24
25
  },
@@ -27,7 +28,8 @@
27
28
  "luxon": "~3.4.0"
28
29
  },
29
30
  "devDependencies": {
30
- "@commitlint/cli": "17.8.0",
31
+ "@commitlint/cli": "18.0.0",
32
+ "@fast-check/jest": "1.7.3",
31
33
  "@insurgentlab/commitlint-config": "18.1.3",
32
34
  "@insurgentlab/conventional-changelog-preset": "7.0.0",
33
35
  "@semantic-release/changelog": "6.0.3",
@@ -41,15 +43,15 @@
41
43
  "@types/sinon": "10.0.20",
42
44
  "@typescript-eslint/eslint-plugin": "6.8.0",
43
45
  "chai": "4.3.10",
44
- "eslint": "8.51.0",
46
+ "eslint": "8.52.0",
45
47
  "eslint-config-prettier": "9.0.0",
46
- "eslint-plugin-jest": "27.4.2",
48
+ "eslint-plugin-jest": "27.4.3",
47
49
  "eslint-plugin-prettier": "5.0.1",
48
50
  "husky": "8.0.3",
49
51
  "jest": "29.7.0",
50
52
  "prettier": "3.0.3",
51
53
  "semantic-release": "22.0.5",
52
- "sinon": "16.1.3",
54
+ "sinon": "17.0.0",
53
55
  "ts-jest": "29.1.1",
54
56
  "typescript": "5.2.2"
55
57
  },