@catbee/utils 1.1.0 → 2.0.0-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +79 -43
- package/array/index.cjs +355 -0
- package/array/index.d.ts +317 -0
- package/array/index.mjs +327 -0
- package/async/index.cjs +484 -0
- package/async/index.d.ts +299 -0
- package/async/index.mjs +463 -0
- package/cache/index.cjs +292 -0
- package/cache/index.d.ts +179 -0
- package/cache/index.mjs +290 -0
- package/config/index.cjs +150 -0
- package/config/index.d.ts +88 -0
- package/config/index.mjs +143 -0
- package/context-store/index.cjs +267 -0
- package/context-store/index.d.ts +216 -0
- package/context-store/index.mjs +261 -0
- package/crypto/index.cjs +182 -0
- package/crypto/index.d.ts +187 -0
- package/crypto/index.mjs +166 -0
- package/date/index.cjs +340 -0
- package/date/index.d.ts +214 -0
- package/date/index.mjs +326 -0
- package/decorators/index.cjs +2051 -0
- package/decorators/index.d.ts +708 -0
- package/decorators/index.mjs +2010 -0
- package/dir/index.cjs +417 -0
- package/dir/index.d.ts +219 -0
- package/dir/index.mjs +390 -0
- package/env/index.cjs +745 -0
- package/env/index.d.ts +403 -0
- package/env/index.mjs +742 -0
- package/exception/index.cjs +362 -0
- package/exception/index.d.ts +256 -0
- package/exception/index.mjs +338 -0
- package/fs/index.cjs +287 -0
- package/fs/index.d.ts +229 -0
- package/fs/index.mjs +258 -0
- package/http-status-codes/index.cjs +96 -0
- package/http-status-codes/index.d.ts +291 -0
- package/http-status-codes/index.mjs +94 -0
- package/id/index.cjs +62 -0
- package/id/index.d.ts +61 -0
- package/id/index.mjs +56 -0
- package/index.cjs +218 -0
- package/index.d.ts +51 -0
- package/index.mjs +51 -0
- package/logger/index.cjs +334 -0
- package/logger/index.d.ts +213 -0
- package/logger/index.mjs +313 -0
- package/middleware/index.cjs +177 -0
- package/middleware/index.d.ts +127 -0
- package/middleware/index.mjs +170 -0
- package/obj/index.cjs +305 -0
- package/obj/index.d.ts +160 -0
- package/obj/index.mjs +289 -0
- package/package.json +172 -20
- package/performance/index.cjs +231 -0
- package/performance/index.d.ts +162 -0
- package/performance/index.mjs +225 -0
- package/request/index.cjs +202 -0
- package/request/index.d.ts +265 -0
- package/request/index.mjs +194 -0
- package/response/index.cjs +234 -0
- package/response/index.d.ts +342 -0
- package/response/index.mjs +222 -0
- package/server/index.cjs +1631 -0
- package/server/index.d.ts +809 -0
- package/server/index.mjs +1622 -0
- package/stream/index.cjs +151 -0
- package/stream/index.d.ts +114 -0
- package/stream/index.mjs +144 -0
- package/string/index.cjs +109 -0
- package/string/index.d.ts +126 -0
- package/string/index.mjs +95 -0
- package/type/index.cjs +129 -0
- package/type/index.d.ts +131 -0
- package/type/index.mjs +119 -0
- package/types/index.cjs +34 -0
- package/types/index.d.ts +798 -0
- package/types/index.mjs +32 -0
- package/url/index.cjs +199 -0
- package/url/index.d.ts +166 -0
- package/url/index.mjs +187 -0
- package/validation/index.cjs +259 -0
- package/validation/index.d.ts +209 -0
- package/validation/index.mjs +231 -0
- package/build/index.cjs +0 -7694
- package/build/index.d.ts +0 -5792
- package/build/index.mjs +0 -7386
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
|
|
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
|
+
import { Request, Response, NextFunction } from 'express';
|
|
26
|
+
|
|
27
|
+
type Middleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
|
|
28
|
+
/**
|
|
29
|
+
* Attaches a unique request ID to each request.
|
|
30
|
+
* Useful for request tracing and correlation between logs.
|
|
31
|
+
*
|
|
32
|
+
* @param {object} [options] - Configuration options
|
|
33
|
+
* @param {string} [options.headerName='X-Request-ID'] - Header name for request ID
|
|
34
|
+
* @param {boolean} [options.exposeHeader=true] - Whether to expose the header in response
|
|
35
|
+
* @param {() => string} [options.generator] - Custom ID generator function
|
|
36
|
+
* @returns {Middleware} Express-compatible middleware
|
|
37
|
+
*/
|
|
38
|
+
declare function requestId(options?: {
|
|
39
|
+
headerName?: string;
|
|
40
|
+
exposeHeader?: boolean;
|
|
41
|
+
generator?: () => string;
|
|
42
|
+
}): Middleware;
|
|
43
|
+
/**
|
|
44
|
+
* Measures request processing time and logs or adds it to response headers.
|
|
45
|
+
*
|
|
46
|
+
* @param {object} [options] - Configuration options
|
|
47
|
+
* @param {boolean} [options.addHeader=true] - Whether to add X-Response-Time header
|
|
48
|
+
* @param {boolean} [options.logOnComplete=false] - Whether to log timing info
|
|
49
|
+
* @returns {Middleware} Express-compatible middleware
|
|
50
|
+
*/
|
|
51
|
+
declare function responseTime(options?: {
|
|
52
|
+
addHeader?: boolean;
|
|
53
|
+
logOnComplete?: boolean;
|
|
54
|
+
}): (req: Request, res: Response, next: NextFunction) => void;
|
|
55
|
+
/**
|
|
56
|
+
* Request timeout middleware.
|
|
57
|
+
* Aborts requests that take too long to process.
|
|
58
|
+
*
|
|
59
|
+
* @param {number} [timeoutMs=30000] - Timeout in milliseconds
|
|
60
|
+
* @returns {Middleware} Express-compatible middleware
|
|
61
|
+
*/
|
|
62
|
+
declare function timeout(timeoutMs?: number): Middleware;
|
|
63
|
+
/**
|
|
64
|
+
* Creates an Express middleware that initializes a per-request context.
|
|
65
|
+
*
|
|
66
|
+
* @param {object} [options] - Optional configuration
|
|
67
|
+
* @param {string} [options.headerName='x-request-id'] - Header to look for request ID
|
|
68
|
+
* @param {boolean} [options.autoLog=true] - Whether to log automatically when context is initialized
|
|
69
|
+
* @returns {(req: Request, res: Response, next: NextFunction) => void} Express middleware function
|
|
70
|
+
*/
|
|
71
|
+
declare function setupRequestContext(options?: {
|
|
72
|
+
headerName?: string;
|
|
73
|
+
autoLog?: boolean;
|
|
74
|
+
}): Middleware;
|
|
75
|
+
interface ErrorHandlerOptions {
|
|
76
|
+
/** Whether to log errors (default: true) */
|
|
77
|
+
logErrors?: boolean;
|
|
78
|
+
/** Whether to include error details in non-production (default: false) */
|
|
79
|
+
includeDetails?: boolean;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Global error handling middleware with enhanced features.
|
|
83
|
+
*
|
|
84
|
+
* @param {ErrorHandlerOptions} options - Error handler options
|
|
85
|
+
* @param {boolean} [options.logErrors=true] - Whether to log errors
|
|
86
|
+
* @param {boolean} [options.includeDetails=false] - Whether to include error details in non-production
|
|
87
|
+
* @returns Error middleware
|
|
88
|
+
*
|
|
89
|
+
* @example
|
|
90
|
+
* import express from 'express';
|
|
91
|
+
* import { errorHandler } from '@catbee/utils';
|
|
92
|
+
*
|
|
93
|
+
* const app = express();
|
|
94
|
+
*
|
|
95
|
+
* // Your routes
|
|
96
|
+
* app.get('/ping', (req, res) => {
|
|
97
|
+
* throw new Error('Something went wrong');
|
|
98
|
+
* });
|
|
99
|
+
*
|
|
100
|
+
* // Error handler (must be last middleware)
|
|
101
|
+
* app.use(errorHandler({ includeDetails: true }));
|
|
102
|
+
*
|
|
103
|
+
* app.listen(3000, () => {
|
|
104
|
+
* console.log('Server running on port 3000');
|
|
105
|
+
* });
|
|
106
|
+
*/
|
|
107
|
+
declare function errorHandler(options?: ErrorHandlerOptions): (err: any, req: Request, res: Response, _next: NextFunction) => Response<any, Record<string, any>>;
|
|
108
|
+
/**
|
|
109
|
+
* Health check middleware for service status and custom checks.
|
|
110
|
+
*
|
|
111
|
+
* @param {object} [options] - Health check options
|
|
112
|
+
* @param {string} [options.path='/healthz'] - Health check endpoint path
|
|
113
|
+
* @param {Array<{name: string; check: () => Promise<boolean> | boolean}>} [options.checks] - Custom health checks
|
|
114
|
+
* @param {boolean} [options.detailed=true] - Show detailed check results
|
|
115
|
+
* @returns {Middleware} Express-compatible middleware
|
|
116
|
+
*/
|
|
117
|
+
declare function healthCheck(options?: {
|
|
118
|
+
path?: string;
|
|
119
|
+
checks?: Array<{
|
|
120
|
+
name: string;
|
|
121
|
+
check: () => Promise<boolean> | boolean;
|
|
122
|
+
}>;
|
|
123
|
+
detailed?: boolean;
|
|
124
|
+
}): Middleware;
|
|
125
|
+
|
|
126
|
+
export { errorHandler, healthCheck, requestId, responseTime, setupRequestContext, timeout };
|
|
127
|
+
export type { ErrorHandlerOptions, Middleware };
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
|
|
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
|
+
import { uuid } from '@catbee/utils/id';
|
|
26
|
+
import { HttpStatusCodes } from '@catbee/utils/http-status-codes';
|
|
27
|
+
import { ErrorResponse, createFinalErrorResponse } from '@catbee/utils/response';
|
|
28
|
+
import { getLogger } from '@catbee/utils/logger';
|
|
29
|
+
import { ContextStore, StoreKeys } from '@catbee/utils/context-store';
|
|
30
|
+
import { RequestTimeoutException } from '@catbee/utils/exception';
|
|
31
|
+
|
|
32
|
+
var __defProp = Object.defineProperty;
|
|
33
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
34
|
+
function requestId(options) {
|
|
35
|
+
const headerName = options?.headerName || "X-Request-ID";
|
|
36
|
+
const exposeHeader = options?.exposeHeader !== false;
|
|
37
|
+
const generateId = options?.generator || uuid;
|
|
38
|
+
return (req, res, next) => {
|
|
39
|
+
const existingId = req.headers[headerName.toLowerCase()];
|
|
40
|
+
const id = existingId || generateId();
|
|
41
|
+
req.id = id;
|
|
42
|
+
if (exposeHeader) {
|
|
43
|
+
res.setHeader(headerName, id);
|
|
44
|
+
}
|
|
45
|
+
next();
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
__name(requestId, "requestId");
|
|
49
|
+
function responseTime(options) {
|
|
50
|
+
const addHeader = options?.addHeader !== false;
|
|
51
|
+
const logOnComplete = options?.logOnComplete === true;
|
|
52
|
+
return (req, res, next) => {
|
|
53
|
+
const start = process.hrtime();
|
|
54
|
+
const getDuration = /* @__PURE__ */ __name(() => {
|
|
55
|
+
const diff = process.hrtime(start);
|
|
56
|
+
return (diff[0] * 1e3 + diff[1] * 1e-6).toFixed(2);
|
|
57
|
+
}, "getDuration");
|
|
58
|
+
if (addHeader) {
|
|
59
|
+
const originalWriteHead = res.writeHead;
|
|
60
|
+
res.writeHead = function(...args) {
|
|
61
|
+
res.setHeader("X-Response-Time", `${getDuration()}ms`);
|
|
62
|
+
return originalWriteHead.apply(this, args);
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
if (logOnComplete) {
|
|
66
|
+
res.on("finish", () => {
|
|
67
|
+
getLogger().info(`${req.method} ${req.url} - ${getDuration()}ms`);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
next();
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
__name(responseTime, "responseTime");
|
|
74
|
+
function timeout(timeoutMs = 3e4) {
|
|
75
|
+
return (_req, res, next) => {
|
|
76
|
+
const timer = setTimeout(() => {
|
|
77
|
+
const response = new RequestTimeoutException("Request timed out");
|
|
78
|
+
res.status(HttpStatusCodes.REQUEST_TIMEOUT).json(response);
|
|
79
|
+
}, timeoutMs);
|
|
80
|
+
res.on("finish", () => {
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
});
|
|
83
|
+
next();
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
__name(timeout, "timeout");
|
|
87
|
+
function setupRequestContext(options = {}) {
|
|
88
|
+
const { headerName = "x-request-id", autoLog = true } = options;
|
|
89
|
+
return (req, _res, next) => {
|
|
90
|
+
const requestId2 = req.headers[headerName] || req?.["id"] || uuid();
|
|
91
|
+
ContextStore.run({
|
|
92
|
+
[StoreKeys.REQUEST_ID]: requestId2
|
|
93
|
+
}, () => {
|
|
94
|
+
const childLogger = getLogger().child({
|
|
95
|
+
requestId: requestId2,
|
|
96
|
+
method: req.method,
|
|
97
|
+
url: req.originalUrl || req.url
|
|
98
|
+
});
|
|
99
|
+
req.logger = childLogger;
|
|
100
|
+
ContextStore.set(StoreKeys.LOGGER, childLogger);
|
|
101
|
+
if (autoLog) {
|
|
102
|
+
req.logger.info("Request context initialized");
|
|
103
|
+
}
|
|
104
|
+
next();
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
__name(setupRequestContext, "setupRequestContext");
|
|
109
|
+
function errorHandler(options) {
|
|
110
|
+
const logErrors = options?.logErrors !== false;
|
|
111
|
+
const includeDetails = options?.includeDetails === true;
|
|
112
|
+
return (err, req, res, _next) => {
|
|
113
|
+
const status = err?.status || err?.statusCode || HttpStatusCodes.INTERNAL_SERVER_ERROR;
|
|
114
|
+
if (logErrors) {
|
|
115
|
+
getLogger().error({
|
|
116
|
+
err
|
|
117
|
+
}, `${err.message || "Unknown error"}`);
|
|
118
|
+
}
|
|
119
|
+
if (err instanceof ErrorResponse) {
|
|
120
|
+
const result = {
|
|
121
|
+
error: true,
|
|
122
|
+
message: err.message,
|
|
123
|
+
timestamp: err.timestamp,
|
|
124
|
+
requestId: err?.requestId || req?.id || uuid(),
|
|
125
|
+
status,
|
|
126
|
+
path: req.originalUrl || req.url
|
|
127
|
+
};
|
|
128
|
+
if (includeDetails && err?.stack) {
|
|
129
|
+
result.stack = err.stack.split("\n").map((line) => line.trim());
|
|
130
|
+
}
|
|
131
|
+
return res.status(status).json(result);
|
|
132
|
+
}
|
|
133
|
+
return res.status(status).json(createFinalErrorResponse(req, status, err?.message || "Internal Server Error", err, {
|
|
134
|
+
includeDetails
|
|
135
|
+
}));
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
__name(errorHandler, "errorHandler");
|
|
139
|
+
function healthCheck(options) {
|
|
140
|
+
const path = options?.path || "/healthz";
|
|
141
|
+
const checks = options?.checks || [];
|
|
142
|
+
const detailed = options?.detailed !== false;
|
|
143
|
+
return async (req, res, next) => {
|
|
144
|
+
if (req.path !== path) return next();
|
|
145
|
+
const results = {};
|
|
146
|
+
let allHealthy = true;
|
|
147
|
+
for (const check of checks) {
|
|
148
|
+
try {
|
|
149
|
+
const result = await Promise.resolve(check.check());
|
|
150
|
+
results[check.name] = !!result;
|
|
151
|
+
if (!result) allHealthy = false;
|
|
152
|
+
} catch {
|
|
153
|
+
results[check.name] = false;
|
|
154
|
+
allHealthy = false;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const status = allHealthy ? HttpStatusCodes.OK : HttpStatusCodes.SERVICE_UNAVAILABLE;
|
|
158
|
+
const response = detailed ? {
|
|
159
|
+
status: allHealthy ? "ok" : "unhealthy",
|
|
160
|
+
checks: results,
|
|
161
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
162
|
+
} : {
|
|
163
|
+
status: allHealthy ? "ok" : "unhealthy"
|
|
164
|
+
};
|
|
165
|
+
res.status(status).json(response);
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
__name(healthCheck, "healthCheck");
|
|
169
|
+
|
|
170
|
+
export { errorHandler, healthCheck, requestId, responseTime, setupRequestContext, timeout };
|
package/obj/index.cjs
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
|
|
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
|
+
'use strict';
|
|
26
|
+
|
|
27
|
+
var __defProp = Object.defineProperty;
|
|
28
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
29
|
+
|
|
30
|
+
// src/obj/obj.utils.ts
|
|
31
|
+
function isObject(value) {
|
|
32
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
33
|
+
}
|
|
34
|
+
__name(isObject, "isObject");
|
|
35
|
+
function isObjEmpty(obj) {
|
|
36
|
+
return isObject(obj) && Object.keys(obj).length === 0;
|
|
37
|
+
}
|
|
38
|
+
__name(isObjEmpty, "isObjEmpty");
|
|
39
|
+
function pick(obj, keys) {
|
|
40
|
+
return Object.fromEntries(keys.map((key) => [
|
|
41
|
+
key,
|
|
42
|
+
obj[key]
|
|
43
|
+
]));
|
|
44
|
+
}
|
|
45
|
+
__name(pick, "pick");
|
|
46
|
+
function omit(obj, keys) {
|
|
47
|
+
return Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key)));
|
|
48
|
+
}
|
|
49
|
+
__name(omit, "omit");
|
|
50
|
+
function deepObjMerge(target, ...sources) {
|
|
51
|
+
const seen = /* @__PURE__ */ new WeakMap();
|
|
52
|
+
const mergeInto = /* @__PURE__ */ __name((t, s) => {
|
|
53
|
+
if (s === void 0) return t;
|
|
54
|
+
if (typeof s === "function" || typeof s === "symbol") return s;
|
|
55
|
+
if (Array.isArray(s)) {
|
|
56
|
+
const cloned = deepClone(s);
|
|
57
|
+
seen.set(s, cloned);
|
|
58
|
+
return cloned;
|
|
59
|
+
}
|
|
60
|
+
if (s && typeof s === "object") {
|
|
61
|
+
if (seen.has(s)) return seen.get(s);
|
|
62
|
+
if (s instanceof Date || s instanceof Map || s instanceof Set || s instanceof RegExp || s instanceof ArrayBuffer || ArrayBuffer.isView(s)) {
|
|
63
|
+
const cloned = deepClone(s);
|
|
64
|
+
seen.set(s, cloned);
|
|
65
|
+
return cloned;
|
|
66
|
+
}
|
|
67
|
+
if (!t || typeof t !== "object") {
|
|
68
|
+
t = Object.create(Object.getPrototypeOf(s));
|
|
69
|
+
}
|
|
70
|
+
seen.set(s, t);
|
|
71
|
+
for (const key of Reflect.ownKeys(s)) {
|
|
72
|
+
if (key === "__proto__") continue;
|
|
73
|
+
const sv = s[key];
|
|
74
|
+
if (sv === void 0) continue;
|
|
75
|
+
t[key] = mergeInto(t[key], sv);
|
|
76
|
+
}
|
|
77
|
+
return t;
|
|
78
|
+
}
|
|
79
|
+
return s;
|
|
80
|
+
}, "mergeInto");
|
|
81
|
+
for (const s of sources) {
|
|
82
|
+
target = mergeInto(target, s);
|
|
83
|
+
}
|
|
84
|
+
return target;
|
|
85
|
+
}
|
|
86
|
+
__name(deepObjMerge, "deepObjMerge");
|
|
87
|
+
function isPlainObject(value) {
|
|
88
|
+
if (typeof value !== "object" || value === null) return false;
|
|
89
|
+
if (Array.isArray(value)) return false;
|
|
90
|
+
const proto = Object.getPrototypeOf(value);
|
|
91
|
+
return proto === Object.prototype || proto === null;
|
|
92
|
+
}
|
|
93
|
+
__name(isPlainObject, "isPlainObject");
|
|
94
|
+
function flattenObject(obj, prefix = "") {
|
|
95
|
+
return Object.entries(obj).reduce((acc, [key, value]) => {
|
|
96
|
+
const newKey = prefix ? `${prefix}.${key}` : key;
|
|
97
|
+
if (key === "__proto__") return acc;
|
|
98
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
99
|
+
Object.assign(acc, flattenObject(value, newKey));
|
|
100
|
+
} else {
|
|
101
|
+
acc[newKey] = value;
|
|
102
|
+
}
|
|
103
|
+
return acc;
|
|
104
|
+
}, {});
|
|
105
|
+
}
|
|
106
|
+
__name(flattenObject, "flattenObject");
|
|
107
|
+
function getValueByPath(obj, path) {
|
|
108
|
+
if (!obj || typeof obj !== "object") return void 0;
|
|
109
|
+
const parts = path.replace(/\[(\d+)\]/g, ".$1").split(".").filter(Boolean);
|
|
110
|
+
return parts.reduce((acc, key) => acc?.[key], obj);
|
|
111
|
+
}
|
|
112
|
+
__name(getValueByPath, "getValueByPath");
|
|
113
|
+
function ensureNextContainer(curr, nextIsIndex) {
|
|
114
|
+
if (curr === void 0 || typeof curr !== "object" || curr === null) {
|
|
115
|
+
return nextIsIndex ? [] : /* @__PURE__ */ Object.create(null);
|
|
116
|
+
}
|
|
117
|
+
return curr;
|
|
118
|
+
}
|
|
119
|
+
__name(ensureNextContainer, "ensureNextContainer");
|
|
120
|
+
function setValueByPath(obj, path, value) {
|
|
121
|
+
if (!obj || typeof obj !== "object") return obj;
|
|
122
|
+
const clone = deepClone(obj);
|
|
123
|
+
const parts = path.replace(/\[(\d+)\]/g, ".$1").split(".").filter(Boolean);
|
|
124
|
+
if (parts.length === 0) return clone;
|
|
125
|
+
const forbiddenKeys = /* @__PURE__ */ new Set([
|
|
126
|
+
"__proto__",
|
|
127
|
+
"prototype",
|
|
128
|
+
"constructor"
|
|
129
|
+
]);
|
|
130
|
+
let current = clone;
|
|
131
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
132
|
+
const key = parts[i];
|
|
133
|
+
if (forbiddenKeys.has(key)) return clone;
|
|
134
|
+
const nextKey = parts[i + 1];
|
|
135
|
+
const nextIsIndex = !Number.isNaN(Number(nextKey));
|
|
136
|
+
current[key] = ensureNextContainer(current[key], nextIsIndex);
|
|
137
|
+
current = current[key];
|
|
138
|
+
}
|
|
139
|
+
const finalKey = parts.at(-1);
|
|
140
|
+
if (forbiddenKeys.has(finalKey)) return clone;
|
|
141
|
+
current[finalKey] = value;
|
|
142
|
+
return clone;
|
|
143
|
+
}
|
|
144
|
+
__name(setValueByPath, "setValueByPath");
|
|
145
|
+
function isEqual(a, b) {
|
|
146
|
+
if (a === b) return true;
|
|
147
|
+
if (a == null || b == null || typeof a !== "object" || typeof b !== "object") return false;
|
|
148
|
+
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
|
|
149
|
+
if (a instanceof RegExp && b instanceof RegExp) return a.source === b.source && a.flags === b.flags;
|
|
150
|
+
if (a instanceof Set && b instanceof Set) return a.size === b.size && [
|
|
151
|
+
...a
|
|
152
|
+
].every((v) => b.has(v));
|
|
153
|
+
if (a instanceof Map && b instanceof Map) return a.size === b.size && [
|
|
154
|
+
...a
|
|
155
|
+
].every(([k, v]) => isEqual(v, b.get(k)));
|
|
156
|
+
if (a instanceof ArrayBuffer && b instanceof ArrayBuffer) return isEqual(new Uint8Array(a), new Uint8Array(b));
|
|
157
|
+
if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((v, i) => isEqual(v, b[i]));
|
|
158
|
+
return Object.keys(a).length === Object.keys(b).length && Object.keys(a).every((key) => isEqual(a[key], b[key]));
|
|
159
|
+
}
|
|
160
|
+
__name(isEqual, "isEqual");
|
|
161
|
+
function filterObject(obj, predicate) {
|
|
162
|
+
return Object.fromEntries(Object.entries(obj).filter(([key, value]) => predicate(value, key, obj)));
|
|
163
|
+
}
|
|
164
|
+
__name(filterObject, "filterObject");
|
|
165
|
+
function mapObject(obj, mapFn) {
|
|
166
|
+
return Object.fromEntries(Object.entries(obj).map(([key, value]) => [
|
|
167
|
+
key,
|
|
168
|
+
mapFn(value, key, obj)
|
|
169
|
+
]));
|
|
170
|
+
}
|
|
171
|
+
__name(mapObject, "mapObject");
|
|
172
|
+
function _deepClone(value, seen) {
|
|
173
|
+
if (typeof value === "function" || typeof value === "symbol") {
|
|
174
|
+
return value;
|
|
175
|
+
}
|
|
176
|
+
if (value === null || typeof value !== "object") {
|
|
177
|
+
return value;
|
|
178
|
+
}
|
|
179
|
+
if (seen.has(value)) {
|
|
180
|
+
return seen.get(value);
|
|
181
|
+
}
|
|
182
|
+
let result;
|
|
183
|
+
if (Array.isArray(value)) {
|
|
184
|
+
result = [];
|
|
185
|
+
seen.set(value, result);
|
|
186
|
+
for (const item of value) {
|
|
187
|
+
result.push(_deepClone(item, seen));
|
|
188
|
+
}
|
|
189
|
+
return result;
|
|
190
|
+
}
|
|
191
|
+
if (value instanceof Date) {
|
|
192
|
+
result = new Date(value.getTime());
|
|
193
|
+
seen.set(value, result);
|
|
194
|
+
return result;
|
|
195
|
+
}
|
|
196
|
+
if (value instanceof Map) {
|
|
197
|
+
result = /* @__PURE__ */ new Map();
|
|
198
|
+
seen.set(value, result);
|
|
199
|
+
for (const [k, v] of value) {
|
|
200
|
+
result.set(_deepClone(k, seen), _deepClone(v, seen));
|
|
201
|
+
}
|
|
202
|
+
return result;
|
|
203
|
+
}
|
|
204
|
+
if (value instanceof Set) {
|
|
205
|
+
result = /* @__PURE__ */ new Set();
|
|
206
|
+
seen.set(value, result);
|
|
207
|
+
for (const v of value) {
|
|
208
|
+
result.add(_deepClone(v, seen));
|
|
209
|
+
}
|
|
210
|
+
return result;
|
|
211
|
+
}
|
|
212
|
+
if (value instanceof RegExp) {
|
|
213
|
+
result = new RegExp(value.source, value.flags);
|
|
214
|
+
seen.set(value, result);
|
|
215
|
+
return result;
|
|
216
|
+
}
|
|
217
|
+
if (ArrayBuffer.isView(value)) {
|
|
218
|
+
if (value instanceof DataView) {
|
|
219
|
+
const buf2 = _deepClone(value.buffer, seen);
|
|
220
|
+
const clone2 = new DataView(buf2, value.byteOffset, value.byteLength);
|
|
221
|
+
seen.set(value, clone2);
|
|
222
|
+
return clone2;
|
|
223
|
+
}
|
|
224
|
+
const typed = value;
|
|
225
|
+
const buf = _deepClone(typed.buffer, seen);
|
|
226
|
+
const clone = new typed.constructor(buf, typed.byteOffset, typed.length);
|
|
227
|
+
seen.set(value, clone);
|
|
228
|
+
return clone;
|
|
229
|
+
}
|
|
230
|
+
if (value instanceof ArrayBuffer) {
|
|
231
|
+
result = value.slice(0);
|
|
232
|
+
seen.set(value, result);
|
|
233
|
+
return result;
|
|
234
|
+
}
|
|
235
|
+
result = Object.create(Object.getPrototypeOf(value));
|
|
236
|
+
seen.set(value, result);
|
|
237
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
238
|
+
const desc = Object.getOwnPropertyDescriptor(value, key);
|
|
239
|
+
if (desc?.get || desc?.set) {
|
|
240
|
+
Object.defineProperty(result, key, {
|
|
241
|
+
get: desc.get,
|
|
242
|
+
set: desc.set,
|
|
243
|
+
enumerable: desc.enumerable,
|
|
244
|
+
configurable: desc.configurable
|
|
245
|
+
});
|
|
246
|
+
} else {
|
|
247
|
+
Object.defineProperty(result, key, {
|
|
248
|
+
value: _deepClone(value[key], seen),
|
|
249
|
+
writable: desc?.writable ?? true,
|
|
250
|
+
enumerable: desc?.enumerable ?? true,
|
|
251
|
+
configurable: desc?.configurable ?? true
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return result;
|
|
256
|
+
}
|
|
257
|
+
__name(_deepClone, "_deepClone");
|
|
258
|
+
function deepClone(value) {
|
|
259
|
+
const seen = /* @__PURE__ */ new WeakMap();
|
|
260
|
+
return _deepClone(value, seen);
|
|
261
|
+
}
|
|
262
|
+
__name(deepClone, "deepClone");
|
|
263
|
+
function deepFreeze(obj) {
|
|
264
|
+
Object.freeze(obj);
|
|
265
|
+
for (const key of Reflect.ownKeys(obj)) {
|
|
266
|
+
const val = obj[key];
|
|
267
|
+
if (isObject(val) && !Object.isFrozen(val)) {
|
|
268
|
+
deepFreeze(val);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return obj;
|
|
272
|
+
}
|
|
273
|
+
__name(deepFreeze, "deepFreeze");
|
|
274
|
+
function getAllPaths(obj, parentPath = "") {
|
|
275
|
+
if (!isObject(obj)) return [];
|
|
276
|
+
return Object.entries(obj).flatMap(([key, value]) => {
|
|
277
|
+
const currentPath = parentPath ? `${parentPath}.${key}` : key;
|
|
278
|
+
if (isObject(value)) {
|
|
279
|
+
return [
|
|
280
|
+
currentPath,
|
|
281
|
+
...getAllPaths(value, currentPath)
|
|
282
|
+
];
|
|
283
|
+
}
|
|
284
|
+
return [
|
|
285
|
+
currentPath
|
|
286
|
+
];
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
__name(getAllPaths, "getAllPaths");
|
|
290
|
+
|
|
291
|
+
exports.deepClone = deepClone;
|
|
292
|
+
exports.deepFreeze = deepFreeze;
|
|
293
|
+
exports.deepObjMerge = deepObjMerge;
|
|
294
|
+
exports.filterObject = filterObject;
|
|
295
|
+
exports.flattenObject = flattenObject;
|
|
296
|
+
exports.getAllPaths = getAllPaths;
|
|
297
|
+
exports.getValueByPath = getValueByPath;
|
|
298
|
+
exports.isEqual = isEqual;
|
|
299
|
+
exports.isObjEmpty = isObjEmpty;
|
|
300
|
+
exports.isObject = isObject;
|
|
301
|
+
exports.isPlainObject = isPlainObject;
|
|
302
|
+
exports.mapObject = mapObject;
|
|
303
|
+
exports.omit = omit;
|
|
304
|
+
exports.pick = pick;
|
|
305
|
+
exports.setValueByPath = setValueByPath;
|