@catbee/utils 0.0.7 → 0.0.8-next.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/LICENSE +1 -1
- package/README.md +26 -1
- package/build/index.cjs +6888 -0
- package/build/index.d.ts +5242 -0
- package/build/index.mjs +6615 -0
- package/package.json +26 -99
- package/build/esm/config.d.ts +0 -122
- package/build/esm/config.js +0 -133
- package/build/esm/config.js.map +0 -1
- package/build/esm/index.d.ts +0 -27
- package/build/esm/index.js +0 -50
- package/build/esm/index.js.map +0 -1
- package/build/esm/servers/server.builder.d.ts +0 -508
- package/build/esm/servers/server.builder.js +0 -702
- package/build/esm/servers/server.builder.js.map +0 -1
- package/build/esm/servers/server.d.ts +0 -256
- package/build/esm/servers/server.js +0 -1201
- package/build/esm/servers/server.js.map +0 -1
- package/build/esm/types/api-response.d.ts +0 -152
- package/build/esm/types/api-response.js +0 -34
- package/build/esm/types/api-response.js.map +0 -1
- package/build/esm/types/index.d.ts +0 -125
- package/build/esm/types/index.js +0 -25
- package/build/esm/types/index.js.map +0 -1
- package/build/esm/types/server.d.ts +0 -268
- package/build/esm/types/server.js +0 -25
- package/build/esm/types/server.js.map +0 -1
- package/build/esm/utils/array.utils.d.ts +0 -168
- package/build/esm/utils/array.utils.js +0 -382
- package/build/esm/utils/array.utils.js.map +0 -1
- package/build/esm/utils/async.utils.d.ts +0 -265
- package/build/esm/utils/async.utils.js +0 -896
- package/build/esm/utils/async.utils.js.map +0 -1
- package/build/esm/utils/cache.utils.d.ts +0 -153
- package/build/esm/utils/cache.utils.js +0 -499
- package/build/esm/utils/cache.utils.js.map +0 -1
- package/build/esm/utils/context-store.utils.d.ts +0 -189
- package/build/esm/utils/context-store.utils.js +0 -307
- package/build/esm/utils/context-store.utils.js.map +0 -1
- package/build/esm/utils/crypto.utils.d.ts +0 -160
- package/build/esm/utils/crypto.utils.js +0 -375
- package/build/esm/utils/crypto.utils.js.map +0 -1
- package/build/esm/utils/date.utils.d.ts +0 -159
- package/build/esm/utils/date.utils.js +0 -389
- package/build/esm/utils/date.utils.js.map +0 -1
- package/build/esm/utils/decorators.utils.d.ts +0 -315
- package/build/esm/utils/decorators.utils.js +0 -666
- package/build/esm/utils/decorators.utils.js.map +0 -1
- package/build/esm/utils/dir.utils.d.ts +0 -196
- package/build/esm/utils/dir.utils.js +0 -998
- package/build/esm/utils/dir.utils.js.map +0 -1
- package/build/esm/utils/env.utils.d.ts +0 -377
- package/build/esm/utils/env.utils.js +0 -873
- package/build/esm/utils/env.utils.js.map +0 -1
- package/build/esm/utils/exception.utils.d.ts +0 -230
- package/build/esm/utils/exception.utils.js +0 -559
- package/build/esm/utils/exception.utils.js.map +0 -1
- package/build/esm/utils/fs.utils.d.ts +0 -164
- package/build/esm/utils/fs.utils.js +0 -580
- package/build/esm/utils/fs.utils.js.map +0 -1
- package/build/esm/utils/http-status-codes.d.ts +0 -266
- package/build/esm/utils/http-status-codes.js +0 -295
- package/build/esm/utils/http-status-codes.js.map +0 -1
- package/build/esm/utils/id.utils.d.ts +0 -36
- package/build/esm/utils/id.utils.js +0 -87
- package/build/esm/utils/id.utils.js.map +0 -1
- package/build/esm/utils/logger.utils.d.ts +0 -160
- package/build/esm/utils/logger.utils.js +0 -341
- package/build/esm/utils/logger.utils.js.map +0 -1
- package/build/esm/utils/middleware.utils.d.ts +0 -83
- package/build/esm/utils/middleware.utils.js +0 -206
- package/build/esm/utils/middleware.utils.js.map +0 -1
- package/build/esm/utils/obj.utils.d.ts +0 -124
- package/build/esm/utils/obj.utils.js +0 -519
- package/build/esm/utils/obj.utils.js.map +0 -1
- package/build/esm/utils/performance.utils.d.ts +0 -136
- package/build/esm/utils/performance.utils.js +0 -376
- package/build/esm/utils/performance.utils.js.map +0 -1
- package/build/esm/utils/request.utils.d.ts +0 -86
- package/build/esm/utils/request.utils.js +0 -223
- package/build/esm/utils/request.utils.js.map +0 -1
- package/build/esm/utils/response.utils.d.ts +0 -163
- package/build/esm/utils/response.utils.js +0 -284
- package/build/esm/utils/response.utils.js.map +0 -1
- package/build/esm/utils/stream.utils.d.ts +0 -88
- package/build/esm/utils/stream.utils.js +0 -284
- package/build/esm/utils/stream.utils.js.map +0 -1
- package/build/esm/utils/string.utils.d.ts +0 -93
- package/build/esm/utils/string.utils.js +0 -169
- package/build/esm/utils/string.utils.js.map +0 -1
- package/build/esm/utils/type.utils.d.ts +0 -90
- package/build/esm/utils/type.utils.js +0 -190
- package/build/esm/utils/type.utils.js.map +0 -1
- package/build/esm/utils/url.utils.d.ts +0 -141
- package/build/esm/utils/url.utils.js +0 -381
- package/build/esm/utils/url.utils.js.map +0 -1
- package/build/esm/utils/validate.utils.d.ts +0 -177
- package/build/esm/utils/validate.utils.js +0 -336
- package/build/esm/utils/validate.utils.js.map +0 -1
- package/build/esnext/config.d.ts +0 -122
- package/build/esnext/config.js +0 -133
- package/build/esnext/config.js.map +0 -1
- package/build/esnext/index.d.ts +0 -27
- package/build/esnext/index.js +0 -50
- package/build/esnext/index.js.map +0 -1
- package/build/esnext/servers/server.builder.d.ts +0 -508
- package/build/esnext/servers/server.builder.js +0 -657
- package/build/esnext/servers/server.builder.js.map +0 -1
- package/build/esnext/servers/server.d.ts +0 -256
- package/build/esnext/servers/server.js +0 -908
- package/build/esnext/servers/server.js.map +0 -1
- package/build/esnext/types/api-response.d.ts +0 -152
- package/build/esnext/types/api-response.js +0 -34
- package/build/esnext/types/api-response.js.map +0 -1
- package/build/esnext/types/index.d.ts +0 -125
- package/build/esnext/types/index.js +0 -25
- package/build/esnext/types/index.js.map +0 -1
- package/build/esnext/types/server.d.ts +0 -268
- package/build/esnext/types/server.js +0 -25
- package/build/esnext/types/server.js.map +0 -1
- package/build/esnext/utils/array.utils.d.ts +0 -168
- package/build/esnext/utils/array.utils.js +0 -345
- package/build/esnext/utils/array.utils.js.map +0 -1
- package/build/esnext/utils/async.utils.d.ts +0 -265
- package/build/esnext/utils/async.utils.js +0 -620
- package/build/esnext/utils/async.utils.js.map +0 -1
- package/build/esnext/utils/cache.utils.d.ts +0 -153
- package/build/esnext/utils/cache.utils.js +0 -293
- package/build/esnext/utils/cache.utils.js.map +0 -1
- package/build/esnext/utils/context-store.utils.d.ts +0 -189
- package/build/esnext/utils/context-store.utils.js +0 -289
- package/build/esnext/utils/context-store.utils.js.map +0 -1
- package/build/esnext/utils/crypto.utils.d.ts +0 -160
- package/build/esnext/utils/crypto.utils.js +0 -276
- package/build/esnext/utils/crypto.utils.js.map +0 -1
- package/build/esnext/utils/date.utils.d.ts +0 -159
- package/build/esnext/utils/date.utils.js +0 -384
- package/build/esnext/utils/date.utils.js.map +0 -1
- package/build/esnext/utils/decorators.utils.d.ts +0 -315
- package/build/esnext/utils/decorators.utils.js +0 -504
- package/build/esnext/utils/decorators.utils.js.map +0 -1
- package/build/esnext/utils/dir.utils.d.ts +0 -196
- package/build/esnext/utils/dir.utils.js +0 -477
- package/build/esnext/utils/dir.utils.js.map +0 -1
- package/build/esnext/utils/env.utils.d.ts +0 -377
- package/build/esnext/utils/env.utils.js +0 -785
- package/build/esnext/utils/env.utils.js.map +0 -1
- package/build/esnext/utils/exception.utils.d.ts +0 -230
- package/build/esnext/utils/exception.utils.js +0 -381
- package/build/esnext/utils/exception.utils.js.map +0 -1
- package/build/esnext/utils/fs.utils.d.ts +0 -164
- package/build/esnext/utils/fs.utils.js +0 -349
- package/build/esnext/utils/fs.utils.js.map +0 -1
- package/build/esnext/utils/http-status-codes.d.ts +0 -266
- package/build/esnext/utils/http-status-codes.js +0 -295
- package/build/esnext/utils/http-status-codes.js.map +0 -1
- package/build/esnext/utils/id.utils.d.ts +0 -36
- package/build/esnext/utils/id.utils.js +0 -84
- package/build/esnext/utils/id.utils.js.map +0 -1
- package/build/esnext/utils/logger.utils.d.ts +0 -160
- package/build/esnext/utils/logger.utils.js +0 -300
- package/build/esnext/utils/logger.utils.js.map +0 -1
- package/build/esnext/utils/middleware.utils.d.ts +0 -83
- package/build/esnext/utils/middleware.utils.js +0 -199
- package/build/esnext/utils/middleware.utils.js.map +0 -1
- package/build/esnext/utils/obj.utils.d.ts +0 -124
- package/build/esnext/utils/obj.utils.js +0 -413
- package/build/esnext/utils/obj.utils.js.map +0 -1
- package/build/esnext/utils/performance.utils.d.ts +0 -136
- package/build/esnext/utils/performance.utils.js +0 -271
- package/build/esnext/utils/performance.utils.js.map +0 -1
- package/build/esnext/utils/request.utils.d.ts +0 -86
- package/build/esnext/utils/request.utils.js +0 -186
- package/build/esnext/utils/request.utils.js.map +0 -1
- package/build/esnext/utils/response.utils.d.ts +0 -163
- package/build/esnext/utils/response.utils.js +0 -247
- package/build/esnext/utils/response.utils.js.map +0 -1
- package/build/esnext/utils/stream.utils.d.ts +0 -88
- package/build/esnext/utils/stream.utils.js +0 -210
- package/build/esnext/utils/stream.utils.js.map +0 -1
- package/build/esnext/utils/string.utils.d.ts +0 -93
- package/build/esnext/utils/string.utils.js +0 -165
- package/build/esnext/utils/string.utils.js.map +0 -1
- package/build/esnext/utils/type.utils.d.ts +0 -90
- package/build/esnext/utils/type.utils.js +0 -187
- package/build/esnext/utils/type.utils.js.map +0 -1
- package/build/esnext/utils/url.utils.d.ts +0 -141
- package/build/esnext/utils/url.utils.js +0 -304
- package/build/esnext/utils/url.utils.js.map +0 -1
- package/build/esnext/utils/validate.utils.d.ts +0 -177
- package/build/esnext/utils/validate.utils.js +0 -320
- package/build/esnext/utils/validate.utils.js.map +0 -1
- package/build/src/config.d.ts +0 -122
- package/build/src/config.js +0 -138
- package/build/src/config.js.map +0 -1
- package/build/src/index.d.ts +0 -27
- package/build/src/index.js +0 -69
- package/build/src/index.js.map +0 -1
- package/build/src/servers/server.builder.d.ts +0 -508
- package/build/src/servers/server.builder.js +0 -661
- package/build/src/servers/server.builder.js.map +0 -1
- package/build/src/servers/server.d.ts +0 -256
- package/build/src/servers/server.js +0 -948
- package/build/src/servers/server.js.map +0 -1
- package/build/src/types/api-response.d.ts +0 -152
- package/build/src/types/api-response.js +0 -37
- package/build/src/types/api-response.js.map +0 -1
- package/build/src/types/index.d.ts +0 -125
- package/build/src/types/index.js +0 -26
- package/build/src/types/index.js.map +0 -1
- package/build/src/types/server.d.ts +0 -268
- package/build/src/types/server.js +0 -26
- package/build/src/types/server.js.map +0 -1
- package/build/src/utils/array.utils.d.ts +0 -168
- package/build/src/utils/array.utils.js +0 -364
- package/build/src/utils/array.utils.js.map +0 -1
- package/build/src/utils/async.utils.d.ts +0 -265
- package/build/src/utils/async.utils.js +0 -641
- package/build/src/utils/async.utils.js.map +0 -1
- package/build/src/utils/cache.utils.d.ts +0 -153
- package/build/src/utils/cache.utils.js +0 -297
- package/build/src/utils/cache.utils.js.map +0 -1
- package/build/src/utils/context-store.utils.d.ts +0 -189
- package/build/src/utils/context-store.utils.js +0 -296
- package/build/src/utils/context-store.utils.js.map +0 -1
- package/build/src/utils/crypto.utils.d.ts +0 -160
- package/build/src/utils/crypto.utils.js +0 -293
- package/build/src/utils/crypto.utils.js.map +0 -1
- package/build/src/utils/date.utils.d.ts +0 -159
- package/build/src/utils/date.utils.js +0 -396
- package/build/src/utils/date.utils.js.map +0 -1
- package/build/src/utils/decorators.utils.d.ts +0 -315
- package/build/src/utils/decorators.utils.js +0 -516
- package/build/src/utils/decorators.utils.js.map +0 -1
- package/build/src/utils/dir.utils.d.ts +0 -196
- package/build/src/utils/dir.utils.js +0 -501
- package/build/src/utils/dir.utils.js.map +0 -1
- package/build/src/utils/env.utils.d.ts +0 -377
- package/build/src/utils/env.utils.js +0 -789
- package/build/src/utils/env.utils.js.map +0 -1
- package/build/src/utils/exception.utils.d.ts +0 -230
- package/build/src/utils/exception.utils.js +0 -407
- package/build/src/utils/exception.utils.js.map +0 -1
- package/build/src/utils/fs.utils.d.ts +0 -164
- package/build/src/utils/fs.utils.js +0 -372
- package/build/src/utils/fs.utils.js.map +0 -1
- package/build/src/utils/http-status-codes.d.ts +0 -266
- package/build/src/utils/http-status-codes.js +0 -298
- package/build/src/utils/http-status-codes.js.map +0 -1
- package/build/src/utils/id.utils.d.ts +0 -36
- package/build/src/utils/id.utils.js +0 -91
- package/build/src/utils/id.utils.js.map +0 -1
- package/build/src/utils/logger.utils.d.ts +0 -160
- package/build/src/utils/logger.utils.js +0 -346
- package/build/src/utils/logger.utils.js.map +0 -1
- package/build/src/utils/middleware.utils.d.ts +0 -83
- package/build/src/utils/middleware.utils.js +0 -206
- package/build/src/utils/middleware.utils.js.map +0 -1
- package/build/src/utils/obj.utils.d.ts +0 -124
- package/build/src/utils/obj.utils.js +0 -429
- package/build/src/utils/obj.utils.js.map +0 -1
- package/build/src/utils/performance.utils.d.ts +0 -136
- package/build/src/utils/performance.utils.js +0 -278
- package/build/src/utils/performance.utils.js.map +0 -1
- package/build/src/utils/request.utils.d.ts +0 -86
- package/build/src/utils/request.utils.js +0 -195
- package/build/src/utils/request.utils.js.map +0 -1
- package/build/src/utils/response.utils.d.ts +0 -163
- package/build/src/utils/response.utils.js +0 -260
- package/build/src/utils/response.utils.js.map +0 -1
- package/build/src/utils/stream.utils.d.ts +0 -88
- package/build/src/utils/stream.utils.js +0 -218
- package/build/src/utils/stream.utils.js.map +0 -1
- package/build/src/utils/string.utils.d.ts +0 -93
- package/build/src/utils/string.utils.js +0 -179
- package/build/src/utils/string.utils.js.map +0 -1
- package/build/src/utils/type.utils.d.ts +0 -90
- package/build/src/utils/type.utils.js +0 -196
- package/build/src/utils/type.utils.js.map +0 -1
- package/build/src/utils/url.utils.d.ts +0 -141
- package/build/src/utils/url.utils.js +0 -317
- package/build/src/utils/url.utils.js.map +0 -1
- package/build/src/utils/validate.utils.d.ts +0 -177
- package/build/src/utils/validate.utils.js +0 -345
- package/build/src/utils/validate.utils.js.map +0 -1
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
import type { Request, Response, NextFunction } from 'express';
|
|
2
|
-
export type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
|
|
3
|
-
/**
|
|
4
|
-
* Attaches a unique request ID to each request.
|
|
5
|
-
* Useful for request tracing and correlation between logs.
|
|
6
|
-
*
|
|
7
|
-
* @param {object} [options] - Configuration options
|
|
8
|
-
* @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
|
|
9
|
-
* @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
|
|
10
|
-
* @param {() => string} [options.generator] - Custom ID generator function
|
|
11
|
-
* @returns {Middleware} Express-compatible middleware
|
|
12
|
-
*/
|
|
13
|
-
export declare function requestId(options?: {
|
|
14
|
-
headerName?: string;
|
|
15
|
-
exposeHeader?: boolean;
|
|
16
|
-
generator?: () => string;
|
|
17
|
-
}): Middleware;
|
|
18
|
-
/**
|
|
19
|
-
* Measures request processing time and logs or adds it to response headers.
|
|
20
|
-
*
|
|
21
|
-
* @param {object} [options] - Configuration options
|
|
22
|
-
* @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header
|
|
23
|
-
* @param {boolean} [options.logOnComplete=false] - Whether to log timing info
|
|
24
|
-
* @returns {Middleware} Express-compatible middleware
|
|
25
|
-
*/
|
|
26
|
-
export declare function responseTime(options?: {
|
|
27
|
-
addHeader?: boolean;
|
|
28
|
-
logOnComplete?: boolean;
|
|
29
|
-
}): (req: Request, res: Response, next: NextFunction) => void;
|
|
30
|
-
/**
|
|
31
|
-
* Request timeout middleware.
|
|
32
|
-
* Aborts requests that take too long to process.
|
|
33
|
-
*
|
|
34
|
-
* @param {number} [timeoutMs=30000] - Timeout in milliseconds
|
|
35
|
-
* @returns {Middleware} Express-compatible middleware
|
|
36
|
-
*/
|
|
37
|
-
export declare function timeout(timeoutMs?: number): Middleware;
|
|
38
|
-
/**
|
|
39
|
-
* Creates an Express middleware that initializes a per-request context.
|
|
40
|
-
*
|
|
41
|
-
* @param {object} [options] - Optional configuration
|
|
42
|
-
* @param {string} [options.headerName='x-request-id'] - Header to look for request ID
|
|
43
|
-
* @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
|
|
44
|
-
* @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
|
|
45
|
-
*/
|
|
46
|
-
export declare function setupRequestContext(options?: {
|
|
47
|
-
headerName?: string;
|
|
48
|
-
autoLog?: boolean;
|
|
49
|
-
}): Middleware;
|
|
50
|
-
export interface ErrorHandlerOptions {
|
|
51
|
-
/** Whether to log errors (default: true) */
|
|
52
|
-
logErrors?: boolean;
|
|
53
|
-
/** Whether to include error details in non-production (default: false) */
|
|
54
|
-
includeDetails?: boolean;
|
|
55
|
-
}
|
|
56
|
-
/**
|
|
57
|
-
* Global error handling middleware with enhanced features.
|
|
58
|
-
*
|
|
59
|
-
* @param {ErrorHandlerOptions} options - Error handler options
|
|
60
|
-
* @param {boolean} [options.logErrors=true] - Whether to log errors
|
|
61
|
-
* @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
|
|
62
|
-
* @returns Error middleware
|
|
63
|
-
*
|
|
64
|
-
* @example
|
|
65
|
-
* import express from 'express';
|
|
66
|
-
* import { errorHandler } from '@catbee/utils';
|
|
67
|
-
*
|
|
68
|
-
* const app = express();
|
|
69
|
-
*
|
|
70
|
-
* // Your routes
|
|
71
|
-
* app.get('/ping', (req, res) => {
|
|
72
|
-
* throw new Error('Something went wrong');
|
|
73
|
-
* });
|
|
74
|
-
*
|
|
75
|
-
* // Error handler (must be last middleware)
|
|
76
|
-
* app.use(errorHandler({ includeDetails: true }));
|
|
77
|
-
*
|
|
78
|
-
* app.listen(3000, () => {
|
|
79
|
-
* console.log('Server running on port 3000');
|
|
80
|
-
* });
|
|
81
|
-
*/
|
|
82
|
-
export declare function errorHandler(options?: ErrorHandlerOptions): (err: any, req: Request, res: Response, _next: NextFunction) => Response<any, Record<string, any>>;
|
|
83
|
-
//# sourceMappingURL=middleware.utils.d.ts.map
|
|
@@ -1,206 +0,0 @@
|
|
|
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
|
-
import { uuid } from './id.utils';
|
|
25
|
-
import { HttpStatusCodes } from './http-status-codes';
|
|
26
|
-
import { createFinalErrorResponse, ErrorResponse } from './response.utils';
|
|
27
|
-
import { getLogger } from './logger.utils';
|
|
28
|
-
import { ContextStore, StoreKeys } from './context-store.utils';
|
|
29
|
-
import { RequestTimeoutException } from './exception.utils';
|
|
30
|
-
/**
|
|
31
|
-
* Attaches a unique request ID to each request.
|
|
32
|
-
* Useful for request tracing and correlation between logs.
|
|
33
|
-
*
|
|
34
|
-
* @param {object} [options] - Configuration options
|
|
35
|
-
* @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
|
|
36
|
-
* @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
|
|
37
|
-
* @param {() => string} [options.generator] - Custom ID generator function
|
|
38
|
-
* @returns {Middleware} Express-compatible middleware
|
|
39
|
-
*/
|
|
40
|
-
export function requestId(options) {
|
|
41
|
-
var headerName = (options === null || options === void 0 ? void 0 : options.headerName) || 'X-Request-ID';
|
|
42
|
-
var exposeHeader = (options === null || options === void 0 ? void 0 : options.exposeHeader) !== false;
|
|
43
|
-
var generateId = (options === null || options === void 0 ? void 0 : options.generator) || uuid;
|
|
44
|
-
return function (req, res, next) {
|
|
45
|
-
// Use existing request ID from header or generate a new one
|
|
46
|
-
var existingId = req.headers[headerName.toLowerCase()];
|
|
47
|
-
var id = existingId || generateId();
|
|
48
|
-
// Attach ID to request object
|
|
49
|
-
req.id = id;
|
|
50
|
-
// Add ID to response headers
|
|
51
|
-
if (exposeHeader) {
|
|
52
|
-
res.setHeader(headerName, id);
|
|
53
|
-
}
|
|
54
|
-
next();
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Measures request processing time and logs or adds it to response headers.
|
|
59
|
-
*
|
|
60
|
-
* @param {object} [options] - Configuration options
|
|
61
|
-
* @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header
|
|
62
|
-
* @param {boolean} [options.logOnComplete=false] - Whether to log timing info
|
|
63
|
-
* @returns {Middleware} Express-compatible middleware
|
|
64
|
-
*/
|
|
65
|
-
export function responseTime(options) {
|
|
66
|
-
var addHeader = (options === null || options === void 0 ? void 0 : options.addHeader) !== false;
|
|
67
|
-
var logOnComplete = (options === null || options === void 0 ? void 0 : options.logOnComplete) === true;
|
|
68
|
-
return function (req, res, next) {
|
|
69
|
-
var start = process.hrtime();
|
|
70
|
-
// Function to calculate duration
|
|
71
|
-
var getDuration = function () {
|
|
72
|
-
var diff = process.hrtime(start);
|
|
73
|
-
return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);
|
|
74
|
-
};
|
|
75
|
-
if (addHeader) {
|
|
76
|
-
// Ensure header is set before response is sent
|
|
77
|
-
var originalWriteHead_1 = res.writeHead;
|
|
78
|
-
res.writeHead = function () {
|
|
79
|
-
var args = [];
|
|
80
|
-
for (var _i = 0; _i < arguments.length; _i++) {
|
|
81
|
-
args[_i] = arguments[_i];
|
|
82
|
-
}
|
|
83
|
-
res.setHeader('X-Response-Time', "".concat(getDuration(), "ms"));
|
|
84
|
-
return originalWriteHead_1.apply(this, args);
|
|
85
|
-
};
|
|
86
|
-
}
|
|
87
|
-
if (logOnComplete) {
|
|
88
|
-
res.on('finish', function () {
|
|
89
|
-
getLogger().info("".concat(req.method, " ").concat(req.url, " - ").concat(getDuration(), "ms"));
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
next();
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
|
-
* Request timeout middleware.
|
|
97
|
-
* Aborts requests that take too long to process.
|
|
98
|
-
*
|
|
99
|
-
* @param {number} [timeoutMs=30000] - Timeout in milliseconds
|
|
100
|
-
* @returns {Middleware} Express-compatible middleware
|
|
101
|
-
*/
|
|
102
|
-
export function timeout(timeoutMs) {
|
|
103
|
-
if (timeoutMs === void 0) { timeoutMs = 30000; }
|
|
104
|
-
return function (_req, res, next) {
|
|
105
|
-
// Set timeout for the request
|
|
106
|
-
var timer = setTimeout(function () {
|
|
107
|
-
var response = new RequestTimeoutException('Request timed out');
|
|
108
|
-
res.status(HttpStatusCodes.REQUEST_TIMEOUT).json(response);
|
|
109
|
-
}, timeoutMs);
|
|
110
|
-
// Clear timeout when response is sent
|
|
111
|
-
res.on('finish', function () {
|
|
112
|
-
clearTimeout(timer);
|
|
113
|
-
});
|
|
114
|
-
next();
|
|
115
|
-
};
|
|
116
|
-
}
|
|
117
|
-
/**
|
|
118
|
-
* Creates an Express middleware that initializes a per-request context.
|
|
119
|
-
*
|
|
120
|
-
* @param {object} [options] - Optional configuration
|
|
121
|
-
* @param {string} [options.headerName='x-request-id'] - Header to look for request ID
|
|
122
|
-
* @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
|
|
123
|
-
* @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
|
|
124
|
-
*/
|
|
125
|
-
export function setupRequestContext(options) {
|
|
126
|
-
if (options === void 0) { options = {}; }
|
|
127
|
-
var _a = options.headerName, headerName = _a === void 0 ? 'x-request-id' : _a, _b = options.autoLog, autoLog = _b === void 0 ? true : _b;
|
|
128
|
-
return function (req, _res, next) {
|
|
129
|
-
var _a;
|
|
130
|
-
// Generate or use existing request ID
|
|
131
|
-
var requestId = req.headers[headerName] || (req === null || req === void 0 ? void 0 : req['id']) || uuid();
|
|
132
|
-
ContextStore.run((_a = {}, _a[StoreKeys.REQUEST_ID] = requestId, _a), function () {
|
|
133
|
-
// Create a child logger for this request
|
|
134
|
-
var childLogger = getLogger().child({
|
|
135
|
-
requestId: requestId,
|
|
136
|
-
method: req.method,
|
|
137
|
-
url: req.originalUrl || req.url
|
|
138
|
-
});
|
|
139
|
-
req.logger = childLogger;
|
|
140
|
-
// Store logger in context
|
|
141
|
-
ContextStore.set(StoreKeys.LOGGER, childLogger);
|
|
142
|
-
if (autoLog) {
|
|
143
|
-
req.logger.info('Request context initialized');
|
|
144
|
-
}
|
|
145
|
-
next();
|
|
146
|
-
});
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
/**
|
|
150
|
-
* Global error handling middleware with enhanced features.
|
|
151
|
-
*
|
|
152
|
-
* @param {ErrorHandlerOptions} options - Error handler options
|
|
153
|
-
* @param {boolean} [options.logErrors=true] - Whether to log errors
|
|
154
|
-
* @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
|
|
155
|
-
* @returns Error middleware
|
|
156
|
-
*
|
|
157
|
-
* @example
|
|
158
|
-
* import express from 'express';
|
|
159
|
-
* import { errorHandler } from '@catbee/utils';
|
|
160
|
-
*
|
|
161
|
-
* const app = express();
|
|
162
|
-
*
|
|
163
|
-
* // Your routes
|
|
164
|
-
* app.get('/ping', (req, res) => {
|
|
165
|
-
* throw new Error('Something went wrong');
|
|
166
|
-
* });
|
|
167
|
-
*
|
|
168
|
-
* // Error handler (must be last middleware)
|
|
169
|
-
* app.use(errorHandler({ includeDetails: true }));
|
|
170
|
-
*
|
|
171
|
-
* app.listen(3000, () => {
|
|
172
|
-
* console.log('Server running on port 3000');
|
|
173
|
-
* });
|
|
174
|
-
*/
|
|
175
|
-
export function errorHandler(options) {
|
|
176
|
-
var logErrors = (options === null || options === void 0 ? void 0 : options.logErrors) !== false;
|
|
177
|
-
var includeDetails = (options === null || options === void 0 ? void 0 : options.includeDetails) === true;
|
|
178
|
-
return function (err, req, res, _next) {
|
|
179
|
-
// Determine status code
|
|
180
|
-
var status = (err === null || err === void 0 ? void 0 : err.status) || (err === null || err === void 0 ? void 0 : err.statusCode) || HttpStatusCodes.INTERNAL_SERVER_ERROR;
|
|
181
|
-
// Log error if enabled
|
|
182
|
-
if (logErrors) {
|
|
183
|
-
getLogger().error({ err: err }, "".concat(err.message || 'Unknown error'));
|
|
184
|
-
}
|
|
185
|
-
// Handle ErrorResponse instances (our custom error class)
|
|
186
|
-
if (err instanceof ErrorResponse) {
|
|
187
|
-
var result = {
|
|
188
|
-
error: true,
|
|
189
|
-
message: err.message,
|
|
190
|
-
timestamp: err.timestamp,
|
|
191
|
-
requestId: (err === null || err === void 0 ? void 0 : err.requestId) || (req === null || req === void 0 ? void 0 : req.id) || uuid(),
|
|
192
|
-
status: status,
|
|
193
|
-
path: req.originalUrl || req.url
|
|
194
|
-
};
|
|
195
|
-
if (includeDetails && (err === null || err === void 0 ? void 0 : err.stack)) {
|
|
196
|
-
result.stack = err.stack.split('\n').map(function (line) { return line.trim(); });
|
|
197
|
-
}
|
|
198
|
-
return res.status(status).json(result);
|
|
199
|
-
}
|
|
200
|
-
// Handle any other errors
|
|
201
|
-
return res
|
|
202
|
-
.status(status)
|
|
203
|
-
.json(createFinalErrorResponse(req, status, (err === null || err === void 0 ? void 0 : err.message) || 'Internal Server Error', err, { includeDetails: includeDetails }));
|
|
204
|
-
};
|
|
205
|
-
}
|
|
206
|
-
//# sourceMappingURL=middleware.utils.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.utils.js","sourceRoot":"","sources":["../../../src/utils/middleware.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClC,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,wBAAwB,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAC3E,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAE3C,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D;;;;;;;;;GASG;AACH,MAAM,UAAU,SAAS,CAAC,OAIzB;IACC,IAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,UAAU,KAAI,cAAc,CAAC;IACzD,IAAM,YAAY,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,MAAK,KAAK,CAAC;IACrD,IAAM,UAAU,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,SAAS,KAAI,IAAI,CAAC;IAE9C,OAAO,UAAC,GAAG,EAAE,GAAG,EAAE,IAAI;QACpB,4DAA4D;QAC5D,IAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,WAAW,EAAE,CAAC,CAAC;QACzD,IAAM,EAAE,GAAI,UAAqB,IAAI,UAAU,EAAE,CAAC;QAElD,8BAA8B;QAC9B,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC;QAEZ,6BAA6B;QAC7B,IAAI,YAAY,EAAE,CAAC;YACjB,GAAG,CAAC,SAAS,CAAC,UAAU,EAAE,EA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AAE,GAAG,CAAC,OAAO;gBACpB,SAAS,EAAE,GAAG,CAAC,SAAS;gBACxB,SAAS,EAAE,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,SAAS,MAAI,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,EAAE,CAAA,IAAI,IAAI,EAAE;gBAC9C,MAAM,QAAA;gBACN,IAAI,EAAE,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,GAAG;aACjC,CAAC;YAEF,IAAI,cAAc,KAAI,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,KAAK,CAAA,EAAE,CAAC;gBACjC,MAAM,CAAC,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,UAAC,IAAY,IAAK,OAAA,IAAI,CAAC,IAAI,EAAE,EAAX,CAAW,CAAC,CAAC;YAC1E,CAAC;YACD,OAAO,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACzC,CAAC;QAED,0BAA0B;QAC1B,OAAO,GAAG;aACP,MAAM,CAAC,MAAM,CAAC;aACd,IAAI,CAAC,wBAAwB,CAAC,GAAG,EAAE,MAAM,EAAE,CAAA,GAAG,aAAH,GAAG,uBAAH,GAAG,CAAE,OAAO,KAAI,uBAAuB,EAAE,GAAG,EAAE,EAAE,cAAc,gBAAA,EAAE,CAAC,CAAC,CAAC;IACnH,CAAC,CAAC;AACJ,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 { uuid } from './id.utils';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { createFinalErrorResponse, ErrorResponse } from './response.utils';\nimport { getLogger } from './logger.utils';\nimport type { Request, Response, NextFunction } from 'express';\nimport { ContextStore, StoreKeys } from './context-store.utils';\nimport { RequestTimeoutException } from './exception.utils';\nimport { ApiErrorResponse } from '../types/api-response';\n\nexport type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;\n\n/**\n * Attaches a unique request ID to each request.\n * Useful for request tracing and correlation between logs.\n *\n * @param {object} [options] - Configuration options\n * @param {string} [options.headerName='X-Request-ID'] - Header name for request ID\n * @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response\n * @param {() => string} [options.generator] - Custom ID generator function\n * @returns {Middleware} Express-compatible middleware\n */\nexport function requestId(options?: {\n headerName?: string;\n exposeHeader?: boolean;\n generator?: () => string;\n}): Middleware {\n const headerName = options?.headerName || 'X-Request-ID';\n const exposeHeader = options?.exposeHeader !== false;\n const generateId = options?.generator || uuid;\n\n return (req, res, next) => {\n // Use existing request ID from header or generate a new one\n const existingId = req.headers[headerName.toLowerCase()];\n const id = (existingId as string) || generateId();\n\n // Attach ID to request object\n req.id = id;\n\n // Add ID to response headers\n if (exposeHeader) {\n res.setHeader(headerName, id);\n }\n\n next();\n };\n}\n\n/**\n * Measures request processing time and logs or adds it to response headers.\n *\n * @param {object} [options] - Configuration options\n * @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header\n * @param {boolean} [options.logOnComplete=false] - Whether to log timing info\n * @returns {Middleware} Express-compatible middleware\n */\nexport function responseTime(options?: { addHeader?: boolean; logOnComplete?: boolean }) {\n const addHeader = options?.addHeader !== false;\n const logOnComplete = options?.logOnComplete === true;\n\n return (req: Request, res: Response, next: NextFunction) => {\n const start = process.hrtime();\n\n // Function to calculate duration\n const getDuration = () => {\n const diff = process.hrtime(start);\n return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);\n };\n\n if (addHeader) {\n // Ensure header is set before response is sent\n const originalWriteHead = res.writeHead;\n res.writeHead = function (...args: any[]) {\n res.setHeader('X-Response-Time', `${getDuration()}ms`);\n return originalWriteHead.apply(this, args as any);\n };\n }\n\n if (logOnComplete) {\n res.on('finish', () => {\n getLogger().info(`${req.method} ${req.url} - ${getDuration()}ms`);\n });\n }\n\n next();\n };\n}\n\n/**\n * Request timeout middleware.\n * Aborts requests that take too long to process.\n *\n * @param {number} [timeoutMs=30000] - Timeout in milliseconds\n * @returns {Middleware} Express-compatible middleware\n */\nexport function timeout(timeoutMs: number = 30000): Middleware {\n return (_req, res, next) => {\n // Set timeout for the request\n const timer = setTimeout(() => {\n const response = new RequestTimeoutException('Request timed out');\n res.status(HttpStatusCodes.REQUEST_TIMEOUT).json(response);\n }, timeoutMs);\n\n // Clear timeout when response is sent\n res.on('finish', () => {\n clearTimeout(timer);\n });\n\n next();\n };\n}\n\n/**\n * Creates an Express middleware that initializes a per-request context.\n *\n * @param {object} [options] - Optional configuration\n * @param {string} [options.headerName='x-request-id'] - Header to look for request ID\n * @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized\n * @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function\n */\nexport function setupRequestContext(options: { headerName?: string; autoLog?: boolean } = {}): Middleware {\n const { headerName = 'x-request-id', autoLog = true } = options;\n return (req, _res, next) => {\n // Generate or use existing request ID\n const requestId = (req.headers[headerName] as string) || req?.['id'] || uuid();\n\n ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n // Create a child logger for this request\n const childLogger = getLogger().child({\n requestId,\n method: req.method,\n url: req.originalUrl || req.url\n });\n\n req.logger = childLogger;\n\n // Store logger in context\n ContextStore.set(StoreKeys.LOGGER, childLogger);\n\n if (autoLog) {\n req.logger.info('Request context initialized');\n }\n\n next();\n });\n };\n}\n\nexport interface ErrorHandlerOptions {\n /** Whether to log errors (default: true) */\n logErrors?: boolean;\n /** Whether to include error details in non-production (default: false) */\n includeDetails?: boolean;\n}\n\n/**\n * Global error handling middleware with enhanced features.\n *\n * @param {ErrorHandlerOptions} options - Error handler options\n * @param {boolean} [options.logErrors=true] - Whether to log errors\n * @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production\n * @returns Error middleware\n *\n * @example\n * import express from 'express';\n * import { errorHandler } from '@catbee/utils';\n *\n * const app = express();\n *\n * // Your routes\n * app.get('/ping', (req, res) => {\n * throw new Error('Something went wrong');\n * });\n *\n * // Error handler (must be last middleware)\n * app.use(errorHandler({ includeDetails: true }));\n *\n * app.listen(3000, () => {\n * console.log('Server running on port 3000');\n * });\n */\nexport function errorHandler(options?: ErrorHandlerOptions) {\n const logErrors = options?.logErrors !== false;\n const includeDetails = options?.includeDetails === true;\n\n return (err: any, req: Request, res: Response, _next: NextFunction) => {\n // Determine status code\n const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;\n\n // Log error if enabled\n if (logErrors) {\n getLogger().error({ err }, `${err.message || 'Unknown error'}`);\n }\n\n // Handle ErrorResponse instances (our custom error class)\n if (err instanceof ErrorResponse) {\n const result: ApiErrorResponse = {\n error: true,\n message: err.message,\n timestamp: err.timestamp,\n requestId: err?.requestId || req?.id || uuid(),\n status,\n path: req.originalUrl || req.url\n };\n\n if (includeDetails && err?.stack) {\n result.stack = err.stack.split('\\n').map((line: string) => line.trim());\n }\n return res.status(status).json(result);\n }\n\n // Handle any other errors\n return res\n .status(status)\n .json(createFinalErrorResponse(req, status, err?.message || 'Internal Server Error', err, { includeDetails }));\n };\n}\n"]}
|
|
@@ -1,124 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Checks whether the object has no own enumerable properties.
|
|
3
|
-
*
|
|
4
|
-
* @param {Record<any, any>} obj - The object to check.
|
|
5
|
-
* @returns {boolean} True if the object is empty, false otherwise.
|
|
6
|
-
*/
|
|
7
|
-
export declare function isObjEmpty(obj: Record<any, any>): boolean;
|
|
8
|
-
/**
|
|
9
|
-
* Returns a new object with only the specified keys picked.
|
|
10
|
-
*
|
|
11
|
-
* @template T
|
|
12
|
-
* @template K
|
|
13
|
-
* @param {T} obj - The source object.
|
|
14
|
-
* @param {K[]} keys - Keys to pick from the object.
|
|
15
|
-
* @returns {Pick<T, K>} New object with picked keys.
|
|
16
|
-
*/
|
|
17
|
-
export declare function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>;
|
|
18
|
-
/**
|
|
19
|
-
* Returns a new object with the specified keys omitted.
|
|
20
|
-
*
|
|
21
|
-
* @template T
|
|
22
|
-
* @template K
|
|
23
|
-
* @param {T} obj - The source object.
|
|
24
|
-
* @param {K[]} keys - Keys to omit from the object.
|
|
25
|
-
* @returns {Omit<T, K>} New object without omitted keys.
|
|
26
|
-
*/
|
|
27
|
-
export declare function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K>;
|
|
28
|
-
/**
|
|
29
|
-
* Deeply merges multiple objects into the target object (mutates and returns the target object, not pure).
|
|
30
|
-
*
|
|
31
|
-
* @template T
|
|
32
|
-
* @param {T} target - The object to merge into (will be mutated).
|
|
33
|
-
* @param {...any[]} sources - The objects to merge from.
|
|
34
|
-
* @returns {T} The merged object (same as target).
|
|
35
|
-
*/
|
|
36
|
-
export declare function deepObjMerge<T extends object>(target: T, ...sources: any[]): T;
|
|
37
|
-
/**
|
|
38
|
-
* Checks if a value is a plain object (i.e., not an array, null, or a built-in object).
|
|
39
|
-
*
|
|
40
|
-
* @param value - The value to check.
|
|
41
|
-
* @returns True if the value is a plain object, false otherwise.
|
|
42
|
-
*/
|
|
43
|
-
export declare function isPlainObject(value: any): value is Record<string, any>;
|
|
44
|
-
/**
|
|
45
|
-
* Flattens a nested object using dot notation for keys (e.g., `{a: {b: 1}}` → `{ "a.b": 1 }`).
|
|
46
|
-
*
|
|
47
|
-
* @template T
|
|
48
|
-
* @param {T} obj - The object to flatten.
|
|
49
|
-
* @param {string} [prefix=""] - Optional prefix for nested keys (used internally).
|
|
50
|
-
* @returns {Record<string, any>} A new object with flattened keys.
|
|
51
|
-
*/
|
|
52
|
-
export declare function flattenObject<T extends Record<string, any>>(obj: T, prefix?: string): Record<string, any>;
|
|
53
|
-
/**
|
|
54
|
-
* Safely gets the value of a deeply nested key in an object using dot/bracket notation path.
|
|
55
|
-
*
|
|
56
|
-
* @template T
|
|
57
|
-
* @param {T} obj - The object to extract from.
|
|
58
|
-
* @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').
|
|
59
|
-
* @returns {any} The value at the given path, or undefined if not found.
|
|
60
|
-
*/
|
|
61
|
-
export declare function getValueByPath<T extends object>(obj: T, path: string): any;
|
|
62
|
-
/**
|
|
63
|
-
* Sets a value at a deeply nested key in an object using dot/bracket notation path.
|
|
64
|
-
* Creates intermediate objects and arrays as needed.
|
|
65
|
-
*
|
|
66
|
-
* @template T
|
|
67
|
-
* @param {T} obj - The object to modify.
|
|
68
|
-
* @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').
|
|
69
|
-
* @param {any} value - The value to set at the path.
|
|
70
|
-
* @returns {T} The modified object.
|
|
71
|
-
*/
|
|
72
|
-
export declare function setValueByPath<T extends object>(obj: T, path: string, value: any): T;
|
|
73
|
-
/**
|
|
74
|
-
* Performs a deep equality check between two objects.
|
|
75
|
-
*
|
|
76
|
-
* @param {any} a - First value to compare.
|
|
77
|
-
* @param {any} b - Second value to compare.
|
|
78
|
-
* @returns {boolean} True if values are deeply equal.
|
|
79
|
-
*/
|
|
80
|
-
export declare function isEqual(a: any, b: any): boolean;
|
|
81
|
-
/**
|
|
82
|
-
* Filters object properties based on a predicate function.
|
|
83
|
-
*
|
|
84
|
-
* @template T
|
|
85
|
-
* @param {T} obj - The source object.
|
|
86
|
-
* @param {(value: any, key: string, obj: T) => boolean} predicate - Filter function.
|
|
87
|
-
* @returns {Partial<T>} New object with filtered properties.
|
|
88
|
-
*/
|
|
89
|
-
export declare function filterObject<T extends object>(obj: T, predicate: (value: any, key: string, obj: T) => boolean): Partial<T>;
|
|
90
|
-
/**
|
|
91
|
-
* Maps object values to new values using a mapping function.
|
|
92
|
-
*
|
|
93
|
-
* @template T
|
|
94
|
-
* @template U
|
|
95
|
-
* @param {T} obj - The source object.
|
|
96
|
-
* @param {(value: any, key: string, obj: T) => U} mapFn - Mapping function.
|
|
97
|
-
* @returns {Record<keyof T, U>} New object with mapped values.
|
|
98
|
-
*/
|
|
99
|
-
export declare function mapObject<T extends object, U>(obj: T, mapFn: (value: any, key: string, obj: T) => U): Record<keyof T, U>;
|
|
100
|
-
/**
|
|
101
|
-
* Recursively freezes an object and all its properties.
|
|
102
|
-
* Makes an object immutable.
|
|
103
|
-
*
|
|
104
|
-
* @template T
|
|
105
|
-
* @param {T} obj - The object to freeze.
|
|
106
|
-
* @returns {Readonly<T>} The frozen object.
|
|
107
|
-
*/
|
|
108
|
-
export declare function deepFreeze<T extends object>(obj: T): Readonly<T>;
|
|
109
|
-
/**
|
|
110
|
-
* Safely checks if a value is an object (not null, not array).
|
|
111
|
-
*
|
|
112
|
-
* @param {unknown} value - Value to check.
|
|
113
|
-
* @returns {boolean} True if value is a non-null, non-array object.
|
|
114
|
-
*/
|
|
115
|
-
export declare function isObject(value: unknown): value is Record<string, any>;
|
|
116
|
-
/**
|
|
117
|
-
* Gets all paths in an object using dot notation.
|
|
118
|
-
*
|
|
119
|
-
* @param {Record<string, any>} obj - Object to analyze.
|
|
120
|
-
* @param {string} [parentPath=""] - Internal param for recursion.
|
|
121
|
-
* @returns {string[]} Array of all paths in dot notation.
|
|
122
|
-
*/
|
|
123
|
-
export declare function getAllPaths(obj: Record<string, any>, parentPath?: string): string[];
|
|
124
|
-
//# sourceMappingURL=obj.utils.d.ts.map
|