@chriscdn/promise-semaphore 3.1.3 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,26 +1,14 @@
1
1
  {
2
2
  "name": "@chriscdn/promise-semaphore",
3
- "version": "3.1.3",
3
+ "version": "4.0.0",
4
4
  "description": "Limit or throttle the simultaneous execution of asynchronous code in separate iterations of the event loop.",
5
5
  "repository": "https://github.com/chriscdn/promise-semaphore",
6
6
  "author": "Christopher Meyer <chris@schwiiz.org>",
7
7
  "license": "MIT",
8
8
  "type": "module",
9
- "main": "./lib/index.cjs",
10
- "module": "./lib/index.js",
9
+ "main": "./lib/index.js",
11
10
  "types": "./lib/index.d.ts",
12
- "exports": {
13
- ".": {
14
- "import": {
15
- "types": "./lib/index.d.ts",
16
- "default": "./lib/index.js"
17
- },
18
- "require": {
19
- "types": "./lib/index.d.cts",
20
- "default": "./lib/index.cjs"
21
- }
22
- }
23
- },
11
+ "exports": "./lib/index.js",
24
12
  "scripts": {
25
13
  "build": "tsup",
26
14
  "watch": "yarn build --watch",
package/lib/index.cjs DELETED
@@ -1,207 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- GroupSemaphore: () => GroupSemaphore,
24
- Semaphore: () => Semaphore
25
- });
26
- module.exports = __toCommonJS(index_exports);
27
-
28
- // src/semaphore.ts
29
- var defaultKey = "_default";
30
- var _isPrimitiveKey = (item) => ["string", "number"].includes(typeof item);
31
- var resolveKey = (item) => (_isPrimitiveKey(item) ? item : item.key) ?? defaultKey;
32
- var resolvePriority = (item) => (_isPrimitiveKey(item) ? 0 : item.priority) ?? 0;
33
- var SemaphoreItem = class {
34
- queue;
35
- maxConcurrent;
36
- /**
37
- * The number of locks.
38
- */
39
- count;
40
- constructor(maxConcurrent) {
41
- this.queue = [];
42
- this.maxConcurrent = maxConcurrent;
43
- this.count = 0;
44
- }
45
- get canAcquire() {
46
- return this.count < this.maxConcurrent;
47
- }
48
- incrementCount() {
49
- this.count++;
50
- }
51
- decrementCount() {
52
- this.count--;
53
- }
54
- acquire(priority) {
55
- if (this.canAcquire) {
56
- this.incrementCount();
57
- return Promise.resolve();
58
- } else {
59
- return new Promise((resolve) => {
60
- this.queue.push({ resolve, priority });
61
- this.queue.sort((a, b) => b.priority - a.priority);
62
- });
63
- }
64
- }
65
- release() {
66
- const resolveFunc = this.queue.shift();
67
- if (resolveFunc) {
68
- setTimeout(resolveFunc.resolve, 0);
69
- } else {
70
- this.decrementCount();
71
- }
72
- }
73
- };
74
- var Semaphore = class {
75
- semaphoreInstances;
76
- maxConcurrent;
77
- /**
78
- * @param {number} [maxConcurrent] The maximum number of concurrent locks.
79
- */
80
- constructor(maxConcurrent = 1) {
81
- this.semaphoreInstances = {};
82
- this.maxConcurrent = maxConcurrent;
83
- if (maxConcurrent < 1) {
84
- throw new Error("The maxConcurrent must be 1 or greater.");
85
- }
86
- }
87
- hasSemaphoreInstance(key = defaultKey) {
88
- return Boolean(this.semaphoreInstances[key]);
89
- }
90
- getSemaphoreInstance(key = defaultKey) {
91
- if (!this.hasSemaphoreInstance(key)) {
92
- this.semaphoreInstances[key] = new SemaphoreItem(
93
- this.maxConcurrent
94
- );
95
- }
96
- return this.semaphoreInstances[key];
97
- }
98
- /**
99
- * @param {string | number} [key]- Optional, the semaphore key.
100
- */
101
- tidy(key = defaultKey) {
102
- if (this.hasSemaphoreInstance(key) && this.getSemaphoreInstance(key).count === 0) {
103
- delete this.semaphoreInstances[key];
104
- }
105
- }
106
- /**
107
- * A synchronous function to determine whether a lock can be acquired.
108
- *
109
- * @param {string | number} [key]- Optional, the semaphore key.
110
- * @returns {boolean} Returns true if the lock on `key` can be acquired, false
111
- * otherwise.
112
- */
113
- canAcquire(key = defaultKey) {
114
- const _key = resolveKey(key);
115
- return !this.hasSemaphoreInstance(_key) || this.getSemaphoreInstance(_key).canAcquire;
116
- }
117
- /**
118
- * @param {string | number} [key]- Optional, the semaphore key.
119
- */
120
- acquire(key = defaultKey) {
121
- const _key = resolveKey(key);
122
- const _priority = resolvePriority(key);
123
- return this.getSemaphoreInstance(_key).acquire(_priority);
124
- }
125
- /**
126
- * @param {string | number} [key]- Optional, the semaphore key.
127
- */
128
- release(key = defaultKey) {
129
- const _key = resolveKey(key);
130
- this.getSemaphoreInstance(_key).release();
131
- this.tidy(_key);
132
- }
133
- /**
134
- * The number of active locks. Will always be less or equal to `max`.
135
- *
136
- * @param {string | number} [key]- Optional, the semaphore key.
137
- */
138
- count(key = defaultKey) {
139
- const _key = resolveKey(key);
140
- return this.hasSemaphoreInstance(_key) ? this.getSemaphoreInstance(_key).count : 0;
141
- }
142
- /**
143
- * @param {string | number} [key]- Optional, the semaphore key.
144
- * @returns {boolean} True if the semaphore and key has locks, false otherwise.
145
- */
146
- hasTasks(key = defaultKey) {
147
- return this.count(key) > 0;
148
- }
149
- /**
150
- * @param {Function<T>} fn The function to execute.
151
- * @param {string | number} [key]- Optional, the semaphore key.
152
- * @returns {Promise<T>}
153
- */
154
- async request(fn, key = defaultKey) {
155
- try {
156
- await this.acquire(key);
157
- return await fn();
158
- } finally {
159
- this.release(key);
160
- }
161
- }
162
- /**
163
- * Asynchronously executes `fn` if a lock can be immediately acquired.
164
- * Otherwise, returns null.
165
- *
166
- * @param {Function<T>} fn The function to execute.
167
- * @param {string | number} [key]- Optional, the semaphore key.
168
- * @returns {Promise<T>}
169
- */
170
- async requestIfAvailable(fn, key = defaultKey) {
171
- if (this.canAcquire(key)) {
172
- return this.request(fn, key);
173
- } else {
174
- return null;
175
- }
176
- }
177
- };
178
-
179
- // src/group-semaphore.ts
180
- var GroupSemaphore = class {
181
- _semaphore = new Semaphore();
182
- _activeCounts = {};
183
- _groupWaiters = {};
184
- async acquire(key) {
185
- const activeCount = this._activeCounts[key] ?? 0;
186
- this._activeCounts[key] = activeCount + 1;
187
- const waiter = this._groupWaiters[key] ?? this._semaphore.acquire();
188
- this._groupWaiters[key] = waiter;
189
- await waiter;
190
- }
191
- release(key) {
192
- const activeCount = this._activeCounts[key];
193
- if (activeCount === 1) {
194
- this._semaphore.release();
195
- delete this._activeCounts[key];
196
- delete this._groupWaiters[key];
197
- } else {
198
- this._activeCounts[key] = activeCount - 1;
199
- }
200
- }
201
- };
202
- // Annotate the CommonJS export names for ESM import in node:
203
- 0 && (module.exports = {
204
- GroupSemaphore,
205
- Semaphore
206
- });
207
- //# sourceMappingURL=index.cjs.map
package/lib/index.cjs.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts","../src/semaphore.ts","../src/group-semaphore.ts"],"sourcesContent":["export { Semaphore } from \"./semaphore\";\nexport { GroupSemaphore } from \"./group-semaphore\";\n","const defaultKey = \"_default\";\n\ntype KeyPrimitive = string | number;\n\ntype Key = KeyPrimitive | { key?: KeyPrimitive };\ntype KeyOptions = Key & { priority?: number };\n\nconst _isPrimitiveKey = (item: Key): item is KeyPrimitive =>\n [\"string\", \"number\"].includes(typeof item);\n\nconst resolveKey = (item: Key): KeyPrimitive =>\n (_isPrimitiveKey(item) ? item : item.key) ?? defaultKey;\n\nconst resolvePriority = (item: KeyOptions) =>\n (_isPrimitiveKey(item) ? 0 : item.priority) ?? 0;\n\nclass SemaphoreItem {\n private queue: Array<{\n resolve: Function;\n priority: number;\n }>;\n private maxConcurrent: number;\n\n /**\n * The number of locks.\n */\n public count: number;\n\n constructor(maxConcurrent: number) {\n this.queue = [];\n this.maxConcurrent = maxConcurrent;\n this.count = 0;\n }\n\n get canAcquire(): boolean {\n return this.count < this.maxConcurrent;\n }\n\n private incrementCount() {\n this.count++;\n }\n\n private decrementCount() {\n this.count--;\n }\n\n acquire(priority: number): Promise<void> {\n if (this.canAcquire) {\n this.incrementCount();\n return Promise.resolve();\n } else {\n return new Promise((resolve) => {\n this.queue.push({ resolve, priority });\n this.queue.sort((a, b) => b.priority - a.priority);\n });\n }\n }\n\n release(): void {\n const resolveFunc = this.queue.shift();\n\n if (resolveFunc) {\n // Give the micro task queue a small break instead of calling resolveFunc() directly\n setTimeout(resolveFunc.resolve, 0);\n // queueMicrotask(() => resolveFunc.resolve());\n } else {\n this.decrementCount();\n }\n }\n}\n\nclass Semaphore {\n private semaphoreInstances: Record<string | number, SemaphoreItem>;\n private maxConcurrent: number;\n\n /**\n * @param {number} [maxConcurrent] The maximum number of concurrent locks.\n */\n constructor(maxConcurrent: number = 1) {\n this.semaphoreInstances = {};\n this.maxConcurrent = maxConcurrent;\n\n if (maxConcurrent < 1) {\n throw new Error(\"The maxConcurrent must be 1 or greater.\");\n }\n }\n\n private hasSemaphoreInstance(key: KeyPrimitive = defaultKey) {\n return Boolean(this.semaphoreInstances[key]);\n }\n\n private getSemaphoreInstance(key: KeyPrimitive = defaultKey) {\n if (!this.hasSemaphoreInstance(key)) {\n this.semaphoreInstances[key] = new SemaphoreItem(\n this.maxConcurrent,\n );\n }\n return this.semaphoreInstances[key] as SemaphoreItem;\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n private tidy(key: KeyPrimitive = defaultKey): void {\n if (\n this.hasSemaphoreInstance(key) &&\n this.getSemaphoreInstance(key).count === 0\n ) {\n delete this.semaphoreInstances[key];\n }\n }\n\n /**\n * A synchronous function to determine whether a lock can be acquired.\n *\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {boolean} Returns true if the lock on `key` can be acquired, false\n * otherwise.\n */\n canAcquire(key: Key = defaultKey): boolean {\n const _key = resolveKey(key);\n\n return !this.hasSemaphoreInstance(_key) ||\n this.getSemaphoreInstance(_key).canAcquire;\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n acquire(key: KeyOptions = defaultKey) {\n const _key = resolveKey(key);\n const _priority = resolvePriority(key);\n\n return this.getSemaphoreInstance(_key).acquire(_priority);\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n release(key: Key = defaultKey): void {\n const _key = resolveKey(key);\n\n this.getSemaphoreInstance(_key).release();\n this.tidy(_key);\n }\n\n /**\n * The number of active locks. Will always be less or equal to `max`.\n *\n * @param {string | number} [key]- Optional, the semaphore key.\n */\n count(key: Key = defaultKey): number {\n const _key = resolveKey(key);\n\n return (this.hasSemaphoreInstance(_key))\n ? this.getSemaphoreInstance(_key).count\n : 0;\n }\n\n /**\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {boolean} True if the semaphore and key has locks, false otherwise.\n */\n hasTasks(key: Key = defaultKey): boolean {\n return this.count(key) > 0;\n }\n\n /**\n * @param {Function<T>} fn The function to execute.\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {Promise<T>}\n */\n async request<T>(\n fn: Function,\n key: KeyOptions = defaultKey,\n ): Promise<T> {\n try {\n await this.acquire(key);\n return await fn();\n } finally {\n this.release(key);\n }\n }\n\n /**\n * Asynchronously executes `fn` if a lock can be immediately acquired.\n * Otherwise, returns null.\n *\n * @param {Function<T>} fn The function to execute.\n * @param {string | number} [key]- Optional, the semaphore key.\n * @returns {Promise<T>}\n */\n async requestIfAvailable<T>(\n fn: Function,\n key: KeyOptions = defaultKey,\n ): Promise<T | null> {\n if (this.canAcquire(key)) {\n return this.request(fn, key);\n } else {\n return null;\n }\n }\n}\n\nexport { Semaphore };\n","import { Semaphore } from \"./semaphore\";\n\n/**\n * GroupSemaphore manages a shared semaphore for different groups of tasks. Each\n * group is identified by a unique key, and the semaphore ensures only one group\n * can run its tasks concurrently.\n *\n * - acquire(key): Increments the active count for the given group. If it's the\n * first task for the group (active count is 0), it acquires the global\n * semaphore, ensuring only one group's tasks can proceed at a time.\n * Subsequent calls in the group increment the count and are permitted to run.\n * - release(key): Decrements the active count for the group. If the last task\n * for that group is released, it releases the global semaphore, allowing\n * other groups to proceed.\n *\n * This ensures that only one group can execute concurrently, but multiple tasks\n * within the same group can run as long as no other tasks from different groups\n * are active.\n */\nclass GroupSemaphore {\n private _semaphore = new Semaphore();\n private _activeCounts: Record<string, number> = {};\n private _groupWaiters: Record<string, Promise<void>> = {};\n\n async acquire(key: string) {\n const activeCount = this._activeCounts[key] ?? 0;\n this._activeCounts[key] = activeCount + 1;\n const waiter = this._groupWaiters[key] ?? this._semaphore.acquire();\n this._groupWaiters[key] = waiter;\n await waiter;\n }\n\n release(key: string) {\n const activeCount = this._activeCounts[key] as number;\n\n if (activeCount === 1) {\n this._semaphore.release();\n delete this._activeCounts[key];\n delete this._groupWaiters[key];\n } else {\n this._activeCounts[key] = activeCount - 1;\n }\n }\n}\n\nexport { GroupSemaphore };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAM,aAAa;AAOnB,IAAM,kBAAkB,CAAC,SACrB,CAAC,UAAU,QAAQ,EAAE,SAAS,OAAO,IAAI;AAE7C,IAAM,aAAa,CAAC,UACf,gBAAgB,IAAI,IAAI,OAAO,KAAK,QAAQ;AAEjD,IAAM,kBAAkB,CAAC,UACpB,gBAAgB,IAAI,IAAI,IAAI,KAAK,aAAa;AAEnD,IAAM,gBAAN,MAAoB;AAAA,EACR;AAAA,EAIA;AAAA;AAAA;AAAA;AAAA,EAKD;AAAA,EAEP,YAAY,eAAuB;AAC/B,SAAK,QAAQ,CAAC;AACd,SAAK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BACF,IACA,MAAkB,YACD;AACjB,QAAI,KAAK,WAAW,GAAG,GAAG;AACtB,aAAO,KAAK,QAAQ,IAAI,GAAG;AAAA,IAC/B,OAAO;AACH,aAAO;AAAA,IACX;AAAA,EACJ;AACJ;;;ACvLA,IAAM,iBAAN,MAAqB;AAAA,EACT,aAAa,IAAI,UAAU;AAAA,EAC3B,gBAAwC,CAAC;AAAA,EACzC,gBAA+C,CAAC;AAAA,EAExD,MAAM,QAAQ,KAAa;AACvB,UAAM,cAAc,KAAK,cAAc,GAAG,KAAK;AAC/C,SAAK,cAAc,GAAG,IAAI,cAAc;AACxC,UAAM,SAAS,KAAK,cAAc,GAAG,KAAK,KAAK,WAAW,QAAQ;AAClE,SAAK,cAAc,GAAG,IAAI;AAC1B,UAAM;AAAA,EACV;AAAA,EAEA,QAAQ,KAAa;AACjB,UAAM,cAAc,KAAK,cAAc,GAAG;AAE1C,QAAI,gBAAgB,GAAG;AACnB,WAAK,WAAW,QAAQ;AACxB,aAAO,KAAK,cAAc,GAAG;AAC7B,aAAO,KAAK,cAAc,GAAG;AAAA,IACjC,OAAO;AACH,WAAK,cAAc,GAAG,IAAI,cAAc;AAAA,IAC5C;AAAA,EACJ;AACJ;","names":[]}
package/lib/index.d.cts DELETED
@@ -1,90 +0,0 @@
1
- type KeyPrimitive = string | number;
2
- type Key = KeyPrimitive | {
3
- key?: KeyPrimitive;
4
- };
5
- type KeyOptions = Key & {
6
- priority?: number;
7
- };
8
- declare class Semaphore {
9
- private semaphoreInstances;
10
- private maxConcurrent;
11
- /**
12
- * @param {number} [maxConcurrent] The maximum number of concurrent locks.
13
- */
14
- constructor(maxConcurrent?: number);
15
- private hasSemaphoreInstance;
16
- private getSemaphoreInstance;
17
- /**
18
- * @param {string | number} [key]- Optional, the semaphore key.
19
- */
20
- private tidy;
21
- /**
22
- * A synchronous function to determine whether a lock can be acquired.
23
- *
24
- * @param {string | number} [key]- Optional, the semaphore key.
25
- * @returns {boolean} Returns true if the lock on `key` can be acquired, false
26
- * otherwise.
27
- */
28
- canAcquire(key?: Key): boolean;
29
- /**
30
- * @param {string | number} [key]- Optional, the semaphore key.
31
- */
32
- acquire(key?: KeyOptions): Promise<void>;
33
- /**
34
- * @param {string | number} [key]- Optional, the semaphore key.
35
- */
36
- release(key?: Key): void;
37
- /**
38
- * The number of active locks. Will always be less or equal to `max`.
39
- *
40
- * @param {string | number} [key]- Optional, the semaphore key.
41
- */
42
- count(key?: Key): number;
43
- /**
44
- * @param {string | number} [key]- Optional, the semaphore key.
45
- * @returns {boolean} True if the semaphore and key has locks, false otherwise.
46
- */
47
- hasTasks(key?: Key): boolean;
48
- /**
49
- * @param {Function<T>} fn The function to execute.
50
- * @param {string | number} [key]- Optional, the semaphore key.
51
- * @returns {Promise<T>}
52
- */
53
- request<T>(fn: Function, key?: KeyOptions): Promise<T>;
54
- /**
55
- * Asynchronously executes `fn` if a lock can be immediately acquired.
56
- * Otherwise, returns null.
57
- *
58
- * @param {Function<T>} fn The function to execute.
59
- * @param {string | number} [key]- Optional, the semaphore key.
60
- * @returns {Promise<T>}
61
- */
62
- requestIfAvailable<T>(fn: Function, key?: KeyOptions): Promise<T | null>;
63
- }
64
-
65
- /**
66
- * GroupSemaphore manages a shared semaphore for different groups of tasks. Each
67
- * group is identified by a unique key, and the semaphore ensures only one group
68
- * can run its tasks concurrently.
69
- *
70
- * - acquire(key): Increments the active count for the given group. If it's the
71
- * first task for the group (active count is 0), it acquires the global
72
- * semaphore, ensuring only one group's tasks can proceed at a time.
73
- * Subsequent calls in the group increment the count and are permitted to run.
74
- * - release(key): Decrements the active count for the group. If the last task
75
- * for that group is released, it releases the global semaphore, allowing
76
- * other groups to proceed.
77
- *
78
- * This ensures that only one group can execute concurrently, but multiple tasks
79
- * within the same group can run as long as no other tasks from different groups
80
- * are active.
81
- */
82
- declare class GroupSemaphore {
83
- private _semaphore;
84
- private _activeCounts;
85
- private _groupWaiters;
86
- acquire(key: string): Promise<void>;
87
- release(key: string): void;
88
- }
89
-
90
- export { GroupSemaphore, Semaphore };