@randajan/pulse 0.0.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022-present Jan Randa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # @randajan/pulse
2
+
3
+
4
+ [![NPM](https://img.shields.io/npm/v/@randajan/pulse.svg)](https://www.npmjs.com/package/@randajan/pulse) 
5
+ [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
6
+
7
+
8
+ ---
9
+
10
+ ## Overview
11
+
12
+ **@randajan/pulse** is a tiny, zero‑dependency scheduler that fires your callback at *wall‑clock‑aligned* intervals. It focuses on precision (no drift), clarity and graceful error handling, so you can drive heart‑beat logic, telemetry or background maintenance tasks with just a few lines of code.
13
+
14
+ The package ships dual builds—**ESM** *and* **CommonJS**—and works the same in Node.js and the browser.
15
+
16
+ ### ESM **&** CommonJS ready
17
+
18
+ ```js
19
+ // ESM
20
+ import createPulse, { Pulse } from "@randajan/pulse";
21
+
22
+ // CommonJS
23
+ const createPulse = require("@randajan/pulse");
24
+ ```
25
+
26
+ ---
27
+
28
+ ## Quick start
29
+
30
+ ```js
31
+ import createPulse from "@randajan/pulse";
32
+
33
+ const pulse = createPulse({
34
+ interval: 1000, // 1 second
35
+ onPulse: meta => {
36
+ console.log("tick", meta.runtime, "ms");
37
+ },
38
+ onError: err => console.error("Pulse error:", err),
39
+ autoStart: true // start immediately
40
+ });
41
+
42
+ // Later…
43
+ setTimeout(() => pulse.stop(), 10_000);
44
+ ```
45
+
46
+ Every time **onPulse** runs it receives a fresh metadata object:
47
+
48
+ ```ts
49
+ interface PulseMeta {
50
+ readonly started: Date;
51
+ readonly runtime: number; // ms since started
52
+ readonly warnings: string[];
53
+ warn(w: string | Error): void; // push warning
54
+ }
55
+ ```
56
+
57
+ ---
58
+
59
+ ## `createPulse(options)` — options reference
60
+
61
+ | Option | Type | Required | Default | Description |
62
+ | ----------- | ---------- | -------- | ------------------ | ------------------------------------------------------------------ |
63
+ | `onPulse` | `function` | ✔︎ | — | Async/sync callback executed on each pulse. Receives `PulseMeta`. |
64
+ | `interval` | `number` | ✔︎ | — | Period in ms. Min **50 ms**, max **2 147 483 647 ms** (\~24 days). |
65
+ | `offset` | `number` |   | `0` | Fixed shift applied to every pulse (0 ≤ offset < interval). |
66
+ | `getNow` | `function` |   | `() => Date.now()` | Custom clock—handy for deterministic tests or time travel. |
67
+ | `onError` | `function` |   | `() => {}` | Called when `onPulse` throws or rejects. |
68
+ | `autoStart` | `boolean` |   | `false` | If `true`, the scheduler starts right after construction. |
69
+
70
+ ---
71
+
72
+ ## API
73
+
74
+ | Member | Returns | Description |
75
+ | ---------------------- | --------- | ---------------------------------------------------- |
76
+ | `createPulse(options)` | `Pulse` | Convenience wrapper around `new Pulse(options)`. |
77
+ | `new Pulse(options)` | `Pulse` | Class constructor when you prefer `new`. |
78
+ | `pulse.start()` | `boolean` | Starts the loop; returns `false` if already running. |
79
+ | `pulse.stop()` | `boolean` | Stops the loop; returns `false` if already stopped. |
80
+ | `pulse.state` | `boolean` | `true` = running, `false` = stopped. |
81
+ | `pulse.interval` | `number` | Interval in ms (read‑only). |
82
+ | `pulse.offset` | `number` | Offset in ms (read‑only). |
83
+
84
+ ---
85
+
86
+ ## Why not `setInterval`?
87
+
88
+ `setInterval` drifts: extra work inside the callback pushes the next tick further, eventually desynchronising your schedule. **Pulse** recalculates the next edge *after* each run and keeps the loop tightly aligned to the original wall‑clock grid.
89
+
90
+ ---
91
+
92
+ ## Recipes
93
+
94
+ ### Long delays (> 24 days)
95
+
96
+ JavaScript timers accept at most **2 147 483 647 ms**. To wait longer, chain pulses:
97
+
98
+ ```js
99
+ createPulse({
100
+ interval: 2_147_483_647,
101
+ onPulse: async meta => {
102
+ if (stillWaiting()) return; // keep sleeping…
103
+ // …real logic here
104
+ },
105
+ autoStart: true
106
+ });
107
+ ```
108
+
109
+
110
+ ---
111
+
112
+ ## License
113
+
114
+ MIT © [randajan](https://github.com/randajan)
115
+
@@ -0,0 +1,154 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/index.js
20
+ var index_exports = {};
21
+ __export(index_exports, {
22
+ Pulse: () => Pulse,
23
+ createPulse: () => createPulse,
24
+ default: () => index_default
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
28
+ // src/Pulse.js
29
+ var import_props = require("@randajan/props");
30
+
31
+ // src/const.js
32
+ var vault = /* @__PURE__ */ new WeakMap();
33
+ var blankFn = () => {
34
+ };
35
+
36
+ // src/tools.js
37
+ var is = (type, any) => typeof any === type;
38
+ var valid = (type, any, req = false, msg = "argument") => {
39
+ if (any == null) {
40
+ if (!req) {
41
+ return;
42
+ }
43
+ throw new Error(`${msg} require typeof '${type}'`);
44
+ }
45
+ if (is(type, any)) {
46
+ return any;
47
+ }
48
+ throw new Error(`${msg} is not typeof '${type}'`);
49
+ };
50
+ var validRange = (min, max, any, req = false, msg = "argument") => {
51
+ const num = valid("number", any, req, msg);
52
+ if (num == null) {
53
+ return;
54
+ }
55
+ if (num < min) {
56
+ throw new Error(`${msg} must be greater than ${min}`);
57
+ }
58
+ if (num > max) {
59
+ throw new Error(`${msg} must be less than ${max}`);
60
+ }
61
+ return num;
62
+ };
63
+
64
+ // src/Pulse.js
65
+ var createMetaData = (_) => {
66
+ const p = {};
67
+ const w = [];
68
+ (0, import_props.solid)(p, "started", /* @__PURE__ */ new Date());
69
+ (0, import_props.virtual)(p, "warnings", (_2) => [...w]);
70
+ (0, import_props.virtual)(p, "runtime", (_2) => Date.now() - p.started.getTime());
71
+ (0, import_props.solid)(p, "warn", (warning) => w.push(warning), false);
72
+ return p;
73
+ };
74
+ var createPulse = (options = {}) => new Pulse(options);
75
+ var Pulse = class {
76
+ /**
77
+ * Create a new Pulse instance.
78
+ * @param {PulseOptions} [options={}] See {@link PulseOptions}.
79
+ */
80
+ constructor(options = {}) {
81
+ const _p = {
82
+ state: false
83
+ };
84
+ const onPulse = valid("function", options.onPulse, true, "options.onPulse");
85
+ const interval = validRange(50, 2147483647, options.interval, true, "options.interval");
86
+ const offset = validRange(0, interval, options.offset, false, "options.offset") || 0;
87
+ const getNow = valid("function", options.getNow, false, "options.getNow") || ((_) => Date.now());
88
+ const onError = valid("function", options.onError, false, "options.onError") || blankFn;
89
+ const autoStart = valid("boolean", options.autoStart, false, "options.autoStart") || false;
90
+ _p.plan = async (_) => {
91
+ if (!_p.state || _p.metaData) {
92
+ return;
93
+ }
94
+ const now = getNow();
95
+ const runIn = interval - now % interval + offset;
96
+ _p.timeoutId = setTimeout(_p.run, runIn);
97
+ };
98
+ _p.run = async (_) => {
99
+ if (!_p.state || _p.metaData) {
100
+ return;
101
+ }
102
+ _p.metaData = createMetaData();
103
+ try {
104
+ await onPulse(_p.metaData);
105
+ } catch (err) {
106
+ onError(err);
107
+ }
108
+ delete _p.metaData;
109
+ _p.plan();
110
+ };
111
+ (0, import_props.virtual)(this, "state", (_) => _p.state);
112
+ (0, import_props.solids)(this, {
113
+ interval,
114
+ offset
115
+ });
116
+ vault.set(this, _p);
117
+ process.on("exit", (_) => this.stop());
118
+ if (autoStart) {
119
+ this.start();
120
+ }
121
+ }
122
+ /**
123
+ * Start the pulse loop (no-op if already running).
124
+ * @returns {boolean} `true` if it started now, `false` if it was already running.
125
+ */
126
+ start() {
127
+ const { state } = this;
128
+ if (state) {
129
+ return false;
130
+ }
131
+ const _p = vault.get(this);
132
+ _p.state = true;
133
+ _p.plan();
134
+ return true;
135
+ }
136
+ /**
137
+ * Stop the pulse loop (no-op if already stopped).
138
+ * @returns {boolean} `true` if it stopped now, `false` if it was already stopped.
139
+ */
140
+ stop() {
141
+ const { state } = this;
142
+ if (!state) {
143
+ return false;
144
+ }
145
+ const _p = vault.get(this);
146
+ _p.state = false;
147
+ clearTimeout(_p.timeoutId);
148
+ return true;
149
+ }
150
+ };
151
+
152
+ // src/index.js
153
+ var index_default = createPulse;
154
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/index.js", "../../src/Pulse.js", "../../src/const.js", "../../src/tools.js"],
4
+ "sourcesContent": ["import { createPulse, Pulse } from \"./Pulse\";\n\nexport default createPulse;\n\nexport { createPulse, Pulse }\n", "import { solid, solids, virtual } from \"@randajan/props\";\r\nimport { blankFn, vault } from \"./const\";\r\nimport { valid, validRange } from \"./tools\";\r\n\r\n/**\r\n * Metadata object passed to every pulse callback.\r\n * @typedef {Object} PulseMeta\r\n * @property {Date} started Timestamp when this pulse began.\r\n * @property {string[]} warnings Snapshot of all warnings collected so far.\r\n * @property {number} runtime Milliseconds elapsed since `started`.\r\n * @property {(warning: string|Error) => void} warn Push a warning into the internal list.\r\n */\r\nconst createMetaData = _ => {\r\n const p = {};\r\n const w = [];\r\n solid(p, \"started\", new Date());\r\n virtual(p, \"warnings\", _ => [...w]);\r\n virtual(p, \"runtime\", _ => Date.now() - p.started.getTime());\r\n solid(p, \"warn\", warning => w.push(warning), false);\r\n return p;\r\n}\r\n\r\n/**\r\n * Configuration object for {@link Pulse}.\r\n * @typedef {Object} PulseOptions\r\n * @property {(meta: PulseMeta) => (void|Promise<void>)} onPulse **required** \u2013 user callback invoked on every pulse.\r\n * @property {number} interval **required** \u2013 period length in ms (50 \u2013 2 147 483 647).\r\n * @property {number} [offset=0] Shift in ms applied to the start of each interval (0 \u2264 offset < interval).\r\n * @property {() => number} [getNow=() => Date.now()] Custom time source, useful for tests or time travel.\r\n * @property {(err: unknown) => void} [onError=blankFn] Error handler for exceptions or rejected `onPulse` promises.\r\n * @property {boolean} [autoStart=false] If true, the loop starts immediately after construction.\r\n */\r\n\r\n/**\r\n * Factory helper \u2013 simply calls `new Pulse(options)`.\r\n * @param {PulseOptions} [options={}] See {@link PulseOptions}.\r\n * @returns {Pulse}\r\n */\r\nexport const createPulse = (options = {}) => new Pulse(options);\r\n\r\n/**\r\n * Periodic scheduler that aligns each callback to exact multiples\r\n * of the given interval (optionally shifted by `offset`).\r\n */\r\nexport class Pulse {\r\n\r\n /**\r\n * Create a new Pulse instance.\r\n * @param {PulseOptions} [options={}] See {@link PulseOptions}.\r\n */\r\n constructor(options = {}) {\r\n const _p = {\r\n state: false,\r\n }\r\n\r\n const onPulse = valid(\"function\", options.onPulse, true, \"options.onPulse\");\r\n const interval = validRange(50, 2_147_483_647, options.interval, true, \"options.interval\");\r\n const offset = (validRange(0, interval, options.offset, false, \"options.offset\") || 0);\r\n const getNow = valid(\"function\", options.getNow, false, \"options.getNow\") || (_ => Date.now());\r\n const onError = valid(\"function\", options.onError, false, \"options.onError\") || blankFn;\r\n const autoStart = valid(\"boolean\", options.autoStart, false, \"options.autoStart\") || false;\r\n\r\n _p.plan = async _ => {\r\n if (!_p.state || _p.metaData) { return; }\r\n const now = getNow();\r\n const runIn = (interval - now % interval) + offset;\r\n _p.timeoutId = setTimeout(_p.run, runIn);\r\n }\r\n\r\n _p.run = async _ => {\r\n if (!_p.state || _p.metaData) { return; }\r\n _p.metaData = createMetaData();\r\n try { await onPulse(_p.metaData); }\r\n catch (err) { onError(err); }\r\n delete _p.metaData;\r\n _p.plan();\r\n }\r\n\r\n virtual(this, \"state\", _ => _p.state);\r\n solids(this, {\r\n interval,\r\n offset\r\n });\r\n\r\n vault.set(this, _p);\r\n\r\n process.on(\"exit\", _ => this.stop());\r\n if (autoStart) { this.start(); }\r\n }\r\n\r\n /**\r\n * Start the pulse loop (no-op if already running).\r\n * @returns {boolean} `true` if it started now, `false` if it was already running.\r\n */\r\n start() {\r\n const { state } = this;\r\n if (state) { return false; }\r\n const _p = vault.get(this);\r\n _p.state = true;\r\n _p.plan();\r\n return true;\r\n }\r\n\r\n /**\r\n * Stop the pulse loop (no-op if already stopped).\r\n * @returns {boolean} `true` if it stopped now, `false` if it was already stopped.\r\n */\r\n stop() {\r\n const { state } = this;\r\n if (!state) { return false; }\r\n const _p = vault.get(this);\r\n _p.state = false;\r\n clearTimeout(_p.timeoutId);\r\n return true;\r\n }\r\n\r\n\r\n}", "\r\n\r\n\r\nexport const vault = new WeakMap();\r\n\r\nexport const blankFn = ()=>{};", "\r\n\r\nexport const is = (type, any)=>typeof any === type;\r\n\r\nexport const valid = (type, any, req=false, msg=\"argument\")=>{\r\n if (any == null) {\r\n if (!req) { return; }\r\n throw new Error(`${msg} require typeof '${type}'`);\r\n }\r\n if (is(type, any)) { return any; }\r\n throw new Error(`${msg} is not typeof '${type}'`);\r\n}\r\n\r\nexport const validRange = (min, max, any, req=false, msg=\"argument\")=>{\r\n const num = valid(\"number\", any, req, msg);\r\n if (num == null) { return; }\r\n if (num < min) { throw new Error(`${msg} must be greater than ${min}`); }\r\n if (num > max) { throw new Error(`${msg} must be less than ${max}`); }\r\n return num;\r\n}"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAAuC;;;ACGhC,IAAM,QAAQ,oBAAI,QAAQ;AAE1B,IAAM,UAAU,MAAI;AAAC;;;ACHrB,IAAM,KAAK,CAAC,MAAM,QAAM,OAAO,QAAQ;AAEvC,IAAM,QAAQ,CAAC,MAAM,KAAK,MAAI,OAAO,MAAI,eAAa;AACzD,MAAI,OAAO,MAAM;AACb,QAAI,CAAC,KAAK;AAAE;AAAA,IAAQ;AACpB,UAAM,IAAI,MAAM,GAAG,GAAG,oBAAoB,IAAI,GAAG;AAAA,EACrD;AACA,MAAI,GAAG,MAAM,GAAG,GAAG;AAAE,WAAO;AAAA,EAAK;AACjC,QAAM,IAAI,MAAM,GAAG,GAAG,mBAAmB,IAAI,GAAG;AACpD;AAEO,IAAM,aAAa,CAAC,KAAK,KAAK,KAAK,MAAI,OAAO,MAAI,eAAa;AAClE,QAAM,MAAM,MAAM,UAAU,KAAK,KAAK,GAAG;AACzC,MAAI,OAAO,MAAM;AAAE;AAAA,EAAQ;AAC3B,MAAI,MAAM,KAAK;AAAE,UAAM,IAAI,MAAM,GAAG,GAAG,yBAAyB,GAAG,EAAE;AAAA,EAAG;AACxE,MAAI,MAAM,KAAK;A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IAC3C;AAEA,OAAG,MAAM,OAAM,MAAK;AAChB,UAAI,CAAC,GAAG,SAAS,GAAG,UAAU;AAAE;AAAA,MAAQ;AACxC,SAAG,WAAW,eAAe;AAC7B,UAAI;AAAE,cAAM,QAAQ,GAAG,QAAQ;AAAA,MAAG,SAC3B,KAAK;AAAE,gBAAQ,GAAG;AAAA,MAAG;AAC5B,aAAO,GAAG;AACV,SAAG,KAAK;AAAA,IACZ;AAEA,8BAAQ,MAAM,SAAS,OAAK,GAAG,KAAK;AACpC,6BAAO,MAAM;AAAA,MACT;AAAA,MACA;AAAA,IACJ,CAAC;AAED,UAAM,IAAI,MAAM,EAAE;AAElB,YAAQ,GAAG,QAAQ,OAAK,KAAK,KAAK,CAAC;AACnC,QAAI,WAAW;AAAE,WAAK,MAAM;AAAA,IAAG;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAQ;AACJ,UAAM,EAAE,MAAM,IAAI;AAClB,QAAI,OAAO;AAAE,aAAO;AAAA,IAAO;AAC3B,UAAM,KAAK,MAAM,IAAI,IAAI;AACzB,OAAG,QAAQ;AACX,OAAG,KAAK;AACR,WAAO;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,OAAO;AACH,UAAM,EAAE,MAAM,IAAI;AAClB,QAAI,CAAC,OAAO;AAAE,aAAO;AAAA,IAAO;AAC5B,UAAM,KAAK,MAAM,IAAI,IAAI;AACzB,OAAG,QAAQ;AACX,iBAAa,GAAG,SAAS;AACzB,WAAO;AAAA,EACX;AAGJ;;;ADnHA,IAAO,gBAAQ;",
6
+ "names": ["_"]
7
+ }
@@ -0,0 +1,132 @@
1
+ // src/Pulse.js
2
+ import { solid, solids, virtual } from "@randajan/props";
3
+
4
+ // src/const.js
5
+ var vault = /* @__PURE__ */ new WeakMap();
6
+ var blankFn = () => {
7
+ };
8
+
9
+ // src/tools.js
10
+ var is = (type, any) => typeof any === type;
11
+ var valid = (type, any, req = false, msg = "argument") => {
12
+ if (any == null) {
13
+ if (!req) {
14
+ return;
15
+ }
16
+ throw new Error(`${msg} require typeof '${type}'`);
17
+ }
18
+ if (is(type, any)) {
19
+ return any;
20
+ }
21
+ throw new Error(`${msg} is not typeof '${type}'`);
22
+ };
23
+ var validRange = (min, max, any, req = false, msg = "argument") => {
24
+ const num = valid("number", any, req, msg);
25
+ if (num == null) {
26
+ return;
27
+ }
28
+ if (num < min) {
29
+ throw new Error(`${msg} must be greater than ${min}`);
30
+ }
31
+ if (num > max) {
32
+ throw new Error(`${msg} must be less than ${max}`);
33
+ }
34
+ return num;
35
+ };
36
+
37
+ // src/Pulse.js
38
+ var createMetaData = (_) => {
39
+ const p = {};
40
+ const w = [];
41
+ solid(p, "started", /* @__PURE__ */ new Date());
42
+ virtual(p, "warnings", (_2) => [...w]);
43
+ virtual(p, "runtime", (_2) => Date.now() - p.started.getTime());
44
+ solid(p, "warn", (warning) => w.push(warning), false);
45
+ return p;
46
+ };
47
+ var createPulse = (options = {}) => new Pulse(options);
48
+ var Pulse = class {
49
+ /**
50
+ * Create a new Pulse instance.
51
+ * @param {PulseOptions} [options={}] See {@link PulseOptions}.
52
+ */
53
+ constructor(options = {}) {
54
+ const _p = {
55
+ state: false
56
+ };
57
+ const onPulse = valid("function", options.onPulse, true, "options.onPulse");
58
+ const interval = validRange(50, 2147483647, options.interval, true, "options.interval");
59
+ const offset = validRange(0, interval, options.offset, false, "options.offset") || 0;
60
+ const getNow = valid("function", options.getNow, false, "options.getNow") || ((_) => Date.now());
61
+ const onError = valid("function", options.onError, false, "options.onError") || blankFn;
62
+ const autoStart = valid("boolean", options.autoStart, false, "options.autoStart") || false;
63
+ _p.plan = async (_) => {
64
+ if (!_p.state || _p.metaData) {
65
+ return;
66
+ }
67
+ const now = getNow();
68
+ const runIn = interval - now % interval + offset;
69
+ _p.timeoutId = setTimeout(_p.run, runIn);
70
+ };
71
+ _p.run = async (_) => {
72
+ if (!_p.state || _p.metaData) {
73
+ return;
74
+ }
75
+ _p.metaData = createMetaData();
76
+ try {
77
+ await onPulse(_p.metaData);
78
+ } catch (err) {
79
+ onError(err);
80
+ }
81
+ delete _p.metaData;
82
+ _p.plan();
83
+ };
84
+ virtual(this, "state", (_) => _p.state);
85
+ solids(this, {
86
+ interval,
87
+ offset
88
+ });
89
+ vault.set(this, _p);
90
+ process.on("exit", (_) => this.stop());
91
+ if (autoStart) {
92
+ this.start();
93
+ }
94
+ }
95
+ /**
96
+ * Start the pulse loop (no-op if already running).
97
+ * @returns {boolean} `true` if it started now, `false` if it was already running.
98
+ */
99
+ start() {
100
+ const { state } = this;
101
+ if (state) {
102
+ return false;
103
+ }
104
+ const _p = vault.get(this);
105
+ _p.state = true;
106
+ _p.plan();
107
+ return true;
108
+ }
109
+ /**
110
+ * Stop the pulse loop (no-op if already stopped).
111
+ * @returns {boolean} `true` if it stopped now, `false` if it was already stopped.
112
+ */
113
+ stop() {
114
+ const { state } = this;
115
+ if (!state) {
116
+ return false;
117
+ }
118
+ const _p = vault.get(this);
119
+ _p.state = false;
120
+ clearTimeout(_p.timeoutId);
121
+ return true;
122
+ }
123
+ };
124
+
125
+ // src/index.js
126
+ var index_default = createPulse;
127
+ export {
128
+ Pulse,
129
+ createPulse,
130
+ index_default as default
131
+ };
132
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/Pulse.js", "../../src/const.js", "../../src/tools.js", "../../src/index.js"],
4
+ "sourcesContent": ["import { solid, solids, virtual } from \"@randajan/props\";\r\nimport { blankFn, vault } from \"./const\";\r\nimport { valid, validRange } from \"./tools\";\r\n\r\n/**\r\n * Metadata object passed to every pulse callback.\r\n * @typedef {Object} PulseMeta\r\n * @property {Date} started Timestamp when this pulse began.\r\n * @property {string[]} warnings Snapshot of all warnings collected so far.\r\n * @property {number} runtime Milliseconds elapsed since `started`.\r\n * @property {(warning: string|Error) => void} warn Push a warning into the internal list.\r\n */\r\nconst createMetaData = _ => {\r\n const p = {};\r\n const w = [];\r\n solid(p, \"started\", new Date());\r\n virtual(p, \"warnings\", _ => [...w]);\r\n virtual(p, \"runtime\", _ => Date.now() - p.started.getTime());\r\n solid(p, \"warn\", warning => w.push(warning), false);\r\n return p;\r\n}\r\n\r\n/**\r\n * Configuration object for {@link Pulse}.\r\n * @typedef {Object} PulseOptions\r\n * @property {(meta: PulseMeta) => (void|Promise<void>)} onPulse **required** \u2013 user callback invoked on every pulse.\r\n * @property {number} interval **required** \u2013 period length in ms (50 \u2013 2 147 483 647).\r\n * @property {number} [offset=0] Shift in ms applied to the start of each interval (0 \u2264 offset < interval).\r\n * @property {() => number} [getNow=() => Date.now()] Custom time source, useful for tests or time travel.\r\n * @property {(err: unknown) => void} [onError=blankFn] Error handler for exceptions or rejected `onPulse` promises.\r\n * @property {boolean} [autoStart=false] If true, the loop starts immediately after construction.\r\n */\r\n\r\n/**\r\n * Factory helper \u2013 simply calls `new Pulse(options)`.\r\n * @param {PulseOptions} [options={}] See {@link PulseOptions}.\r\n * @returns {Pulse}\r\n */\r\nexport const createPulse = (options = {}) => new Pulse(options);\r\n\r\n/**\r\n * Periodic scheduler that aligns each callback to exact multiples\r\n * of the given interval (optionally shifted by `offset`).\r\n */\r\nexport class Pulse {\r\n\r\n /**\r\n * Create a new Pulse instance.\r\n * @param {PulseOptions} [options={}] See {@link PulseOptions}.\r\n */\r\n constructor(options = {}) {\r\n const _p = {\r\n state: false,\r\n }\r\n\r\n const onPulse = valid(\"function\", options.onPulse, true, \"options.onPulse\");\r\n const interval = validRange(50, 2_147_483_647, options.interval, true, \"options.interval\");\r\n const offset = (validRange(0, interval, options.offset, false, \"options.offset\") || 0);\r\n const getNow = valid(\"function\", options.getNow, false, \"options.getNow\") || (_ => Date.now());\r\n const onError = valid(\"function\", options.onError, false, \"options.onError\") || blankFn;\r\n const autoStart = valid(\"boolean\", options.autoStart, false, \"options.autoStart\") || false;\r\n\r\n _p.plan = async _ => {\r\n if (!_p.state || _p.metaData) { return; }\r\n const now = getNow();\r\n const runIn = (interval - now % interval) + offset;\r\n _p.timeoutId = setTimeout(_p.run, runIn);\r\n }\r\n\r\n _p.run = async _ => {\r\n if (!_p.state || _p.metaData) { return; }\r\n _p.metaData = createMetaData();\r\n try { await onPulse(_p.metaData); }\r\n catch (err) { onError(err); }\r\n delete _p.metaData;\r\n _p.plan();\r\n }\r\n\r\n virtual(this, \"state\", _ => _p.state);\r\n solids(this, {\r\n interval,\r\n offset\r\n });\r\n\r\n vault.set(this, _p);\r\n\r\n process.on(\"exit\", _ => this.stop());\r\n if (autoStart) { this.start(); }\r\n }\r\n\r\n /**\r\n * Start the pulse loop (no-op if already running).\r\n * @returns {boolean} `true` if it started now, `false` if it was already running.\r\n */\r\n start() {\r\n const { state } = this;\r\n if (state) { return false; }\r\n const _p = vault.get(this);\r\n _p.state = true;\r\n _p.plan();\r\n return true;\r\n }\r\n\r\n /**\r\n * Stop the pulse loop (no-op if already stopped).\r\n * @returns {boolean} `true` if it stopped now, `false` if it was already stopped.\r\n */\r\n stop() {\r\n const { state } = this;\r\n if (!state) { return false; }\r\n const _p = vault.get(this);\r\n _p.state = false;\r\n clearTimeout(_p.timeoutId);\r\n return true;\r\n }\r\n\r\n\r\n}", "\r\n\r\n\r\nexport const vault = new WeakMap();\r\n\r\nexport const blankFn = ()=>{};", "\r\n\r\nexport const is = (type, any)=>typeof any === type;\r\n\r\nexport const valid = (type, any, req=false, msg=\"argument\")=>{\r\n if (any == null) {\r\n if (!req) { return; }\r\n throw new Error(`${msg} require typeof '${type}'`);\r\n }\r\n if (is(type, any)) { return any; }\r\n throw new Error(`${msg} is not typeof '${type}'`);\r\n}\r\n\r\nexport const validRange = (min, max, any, req=false, msg=\"argument\")=>{\r\n const num = valid(\"number\", any, req, msg);\r\n if (num == null) { return; }\r\n if (num < min) { throw new Error(`${msg} must be greater than ${min}`); }\r\n if (num > max) { throw new Error(`${msg} must be less than ${max}`); }\r\n return num;\r\n}", "import { createPulse, Pulse } from \"./Pulse\";\n\n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AK,KAAK,CAAC;AACnC,QAAI,WAAW;AAAE,WAAK,MAAM;AAAA,IAAG;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAQ;AACJ,UAAM,EAAE,MAAM,IAAI;AAClB,QAAI,OAAO;AAAE,aAAO;AAAA,IAAO;AAC3B,UAAM,KAAK,MAAM,IAAI,IAAI;AACzB,OAAG,QAAQ;AACX,OAAG,KAAK;AACR,WAAO;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,OAAO;AACH,UAAM,EAAE,MAAM,IAAI;AAClB,QAAI,CAAC,OAAO;AAAE,aAAO;AAAA,IAAO;AAC5B,UAAM,KAAK,MAAM,IAAI,IAAI;AACzB,OAAG,QAAQ;AACX,iBAAa,GAAG,SAAS;AACzB,WAAO;AAAA,EACX;AAGJ;;;AGnHA,IAAO,gBAAQ;",
6
+ "names": ["_"]
7
+ }
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@randajan/pulse",
3
+ "version": "0.0.2",
4
+ "description": "Lightweight, promise-friendly scheduler that outperforms classic cron for any interval shorter than one month.",
5
+ "repository": "randajan/pulse",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "module": "dist/index.js",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/esm/index.mjs",
12
+ "require": "./dist/cjs/index.cjs"
13
+ }
14
+ },
15
+ "license": "MIT",
16
+ "devDependencies": {
17
+ "@randajan/simple-lib": "^3.2.0"
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "keywords": [
25
+ "scheduler",
26
+ "cron",
27
+ "cron-alternative",
28
+ "job-scheduling",
29
+ "interval-timer",
30
+ "sub-monthly",
31
+ "promise-friendly",
32
+ "zero-dependency",
33
+ "nodejs",
34
+ "pulse"
35
+ ],
36
+ "homepage": "https://github.com/randajan/pulse",
37
+ "bugs": {
38
+ "url": "https://github.com/randajan/pulse/issues"
39
+ },
40
+ "author": {
41
+ "name": "Jan Randa",
42
+ "email": "jnranda@gmail.com",
43
+ "url": "https://www.linkedin.com/in/randajan/"
44
+ },
45
+ "dependencies": {
46
+ "@randajan/props": "^0.1.4"
47
+ }
48
+ }