@catbee/utils 0.0.6 → 0.0.7

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.
Files changed (122) hide show
  1. package/README.md +51 -1106
  2. package/build/esm/config.d.ts +5 -13
  3. package/build/esm/config.js +0 -12
  4. package/build/esm/config.js.map +1 -1
  5. package/build/esm/servers/server.builder.d.ts +1 -118
  6. package/build/esm/servers/server.builder.js +0 -20
  7. package/build/esm/servers/server.builder.js.map +1 -1
  8. package/build/esm/servers/server.d.ts +2 -2
  9. package/build/esm/servers/server.js +3 -13
  10. package/build/esm/servers/server.js.map +1 -1
  11. package/build/esm/types/api-response.d.ts +28 -0
  12. package/build/esm/types/api-response.js +10 -1
  13. package/build/esm/types/api-response.js.map +1 -1
  14. package/build/esm/types/server.d.ts +0 -17
  15. package/build/esm/types/server.js.map +1 -1
  16. package/build/esm/utils/async.utils.d.ts +91 -0
  17. package/build/esm/utils/async.utils.js +244 -0
  18. package/build/esm/utils/async.utils.js.map +1 -1
  19. package/build/esm/utils/context-store.utils.d.ts +3 -0
  20. package/build/esm/utils/context-store.utils.js +9 -6
  21. package/build/esm/utils/context-store.utils.js.map +1 -1
  22. package/build/esm/utils/date.utils.d.ts +159 -0
  23. package/build/esm/utils/date.utils.js +389 -0
  24. package/build/esm/utils/date.utils.js.map +1 -0
  25. package/build/esm/utils/logger.utils.d.ts +3 -9
  26. package/build/esm/utils/logger.utils.js +3 -9
  27. package/build/esm/utils/logger.utils.js.map +1 -1
  28. package/build/esm/utils/middleware.utils.js +2 -1
  29. package/build/esm/utils/middleware.utils.js.map +1 -1
  30. package/build/esm/utils/performance.utils.d.ts +136 -0
  31. package/build/esm/utils/performance.utils.js +376 -0
  32. package/build/esm/utils/performance.utils.js.map +1 -0
  33. package/build/esm/utils/request.utils.d.ts +9 -0
  34. package/build/esm/utils/request.utils.js +32 -5
  35. package/build/esm/utils/request.utils.js.map +1 -1
  36. package/build/esm/utils/stream.utils.d.ts +88 -0
  37. package/build/esm/utils/stream.utils.js +284 -0
  38. package/build/esm/utils/stream.utils.js.map +1 -0
  39. package/build/esm/utils/type.utils.d.ts +90 -0
  40. package/build/esm/utils/type.utils.js +190 -0
  41. package/build/esm/utils/type.utils.js.map +1 -0
  42. package/build/esnext/config.d.ts +5 -13
  43. package/build/esnext/config.js +0 -12
  44. package/build/esnext/config.js.map +1 -1
  45. package/build/esnext/servers/server.builder.d.ts +1 -118
  46. package/build/esnext/servers/server.builder.js +0 -20
  47. package/build/esnext/servers/server.builder.js.map +1 -1
  48. package/build/esnext/servers/server.d.ts +2 -2
  49. package/build/esnext/servers/server.js +3 -13
  50. package/build/esnext/servers/server.js.map +1 -1
  51. package/build/esnext/types/api-response.d.ts +28 -0
  52. package/build/esnext/types/api-response.js +10 -1
  53. package/build/esnext/types/api-response.js.map +1 -1
  54. package/build/esnext/types/server.d.ts +0 -17
  55. package/build/esnext/types/server.js.map +1 -1
  56. package/build/esnext/utils/async.utils.d.ts +91 -0
  57. package/build/esnext/utils/async.utils.js +190 -0
  58. package/build/esnext/utils/async.utils.js.map +1 -1
  59. package/build/esnext/utils/context-store.utils.d.ts +3 -0
  60. package/build/esnext/utils/context-store.utils.js +9 -6
  61. package/build/esnext/utils/context-store.utils.js.map +1 -1
  62. package/build/esnext/utils/date.utils.d.ts +159 -0
  63. package/build/esnext/utils/date.utils.js +384 -0
  64. package/build/esnext/utils/date.utils.js.map +1 -0
  65. package/build/esnext/utils/logger.utils.d.ts +3 -9
  66. package/build/esnext/utils/logger.utils.js +3 -9
  67. package/build/esnext/utils/logger.utils.js.map +1 -1
  68. package/build/esnext/utils/middleware.utils.js +2 -1
  69. package/build/esnext/utils/middleware.utils.js.map +1 -1
  70. package/build/esnext/utils/performance.utils.d.ts +136 -0
  71. package/build/esnext/utils/performance.utils.js +271 -0
  72. package/build/esnext/utils/performance.utils.js.map +1 -0
  73. package/build/esnext/utils/request.utils.d.ts +9 -0
  74. package/build/esnext/utils/request.utils.js +23 -5
  75. package/build/esnext/utils/request.utils.js.map +1 -1
  76. package/build/esnext/utils/stream.utils.d.ts +88 -0
  77. package/build/esnext/utils/stream.utils.js +210 -0
  78. package/build/esnext/utils/stream.utils.js.map +1 -0
  79. package/build/esnext/utils/type.utils.d.ts +90 -0
  80. package/build/esnext/utils/type.utils.js +187 -0
  81. package/build/esnext/utils/type.utils.js.map +1 -0
  82. package/build/src/config.d.ts +5 -13
  83. package/build/src/config.js +0 -12
  84. package/build/src/config.js.map +1 -1
  85. package/build/src/servers/server.builder.d.ts +1 -118
  86. package/build/src/servers/server.builder.js +0 -20
  87. package/build/src/servers/server.builder.js.map +1 -1
  88. package/build/src/servers/server.d.ts +2 -2
  89. package/build/src/servers/server.js +2 -12
  90. package/build/src/servers/server.js.map +1 -1
  91. package/build/src/types/api-response.d.ts +28 -0
  92. package/build/src/types/api-response.js +11 -0
  93. package/build/src/types/api-response.js.map +1 -1
  94. package/build/src/types/server.d.ts +0 -17
  95. package/build/src/types/server.js.map +1 -1
  96. package/build/src/utils/async.utils.d.ts +91 -0
  97. package/build/src/utils/async.utils.js +194 -0
  98. package/build/src/utils/async.utils.js.map +1 -1
  99. package/build/src/utils/context-store.utils.d.ts +3 -0
  100. package/build/src/utils/context-store.utils.js +9 -6
  101. package/build/src/utils/context-store.utils.js.map +1 -1
  102. package/build/src/utils/date.utils.d.ts +159 -0
  103. package/build/src/utils/date.utils.js +396 -0
  104. package/build/src/utils/date.utils.js.map +1 -0
  105. package/build/src/utils/logger.utils.d.ts +3 -9
  106. package/build/src/utils/logger.utils.js +4 -10
  107. package/build/src/utils/logger.utils.js.map +1 -1
  108. package/build/src/utils/middleware.utils.js +2 -1
  109. package/build/src/utils/middleware.utils.js.map +1 -1
  110. package/build/src/utils/performance.utils.d.ts +136 -0
  111. package/build/src/utils/performance.utils.js +278 -0
  112. package/build/src/utils/performance.utils.js.map +1 -0
  113. package/build/src/utils/request.utils.d.ts +9 -0
  114. package/build/src/utils/request.utils.js +25 -5
  115. package/build/src/utils/request.utils.js.map +1 -1
  116. package/build/src/utils/stream.utils.d.ts +88 -0
  117. package/build/src/utils/stream.utils.js +218 -0
  118. package/build/src/utils/stream.utils.js.map +1 -0
  119. package/build/src/utils/type.utils.d.ts +90 -0
  120. package/build/src/utils/type.utils.js +196 -0
  121. package/build/src/utils/type.utils.js.map +1 -0
  122. package/package.json +6 -2
