@catbee/utils 1.0.1 → 1.0.3
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 +1 -2
- package/build/index.cjs +674 -7
- package/build/index.d.ts +491 -1
- package/build/index.mjs +647 -8
- package/package.json +3 -3
package/build/index.d.ts
CHANGED
|
@@ -26,6 +26,7 @@ import { AsyncLocalStorage } from 'async_hooks';
|
|
|
26
26
|
import { BinaryToTextEncoding, CipherGCMTypes } from 'crypto';
|
|
27
27
|
import express, { RequestHandler, Router, Request, Response, NextFunction, Express, json, urlencoded } from 'express';
|
|
28
28
|
import fs, { Stats } from 'fs';
|
|
29
|
+
import { Readable, Transform } from 'stream';
|
|
29
30
|
import * as prom_client from 'prom-client';
|
|
30
31
|
import http from 'http';
|
|
31
32
|
import https from 'https';
|
|
@@ -228,6 +229,10 @@ declare let config: {
|
|
|
228
229
|
* Has no effect in production.
|
|
229
230
|
*/
|
|
230
231
|
pretty: boolean;
|
|
232
|
+
/**
|
|
233
|
+
* Enables colorized output for pretty-print (default: true)
|
|
234
|
+
*/
|
|
235
|
+
colorize: boolean;
|
|
231
236
|
/**
|
|
232
237
|
* Single line output for pretty-print (default: false)
|
|
233
238
|
*/
|
|
@@ -239,6 +244,20 @@ declare let config: {
|
|
|
239
244
|
*/
|
|
240
245
|
defaultTtl: number;
|
|
241
246
|
};
|
|
247
|
+
server: {
|
|
248
|
+
/**
|
|
249
|
+
* Skip healthz endpoint even if health checks are configured
|
|
250
|
+
* Default: false
|
|
251
|
+
* Set to true to return 200 OK for /healthz without checks
|
|
252
|
+
* Useful in environments where a simple liveness probe is needed
|
|
253
|
+
* without performing actual health checks
|
|
254
|
+
* Example: Kubernetes liveness probe
|
|
255
|
+
* Note: This does not disable the health check functionality itself
|
|
256
|
+
* Health checks can still be performed programmatically
|
|
257
|
+
* or via other endpoints if needed
|
|
258
|
+
*/
|
|
259
|
+
skipHealthz: boolean;
|
|
260
|
+
};
|
|
242
261
|
};
|
|
243
262
|
/**
|
|
244
263
|
* Update the @catbee/utils configuration.
|
|
@@ -1184,6 +1203,165 @@ declare function createSignedToken(payload: Record<string, any>, secret: string,
|
|
|
1184
1203
|
*/
|
|
1185
1204
|
declare function verifySignedToken(token: string, secret: string): Record<string, any> | null;
|
|
1186
1205
|
|
|
1206
|
+
/**
|
|
1207
|
+
* Format options for the formatDate function
|
|
1208
|
+
*/
|
|
1209
|
+
interface DateFormatOptions {
|
|
1210
|
+
/** Date format pattern (default: 'yyyy-MM-dd') */
|
|
1211
|
+
format?: string;
|
|
1212
|
+
/** Locale to use for formatting (default: system locale) */
|
|
1213
|
+
locale?: string | string[];
|
|
1214
|
+
/** Time zone to use (default: system time zone) */
|
|
1215
|
+
timeZone?: string;
|
|
1216
|
+
}
|
|
1217
|
+
/**
|
|
1218
|
+
* Format a date according to the specified format pattern.
|
|
1219
|
+
*
|
|
1220
|
+
* @param date - Date to format
|
|
1221
|
+
* @param options - Formatting options
|
|
1222
|
+
* @returns Formatted date string
|
|
1223
|
+
*
|
|
1224
|
+
* @example
|
|
1225
|
+
* ```typescript
|
|
1226
|
+
* // Format as ISO date
|
|
1227
|
+
* formatDate(new Date(), { format: 'yyyy-MM-dd' }); // '2023-05-15'
|
|
1228
|
+
*
|
|
1229
|
+
* // Format with time
|
|
1230
|
+
* formatDate(new Date(), { format: 'yyyy-MM-dd HH:mm:ss' }); // '2023-05-15 14:30:22'
|
|
1231
|
+
*
|
|
1232
|
+
* // Format with locale
|
|
1233
|
+
* formatDate(new Date(), { format: 'PPPP', locale: 'fr-FR' }); // 'lundi 15 mai 2023'
|
|
1234
|
+
* ```
|
|
1235
|
+
*/
|
|
1236
|
+
declare function formatDate(date: Date | number, options?: DateFormatOptions): string;
|
|
1237
|
+
/**
|
|
1238
|
+
* Format a date as relative time (e.g., "5 minutes ago", "in 3 days").
|
|
1239
|
+
*
|
|
1240
|
+
* @param date - Date to format
|
|
1241
|
+
* @param now - Reference date (default: current time)
|
|
1242
|
+
* @param locale - Locale to use for formatting
|
|
1243
|
+
* @returns Formatted relative time string
|
|
1244
|
+
*/
|
|
1245
|
+
declare function formatRelativeTime(date: Date | number, now?: Date | number, locale?: string | string[]): string;
|
|
1246
|
+
/**
|
|
1247
|
+
* Parse a date string or timestamp into a Date object.
|
|
1248
|
+
*
|
|
1249
|
+
* @param input - Date string or timestamp to parse
|
|
1250
|
+
* @param fallback - Fallback date if parsing fails
|
|
1251
|
+
* @returns Parsed Date object or fallback
|
|
1252
|
+
*
|
|
1253
|
+
* @example
|
|
1254
|
+
* ```typescript
|
|
1255
|
+
* parseDate('2023-05-15'); // Date object for May 15, 2023
|
|
1256
|
+
* parseDate('invalid', new Date()); // Returns current date as fallback
|
|
1257
|
+
* ```
|
|
1258
|
+
*/
|
|
1259
|
+
declare function parseDate(input: string | number, fallback?: Date): Date | null;
|
|
1260
|
+
/**
|
|
1261
|
+
* Calculate the difference between two dates in the specified unit.
|
|
1262
|
+
*
|
|
1263
|
+
* @param date1 - First date
|
|
1264
|
+
* @param date2 - Second date (default: current time)
|
|
1265
|
+
* @param unit - Unit of time for the difference
|
|
1266
|
+
* @returns Difference in the specified unit
|
|
1267
|
+
*
|
|
1268
|
+
* @example
|
|
1269
|
+
* ```typescript
|
|
1270
|
+
* // Get difference in days
|
|
1271
|
+
* dateDiff(new Date('2023-05-15'), new Date('2023-05-10'), 'days'); // 5
|
|
1272
|
+
*
|
|
1273
|
+
* // Get difference in hours
|
|
1274
|
+
* dateDiff(new Date('2023-05-15T10:00:00'), new Date('2023-05-15T06:00:00'), 'hours'); // 4
|
|
1275
|
+
* ```
|
|
1276
|
+
*/
|
|
1277
|
+
declare function dateDiff(date1: Date | number, date2?: Date | number, unit?: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'): number;
|
|
1278
|
+
/**
|
|
1279
|
+
* Add a specified amount of time to a date.
|
|
1280
|
+
*
|
|
1281
|
+
* @param date - Base date
|
|
1282
|
+
* @param amount - Amount to add (can be negative)
|
|
1283
|
+
* @param unit - Unit of time to add
|
|
1284
|
+
* @returns New date with the addition
|
|
1285
|
+
*
|
|
1286
|
+
* @example
|
|
1287
|
+
* ```typescript
|
|
1288
|
+
* // Add 5 days
|
|
1289
|
+
* addToDate(new Date('2023-05-15'), 5, 'days'); // Date for May 20, 2023
|
|
1290
|
+
*
|
|
1291
|
+
* // Subtract 2 hours
|
|
1292
|
+
* addToDate(new Date('2023-05-15T10:00:00'), -2, 'hours'); // Date for May 15, 2023 08:00:00
|
|
1293
|
+
* ```
|
|
1294
|
+
*/
|
|
1295
|
+
declare function addToDate(date: Date | number, amount: number, unit: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'): Date;
|
|
1296
|
+
/**
|
|
1297
|
+
* Get the start of a time period containing the specified date.
|
|
1298
|
+
*
|
|
1299
|
+
* @param date - Date to get the start from
|
|
1300
|
+
* @param unit - Time unit
|
|
1301
|
+
* @returns Date object representing the start of the time unit
|
|
1302
|
+
*
|
|
1303
|
+
* @example
|
|
1304
|
+
* ```typescript
|
|
1305
|
+
* // Get start of day (midnight)
|
|
1306
|
+
* startOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 00:00:00
|
|
1307
|
+
*
|
|
1308
|
+
* // Get start of month
|
|
1309
|
+
* startOf(new Date('2023-05-15'), 'month'); // Date for May 1, 2023
|
|
1310
|
+
* ```
|
|
1311
|
+
*/
|
|
1312
|
+
declare function startOf(date: Date | number, unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'): Date;
|
|
1313
|
+
/**
|
|
1314
|
+
* Get the end of a time period containing the specified date.
|
|
1315
|
+
*
|
|
1316
|
+
* @param date - Date to get the end from
|
|
1317
|
+
* @param unit - Time unit
|
|
1318
|
+
* @returns Date object representing the end of the time unit
|
|
1319
|
+
*
|
|
1320
|
+
* @example
|
|
1321
|
+
* ```typescript
|
|
1322
|
+
* // Get end of day (23:59:59.999)
|
|
1323
|
+
* endOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 23:59:59.999
|
|
1324
|
+
*
|
|
1325
|
+
* // Get end of month
|
|
1326
|
+
* endOf(new Date('2023-05-15'), 'month'); // Date for May 31, 2023 23:59:59.999
|
|
1327
|
+
* ```
|
|
1328
|
+
*/
|
|
1329
|
+
declare function endOf(date: Date | number, unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'): Date;
|
|
1330
|
+
/**
|
|
1331
|
+
* Check if a date is between two other dates.
|
|
1332
|
+
*
|
|
1333
|
+
* @param date - Date to check
|
|
1334
|
+
* @param start - Start date of the range
|
|
1335
|
+
* @param end - End date of the range
|
|
1336
|
+
* @param inclusive - Whether the comparison should be inclusive of start/end
|
|
1337
|
+
* @returns True if the date is within the range
|
|
1338
|
+
*
|
|
1339
|
+
* @example
|
|
1340
|
+
* ```typescript
|
|
1341
|
+
* const date = new Date('2023-05-15');
|
|
1342
|
+
* const start = new Date('2023-05-10');
|
|
1343
|
+
* const end = new Date('2023-05-20');
|
|
1344
|
+
*
|
|
1345
|
+
* isBetween(date, start, end); // true
|
|
1346
|
+
* ```
|
|
1347
|
+
*/
|
|
1348
|
+
declare function isBetween(date: Date | number, start: Date | number, end: Date | number, inclusive?: boolean): boolean;
|
|
1349
|
+
/**
|
|
1350
|
+
* Check if a year is a leap year.
|
|
1351
|
+
*
|
|
1352
|
+
* @param year - Year to check (or date object)
|
|
1353
|
+
* @returns True if the year is a leap year
|
|
1354
|
+
*/
|
|
1355
|
+
declare function isLeapYear(year: number | Date): boolean;
|
|
1356
|
+
/**
|
|
1357
|
+
* Get the number of days in a month.
|
|
1358
|
+
*
|
|
1359
|
+
* @param year - Year
|
|
1360
|
+
* @param month - Month (0-11)
|
|
1361
|
+
* @returns Number of days in the month
|
|
1362
|
+
*/
|
|
1363
|
+
declare function daysInMonth(year: number | Date, month?: number): number;
|
|
1364
|
+
|
|
1187
1365
|
/**
|
|
1188
1366
|
* Parameter decoration definition for method parameters
|
|
1189
1367
|
*/
|
|
@@ -3642,6 +3820,142 @@ declare function isObject(value: unknown): value is Record<string, any>;
|
|
|
3642
3820
|
*/
|
|
3643
3821
|
declare function getAllPaths(obj: Record<string, any>, parentPath?: string): string[];
|
|
3644
3822
|
|
|
3823
|
+
/**
|
|
3824
|
+
* Options for timing function execution.
|
|
3825
|
+
*/
|
|
3826
|
+
interface TimingOptions {
|
|
3827
|
+
/** Optional label for the timing (defaults to function name) */
|
|
3828
|
+
label?: string;
|
|
3829
|
+
/** Whether to log the timing (default: false) */
|
|
3830
|
+
log?: boolean;
|
|
3831
|
+
/** Log level to use if logging is enabled (default: 'debug') */
|
|
3832
|
+
logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error';
|
|
3833
|
+
}
|
|
3834
|
+
/**
|
|
3835
|
+
* Result of a timing operation.
|
|
3836
|
+
*/
|
|
3837
|
+
interface TimingResult {
|
|
3838
|
+
/** Duration in milliseconds */
|
|
3839
|
+
durationMs: number;
|
|
3840
|
+
/** Duration in seconds */
|
|
3841
|
+
durationSec: number;
|
|
3842
|
+
/** Start timestamp */
|
|
3843
|
+
startTime: number;
|
|
3844
|
+
/** End timestamp */
|
|
3845
|
+
endTime: number;
|
|
3846
|
+
/** Label used for the timing */
|
|
3847
|
+
label: string;
|
|
3848
|
+
}
|
|
3849
|
+
/**
|
|
3850
|
+
* Measure the execution time of a synchronous function.
|
|
3851
|
+
*
|
|
3852
|
+
* @param fn - Function to measure
|
|
3853
|
+
* @param options - Timing options
|
|
3854
|
+
* @returns Result containing the return value and timing information
|
|
3855
|
+
*
|
|
3856
|
+
* @example
|
|
3857
|
+
* ```typescript
|
|
3858
|
+
* const { result, timing } = timeSync(() => {
|
|
3859
|
+
* // Some expensive operation
|
|
3860
|
+
* return computeResult();
|
|
3861
|
+
* }, { label: 'Computation', log: true });
|
|
3862
|
+
*
|
|
3863
|
+
* console.log(`Result: ${result}, took ${timing.durationMs}ms`);
|
|
3864
|
+
* ```
|
|
3865
|
+
*/
|
|
3866
|
+
declare function timeSync<T>(fn: () => T, options?: TimingOptions): {
|
|
3867
|
+
result: T;
|
|
3868
|
+
timing: TimingResult;
|
|
3869
|
+
};
|
|
3870
|
+
/**
|
|
3871
|
+
* Measure the execution time of an asynchronous function.
|
|
3872
|
+
*
|
|
3873
|
+
* @param fn - Async function to measure
|
|
3874
|
+
* @param options - Timing options
|
|
3875
|
+
* @returns Promise resolving to result and timing information
|
|
3876
|
+
*
|
|
3877
|
+
* @example
|
|
3878
|
+
* ```typescript
|
|
3879
|
+
* const { result, timing } = await timeAsync(async () => {
|
|
3880
|
+
* // Some expensive async operation
|
|
3881
|
+
* const data = await fetchData();
|
|
3882
|
+
* return processData(data);
|
|
3883
|
+
* }, { label: 'API Request', log: true });
|
|
3884
|
+
*
|
|
3885
|
+
* console.log(`Fetched ${result.length} items in ${timing.durationSec.toFixed(2)}s`);
|
|
3886
|
+
* ```
|
|
3887
|
+
*/
|
|
3888
|
+
declare function timeAsync<T>(fn: () => Promise<T>, options?: TimingOptions): Promise<{
|
|
3889
|
+
result: T;
|
|
3890
|
+
timing: TimingResult;
|
|
3891
|
+
}>;
|
|
3892
|
+
/**
|
|
3893
|
+
* Create a timing decorator for class methods.
|
|
3894
|
+
*
|
|
3895
|
+
* @param options - Timing options
|
|
3896
|
+
* @returns Method decorator
|
|
3897
|
+
*
|
|
3898
|
+
* @example
|
|
3899
|
+
* ```typescript
|
|
3900
|
+
* class DataService {
|
|
3901
|
+
* @timed({ log: true, logLevel: 'info' })
|
|
3902
|
+
* async fetchData() {
|
|
3903
|
+
* // ...implementation
|
|
3904
|
+
* }
|
|
3905
|
+
* }
|
|
3906
|
+
* ```
|
|
3907
|
+
*/
|
|
3908
|
+
declare function timed(options?: TimingOptions): (target: any, propertyKeyOrContext: string | symbol | any, descriptor?: PropertyDescriptor) => void;
|
|
3909
|
+
/**
|
|
3910
|
+
* Memoize function results with optional TTL and max cache size.
|
|
3911
|
+
*
|
|
3912
|
+
* @param fn - Function to memoize
|
|
3913
|
+
* @param options - Memoization options
|
|
3914
|
+
* @returns Memoized function
|
|
3915
|
+
*
|
|
3916
|
+
* @example
|
|
3917
|
+
* ```typescript
|
|
3918
|
+
* // Cache results for 30 seconds, with a maximum of 100 entries
|
|
3919
|
+
* const cachedFetch = memoize(
|
|
3920
|
+
* async (url) => {
|
|
3921
|
+
* const response = await fetch(url);
|
|
3922
|
+
* return response.json();
|
|
3923
|
+
* },
|
|
3924
|
+
* { ttl: 30000, maxSize: 100, cacheKey: (url) => url }
|
|
3925
|
+
* );
|
|
3926
|
+
* ```
|
|
3927
|
+
*/
|
|
3928
|
+
declare function memoize<T, Args extends any[]>(fn: (...args: Args) => T, options?: {
|
|
3929
|
+
/** Time-to-live in milliseconds (default: indefinite) */
|
|
3930
|
+
ttl?: number;
|
|
3931
|
+
/** Maximum cache size (default: unlimited) */
|
|
3932
|
+
maxSize?: number;
|
|
3933
|
+
/** Function to generate a cache key from arguments */
|
|
3934
|
+
cacheKey?: (...args: Args) => string;
|
|
3935
|
+
/** Auto-cleanup interval in milliseconds (default: disabled) */
|
|
3936
|
+
autoCleanupMs?: number;
|
|
3937
|
+
}): (...args: Args) => T;
|
|
3938
|
+
/**
|
|
3939
|
+
* Track memory usage for a function execution.
|
|
3940
|
+
*
|
|
3941
|
+
* @param fn - Function to track
|
|
3942
|
+
* @param options - Memory tracking options
|
|
3943
|
+
* @returns Result and memory usage information
|
|
3944
|
+
*/
|
|
3945
|
+
declare function trackMemoryUsage<T>(fn: () => T, options?: {
|
|
3946
|
+
/** Whether to log the memory usage (default: false) */
|
|
3947
|
+
log?: boolean;
|
|
3948
|
+
/** Label for the memory tracking (default: function name) */
|
|
3949
|
+
label?: string;
|
|
3950
|
+
}): {
|
|
3951
|
+
result: T;
|
|
3952
|
+
memoryUsage: {
|
|
3953
|
+
before: NodeJS.MemoryUsage;
|
|
3954
|
+
after: NodeJS.MemoryUsage;
|
|
3955
|
+
diff: Record<string, number>;
|
|
3956
|
+
};
|
|
3957
|
+
};
|
|
3958
|
+
|
|
3645
3959
|
/**
|
|
3646
3960
|
* Options for parsing and validating request parameters.
|
|
3647
3961
|
*/
|
|
@@ -3726,6 +4040,92 @@ declare function extractSortParams(query: Record<string, string | string[]>, all
|
|
|
3726
4040
|
*/
|
|
3727
4041
|
declare function extractFilterParams(query: Record<string, string | string[]>, allowedFilters: string[]): Record<string, string | string[]>;
|
|
3728
4042
|
|
|
4043
|
+
/**
|
|
4044
|
+
* Convert a buffer or string to a readable stream.
|
|
4045
|
+
*
|
|
4046
|
+
* @param data - Buffer or string to convert
|
|
4047
|
+
* @returns Readable stream containing the data
|
|
4048
|
+
*
|
|
4049
|
+
* @example
|
|
4050
|
+
* ```typescript
|
|
4051
|
+
* const stream = bufferToStream(Buffer.from('Hello world'));
|
|
4052
|
+
* // or
|
|
4053
|
+
* const stream = bufferToStream('Hello world');
|
|
4054
|
+
* ```
|
|
4055
|
+
*/
|
|
4056
|
+
declare function bufferToStream(data: Buffer | string): Readable;
|
|
4057
|
+
/**
|
|
4058
|
+
* Convert a readable stream to a buffer.
|
|
4059
|
+
*
|
|
4060
|
+
* @param stream - Readable stream to convert
|
|
4061
|
+
* @returns Promise resolving to a buffer containing all stream data
|
|
4062
|
+
*
|
|
4063
|
+
* @example
|
|
4064
|
+
* ```typescript
|
|
4065
|
+
* const buffer = await streamToBuffer(fs.createReadStream('file.txt'));
|
|
4066
|
+
* console.log(buffer.toString()); // Contents of file.txt
|
|
4067
|
+
* ```
|
|
4068
|
+
*/
|
|
4069
|
+
declare function streamToBuffer(stream: Readable): Promise<Buffer>;
|
|
4070
|
+
/**
|
|
4071
|
+
* Convert a readable stream to a string.
|
|
4072
|
+
*
|
|
4073
|
+
* @param stream - Readable stream to convert
|
|
4074
|
+
* @param encoding - Character encoding (default: 'utf8')
|
|
4075
|
+
* @returns Promise resolving to a string containing all stream data
|
|
4076
|
+
*
|
|
4077
|
+
* @example
|
|
4078
|
+
* ```typescript
|
|
4079
|
+
* const content = await streamToString(fs.createReadStream('file.txt'));
|
|
4080
|
+
* console.log(content); // Contents of file.txt as string
|
|
4081
|
+
* ```
|
|
4082
|
+
*/
|
|
4083
|
+
declare function streamToString(stream: Readable, encoding?: BufferEncoding): Promise<string>;
|
|
4084
|
+
/**
|
|
4085
|
+
* Create a transform stream that limits the rate of data flow.
|
|
4086
|
+
*
|
|
4087
|
+
* @param bytesPerSecond - Maximum bytes per second
|
|
4088
|
+
* @returns Transform stream that throttles data flow
|
|
4089
|
+
*/
|
|
4090
|
+
declare function createThrottleStream(bytesPerSecond: number): Transform;
|
|
4091
|
+
/**
|
|
4092
|
+
* Create a transform stream that batches data into chunks of specified size.
|
|
4093
|
+
*
|
|
4094
|
+
* @param size - Size of each batch (items for object mode, bytes for binary mode)
|
|
4095
|
+
* @param options - Stream options
|
|
4096
|
+
* @returns Transform stream that batches data
|
|
4097
|
+
*
|
|
4098
|
+
* @example
|
|
4099
|
+
* ```typescript
|
|
4100
|
+
* // Batch lines from a file into arrays of 100 lines each
|
|
4101
|
+
* createReadStream('large-file.txt')
|
|
4102
|
+
* .pipe(createLineStream())
|
|
4103
|
+
* .pipe(createBatchStream(100))
|
|
4104
|
+
* .on('data', batch => console.log(`Processing batch of ${batch.length} lines`));
|
|
4105
|
+
* ```
|
|
4106
|
+
*/
|
|
4107
|
+
declare function createBatchStream(size: number, options?: {
|
|
4108
|
+
objectMode?: boolean;
|
|
4109
|
+
}): Transform;
|
|
4110
|
+
/**
|
|
4111
|
+
* Create a transform stream that splits text data by newlines.
|
|
4112
|
+
*
|
|
4113
|
+
* @param options - Options for the line stream
|
|
4114
|
+
* @returns Transform stream that emits lines
|
|
4115
|
+
*
|
|
4116
|
+
* @example
|
|
4117
|
+
* ```typescript
|
|
4118
|
+
* // Process a file line by line
|
|
4119
|
+
* createReadStream('file.txt')
|
|
4120
|
+
* .pipe(createLineStream())
|
|
4121
|
+
* .on('data', line => console.log(`Line: ${line}`));
|
|
4122
|
+
* ```
|
|
4123
|
+
*/
|
|
4124
|
+
declare function createLineStream(options?: {
|
|
4125
|
+
encoding?: BufferEncoding;
|
|
4126
|
+
includeNewlines?: boolean;
|
|
4127
|
+
}): Transform;
|
|
4128
|
+
|
|
3729
4129
|
/**
|
|
3730
4130
|
* Capitalizes the first character of a string.
|
|
3731
4131
|
*
|
|
@@ -3819,6 +4219,96 @@ declare function reverse(str: string): string;
|
|
|
3819
4219
|
*/
|
|
3820
4220
|
declare function countOccurrences(str: string, substring: string, caseSensitive?: boolean): number;
|
|
3821
4221
|
|
|
4222
|
+
/**
|
|
4223
|
+
* Check if a value is of a specific primitive type.
|
|
4224
|
+
*
|
|
4225
|
+
* @param value - Value to check
|
|
4226
|
+
* @param type - Type to check against
|
|
4227
|
+
* @returns Whether the value is of the specified type
|
|
4228
|
+
*
|
|
4229
|
+
* @example
|
|
4230
|
+
* ```typescript
|
|
4231
|
+
* isPrimitiveType('hello', 'string'); // true
|
|
4232
|
+
* isPrimitiveType(42, 'number'); // true
|
|
4233
|
+
* isPrimitiveType(true, 'boolean'); // true
|
|
4234
|
+
* isPrimitiveType(null, 'null'); // true
|
|
4235
|
+
* isPrimitiveType(undefined, 'undefined'); // true
|
|
4236
|
+
* isPrimitiveType({}, 'object'); // true
|
|
4237
|
+
* isPrimitiveType([], 'array'); // true
|
|
4238
|
+
* ```
|
|
4239
|
+
*/
|
|
4240
|
+
declare function isPrimitiveType(value: unknown, type: 'string' | 'number' | 'boolean' | 'symbol' | 'bigint' | 'function' | 'object' | 'array' | 'null' | 'undefined'): boolean;
|
|
4241
|
+
/**
|
|
4242
|
+
* Get the primitive type of a value as a string.
|
|
4243
|
+
*
|
|
4244
|
+
* @param value - Value to get the type of
|
|
4245
|
+
* @returns String representing the type
|
|
4246
|
+
*
|
|
4247
|
+
* @example
|
|
4248
|
+
* ```typescript
|
|
4249
|
+
* getTypeOf('hello'); // 'string'
|
|
4250
|
+
* getTypeOf(42); // 'number'
|
|
4251
|
+
* getTypeOf([]); // 'array'
|
|
4252
|
+
* getTypeOf(null); // 'null'
|
|
4253
|
+
* ```
|
|
4254
|
+
*/
|
|
4255
|
+
declare function getTypeOf(value: unknown): string;
|
|
4256
|
+
/**
|
|
4257
|
+
* Type guard for checking if a value is an array of a specific type.
|
|
4258
|
+
*
|
|
4259
|
+
* @param value - Value to check
|
|
4260
|
+
* @param itemTypeGuard - Function that checks if items are of the expected type
|
|
4261
|
+
* @returns True if the value is an array with items of the expected type
|
|
4262
|
+
*
|
|
4263
|
+
* @example
|
|
4264
|
+
* ```typescript
|
|
4265
|
+
* isArrayOf([1, 2, 3], (item): item is number => typeof item === 'number'); // true
|
|
4266
|
+
* isArrayOf(['a', 'b', 'c'], (item): item is string => typeof item === 'string'); // true
|
|
4267
|
+
* isArrayOf([1, '2', 3], (item): item is number => typeof item === 'number'); // false
|
|
4268
|
+
* ```
|
|
4269
|
+
*/
|
|
4270
|
+
declare function isArrayOf<T>(value: unknown, itemTypeGuard: (item: unknown) => item is T): value is T[];
|
|
4271
|
+
/**
|
|
4272
|
+
* Convert a value to a string.
|
|
4273
|
+
*
|
|
4274
|
+
* @param value - Value to convert
|
|
4275
|
+
* @param defaultValue - Default value if conversion fails
|
|
4276
|
+
* @returns String representation of the value
|
|
4277
|
+
*/
|
|
4278
|
+
declare function toStr(value: unknown, defaultValue?: string): string;
|
|
4279
|
+
/**
|
|
4280
|
+
* Convert a value to a number.
|
|
4281
|
+
*
|
|
4282
|
+
* @param value - Value to convert
|
|
4283
|
+
* @param defaultValue - Default value if conversion fails
|
|
4284
|
+
* @returns Numeric representation of the value
|
|
4285
|
+
*/
|
|
4286
|
+
declare function toNum(value: unknown, defaultValue?: number): number;
|
|
4287
|
+
/**
|
|
4288
|
+
* Convert a value to a boolean.
|
|
4289
|
+
*
|
|
4290
|
+
* @param value - Value to convert
|
|
4291
|
+
* @param defaultValue - Default value if conversion fails
|
|
4292
|
+
* @returns Boolean representation of the value
|
|
4293
|
+
*/
|
|
4294
|
+
declare function toBool(value: unknown, defaultValue?: boolean): boolean;
|
|
4295
|
+
/**
|
|
4296
|
+
* Ensure a value matches the expected type, or provide a default.
|
|
4297
|
+
*
|
|
4298
|
+
* @param value - Value to check
|
|
4299
|
+
* @param expectedType - Expected primitive type
|
|
4300
|
+
* @param defaultValue - Default value to use if type doesn't match
|
|
4301
|
+
* @returns The value if it matches the type, otherwise the default
|
|
4302
|
+
*
|
|
4303
|
+
* @example
|
|
4304
|
+
* ```typescript
|
|
4305
|
+
* ensureType(42, 'number', 0); // 42
|
|
4306
|
+
* ensureType('42', 'number', 0); // 0
|
|
4307
|
+
* ensureType(undefined, 'string', 'default'); // 'default'
|
|
4308
|
+
* ```
|
|
4309
|
+
*/
|
|
4310
|
+
declare function ensureType<T>(value: unknown, expectedType: string, defaultValue: T): T;
|
|
4311
|
+
|
|
3822
4312
|
/**
|
|
3823
4313
|
* Appends query parameters to a given URL.
|
|
3824
4314
|
*
|
|
@@ -5281,4 +5771,4 @@ declare class ServerConfigBuilder {
|
|
|
5281
5771
|
private setEnabled;
|
|
5282
5772
|
}
|
|
5283
5773
|
|
|
5284
|
-
export { After, type ApiErrorResponse, type ApiResponse, type ApiSuccessResponse, type AsyncOperationResponse, type Awaited$1 as Awaited, BUILD_MARKER, BadGatewayException, BadRequestException, type BatchResponse, Before, Body, type BufferEncoding, Cache, CircuitBreakerOpenError, type CircuitBreakerOptions, CircuitBreakerState, ConflictException, Connect, ContentType, ContextStore, Controller, DIContainer, type DecryptionOptions, type DeepPartial, type DeepReadonly, type DeepRequired, type DeepStringifyOrNull, Delete, type EncryptionOptions, type EncryptionResult, Env, Environment, type ErrorHandlerOptions, ErrorResponse, ExpressServer, ForbiddenException, type Func, GatewayTimeoutException, Get, Head, Header, Headers, HttpCode, HttpError, HttpStatusCodes, Inject, Injectable, InsufficientStorageException, InternalServerErrorException, type IsEqual, type KeysOfType, Log, type Logger, type LoggerLevels, type MaybePromise, MethodNotAllowedException, type Middleware, type Mutable, NoContentResponse, type NonEmptyArray, NotAcceptableException, NotFoundException, type Nullable, type Optional, type Optional2, Options, PaginatedResponse, type Pagination, type PaginationParams, type PaginationResponse, Param, type ParamOptions, type PartialPick, Patch, type PathOptions, PayloadTooLargeException, type PickByType, Post, type Primitive, Put, Query, RateLimit, type RecordOptional, Redirect, RedirectResponse, Req, ReqCookie, ReqHeader, ReqId, ReqLogger, RequestTimeoutException, type RequireAtLeastOne, Res, Roles, type ServerConfig, ServerConfigBuilder, type ServerHooks, ServiceUnavailableException, SortDirection, type Store, StoreKeys, type StreamResponse, type StringKeyedRecord, SuccessResponse, TTLCache, type TTLCacheOptions, type TaskQueue, Timeout, type ToggleConfig, TooManyRequestsException, Trace, TypedContextKey, UnauthorizedException, type UnionToIntersection, UnprocessableEntityException, UnsupportedMediaTypeException, type UrlOptions, Use, type ValidationOptions, type ValidationResult, type ValueOf, Version, type WithPagination, type Without, type Writable, _globalThis, abortable, addRedactFields, addSensitiveFields, appendQueryParams, appendTextFile, capitalize, chunk, circuitBreaker, compact, copyDir, copyFile, countBy, countOccurrences, createChildLogger, createDeferred, createDirectory, createErrorResponse, createFinalErrorResponse, createHttpError, createPaginatedResponse, createParamDecorator, createParamDecoratorWithoutParam, createRequestLogger, createSignedToken, createSuccessResponse, createTaskQueue, createTempDir, createTempFile, createUrlBuilder, debounce, decrypt, deepFreeze, deepObjMerge, defaultSensitiveFields, deleteDirRecursive, deleteFileIfExists, difference, emptyDir, encrypt, ensureDir, ensureEmptyDir, equalsIgnoreCase, errorHandler, extractFilterParams, extractPaginationParams, extractQueryParams, extractSortParams, fileExists, filterObject, findFilesByPattern, findInDir, findNewestFile, findOldestFile, flattenDeep, flattenObject, generateApiKey, generateRandomBytes, generateRandomBytesAsString, getAllPaths, getConfig, getDirSize, getDirStats, getDomain, getErrorMessage, getExtension, getFileSize, getFileStats, getFromContext, getLogger, getPaginationParams, getRedactCensor, getRequestId, getSubdirectories, getValueByPath, groupBy, hasErrorShape, hasRequiredProps, hash, healthCheck, hmac, inject, intersect, isAlpha, isAlphanumeric, isArray, isBase64, isCreditCard, isDateInRange, isDirectory, isEmail, isEqual, isFile, isHexColor, isHttpError, isIPv4, isIPv6, isISODate, isLengthBetween, isNumberBetween, isNumeric, isObjEmpty, isObject, isPhone, isPlainObject, isPort, isStrongPassword, isURL, isUUID, isValidJSON, isValidUrl, joinPaths, listFiles, logError, logger, mapObject, mask, matchesPattern, md5, memoizeAsync, mergeSort, moveDir, moveFile, nanoId, normalizeUrl, omit, parseBooleanParam, parseNumberParam, parseQueryString, parseTypedQueryParams, partition, pick, pluck, random, randomBase64, randomHex, randomInt, randomString, range, rateLimit, readDirectory, readFileBuffer, readJsonFile, readTextFile, redact, registerControllers, removeQueryParams, requestId, responseTime, retry, reverse, runInBatches, runInSeries, runWithConcurrency, safeCompare, safeReadJsonFile, sendResponse, setConfig, setRedactCensor, setSensitiveFields, setValueByPath, settleAll, setupRequestContext, sha1, sha256, sha256Hmac, shuffle, singletonAsync, sleep, slugify, streamFile, stripHtml, take, takeWhile, throttle, timeout, toCamelCase, toKebabCase, toPascalCase, toSnakeCase, truncate, unique, uuid, validateAll, verifySignedToken, walkDir, watchDir, watchDirRecursive, waterfall, withErrorHandling, withTimeout, writeJsonFile, writeTextFile, zip };
|
|
5774
|
+
export { After, type ApiErrorResponse, type ApiResponse, type ApiSuccessResponse, type AsyncOperationResponse, type Awaited$1 as Awaited, BUILD_MARKER, BadGatewayException, BadRequestException, type BatchResponse, Before, Body, type BufferEncoding, Cache, CircuitBreakerOpenError, type CircuitBreakerOptions, CircuitBreakerState, ConflictException, Connect, ContentType, ContextStore, Controller, DIContainer, type DateFormatOptions, type DecryptionOptions, type DeepPartial, type DeepReadonly, type DeepRequired, type DeepStringifyOrNull, Delete, type EncryptionOptions, type EncryptionResult, Env, Environment, type ErrorHandlerOptions, ErrorResponse, ExpressServer, ForbiddenException, type Func, GatewayTimeoutException, Get, Head, Header, Headers, HttpCode, HttpError, HttpStatusCodes, Inject, Injectable, InsufficientStorageException, InternalServerErrorException, type IsEqual, type KeysOfType, Log, type Logger, type LoggerLevels, type MaybePromise, MethodNotAllowedException, type Middleware, type Mutable, NoContentResponse, type NonEmptyArray, NotAcceptableException, NotFoundException, type Nullable, type Optional, type Optional2, Options, PaginatedResponse, type Pagination, type PaginationParams, type PaginationResponse, Param, type ParamOptions, type PartialPick, Patch, type PathOptions, PayloadTooLargeException, type PickByType, Post, type Primitive, Put, Query, RateLimit, type RecordOptional, Redirect, RedirectResponse, Req, ReqCookie, ReqHeader, ReqId, ReqLogger, RequestTimeoutException, type RequireAtLeastOne, Res, Roles, type ServerConfig, ServerConfigBuilder, type ServerHooks, ServiceUnavailableException, SortDirection, type Store, StoreKeys, type StreamResponse, type StringKeyedRecord, SuccessResponse, TTLCache, type TTLCacheOptions, type TaskQueue, Timeout, type TimingOptions, type TimingResult, type ToggleConfig, TooManyRequestsException, Trace, TypedContextKey, UnauthorizedException, type UnionToIntersection, UnprocessableEntityException, UnsupportedMediaTypeException, type UrlOptions, Use, type ValidationOptions, type ValidationResult, type ValueOf, Version, type WithPagination, type Without, type Writable, _globalThis, abortable, addRedactFields, addSensitiveFields, addToDate, appendQueryParams, appendTextFile, bufferToStream, capitalize, chunk, circuitBreaker, compact, copyDir, copyFile, countBy, countOccurrences, createBatchStream, createChildLogger, createDeferred, createDirectory, createErrorResponse, createFinalErrorResponse, createHttpError, createLineStream, createPaginatedResponse, createParamDecorator, createParamDecoratorWithoutParam, createRequestLogger, createSignedToken, createSuccessResponse, createTaskQueue, createTempDir, createTempFile, createThrottleStream, createUrlBuilder, dateDiff, daysInMonth, debounce, decrypt, deepFreeze, deepObjMerge, defaultSensitiveFields, deleteDirRecursive, deleteFileIfExists, difference, emptyDir, encrypt, endOf, ensureDir, ensureEmptyDir, ensureType, equalsIgnoreCase, errorHandler, extractFilterParams, extractPaginationParams, extractQueryParams, extractSortParams, fileExists, filterObject, findFilesByPattern, findInDir, findNewestFile, findOldestFile, flattenDeep, flattenObject, formatDate, formatRelativeTime, generateApiKey, generateRandomBytes, generateRandomBytesAsString, getAllPaths, getConfig, getDirSize, getDirStats, getDomain, getErrorMessage, getExtension, getFileSize, getFileStats, getFromContext, getLogger, getPaginationParams, getRedactCensor, getRequestId, getSubdirectories, getTypeOf, getValueByPath, groupBy, hasErrorShape, hasRequiredProps, hash, healthCheck, hmac, inject, intersect, isAlpha, isAlphanumeric, isArray, isArrayOf, isBase64, isBetween, isCreditCard, isDateInRange, isDirectory, isEmail, isEqual, isFile, isHexColor, isHttpError, isIPv4, isIPv6, isISODate, isLeapYear, isLengthBetween, isNumberBetween, isNumeric, isObjEmpty, isObject, isPhone, isPlainObject, isPort, isPrimitiveType, isStrongPassword, isURL, isUUID, isValidJSON, isValidUrl, joinPaths, listFiles, logError, logger, mapObject, mask, matchesPattern, md5, memoize, memoizeAsync, mergeSort, moveDir, moveFile, nanoId, normalizeUrl, omit, parseBooleanParam, parseDate, parseNumberParam, parseQueryString, parseTypedQueryParams, partition, pick, pluck, random, randomBase64, randomHex, randomInt, randomString, range, rateLimit, readDirectory, readFileBuffer, readJsonFile, readTextFile, redact, registerControllers, removeQueryParams, requestId, responseTime, retry, reverse, runInBatches, runInSeries, runWithConcurrency, safeCompare, safeReadJsonFile, sendResponse, setConfig, setRedactCensor, setSensitiveFields, setValueByPath, settleAll, setupRequestContext, sha1, sha256, sha256Hmac, shuffle, singletonAsync, sleep, slugify, startOf, streamFile, streamToBuffer, streamToString, stripHtml, take, takeWhile, throttle, timeAsync, timeSync, timed, timeout, toBool, toCamelCase, toKebabCase, toNum, toPascalCase, toSnakeCase, toStr, trackMemoryUsage, truncate, unique, uuid, validateAll, verifySignedToken, walkDir, watchDir, watchDirRecursive, waterfall, withErrorHandling, withTimeout, writeJsonFile, writeTextFile, zip };
|