@d-zero/dealer 1.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 D-ZERO Co., Ltd.
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,34 @@
1
+ # Dealer
2
+
3
+ Dealer is an API and CLI that processes a given collection in parallel and logs the output in sequence to the standard output.
4
+
5
+ ## Install
6
+
7
+ ```shell
8
+ npm install @d-zero/dealer
9
+ ```
10
+
11
+ ## API
12
+
13
+ ```ts
14
+ import { deal } from '@d-zero/dealer';
15
+
16
+ await deal(items, {
17
+ limit: 30,
18
+ header: (progress, done, total, limit) =>
19
+ progress === 1
20
+ ? 'HeaderMessage: Done!'
21
+ : `HeaderMessage: %earth% %dots% %block% %propeller%`,
22
+ setup: (item, update, index) => {
23
+ item.setup();
24
+ item.addListeners((state) => {
25
+ update(`item(${index}): ${state}`);
26
+ });
27
+
28
+ return async () => {
29
+ await item.start();
30
+ item.cleanup();
31
+ };
32
+ },
33
+ });
34
+ ```
@@ -0,0 +1 @@
1
+ export declare function animate(chars: string[], time: number): string | undefined;
@@ -0,0 +1,3 @@
1
+ export function animate(chars, time) {
2
+ return chars[time % chars.length];
3
+ }
@@ -0,0 +1,6 @@
1
+ export declare function countDownFunctionParser(text: string): {
2
+ id: string;
3
+ time: number;
4
+ placeholder: string;
5
+ unit: string;
6
+ } | null;
@@ -0,0 +1,22 @@
1
+ export function countDownFunctionParser(text) {
2
+ const matched = /%countdown\((?<time>\d+)\s*,\s*(?<id>[^\s),]+)(?:\s*,\s*(?<unit>m?s))?\)%/i.exec(text);
3
+ if (!matched) {
4
+ return null;
5
+ }
6
+ if (!matched[0] || !matched.groups?.time || !matched.groups?.id) {
7
+ return null;
8
+ }
9
+ const time = Number.parseInt(matched.groups?.time, 10);
10
+ if (Number.isNaN(time)) {
11
+ return null;
12
+ }
13
+ const unit = matched.groups?.unit === 's' ? 's' : 'ms';
14
+ const id = matched.groups?.id;
15
+ const placeholder = matched[0];
16
+ return {
17
+ id,
18
+ time,
19
+ placeholder,
20
+ unit,
21
+ };
22
+ }
package/dist/deal.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import type { DealerOptions } from './dealer.js';
2
+ import type { LanesOptions } from './lanes.js';
3
+ type Options = DealerOptions & LanesOptions & {
4
+ header?: (progress: number, done: number, total: number, limit: number) => string;
5
+ debug?: boolean;
6
+ };
7
+ export declare function deal<T extends WeakKey>(items: readonly T[], setup: (process: T, update: (log: string) => void, index: number) => () => void | Promise<void>, options: Options): Promise<void>;
8
+ export {};
package/dist/deal.js ADDED
@@ -0,0 +1,32 @@
1
+ import { Dealer } from './dealer.js';
2
+ import { Lanes } from './lanes.js';
3
+ const DEBUG_ID = Number.MIN_SAFE_INTEGER;
4
+ export async function deal(items, setup, options) {
5
+ const dealer = new Dealer(items, options);
6
+ const lanes = new Lanes(options);
7
+ if (options?.header) {
8
+ dealer.progress((progress, done, total, limit) => {
9
+ lanes.header(options.header(progress, done, total, limit));
10
+ });
11
+ }
12
+ dealer.setup((process, index) => {
13
+ const update = (log) => lanes.update(index, log);
14
+ const start = setup(process, update, index);
15
+ return async () => {
16
+ await start();
17
+ lanes.delete(index);
18
+ };
19
+ });
20
+ if (options.debug) {
21
+ dealer.debug((log) => {
22
+ lanes.update(DEBUG_ID, `[DEBUG]: ${log}`);
23
+ });
24
+ }
25
+ return new Promise((resolve) => {
26
+ dealer.finish(() => {
27
+ lanes.close();
28
+ resolve();
29
+ });
30
+ dealer.play();
31
+ });
32
+ }
@@ -0,0 +1,13 @@
1
+ import type { ProcessInitializer } from './types.js';
2
+ export interface DealerOptions {
3
+ limit?: number;
4
+ }
5
+ export declare class Dealer<T extends WeakKey> {
6
+ #private;
7
+ constructor(items: readonly T[], options?: DealerOptions);
8
+ debug(listener: (log: string) => void): void;
9
+ finish(listener: () => void): void;
10
+ play(): void;
11
+ progress(listener: (progress: number, done: number, total: number, limit: number) => void): void;
12
+ setup(initializer: ProcessInitializer<T>): void;
13
+ }
package/dist/dealer.js ADDED
@@ -0,0 +1,70 @@
1
+ export class Dealer {
2
+ #done = new WeakSet();
3
+ #doneCount = 0;
4
+ #items;
5
+ #limit;
6
+ #starts = new WeakMap();
7
+ #workers = new Set();
8
+ #debug = () => { };
9
+ #finish = () => { };
10
+ #progress = () => { };
11
+ constructor(items, options) {
12
+ this.#items = items;
13
+ this.#limit = options?.limit ?? 10;
14
+ }
15
+ debug(listener) {
16
+ this.#debug = listener;
17
+ }
18
+ finish(listener) {
19
+ this.#finish = listener;
20
+ }
21
+ play() {
22
+ this.#deal();
23
+ }
24
+ progress(listener) {
25
+ this.#progress = listener;
26
+ }
27
+ setup(initializer) {
28
+ for (const [index, item] of this.#items.entries()) {
29
+ const start = initializer(item, index);
30
+ this.#starts.set(item, async () => await start());
31
+ }
32
+ this.#progress(this.#doneCount / this.#items.length, this.#doneCount, this.#items.length, this.#limit);
33
+ }
34
+ #deal() {
35
+ this.#debug(`Done: ${this.#doneCount}/${this.#items.length} (Limit: ${this.#limit})`);
36
+ this.#progress(this.#doneCount / this.#items.length, this.#doneCount, this.#items.length, this.#limit);
37
+ if (this.#doneCount === this.#items.length) {
38
+ this.#finish();
39
+ }
40
+ while (this.#workers.size <= this.#limit) {
41
+ const worker = this.#draw();
42
+ if (!worker) {
43
+ return;
44
+ }
45
+ this.#workers.add(worker);
46
+ const start = this.#starts.get(worker);
47
+ if (!start) {
48
+ throw new Error(`Didn't have a starting function`);
49
+ }
50
+ void start().then(() => {
51
+ this.#workers.delete(worker);
52
+ this.#done.add(worker);
53
+ this.#doneCount++;
54
+ this.#deal();
55
+ });
56
+ }
57
+ }
58
+ #draw() {
59
+ for (const item of this.#items) {
60
+ if (this.#done.has(item)) {
61
+ continue;
62
+ }
63
+ if (this.#workers.has(item)) {
64
+ continue;
65
+ }
66
+ return item;
67
+ }
68
+ return null;
69
+ }
70
+ }
@@ -0,0 +1,13 @@
1
+ import type { Animations, FPS } from './types.js';
2
+ interface Options {
3
+ animations?: Animations;
4
+ fps?: FPS;
5
+ }
6
+ export declare class Display {
7
+ #private;
8
+ constructor(options?: Options);
9
+ close(): void;
10
+ verboseMode(): void;
11
+ write(...logs: string[]): void;
12
+ }
13
+ export {};
@@ -0,0 +1,109 @@
1
+ import readline from 'node:readline';
2
+ import c from 'ansi-colors';
3
+ import { countDownFunctionParser } from './count-down-function-parser.js';
4
+ import { riffle } from './riffle.js';
5
+ const RESET = c.reset('');
6
+ const animationPresets = {
7
+ earth: [2, '🌏', '🌍', '🌎'],
8
+ dots: [5, '. ', '.. ', '...'],
9
+ block: [20, '▘', '▀', '▜', '▉', '▟', '▃', '▖', ' '],
10
+ propeller: [25, '\\', '|', '/', '-'],
11
+ };
12
+ export class Display {
13
+ #animations;
14
+ #coundDownMap = new Map();
15
+ #debugMessages = [];
16
+ #frameInterval;
17
+ #lastWroteLineNum = 0;
18
+ #stack = null;
19
+ #startTime = Date.now();
20
+ #timer = null;
21
+ #verbose = false;
22
+ constructor(options) {
23
+ this.#animations = {
24
+ ...animationPresets,
25
+ ...options?.animations,
26
+ };
27
+ const fps = options?.fps ?? 30;
28
+ this.#frameInterval = 1000 / fps;
29
+ process.stdout.on('resize', () => this.#resize());
30
+ }
31
+ close() {
32
+ if (this.#verbose) {
33
+ return;
34
+ }
35
+ if (this.#timer) {
36
+ clearTimeout(this.#timer);
37
+ this.#timer = null;
38
+ }
39
+ this.#write();
40
+ this.#lastWroteLineNum = 0;
41
+ this.#stack = null;
42
+ }
43
+ verboseMode() {
44
+ this.#verbose = true;
45
+ }
46
+ write(...logs) {
47
+ if (this.#verbose) {
48
+ process.stdout.write(logs.map((log) => log.trim()).join('\n'));
49
+ return;
50
+ }
51
+ this.#stack = [...this.#debugMessages, ...logs];
52
+ if (this.#timer) {
53
+ return;
54
+ }
55
+ this.#enterFrame();
56
+ }
57
+ #clear() {
58
+ if (this.#verbose) {
59
+ return;
60
+ }
61
+ for (let i = 0; i < this.#lastWroteLineNum; i++) {
62
+ readline.moveCursor(process.stdout, 0, -1);
63
+ readline.cursorTo(process.stdout, 0);
64
+ readline.clearLine(process.stdout, 0);
65
+ }
66
+ }
67
+ #countDown(text) {
68
+ const parsed = countDownFunctionParser(text);
69
+ if (!parsed) {
70
+ return text;
71
+ }
72
+ const { id, time, placeholder, unit } = parsed;
73
+ const currentTime = this.#coundDownMap.get(id);
74
+ let displayTimeMS;
75
+ if (currentTime == null) {
76
+ this.#coundDownMap.set(id, Date.now());
77
+ displayTimeMS = time;
78
+ }
79
+ else {
80
+ const elapsedTime = Date.now() - currentTime;
81
+ displayTimeMS = Math.max(time - elapsedTime, 0);
82
+ }
83
+ const displayTime = unit === 's' ? Math.round(displayTimeMS / 1000) : displayTimeMS;
84
+ return text.replace(placeholder, `${displayTime}`);
85
+ }
86
+ #enterFrame() {
87
+ this.#timer = setTimeout(() => this.#enterFrame(), this.#frameInterval);
88
+ this.#write();
89
+ }
90
+ #resize() {
91
+ if (this.#verbose) {
92
+ return;
93
+ }
94
+ this.#write();
95
+ }
96
+ #write() {
97
+ if (!this.#stack) {
98
+ return;
99
+ }
100
+ this.#clear();
101
+ for (const stack of this.#stack) {
102
+ let text = riffle(stack, Date.now() - this.#startTime, this.#animations);
103
+ text = this.#countDown(text);
104
+ const displayText = text.slice(0, process.stdout.columns);
105
+ process.stdout.write(`${RESET}${displayText}${RESET}\n`);
106
+ }
107
+ this.#lastWroteLineNum = this.#stack.length;
108
+ }
109
+ }
@@ -0,0 +1,3 @@
1
+ export { deal } from './deal.js';
2
+ export { Dealer } from './dealer.js';
3
+ export { Lanes } from './lanes.js';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { deal } from './deal.js';
2
+ export { Dealer } from './dealer.js';
3
+ export { Lanes } from './lanes.js';
@@ -0,0 +1,19 @@
1
+ import type { Animations, FPS } from './types.js';
2
+ type Log = [id: number, message: string];
3
+ type SortFunc = (a: Log, b: Log) => number;
4
+ export type LanesOptions = {
5
+ animations?: Animations;
6
+ fps?: FPS;
7
+ indent?: string;
8
+ sort?: SortFunc;
9
+ };
10
+ export declare class Lanes {
11
+ #private;
12
+ constructor(options?: LanesOptions);
13
+ close(): void;
14
+ delete(id: number): void;
15
+ header(text: string): void;
16
+ update(id: number, log: string): void;
17
+ write(): void;
18
+ }
19
+ export {};
package/dist/lanes.js ADDED
@@ -0,0 +1,40 @@
1
+ import { Display } from './display.js';
2
+ export class Lanes {
3
+ #display;
4
+ #header;
5
+ #indent = '';
6
+ #logs = new Map();
7
+ #sort = ([a], [b]) => a - b;
8
+ constructor(options) {
9
+ this.#display = new Display({
10
+ animations: options?.animations,
11
+ fps: options?.fps,
12
+ });
13
+ this.#indent = options?.indent ?? this.#indent;
14
+ this.#sort = options?.sort ?? this.#sort;
15
+ }
16
+ close() {
17
+ this.#display.close();
18
+ }
19
+ delete(id) {
20
+ this.#logs.delete(id);
21
+ this.write();
22
+ }
23
+ header(text) {
24
+ this.#header = text;
25
+ this.write();
26
+ }
27
+ update(id, log) {
28
+ this.#logs.set(id, log);
29
+ this.write();
30
+ }
31
+ write() {
32
+ const logs = [...this.#logs.entries()];
33
+ logs.sort(this.#sort);
34
+ const messages = logs.map(([, message]) => `${this.#indent}${message}`);
35
+ if (this.#header) {
36
+ messages.unshift(this.#header);
37
+ }
38
+ this.#display.write(...messages);
39
+ }
40
+ }
@@ -0,0 +1,14 @@
1
+ import type { Animations, FPS } from './types.js';
2
+ interface Options {
3
+ animations?: Animations;
4
+ fps?: FPS;
5
+ }
6
+ export declare class Logger {
7
+ #private;
8
+ constructor(options?: Options);
9
+ clear(): void;
10
+ close(): void;
11
+ verboseMode(): void;
12
+ write(...logs: string[]): void;
13
+ }
14
+ export {};
package/dist/logger.js ADDED
@@ -0,0 +1,111 @@
1
+ import readline from 'node:readline';
2
+ import c from 'ansi-colors';
3
+ import { countDownFunctionParser } from './count-down-function-parser.js';
4
+ import { riffle } from './riffle.js';
5
+ import { writeVerbosely } from './write-verbosely.js';
6
+ const animationPresets = {
7
+ earth: ['🌏', '🌍', '🌎'],
8
+ dots: ['. ', '.. ', '...'],
9
+ block: ['▘', '▀', '▜', '▉', '▟', '▃', '▖', ' '],
10
+ propeller: ['\\', '|', '/', '-'],
11
+ };
12
+ export class Logger {
13
+ #animations;
14
+ #coundDownMap = new Map();
15
+ #frameInterval;
16
+ #lastWroteLineNum = 0;
17
+ #stack = null;
18
+ #time = 0;
19
+ #timer = null;
20
+ #verbose = false;
21
+ constructor(options) {
22
+ this.#animations = {
23
+ ...animationPresets,
24
+ ...options?.animations,
25
+ };
26
+ const fps = options?.fps ?? 30;
27
+ this.#frameInterval = 1000 / fps;
28
+ process.stdout.on('resize', () => this.#resize());
29
+ }
30
+ clear() {
31
+ if (this.#verbose) {
32
+ return;
33
+ }
34
+ const cursorY = this.#lastWroteLineNum * -1;
35
+ readline.moveCursor(process.stdout, 0, cursorY);
36
+ readline.cursorTo(process.stdout, 0);
37
+ }
38
+ close() {
39
+ if (this.#verbose) {
40
+ return;
41
+ }
42
+ // Writing last stack
43
+ if (this.#timer) {
44
+ clearTimeout(this.#timer);
45
+ this.#timer = null;
46
+ }
47
+ this.#write();
48
+ this.#time = 0;
49
+ this.#lastWroteLineNum = 0;
50
+ this.#stack = null;
51
+ }
52
+ verboseMode() {
53
+ this.#verbose = true;
54
+ }
55
+ write(...logs) {
56
+ if (this.#verbose) {
57
+ writeVerbosely(...logs);
58
+ return;
59
+ }
60
+ this.#stack = logs;
61
+ if (this.#timer) {
62
+ return;
63
+ }
64
+ this.#run();
65
+ }
66
+ #countDown(text) {
67
+ const parsed = countDownFunctionParser(text);
68
+ if (!parsed) {
69
+ return text;
70
+ }
71
+ const { id, time, placeholder, unit } = parsed;
72
+ const currentTime = this.#coundDownMap.get(id);
73
+ let displayTimeMS;
74
+ if (currentTime == null) {
75
+ this.#coundDownMap.set(id, Date.now());
76
+ displayTimeMS = time;
77
+ }
78
+ else {
79
+ const elapsedTime = Date.now() - currentTime;
80
+ displayTimeMS = Math.max(time - elapsedTime, 0);
81
+ }
82
+ const displayTime = unit === 's' ? Math.round(displayTimeMS / 1000) : displayTimeMS;
83
+ return text.replace(placeholder, `${displayTime}`);
84
+ }
85
+ #resize() {
86
+ if (this.#verbose) {
87
+ return;
88
+ }
89
+ this.#write();
90
+ }
91
+ #run() {
92
+ this.#time += 1;
93
+ this.#timer = setTimeout(() => this.#run(), this.#frameInterval);
94
+ this.#write();
95
+ }
96
+ #write() {
97
+ if (!this.#stack) {
98
+ return;
99
+ }
100
+ this.clear();
101
+ const reset = c.reset('');
102
+ for (const line of this.#stack) {
103
+ readline.clearLine(process.stdout, 0);
104
+ let text = riffle(line, this.#time, this.#animations ?? {});
105
+ text = this.#countDown(text);
106
+ const displayText = text.slice(0, process.stdout.columns);
107
+ process.stdout.write(`${reset}${displayText}${reset}\n`);
108
+ }
109
+ this.#lastWroteLineNum = this.#stack.length;
110
+ }
111
+ }
@@ -0,0 +1,2 @@
1
+ import type { Animations } from './types.js';
2
+ export declare function riffle(text: string, elapsed: number, animations: Animations): string;
package/dist/riffle.js ADDED
@@ -0,0 +1,17 @@
1
+ export function riffle(text, elapsed, animations) {
2
+ for (const key of Object.keys(animations)) {
3
+ const animation = animations[key];
4
+ if (!animation) {
5
+ continue;
6
+ }
7
+ const [fps, ...sprites] = animation;
8
+ const frameDuration = 1000 / fps;
9
+ const currentFrame = Math.floor(elapsed / frameDuration) % sprites.length;
10
+ const replacement = sprites[currentFrame];
11
+ if (!replacement) {
12
+ continue;
13
+ }
14
+ text = text.replaceAll(`%${key}%`, replacement);
15
+ }
16
+ return text;
17
+ }
@@ -0,0 +1,5 @@
1
+ export type Animations = Record<string, [fps: number, ...sprites: string[]]>;
2
+ export type FPS = 12 | 24 | 30 | 60;
3
+ export interface ProcessInitializer<T> {
4
+ (process: T, index: number): () => Promise<void> | void;
5
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export declare function writeVerbosely(...lines: string[]): void;
@@ -0,0 +1,3 @@
1
+ export function writeVerbosely(...lines) {
2
+ process.stdout.write(lines.map((line) => line.trim()).join('\n'));
3
+ }
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "@d-zero/dealer",
3
+ "version": "1.0.0-alpha.1",
4
+ "description": "A tool that provides an API and CLI for parallel processing of collections and sequential logging to standard output",
5
+ "author": "D-ZERO",
6
+ "license": "MIT",
7
+ "private": false,
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "type": "module",
12
+ "module": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "scripts": {
18
+ "build": "tsc",
19
+ "clean": "tsc --build --clean"
20
+ },
21
+ "dependencies": {
22
+ "ansi-colors": "4.1.3"
23
+ },
24
+ "gitHead": "feffce2ac8ca616a0fbca4b19987c3bff5291d3d"
25
+ }