qpass 1.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/README.md ADDED
@@ -0,0 +1,160 @@
1
+ # Qpass
2
+
3
+ Qpass is a JavaScript/TypeScript queue library for processing tasks sequentially.
4
+ It supports batch execution, error handling options, and progress callbacks.
5
+
6
+ ## πŸ“Œ Getting started
7
+
8
+ ```js
9
+ npm install qpass
10
+ ```
11
+
12
+ ## πŸ“Œ Usage
13
+
14
+ ### Basic usage
15
+
16
+ ```js
17
+ import Qpass from "qpass";
18
+
19
+ const queue = new Qpass();
20
+
21
+ const job1 = () => Promise.resolve("job1 completed");
22
+ const job2 = () => Promise.resolve("job2 completed");
23
+
24
+ queue.add([job1, job2]);
25
+ ```
26
+
27
+ ### Option
28
+
29
+ You can configure options when creating a Qpass instance.
30
+
31
+ ```ts
32
+ const queue = new Qpass({
33
+ breakWhenError?: boolean;
34
+ onProgress?: (progress: {
35
+ batchToProcess: number; // Total number of batches remaining
36
+ itemsToProcess: number; // Total remaining tasks
37
+ completed?: any[]; // Array of completed task results
38
+ }) => void;
39
+ batchSize?: number; // must be β‰₯ 1, default is 1
40
+ });
41
+ ```
42
+
43
+ ### πŸ” OnProgress
44
+
45
+ The onProgress callback runs when the queue starts and after each batch is completed.
46
+
47
+ ```js
48
+ const queue = new Qpass({
49
+ batchSize: 2,
50
+ onProgress: (progress) => {
51
+ console.log(progress);
52
+ },
53
+ });
54
+
55
+ await queue.add([
56
+ () => Promise.resolve("Job 1"),
57
+ () => Promise.resolve("Job 2"),
58
+ () => Promise.resolve("Job 3"),
59
+ () => Promise.resolve("Job 4"),
60
+ ]);
61
+
62
+ // Example output:
63
+ // { batchToProcess: 1, itemsToProcess: 2, completed: ["Job 1", "Job 2"] }
64
+ // { batchToProcess: 0, itemsToProcess: 0, completed: ["Job 3", "Job 4"] }
65
+ ```
66
+
67
+ ## ❗Handling Errors
68
+
69
+ Qpass lets you choose whether to stop on error or continue execution when an error occurs.
70
+ <br>
71
+ This behavior is controlled via the breakWhenError option.
72
+
73
+ ### βœ… Continue execution even on errors (breakWhenError: false)
74
+
75
+ ```js
76
+ const queue = new Qpass({
77
+ breakWhenError: false, // default
78
+ onProgress: (progress) => {
79
+ console.log("Completed jobs: ", progress.completed);
80
+ },
81
+ });
82
+
83
+ const jobs = [
84
+ () => Promise.resolve("First success"),
85
+ () => Promise.reject("Second failed ❌"),
86
+ () => Promise.resolve("Third success βœ…"),
87
+ ];
88
+
89
+ await queue.add(jobs);
90
+ ```
91
+
92
+ Result
93
+
94
+ ```js
95
+ Completed jobs: ["First success"]
96
+ Completed jobs: ["First success", "Second failed ❌", "Third success βœ…"]
97
+ // Errors are stored as error objects and execution continues.
98
+ ```
99
+
100
+ ### πŸ›‘ Stop immediately on error (breakWhenError: true)
101
+
102
+ ```js
103
+ const queue = new Qpass({
104
+ breakWhenError: true,
105
+ onProgress: (progress) => {
106
+ console.log(`Completed jobs:: `, progress.completed);
107
+ },
108
+ });
109
+
110
+ const jobs = [
111
+ () => Promise.resolve("First success"),
112
+ () => Promise.reject("Second failed ❌"),
113
+ () => Promise.resolve("Third will not run 🚫"),
114
+ ];
115
+
116
+ try {
117
+ await queue.add(jobs);
118
+ } catch (err) {
119
+ console.error("Execution stopped: ", err);
120
+ }
121
+ ```
122
+
123
+ Result
124
+
125
+ ```js
126
+ Completed jobs: ["First success"]
127
+ Execution stopped: Second failed ❌
128
+ // Stops immediately on error, so the third job is never executed.
129
+ ```
130
+
131
+ ## πŸ“Œ Practical Example
132
+
133
+ ```js
134
+ const queue = new Qpass({
135
+ batchSize: 5,
136
+ onProgress: (progress) => {
137
+ console.log(
138
+ `Remaining batches: ${progress.batchToProcess}, Remaining tasks: ${progress.itemsToProcess}`
139
+ );
140
+ },
141
+ });
142
+
143
+ const jobs = [];
144
+
145
+ for (let i = 0; i < 100; i++) {
146
+ jobs.push(() => fetch(`/api/data/${i}`).then((res) => res.json()));
147
+ }
148
+
149
+ queue.add(jobs);
150
+ ```
151
+
152
+ ## πŸ“Œ Features
153
+
154
+ β€’ Batch processing (batchSize) β€” control how many jobs run in parallel
155
+ <br>
156
+ β€’ Error control (breakWhenError) β€” choose whether to stop or continue on failure
157
+ <br>
158
+ β€’ Progress tracking (onProgress) β€” monitor task progress in real time
159
+ <br>
160
+ β€’ Execution state (isRunning) β€” check whether the queue is currently running
package/index.js ADDED
@@ -0,0 +1,109 @@
1
+ class Qpass {
2
+ version = "1.0.0"; // version info
3
+ items = []; // job queue
4
+ breakWhenError = false; // whether to stop on error
5
+ batchSize = 1; // number of jobs to process at once
6
+ onProgress; // progress callback
7
+ completed = []; // completed job results array
8
+ runningBatches = []; // currently running batch count
9
+ runningSlots = []; // running slot status array
10
+ get batchToProcess() {
11
+ // calculate total batch count
12
+ return Math.ceil(this.items.length / this.batchSize);
13
+ }
14
+ get batchProcessFinished() {
15
+ let completedCount = Object.keys(this.completed).length;
16
+ let isFinished = completedCount === this.runningBatches.length;
17
+ if (isFinished) {
18
+ const completed = this.completed; // copy
19
+ // reset state before calling callback
20
+ this.completed = [];
21
+ this.runningBatches = [];
22
+ this.runningSlots = [];
23
+ if (this.onProgress) {
24
+ this.onProgress({
25
+ batchToProcess: this.batchToProcess,
26
+ itemsToProcess: this.items.length,
27
+ completed: completed,
28
+ });
29
+ }
30
+ }
31
+ return isFinished;
32
+ }
33
+ constructor(option) {
34
+ this.breakWhenError = !!option?.breakWhenError;
35
+ this.batchSize = option?.batchSize ?? 1;
36
+ if (typeof this.batchSize !== "number" || this.batchSize < 1) {
37
+ throw new Error("batchSize must be at least 1");
38
+ }
39
+ if (option?.onProgress) {
40
+ if (typeof option.onProgress === "function") {
41
+ this.onProgress = option.onProgress;
42
+ }
43
+ else {
44
+ throw new Error("onProgress must be a function");
45
+ }
46
+ }
47
+ }
48
+ // add jobs to the queue at once
49
+ add(jobs) {
50
+ // check if jobs is an array, if not convert to array
51
+ const jobsArray = Array.isArray(jobs) ? jobs : [jobs];
52
+ // check if each job is a function, if so add to queue
53
+ for (const job of jobsArray) {
54
+ if (typeof job !== "function") {
55
+ throw new Error("Each job must be a function that returns a Promise");
56
+ }
57
+ this.items.push(job);
58
+ }
59
+ this.processNext();
60
+ }
61
+ // process next batch of jobs
62
+ processNext() {
63
+ // exit if queue is empty
64
+ if (this.items.length === 0) {
65
+ return;
66
+ }
67
+ const batchToRun = this.batchSize - this.runningBatches.length;
68
+ if (batchToRun <= 0) {
69
+ // exit if current running batches reached maximum
70
+ return;
71
+ }
72
+ // extract batchToRun amount of jobs
73
+ this.runningBatches.push(...this.items.splice(0, batchToRun));
74
+ for (let i = 0; i < this.runningBatches.length; i++) {
75
+ if (this.runningSlots?.[i]) {
76
+ continue;
77
+ }
78
+ this.runningSlots[i] = true;
79
+ this.runningBatches[i]()
80
+ .then((result) => {
81
+ if (this.completed[i]) {
82
+ return result;
83
+ }
84
+ this.completed[i] = result;
85
+ if (this.batchProcessFinished) {
86
+ return this.processNext();
87
+ }
88
+ return result;
89
+ })
90
+ .catch((err) => {
91
+ // error handling
92
+ if (this.breakWhenError) {
93
+ throw err;
94
+ }
95
+ this.completed[i] = err;
96
+ if (this.batchProcessFinished) {
97
+ return this.processNext();
98
+ }
99
+ return err;
100
+ });
101
+ }
102
+ }
103
+ terminate() {
104
+ // remove all remaining jobs from queue
105
+ this.items = [];
106
+ }
107
+ }
108
+ export default Qpass;
109
+ //# sourceMappingURL=index.js.map
package/index.ts ADDED
@@ -0,0 +1,148 @@
1
+ class Qpass {
2
+ version = "1.0.0"; // version info
3
+
4
+ private items: (() => Promise<any>)[] = []; // job queue
5
+ private breakWhenError: boolean = false; // whether to stop on error
6
+ private batchSize: number = 1; // number of jobs to process at once
7
+ private onProgress?: (progress: {
8
+ batchToProcess: number; // remaining batch count
9
+ itemsToProcess: number; // remaining job count
10
+ completed: any[]; // completed job results array
11
+ }) => void; // progress callback
12
+
13
+ private completed: any[] = []; // completed job results array
14
+ private runningBatches: (() => Promise<any>)[] = []; // currently running batch count
15
+ private runningSlots: boolean[] = []; // running slot status array
16
+
17
+ private get batchToProcess() {
18
+ // calculate total batch count
19
+ return Math.ceil(this.items.length / this.batchSize);
20
+ }
21
+
22
+ private get batchProcessFinished() {
23
+ let completedCount = Object.keys(this.completed).length;
24
+ let isFinished = completedCount === this.runningBatches.length;
25
+
26
+ if (isFinished) {
27
+ const completed = this.completed; // copy
28
+
29
+ // reset state before calling callback
30
+ this.completed = [];
31
+ this.runningBatches = [];
32
+ this.runningSlots = [];
33
+
34
+ if (this.onProgress) {
35
+ this.onProgress({
36
+ batchToProcess: this.batchToProcess,
37
+ itemsToProcess: this.items.length,
38
+ completed: completed,
39
+ });
40
+ }
41
+ }
42
+
43
+ return isFinished;
44
+ }
45
+
46
+ constructor(option?: {
47
+ breakWhenError?: boolean;
48
+ onProgress?: (progress: {
49
+ batchToProcess: number;
50
+ itemsToProcess: number;
51
+ completed: any[];
52
+ }) => void;
53
+ batchSize?: number; // must be at least 1, default is 1
54
+ }) {
55
+ this.breakWhenError = !!option?.breakWhenError;
56
+ this.batchSize = option?.batchSize ?? 1;
57
+
58
+ if (typeof this.batchSize !== "number" || this.batchSize < 1) {
59
+ throw new Error("batchSize must be at least 1");
60
+ }
61
+
62
+ if (option?.onProgress) {
63
+ if (typeof option.onProgress === "function") {
64
+ this.onProgress = option.onProgress;
65
+ } else {
66
+ throw new Error("onProgress must be a function");
67
+ }
68
+ }
69
+ }
70
+
71
+ // add jobs to the queue at once
72
+ add(jobs: (() => Promise<any>)[] | (() => Promise<any>)) {
73
+ // check if jobs is an array, if not convert to array
74
+ const jobsArray = Array.isArray(jobs) ? jobs : [jobs];
75
+
76
+ // check if each job is a function, if so add to queue
77
+ for (const job of jobsArray) {
78
+ if (typeof job !== "function") {
79
+ throw new Error(
80
+ "Each job must be a function that returns a Promise"
81
+ );
82
+ }
83
+ this.items.push(job);
84
+ }
85
+
86
+ this.processNext();
87
+ }
88
+
89
+ // process next batch of jobs
90
+ private processNext() {
91
+ // exit if queue is empty
92
+ if (this.items.length === 0) {
93
+ return;
94
+ }
95
+
96
+ const batchToRun = this.batchSize - this.runningBatches.length;
97
+ if (batchToRun <= 0) {
98
+ // exit if current running batches reached maximum
99
+ return;
100
+ }
101
+
102
+ // extract batchToRun amount of jobs
103
+ this.runningBatches.push(...this.items.splice(0, batchToRun));
104
+
105
+ for (let i = 0; i < this.runningBatches.length; i++) {
106
+ if (this.runningSlots?.[i]) {
107
+ continue;
108
+ }
109
+
110
+ this.runningSlots[i] = true;
111
+ (this.runningBatches[i] as () => Promise<any>)()
112
+ .then((result) => {
113
+ if (this.completed[i]) {
114
+ return result;
115
+ }
116
+
117
+ this.completed[i] = result;
118
+
119
+ if (this.batchProcessFinished) {
120
+ return this.processNext();
121
+ }
122
+
123
+ return result;
124
+ })
125
+ .catch((err) => {
126
+ // error handling
127
+ if (this.breakWhenError) {
128
+ throw err;
129
+ }
130
+
131
+ this.completed[i] = err;
132
+
133
+ if (this.batchProcessFinished) {
134
+ return this.processNext();
135
+ }
136
+
137
+ return err;
138
+ });
139
+ }
140
+ }
141
+
142
+ terminate() {
143
+ // remove all remaining jobs from queue
144
+ this.items = [];
145
+ }
146
+ }
147
+
148
+ export default Qpass;
package/package.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "qpass",
3
+ "version": "1.0.0",
4
+ "description": "Asynchronous function handler with adjustable concurrency",
5
+ "main": "index.js",
6
+ "type": "module",
7
+ "scripts": {
8
+ "test": "echo \"Error: no test specified\" && exit 1",
9
+ "build": "npx tsc --project tsconfig.json"
10
+ },
11
+ "author": "",
12
+ "license": "ISC",
13
+ "devDependencies": {
14
+ "typescript": "^5.9.3"
15
+ }
16
+ }
package/test.js ADDED
@@ -0,0 +1,68 @@
1
+ import Qpass from "./index.js";
2
+
3
+ // job creator
4
+ const createJob =
5
+ (id, duration, shouldFail = false) =>
6
+ () => {
7
+ return new Promise((resolve, reject) => {
8
+ setTimeout(() => {
9
+ if (shouldFail) {
10
+ reject(new Error(`Job ${id} failed`));
11
+ } else {
12
+ resolve(`Job ${id} completed`);
13
+ }
14
+ }, duration);
15
+ });
16
+ };
17
+
18
+ // test code
19
+ console.log("πŸš€ Qpass test started\n");
20
+
21
+ let did2ndTest = false;
22
+
23
+ const onProgress = ({ batchToProcess, itemsToProcess, completed }) => {
24
+ console.log(`Remaining batches: ${batchToProcess}`);
25
+ console.log(`Remaining jobs: ${itemsToProcess}`);
26
+ if(itemsToProcess === 5) {
27
+ queue.terminate();
28
+ }
29
+ console.log(
30
+ "Completed:",
31
+ completed.map((r) => (r instanceof Error ? `Error: ${r.message}` : r))
32
+ );
33
+
34
+ console.log("---");
35
+
36
+ if (itemsToProcess === 0) {
37
+ console.log("πŸš€ Qpass test completed");
38
+
39
+ if (!did2ndTest) {
40
+ console.log("\nπŸš€ Qpass array addition 2nd test started\n");
41
+
42
+ did2ndTest = true;
43
+ testArray();
44
+ }
45
+ }
46
+ };
47
+
48
+ const queue = new Qpass({
49
+ breakWhenError: false,
50
+ batchSize: 3,
51
+ onProgress: onProgress,
52
+ });
53
+
54
+ const testLoop = () => {
55
+ for (let i = 1; i <= 14; i++) {
56
+ queue.add(createJob(i, 800, i % 3 === 0)); // multiples of 3 will fail
57
+ }
58
+ };
59
+
60
+ testLoop();
61
+
62
+ const testArray = () => {
63
+ let jobs = [];
64
+ for (let i = 1; i <= 14; i++) {
65
+ jobs.push(createJob(i, 800, i % 3 === 0)); // multiples of 3 will fail
66
+ }
67
+ queue.add(jobs);
68
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ // Visit https://aka.ms/tsconfig to read more about this file
3
+ "compilerOptions": {
4
+ // File Layout
5
+ // "rootDir": "./src",
6
+ // "outDir": "./dist",
7
+
8
+ // Environment Settings
9
+ // See also https://aka.ms/tsconfig/module
10
+ "module": "nodenext",
11
+ "target": "esnext",
12
+ "types": [],
13
+ // For nodejs:
14
+ // "lib": ["esnext"],
15
+ // "types": ["node"],
16
+ // and npm install -D @types/node
17
+
18
+ // Other Outputs
19
+ "sourceMap": true,
20
+ "declaration": true,
21
+ "declarationMap": true,
22
+
23
+ // Stricter Typechecking Options
24
+ "noUncheckedIndexedAccess": true,
25
+ "exactOptionalPropertyTypes": true,
26
+
27
+ // Style Options
28
+ // "noImplicitReturns": true,
29
+ // "noImplicitOverride": true,
30
+ // "noUnusedLocals": true,
31
+ // "noUnusedParameters": true,
32
+ // "noFallthroughCasesInSwitch": true,
33
+ // "noPropertyAccessFromIndexSignature": true,
34
+
35
+ // Recommended Options
36
+ "strict": true,
37
+ "jsx": "react-jsx",
38
+ "verbatimModuleSyntax": true,
39
+ "isolatedModules": true,
40
+ "noUncheckedSideEffectImports": true,
41
+ "moduleDetection": "force",
42
+ "skipLibCheck": true,
43
+
44
+ // "target": "ES2015", // λ˜λŠ” "ES6"
45
+ "lib": ["ES2015", "DOM"] // Promise와 λΈŒλΌμš°μ € κ΄€λ ¨ APIλ₯Ό 지원
46
+ }
47
+ }