@@ -0,0 +1,88 @@
1
+ import { Readable, Transform } from 'stream';
2
+ import { BufferEncoding } from './crypto.utils';
3
+ /**
4
+ * Convert a buffer or string to a readable stream.
5
+ *
6
+ * @param data - Buffer or string to convert
7
+ * @returns Readable stream containing the data
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * const stream = bufferToStream(Buffer.from('Hello world'));
12
+ * // or
13
+ * const stream = bufferToStream('Hello world');
14
+ * ```
15
+ */
16
+ export declare function bufferToStream(data: Buffer | string): Readable;
17
+ /**
18
+ * Convert a readable stream to a buffer.
19
+ *
20
+ * @param stream - Readable stream to convert
21
+ * @returns Promise resolving to a buffer containing all stream data
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * const buffer = await streamToBuffer(fs.createReadStream('file.txt'));
26
+ * console.log(buffer.toString()); // Contents of file.txt
27
+ * ```
28
+ */
29
+ export declare function streamToBuffer(stream: Readable): Promise<Buffer>;
30
+ /**
31
+ * Convert a readable stream to a string.
32
+ *
33
+ * @param stream - Readable stream to convert
34
+ * @param encoding - Character encoding (default: 'utf8')
35
+ * @returns Promise resolving to a string containing all stream data
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * const content = await streamToString(fs.createReadStream('file.txt'));
40
+ * console.log(content); // Contents of file.txt as string
41
+ * ```
42
+ */
43
+ export declare function streamToString(stream: Readable, encoding?: BufferEncoding): Promise<string>;
44
+ /**
45
+ * Create a transform stream that limits the rate of data flow.
46
+ *
47
+ * @param bytesPerSecond - Maximum bytes per second
48
+ * @returns Transform stream that throttles data flow
49
+ */
50
+ export declare function createThrottleStream(bytesPerSecond: number): Transform;
51
+ /**
52
+ * Create a transform stream that batches data into chunks of specified size.
53
+ *
54
+ * @param size - Size of each batch (items for object mode, bytes for binary mode)
55
+ * @param options - Stream options
56
+ * @returns Transform stream that batches data
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * // Batch lines from a file into arrays of 100 lines each
61
+ * createReadStream('large-file.txt')
62
+ * .pipe(createLineStream())
63
+ * .pipe(createBatchStream(100))
64
+ * .on('data', batch => console.log(`Processing batch of ${batch.length} lines`));
65
+ * ```
66
+ */
67
+ export declare function createBatchStream(size: number, options?: {
68
+ objectMode?: boolean;
69
+ }): Transform;
70
+ /**
71
+ * Create a transform stream that splits text data by newlines.
72
+ *
73
+ * @param options - Options for the line stream
74
+ * @returns Transform stream that emits lines
75
+ *
76
+ * @example
77
+ * ```typescript
78
+ * // Process a file line by line
79
+ * createReadStream('file.txt')
80
+ * .pipe(createLineStream())
81
+ * .on('data', line => console.log(`Line: ${line}`));
82
+ * ```
83
+ */
84
+ export declare function createLineStream(options?: {
85
+ encoding?: BufferEncoding;
86
+ includeNewlines?: boolean;
87
+ }): Transform;
88
+ //# sourceMappingURL=stream.utils.d.ts.map
@@ -0,0 +1,284 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
25
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
26
+ return new (P || (P = Promise))(function (resolve, reject) {
27
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
28
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
29
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
30
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
31
+ });
32
+ };
33
+ var __generator = (this && this.__generator) || function (thisArg, body) {
34
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
35
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
36
+ function verb(n) { return function (v) { return step([n, v]); }; }
37
+ function step(op) {
38
+ if (f) throw new TypeError("Generator is already executing.");
39
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
40
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
41
+ if (y = 0, t) op = [op[0] & 2, t.value];
42
+ switch (op[0]) {
43
+ case 0: case 1: t = op; break;
44
+ case 4: _.label++; return { value: op[1], done: false };
45
+ case 5: _.label++; y = op[1]; op = [0]; continue;
46
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
47
+ default:
48
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
49
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
50
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
51
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
52
+ if (t[2]) _.ops.pop();
53
+ _.trys.pop(); continue;
54
+ }
55
+ op = body.call(thisArg, _);
56
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
57
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
58
+ }
59
+ };
60
+ var __values = (this && this.__values) || function(o) {
61
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
62
+ if (m) return m.call(o);
63
+ if (o && typeof o.length === "number") return {
64
+ next: function () {
65
+ if (o && i >= o.length) o = void 0;
66
+ return { value: o && o[i++], done: !o };
67
+ }
68
+ };
69
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
70
+ };
71
+ import { Readable, Transform } from 'stream';
72
+ /**
73
+ * Convert a buffer or string to a readable stream.
74
+ *
75
+ * @param data - Buffer or string to convert
76
+ * @returns Readable stream containing the data
77
+ *
78
+ * @example
79
+ * ```typescript
80
+ * const stream = bufferToStream(Buffer.from('Hello world'));
81
+ * // or
82
+ * const stream = bufferToStream('Hello world');
83
+ * ```
84
+ */
85
+ export function bufferToStream(data) {
86
+ var readable = new Readable();
87
+ readable.push(data);
88
+ readable.push(null); // End of stream
89
+ return readable;
90
+ }
91
+ /**
92
+ * Convert a readable stream to a buffer.
93
+ *
94
+ * @param stream - Readable stream to convert
95
+ * @returns Promise resolving to a buffer containing all stream data
96
+ *
97
+ * @example
98
+ * ```typescript
99
+ * const buffer = await streamToBuffer(fs.createReadStream('file.txt'));
100
+ * console.log(buffer.toString()); // Contents of file.txt
101
+ * ```
102
+ */
103
+ export function streamToBuffer(stream) {
104
+ return __awaiter(this, void 0, void 0, function () {
105
+ return __generator(this, function (_a) {
106
+ return [2 /*return*/, new Promise(function (resolve, reject) {
107
+ var chunks = [];
108
+ stream.on('data', function (chunk) { return chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); });
109
+ stream.on('end', function () { return resolve(Buffer.concat(chunks)); });
110
+ stream.on('error', reject);
111
+ })];
112
+ });
113
+ });
114
+ }
115
+ /**
116
+ * Convert a readable stream to a string.
117
+ *
118
+ * @param stream - Readable stream to convert
119
+ * @param encoding - Character encoding (default: 'utf8')
120
+ * @returns Promise resolving to a string containing all stream data
121
+ *
122
+ * @example
123
+ * ```typescript
124
+ * const content = await streamToString(fs.createReadStream('file.txt'));
125
+ * console.log(content); // Contents of file.txt as string
126
+ * ```
127
+ */
128
+ export function streamToString(stream_1) {
129
+ return __awaiter(this, arguments, void 0, function (stream, encoding) {
130
+ var buffer;
131
+ if (encoding === void 0) { encoding = 'utf8'; }
132
+ return __generator(this, function (_a) {
133
+ switch (_a.label) {
134
+ case 0: return [4 /*yield*/, streamToBuffer(stream)];
135
+ case 1:
136
+ buffer = _a.sent();
137
+ return [2 /*return*/, buffer.toString(encoding)];
138
+ }
139
+ });
140
+ });
141
+ }
142
+ /**
143
+ * Create a transform stream that limits the rate of data flow.
144
+ *
145
+ * @param bytesPerSecond - Maximum bytes per second
146
+ * @returns Transform stream that throttles data flow
147
+ */
148
+ export function createThrottleStream(bytesPerSecond) {
149
+ var bytesSent = 0;
150
+ var startTime = Date.now();
151
+ return new Transform({
152
+ transform: function (chunk, _encoding, callback) {
153
+ var elapsedSeconds = (Date.now() - startTime) / 1000;
154
+ var targetBytes = bytesPerSecond * elapsedSeconds;
155
+ var chunkSize = chunk.length;
156
+ // If we've sent fewer bytes than our target, just send the chunk
157
+ if (bytesSent + chunkSize <= targetBytes) {
158
+ bytesSent += chunkSize;
159
+ callback(null, chunk);
160
+ return;
161
+ }
162
+ // Otherwise we need to throttle
163
+ var delay = ((bytesSent + chunkSize) / bytesPerSecond - elapsedSeconds) * 1000;
164
+ setTimeout(function () {
165
+ bytesSent += chunkSize;
166
+ callback(null, chunk);
167
+ }, delay);
168
+ }
169
+ });
170
+ }
171
+ /**
172
+ * Create a transform stream that batches data into chunks of specified size.
173
+ *
174
+ * @param size - Size of each batch (items for object mode, bytes for binary mode)
175
+ * @param options - Stream options
176
+ * @returns Transform stream that batches data
177
+ *
178
+ * @example
179
+ * ```typescript
180
+ * // Batch lines from a file into arrays of 100 lines each
181
+ * createReadStream('large-file.txt')
182
+ * .pipe(createLineStream())
183
+ * .pipe(createBatchStream(100))
184
+ * .on('data', batch => console.log(`Processing batch of ${batch.length} lines`));
185
+ * ```
186
+ */
187
+ export function createBatchStream(size, options) {
188
+ if (options === void 0) { options = {}; }
189
+ var objectMode = options.objectMode !== false;
190
+ var batch = [];
191
+ var buffers = [];
192
+ var bufferSize = 0;
193
+ return new Transform({
194
+ objectMode: objectMode,
195
+ transform: function (chunk, _encoding, callback) {
196
+ if (objectMode) {
197
+ batch.push(chunk);
198
+ if (batch.length >= size) {
199
+ this.push(batch);
200
+ batch = [];
201
+ }
202
+ }
203
+ else {
204
+ var buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
205
+ buffers.push(buffer);
206
+ bufferSize += buffer.length;
207
+ // Emit batches of exact size
208
+ var combined = Buffer.concat(buffers, bufferSize);
209
+ while (combined.length >= size) {
210
+ this.push(combined.slice(0, size));
211
+ combined = combined.slice(size);
212
+ }
213
+ buffers = combined.length > 0 ? [combined] : [];
214
+ bufferSize = combined.length;
215
+ }
216
+ callback();
217
+ },
218
+ flush: function (callback) {
219
+ if (objectMode && batch.length > 0) {
220
+ this.push(batch);
221
+ }
222
+ else if (!objectMode && buffers.length > 0 && bufferSize > 0) {
223
+ var combined = Buffer.concat(buffers, bufferSize);
224
+ while (combined.length >= size) {
225
+ this.push(combined.slice(0, size));
226
+ combined = combined.slice(size);
227
+ }
228
+ if (combined.length > 0) {
229
+ this.push(combined);
230
+ }
231
+ }
232
+ callback();
233
+ }
234
+ });
235
+ }
236
+ /**
237
+ * Create a transform stream that splits text data by newlines.
238
+ *
239
+ * @param options - Options for the line stream
240
+ * @returns Transform stream that emits lines
241
+ *
242
+ * @example
243
+ * ```typescript
244
+ * // Process a file line by line
245
+ * createReadStream('file.txt')
246
+ * .pipe(createLineStream())
247
+ * .on('data', line => console.log(`Line: ${line}`));
248
+ * ```
249
+ */
250
+ export function createLineStream(options) {
251
+ if (options === void 0) { options = {}; }
252
+ var _a = options.encoding, encoding = _a === void 0 ? 'utf8' : _a, _b = options.includeNewlines, includeNewlines = _b === void 0 ? false : _b;
253
+ var buffer = '';
254
+ return new Transform({
255
+ objectMode: true,
256
+ transform: function (chunk, _encoding, callback) {
257
+ var e_1, _a;
258
+ var str = buffer + (Buffer.isBuffer(chunk) ? chunk.toString(encoding) : chunk);
259
+ var lines = str.split(/\r?\n/);
260
+ buffer = lines.pop() || '';
261
+ try {
262
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
263
+ var line = lines_1_1.value;
264
+ this.push(includeNewlines ? line + '\n' : line);
265
+ }
266
+ }
267
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
268
+ finally {
269
+ try {
270
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
271
+ }
272
+ finally { if (e_1) throw e_1.error; }
273
+ }
274
+ callback();
275
+ },
276
+ flush: function (callback) {
277
+ if (buffer) {
278
+ this.push(buffer);
279
+ }
280
+ callback();
281
+ }
282
+ });
283
+ }
284
+ //# sourceMappingURL=stream.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream.utils.js","sourceRoot":"","sources":["../../../src/utils/stream.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;;;;;;;;;;;;;;;;;;;;;;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AC;;gBAE3B,KAAmB,IAAA,UAAA,SAAA,KAAK,CAAA,4BAAA,+CAAE,CAAC;oBAAtB,IAAM,IAAI,kBAAA;oBACb,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;gBAClD,CAAC;;;;;;;;;YAED,QAAQ,EAAE,CAAC;QACb,CAAC;QAED,KAAK,YAAC,QAAQ;YACZ,IAAI,MAAM,EAAE,CAAC;gBACX,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACpB,CAAC;YACD,QAAQ,EAAE,CAAC;QACb,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Readable, Transform, TransformCallback } from 'stream';\nimport { BufferEncoding } from './crypto.utils';\n\n/**\n * Convert a buffer or string to a readable stream.\n *\n * @param data - Buffer or string to convert\n * @returns Readable stream containing the data\n *\n * @example\n * ```typescript\n * const stream = bufferToStream(Buffer.from('Hello world'));\n * // or\n * const stream = bufferToStream('Hello world');\n * ```\n */\nexport function bufferToStream(data: Buffer | string): Readable {\n const readable = new Readable();\n readable.push(data);\n readable.push(null); // End of stream\n return readable;\n}\n\n/**\n * Convert a readable stream to a buffer.\n *\n * @param stream - Readable stream to convert\n * @returns Promise resolving to a buffer containing all stream data\n *\n * @example\n * ```typescript\n * const buffer = await streamToBuffer(fs.createReadStream('file.txt'));\n * console.log(buffer.toString()); // Contents of file.txt\n * ```\n */\nexport async function streamToBuffer(stream: Readable): Promise<Buffer> {\n return new Promise<Buffer>((resolve, reject) => {\n const chunks: Buffer[] = [];\n stream.on('data', chunk => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));\n stream.on('end', () => resolve(Buffer.concat(chunks)));\n stream.on('error', reject);\n });\n}\n\n/**\n * Convert a readable stream to a string.\n *\n * @param stream - Readable stream to convert\n * @param encoding - Character encoding (default: 'utf8')\n * @returns Promise resolving to a string containing all stream data\n *\n * @example\n * ```typescript\n * const content = await streamToString(fs.createReadStream('file.txt'));\n * console.log(content); // Contents of file.txt as string\n * ```\n */\nexport async function streamToString(stream: Readable, encoding: BufferEncoding = 'utf8'): Promise<string> {\n const buffer = await streamToBuffer(stream);\n return buffer.toString(encoding);\n}\n\n/**\n * Create a transform stream that limits the rate of data flow.\n *\n * @param bytesPerSecond - Maximum bytes per second\n * @returns Transform stream that throttles data flow\n */\nexport function createThrottleStream(bytesPerSecond: number): Transform {\n let bytesSent = 0;\n let startTime = Date.now();\n\n return new Transform({\n transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback) {\n const elapsedSeconds = (Date.now() - startTime) / 1000;\n const targetBytes = bytesPerSecond * elapsedSeconds;\n const chunkSize = chunk.length;\n\n // If we've sent fewer bytes than our target, just send the chunk\n if (bytesSent + chunkSize <= targetBytes) {\n bytesSent += chunkSize;\n callback(null, chunk);\n return;\n }\n\n // Otherwise we need to throttle\n const delay = ((bytesSent + chunkSize) / bytesPerSecond - elapsedSeconds) * 1000;\n\n setTimeout(() => {\n bytesSent += chunkSize;\n callback(null, chunk);\n }, delay);\n }\n });\n}\n\n/**\n * Create a transform stream that batches data into chunks of specified size.\n *\n * @param size - Size of each batch (items for object mode, bytes for binary mode)\n * @param options - Stream options\n * @returns Transform stream that batches data\n *\n * @example\n * ```typescript\n * // Batch lines from a file into arrays of 100 lines each\n * createReadStream('large-file.txt')\n * .pipe(createLineStream())\n * .pipe(createBatchStream(100))\n * .on('data', batch => console.log(`Processing batch of ${batch.length} lines`));\n * ```\n */\nexport function createBatchStream(size: number, options: { objectMode?: boolean } = {}): Transform {\n const objectMode = options.objectMode !== false;\n let batch: any[] = [];\n let buffers: Buffer[] = [];\n let bufferSize = 0;\n\n return new Transform({\n objectMode,\n transform(chunk, _encoding, callback) {\n if (objectMode) {\n batch.push(chunk);\n if (batch.length >= size) {\n this.push(batch);\n batch = [];\n }\n } else {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n buffers.push(buffer);\n bufferSize += buffer.length;\n\n // Emit batches of exact size\n let combined = Buffer.concat(buffers, bufferSize);\n while (combined.length >= size) {\n this.push(combined.slice(0, size));\n combined = combined.slice(size);\n }\n buffers = combined.length > 0 ? [combined] : [];\n bufferSize = combined.length;\n }\n\n callback();\n },\n\n flush(callback) {\n if (objectMode && batch.length > 0) {\n this.push(batch);\n } else if (!objectMode && buffers.length > 0 && bufferSize > 0) {\n let combined = Buffer.concat(buffers, bufferSize);\n while (combined.length >= size) {\n this.push(combined.slice(0, size));\n combined = combined.slice(size);\n }\n if (combined.length > 0) {\n this.push(combined);\n }\n }\n callback();\n }\n });\n}\n\n/**\n * Create a transform stream that splits text data by newlines.\n *\n * @param options - Options for the line stream\n * @returns Transform stream that emits lines\n *\n * @example\n * ```typescript\n * // Process a file line by line\n * createReadStream('file.txt')\n * .pipe(createLineStream())\n * .on('data', line => console.log(`Line: ${line}`));\n * ```\n */\nexport function createLineStream(\n options: {\n encoding?: BufferEncoding;\n includeNewlines?: boolean;\n } = {}\n): Transform {\n const { encoding = 'utf8', includeNewlines = false } = options;\n let buffer = '';\n\n return new Transform({\n objectMode: true,\n transform(chunk, _encoding, callback) {\n const str = buffer + (Buffer.isBuffer(chunk) ? chunk.toString(encoding) : chunk);\n const lines = str.split(/\\r?\\n/);\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n this.push(includeNewlines ? line + '\\n' : line);\n }\n\n callback();\n },\n\n flush(callback) {\n if (buffer) {\n this.push(buffer);\n }\n callback();\n }\n });\n}\n"]}
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Check if a value is of a specific primitive type.
3
+ *
4
+ * @param value - Value to check
5
+ * @param type - Type to check against
6
+ * @returns Whether the value is of the specified type
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * isPrimitiveType('hello', 'string'); // true
11
+ * isPrimitiveType(42, 'number'); // true
12
+ * isPrimitiveType(true, 'boolean'); // true
13
+ * isPrimitiveType(null, 'null'); // true
14
+ * isPrimitiveType(undefined, 'undefined'); // true
15
+ * isPrimitiveType({}, 'object'); // true
16
+ * isPrimitiveType([], 'array'); // true
17
+ * ```
18
+ */
19
+ export declare function isPrimitiveType(value: unknown, type: 'string' | 'number' | 'boolean' | 'symbol' | 'bigint' | 'function' | 'object' | 'array' | 'null' | 'undefined'): boolean;
20
+ /**
21
+ * Get the primitive type of a value as a string.
22
+ *
23
+ * @param value - Value to get the type of
24
+ * @returns String representing the type
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * getTypeOf('hello'); // 'string'
29
+ * getTypeOf(42); // 'number'
30
+ * getTypeOf([]); // 'array'
31
+ * getTypeOf(null); // 'null'
32
+ * ```
33
+ */
34
+ export declare function getTypeOf(value: unknown): string;
35
+ /**
36
+ * Type guard for checking if a value is an array of a specific type.
37
+ *
38
+ * @param value - Value to check
39
+ * @param itemTypeGuard - Function that checks if items are of the expected type
40
+ * @returns True if the value is an array with items of the expected type
41
+ *
42
+ * @example
43
+ * ```typescript
44
+ * isArrayOf([1, 2, 3], (item): item is number => typeof item === 'number'); // true
45
+ * isArrayOf(['a', 'b', 'c'], (item): item is string => typeof item === 'string'); // true
46
+ * isArrayOf([1, '2', 3], (item): item is number => typeof item === 'number'); // false
47
+ * ```
48
+ */
49
+ export declare function isArrayOf<T>(value: unknown, itemTypeGuard: (item: unknown) => item is T): value is T[];
50
+ /**
51
+ * Convert a value to a string.
52
+ *
53
+ * @param value - Value to convert
54
+ * @param defaultValue - Default value if conversion fails
55
+ * @returns String representation of the value
56
+ */
57
+ export declare function toStr(value: unknown, defaultValue?: string): string;
58
+ /**
59
+ * Convert a value to a number.
60
+ *
61
+ * @param value - Value to convert
62
+ * @param defaultValue - Default value if conversion fails
63
+ * @returns Numeric representation of the value
64
+ */
65
+ export declare function toNum(value: unknown, defaultValue?: number): number;
66
+ /**
67
+ * Convert a value to a boolean.
68
+ *
69
+ * @param value - Value to convert
70
+ * @param defaultValue - Default value if conversion fails
71
+ * @returns Boolean representation of the value
72
+ */
73
+ export declare function toBool(value: unknown, defaultValue?: boolean): boolean;
74
+ /**
75
+ * Ensure a value matches the expected type, or provide a default.
76
+ *
77
+ * @param value - Value to check
78
+ * @param expectedType - Expected primitive type
79
+ * @param defaultValue - Default value to use if type doesn't match
80
+ * @returns The value if it matches the type, otherwise the default
81
+ *
82
+ * @example
83
+ * ```typescript
84
+ * ensureType(42, 'number', 0); // 42
85
+ * ensureType('42', 'number', 0); // 0
86
+ * ensureType(undefined, 'string', 'default'); // 'default'
87
+ * ```
88
+ */
89
+ export declare function ensureType<T>(value: unknown, expectedType: string, defaultValue: T): T;
90
+ //# sourceMappingURL=type.utils.d.ts.map
@@ -0,0 +1,190 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+ /**
25
+ * Check if a value is of a specific primitive type.
26
+ *
27
+ * @param value - Value to check
28
+ * @param type - Type to check against
29
+ * @returns Whether the value is of the specified type
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * isPrimitiveType('hello', 'string'); // true
34
+ * isPrimitiveType(42, 'number'); // true
35
+ * isPrimitiveType(true, 'boolean'); // true
36
+ * isPrimitiveType(null, 'null'); // true
37
+ * isPrimitiveType(undefined, 'undefined'); // true
38
+ * isPrimitiveType({}, 'object'); // true
39
+ * isPrimitiveType([], 'array'); // true
40
+ * ```
41
+ */
42
+ export function isPrimitiveType(value, type) {
43
+ if (type === 'array') {
44
+ return Array.isArray(value);
45
+ }
46
+ if (type === 'null') {
47
+ return value === null;
48
+ }
49
+ if (type === 'undefined') {
50
+ return value === undefined;
51
+ }
52
+ if (type === 'object') {
53
+ // Only plain objects, not arrays or null
54
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
55
+ }
56
+ return typeof value === type;
57
+ }
58
+ /**
59
+ * Get the primitive type of a value as a string.
60
+ *
61
+ * @param value - Value to get the type of
62
+ * @returns String representing the type
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * getTypeOf('hello'); // 'string'
67
+ * getTypeOf(42); // 'number'
68
+ * getTypeOf([]); // 'array'
69
+ * getTypeOf(null); // 'null'
70
+ * ```
71
+ */
72
+ export function getTypeOf(value) {
73
+ if (value === null)
74
+ return 'null';
75
+ if (value === undefined)
76
+ return 'undefined';
77
+ if (Array.isArray(value))
78
+ return 'array';
79
+ return typeof value;
80
+ }
81
+ /**
82
+ * Type guard for checking if a value is an array of a specific type.
83
+ *
84
+ * @param value - Value to check
85
+ * @param itemTypeGuard - Function that checks if items are of the expected type
86
+ * @returns True if the value is an array with items of the expected type
87
+ *
88
+ * @example
89
+ * ```typescript
90
+ * isArrayOf([1, 2, 3], (item): item is number => typeof item === 'number'); // true
91
+ * isArrayOf(['a', 'b', 'c'], (item): item is string => typeof item === 'string'); // true
92
+ * isArrayOf([1, '2', 3], (item): item is number => typeof item === 'number'); // false
93
+ * ```
94
+ */
95
+ export function isArrayOf(value, itemTypeGuard) {
96
+ if (!Array.isArray(value))
97
+ return false;
98
+ return value.every(function (item) { return itemTypeGuard(item); });
99
+ }
100
+ /**
101
+ * Convert a value to a string.
102
+ *
103
+ * @param value - Value to convert
104
+ * @param defaultValue - Default value if conversion fails
105
+ * @returns String representation of the value
106
+ */
107
+ export function toStr(value, defaultValue) {
108
+ if (defaultValue === void 0) { defaultValue = ''; }
109
+ if (value === null || value === undefined)
110
+ return defaultValue;
111
+ try {
112
+ if (typeof value === 'object') {
113
+ return JSON.stringify(value);
114
+ }
115
+ return String(value);
116
+ }
117
+ catch (_a) {
118
+ return defaultValue;
119
+ }
120
+ }
121
+ /**
122
+ * Convert a value to a number.
123
+ *
124
+ * @param value - Value to convert
125
+ * @param defaultValue - Default value if conversion fails
126
+ * @returns Numeric representation of the value
127
+ */
128
+ export function toNum(value, defaultValue) {
129
+ if (defaultValue === void 0) { defaultValue = 0; }
130
+ if (value === null || value === undefined)
131
+ return defaultValue;
132
+ if (typeof value === 'number')
133
+ return value;
134
+ try {
135
+ var num = Number(value);
136
+ return isNaN(num) ? defaultValue : num;
137
+ }
138
+ catch (_a) {
139
+ return defaultValue;
140
+ }
141
+ }
142
+ /**
143
+ * Convert a value to a boolean.
144
+ *
145
+ * @param value - Value to convert
146
+ * @param defaultValue - Default value if conversion fails
147
+ * @returns Boolean representation of the value
148
+ */
149
+ export function toBool(value, defaultValue) {
150
+ if (defaultValue === void 0) { defaultValue = false; }
151
+ if (value === null || value === undefined)
152
+ return defaultValue;
153
+ if (typeof value === 'boolean')
154
+ return value;
155
+ if (typeof value === 'string') {
156
+ var lowercased = value.toLowerCase();
157
+ if (lowercased === 'true' || lowercased === 'yes' || lowercased === 'y' || lowercased === '1') {
158
+ return true;
159
+ }
160
+ if (lowercased === 'false' || lowercased === 'no' || lowercased === 'n' || lowercased === '0') {
161
+ return false;
162
+ }
163
+ }
164
+ if (typeof value === 'number') {
165
+ return value !== 0;
166
+ }
167
+ return defaultValue;
168
+ }
169
+ /**
170
+ * Ensure a value matches the expected type, or provide a default.
171
+ *
172
+ * @param value - Value to check
173
+ * @param expectedType - Expected primitive type
174
+ * @param defaultValue - Default value to use if type doesn't match
175
+ * @returns The value if it matches the type, otherwise the default
176
+ *
177
+ * @example
178
+ * ```typescript
179
+ * ensureType(42, 'number', 0); // 42
180
+ * ensureType('42', 'number', 0); // 0
181
+ * ensureType(undefined, 'string', 'default'); // 'default'
182
+ * ```
183
+ */
184
+ export function ensureType(value, expectedType, defaultValue) {
185
+ if (getTypeOf(value) === expectedType) {
186
+ return value;
187
+ }
188
+ return defaultValue;
189
+ }
190
+ //# sourceMappingURL=type.utils.js.map