@catbee/utils 2.0.0-next.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/README.md +52 -16
- package/array/index.cjs +180 -71
- package/array/index.d.ts +293 -1
- package/array/index.mjs +171 -72
- package/async/index.cjs +92 -36
- package/async/index.d.ts +275 -1
- package/async/index.mjs +92 -36
- package/cache/index.cjs +1 -1
- package/cache/index.d.ts +155 -1
- package/cache/index.mjs +2 -2
- package/config/index.cjs +78 -64
- package/config/index.d.ts +64 -2
- package/config/index.mjs +76 -64
- package/context-store/index.d.ts +192 -1
- package/crypto/index.d.ts +163 -1
- package/date/index.cjs +46 -1
- package/date/index.d.ts +190 -1
- package/date/index.mjs +45 -2
- package/decorators/index.cjs +1156 -18
- package/decorators/index.d.ts +684 -1
- package/decorators/index.mjs +1156 -18
- package/dir/index.cjs +4 -3
- package/dir/index.d.ts +195 -1
- package/dir/index.mjs +4 -3
- package/env/index.cjs +10 -26
- package/env/index.d.ts +379 -1
- package/env/index.mjs +10 -26
- package/exception/index.d.ts +232 -1
- package/fs/index.cjs +70 -36
- package/fs/index.d.ts +205 -1
- package/fs/index.mjs +64 -34
- package/http-status-codes/index.d.ts +267 -1
- package/id/index.d.ts +37 -1
- package/index.cjs +3 -3
- package/index.d.ts +1 -1
- package/index.mjs +1 -1
- package/logger/index.cjs +11 -11
- package/logger/index.d.ts +189 -1
- package/logger/index.mjs +12 -12
- package/middleware/index.d.ts +103 -1
- package/obj/index.cjs +150 -162
- package/obj/index.d.ts +136 -1
- package/obj/index.mjs +150 -162
- package/package.json +11 -11
- package/performance/index.cjs +2 -2
- package/performance/index.d.ts +138 -1
- package/performance/index.mjs +2 -2
- package/request/index.cjs +1 -1
- package/request/index.d.ts +241 -2
- package/request/index.mjs +1 -1
- package/response/index.d.ts +318 -2
- package/server/index.cjs +27 -23
- package/server/index.d.ts +785 -4
- package/server/index.mjs +28 -23
- package/stream/index.d.ts +90 -1
- package/string/index.d.ts +102 -1
- package/type/index.cjs +1 -1
- package/type/index.d.ts +107 -1
- package/type/index.mjs +1 -1
- package/types/index.d.ts +774 -4
- package/url/index.cjs +2 -4
- package/url/index.d.ts +142 -1
- package/url/index.mjs +2 -4
- package/{validate → validation}/index.cjs +89 -42
- package/{validate/validate.utils.d.ts → validation/index.d.ts} +32 -23
- package/{validate → validation}/index.mjs +85 -42
- package/array/array.utils.d.ts +0 -191
- package/async/async.utils.d.ts +0 -296
- package/cache/cache.utils.d.ts +0 -176
- package/config/config.d.ts +0 -57
- package/context-store/context-store.utils.d.ts +0 -212
- package/crypto/crypto.utils.d.ts +0 -183
- package/date/date.utils.d.ts +0 -190
- package/decorators/decorators.utils.d.ts +0 -705
- package/dir/dir.utils.d.ts +0 -216
- package/env/env.utils.d.ts +0 -400
- package/exception/exception.utils.d.ts +0 -253
- package/fs/fs.utils.d.ts +0 -196
- package/http-status-codes/http-status-codes.d.ts +0 -289
- package/id/id.utils.d.ts +0 -59
- package/logger/logger.utils.d.ts +0 -210
- package/middleware/middleware.utils.d.ts +0 -123
- package/obj/obj.utils.d.ts +0 -156
- package/performance/performance.utils.d.ts +0 -159
- package/request/request.utils.d.ts +0 -109
- package/response/response.utils.d.ts +0 -186
- package/server/server.builder.d.ts +0 -531
- package/server/server.d.ts +0 -303
- package/stream/stream.utils.d.ts +0 -111
- package/string/string.utils.d.ts +0 -124
- package/type/type.utils.d.ts +0 -129
- package/types/api-response.d.ts +0 -175
- package/types/common.d.ts +0 -148
- package/types/config.d.ts +0 -88
- package/types/server.d.ts +0 -291
- package/url/url.utils.d.ts +0 -164
- package/validate/index.d.ts +0 -25
package/config/index.mjs
CHANGED
|
@@ -24,57 +24,39 @@
|
|
|
24
24
|
|
|
25
25
|
import { Env } from '@catbee/utils/env';
|
|
26
26
|
import { uuid } from '@catbee/utils/id';
|
|
27
|
-
import { deepObjMerge } from '@catbee/utils/obj';
|
|
27
|
+
import { deepClone, deepObjMerge } from '@catbee/utils/obj';
|
|
28
28
|
|
|
29
29
|
var __defProp = Object.defineProperty;
|
|
30
30
|
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
31
|
-
var defaultCatbeeConfig = {
|
|
32
|
-
logger: {
|
|
33
|
-
level: Env.get("LOGGER_LEVEL", Env.isDev() ? "debug" : "info"),
|
|
34
|
-
name: Env.get("LOGGER_NAME", Env.get("npm_package_name", "@catbee/utils")),
|
|
35
|
-
pretty: Env.getBoolean("LOGGER_PRETTY", false),
|
|
36
|
-
colorize: Env.getBoolean("LOGGER_PRETTY_COLORIZE", true),
|
|
37
|
-
singleLine: Env.getBoolean("LOGGER_PRETTY_SINGLE_LINE", false),
|
|
38
|
-
dir: Env.getPath("LOGGER_DIR", "", {
|
|
39
|
-
mustExist: false
|
|
40
|
-
})
|
|
41
|
-
},
|
|
42
|
-
cache: {
|
|
43
|
-
defaultTtl: Env.getNumber("CACHE_DEFAULT_TTL_SECONDS", 3600) * 1e3
|
|
44
|
-
},
|
|
45
|
-
server: {
|
|
46
|
-
skipHealthz: Env.getBoolean("SERVER_SKIP_HEALTHZ", false)
|
|
47
|
-
}
|
|
48
|
-
};
|
|
49
31
|
var defaultServerConfig = {
|
|
50
|
-
port: 3e3,
|
|
51
|
-
host: "0.0.0.0",
|
|
52
|
-
cors: false,
|
|
53
|
-
helmet: false,
|
|
54
|
-
compression: false,
|
|
32
|
+
port: Env.getNumber("SERVER_PORT", 0) || Env.getNumber("PORT", 3e3),
|
|
33
|
+
host: Env.get("SERVER_HOST", "") || Env.get("HOST", "0.0.0.0"),
|
|
34
|
+
cors: Env.getBoolean("SERVER_CORS_ENABLE", false) ? {} : false,
|
|
35
|
+
helmet: Env.getBoolean("SERVER_HELMET_ENABLE", false) ? {} : false,
|
|
36
|
+
compression: Env.getBoolean("SERVER_COMPRESSION_ENABLE", false) ? {} : false,
|
|
55
37
|
bodyParser: {
|
|
56
38
|
json: {
|
|
57
|
-
limit: "1mb"
|
|
39
|
+
limit: Env.get("SERVER_BODY_PARSER_JSON_LIMIT", "1mb")
|
|
58
40
|
},
|
|
59
41
|
urlencoded: {
|
|
60
42
|
extended: true,
|
|
61
|
-
limit: "1mb"
|
|
43
|
+
limit: Env.get("SERVER_BODY_PARSER_URLENCODED_LIMIT", "1mb")
|
|
62
44
|
}
|
|
63
45
|
},
|
|
64
|
-
cookieParser: false,
|
|
65
|
-
isMicroservice: false,
|
|
66
|
-
appName: "
|
|
67
|
-
globalHeaders: {},
|
|
46
|
+
cookieParser: Env.getBoolean("SERVER_COOKIE_PARSER_ENABLE", false) ? {} : false,
|
|
47
|
+
isMicroservice: Env.getBoolean("SERVER_IS_MICROSERVICE", false),
|
|
48
|
+
appName: Env.get("SERVER_APP_NAME", Env.get("npm_package_name", "catbee_server")),
|
|
49
|
+
globalHeaders: Env.getJSON("SERVER_GLOBAL_HEADERS", {}),
|
|
68
50
|
rateLimit: {
|
|
69
|
-
enable: false,
|
|
70
|
-
windowMs: 15 * 60 * 1e3,
|
|
71
|
-
max: 100,
|
|
72
|
-
message: "Too many requests",
|
|
73
|
-
standardHeaders: true,
|
|
74
|
-
legacyHeaders: false
|
|
51
|
+
enable: Env.getBoolean("SERVER_RATE_LIMIT_ENABLE", false),
|
|
52
|
+
windowMs: Env.getDuration("SERVER_RATE_LIMIT_WINDOW_MS", 15 * 60 * 1e3),
|
|
53
|
+
max: Env.getNumber("SERVER_RATE_LIMIT_MAX", 100),
|
|
54
|
+
message: Env.get("SERVER_RATE_LIMIT_MESSAGE", "Too many requests, please try again later."),
|
|
55
|
+
standardHeaders: Env.getBoolean("SERVER_RATE_LIMIT_STANDARD_HEADERS", true),
|
|
56
|
+
legacyHeaders: Env.getBoolean("SERVER_RATE_LIMIT_LEGACY_HEADERS", false)
|
|
75
57
|
},
|
|
76
58
|
requestLogging: {
|
|
77
|
-
enable: Env.isDev(),
|
|
59
|
+
enable: Env.getBoolean("SERVER_REQUEST_LOGGING_ENABLE", Env.isDev()),
|
|
78
60
|
ignorePaths: /* @__PURE__ */ __name((req, _res) => {
|
|
79
61
|
const skipPaths = [
|
|
80
62
|
"/healthz",
|
|
@@ -85,47 +67,77 @@ var defaultServerConfig = {
|
|
|
85
67
|
];
|
|
86
68
|
return skipPaths.some((path) => req.path.startsWith(path));
|
|
87
69
|
}, "ignorePaths"),
|
|
88
|
-
skipNotFoundRoutes:
|
|
70
|
+
skipNotFoundRoutes: Env.getBoolean("SERVER_REQUEST_LOGGING_SKIP_NOT_FOUND_ROUTES", true)
|
|
89
71
|
},
|
|
72
|
+
trustProxy: Env.getBoolean("SERVER_TRUST_PROXY_ENABLE", false),
|
|
90
73
|
openApi: {
|
|
91
|
-
enable: false,
|
|
92
|
-
mountPath: "/docs",
|
|
93
|
-
verbose: false,
|
|
94
|
-
withGlobalPrefix: false
|
|
74
|
+
enable: Env.getBoolean("SERVER_OPENAPI_ENABLE", false),
|
|
75
|
+
mountPath: Env.get("SERVER_OPENAPI_MOUNT_PATH", "/docs"),
|
|
76
|
+
verbose: Env.getBoolean("SERVER_OPENAPI_VERBOSE", false),
|
|
77
|
+
withGlobalPrefix: Env.getBoolean("SERVER_OPENAPI_WITH_GLOBAL_PREFIX", false)
|
|
95
78
|
},
|
|
96
79
|
healthCheck: {
|
|
97
|
-
path: "/healthz",
|
|
98
|
-
detailed: true
|
|
80
|
+
path: Env.get("SERVER_HEALTH_CHECK_PATH", "/healthz"),
|
|
81
|
+
detailed: Env.getBoolean("SERVER_HEALTH_CHECK_DETAILED_OUTPUT", true),
|
|
82
|
+
withGlobalPrefix: Env.getBoolean("SERVER_HEALTH_CHECK_WITH_GLOBAL_PREFIX", false)
|
|
99
83
|
},
|
|
100
|
-
requestTimeout:
|
|
84
|
+
requestTimeout: Env.getDuration("SERVER_REQUEST_TIMEOUT_MS", 0),
|
|
101
85
|
responseTime: {
|
|
102
|
-
enable: false,
|
|
103
|
-
addHeader: true,
|
|
104
|
-
logOnComplete: false
|
|
86
|
+
enable: Env.getBoolean("SERVER_RESPONSE_TIME_ENABLE", false),
|
|
87
|
+
addHeader: Env.getBoolean("SERVER_RESPONSE_TIME_ADD_HEADER", true),
|
|
88
|
+
logOnComplete: Env.getBoolean("SERVER_RESPONSE_TIME_LOG_ON_COMPLETE", false)
|
|
105
89
|
},
|
|
106
90
|
requestId: {
|
|
107
|
-
headerName: "x-request-id",
|
|
108
|
-
exposeHeader: true,
|
|
91
|
+
headerName: Env.get("SERVER_REQUEST_ID_HEADER_NAME", "x-request-id"),
|
|
92
|
+
exposeHeader: Env.getBoolean("SERVER_REQUEST_ID_EXPOSE_HEADER", true),
|
|
109
93
|
generator: /* @__PURE__ */ __name(() => uuid(), "generator")
|
|
110
94
|
},
|
|
111
95
|
metrics: {
|
|
112
|
-
enable: false,
|
|
113
|
-
path: "/metrics",
|
|
114
|
-
withGlobalPrefix: false
|
|
96
|
+
enable: Env.getBoolean("SERVER_METRICS_ENABLE", false),
|
|
97
|
+
path: Env.get("SERVER_METRICS_PATH", "/metrics"),
|
|
98
|
+
withGlobalPrefix: Env.getBoolean("SERVER_METRICS_WITH_GLOBAL_PREFIX", false)
|
|
115
99
|
},
|
|
116
100
|
serviceVersion: {
|
|
117
|
-
enable: false,
|
|
118
|
-
headerName: "x-service-version",
|
|
119
|
-
version: "0.0.0"
|
|
120
|
-
}
|
|
101
|
+
enable: Env.getBoolean("SERVER_SERVICE_VERSION_ENABLE", false),
|
|
102
|
+
headerName: Env.get("SERVER_SERVICE_VERSION_HEADER_NAME", "x-service-version"),
|
|
103
|
+
version: Env.get("SERVER_SERVICE_VERSION", "0.0.0")
|
|
104
|
+
},
|
|
105
|
+
skipHealthz: Env.getBoolean("SERVER_SKIP_HEALTHZ", false)
|
|
121
106
|
};
|
|
122
|
-
|
|
123
|
-
|
|
107
|
+
var defaultCatbeeConfig = {
|
|
108
|
+
logger: {
|
|
109
|
+
level: Env.get("LOGGER_LEVEL", Env.isDev() || Env.isTest() ? "debug" : "info"),
|
|
110
|
+
name: Env.get("LOGGER_NAME", Env.get("npm_package_name", "@catbee/utils")),
|
|
111
|
+
pretty: Env.getBoolean("LOGGER_PRETTY", false),
|
|
112
|
+
colorize: Env.getBoolean("LOGGER_PRETTY_COLORIZE", true),
|
|
113
|
+
singleLine: Env.getBoolean("LOGGER_PRETTY_SINGLE_LINE", false),
|
|
114
|
+
dir: Env.getPath("LOGGER_DIR", "", {
|
|
115
|
+
mustExist: false
|
|
116
|
+
})
|
|
117
|
+
},
|
|
118
|
+
cache: {
|
|
119
|
+
defaultTtl: Env.getNumber("CACHE_DEFAULT_TTL_SECONDS", 3600) * 1e3
|
|
120
|
+
},
|
|
121
|
+
server: defaultServerConfig
|
|
122
|
+
};
|
|
123
|
+
var _config = deepClone(defaultCatbeeConfig);
|
|
124
|
+
function getCatbeeGlobalConfig() {
|
|
125
|
+
return deepClone(_config);
|
|
126
|
+
}
|
|
127
|
+
__name(getCatbeeGlobalConfig, "getCatbeeGlobalConfig");
|
|
128
|
+
var getConfig = getCatbeeGlobalConfig;
|
|
129
|
+
function setCatbeeGlobalConfig(value) {
|
|
130
|
+
_config = deepObjMerge(_config, value);
|
|
131
|
+
}
|
|
132
|
+
__name(setCatbeeGlobalConfig, "setCatbeeGlobalConfig");
|
|
133
|
+
var setConfig = setCatbeeGlobalConfig;
|
|
134
|
+
function setCatbeeServerGlobalConfig(value) {
|
|
135
|
+
_config.server = deepObjMerge(_config.server, value);
|
|
124
136
|
}
|
|
125
|
-
__name(
|
|
126
|
-
function
|
|
127
|
-
return
|
|
137
|
+
__name(setCatbeeServerGlobalConfig, "setCatbeeServerGlobalConfig");
|
|
138
|
+
function getCatbeeServerGlobalConfig() {
|
|
139
|
+
return getCatbeeGlobalConfig().server;
|
|
128
140
|
}
|
|
129
|
-
__name(
|
|
141
|
+
__name(getCatbeeServerGlobalConfig, "getCatbeeServerGlobalConfig");
|
|
130
142
|
|
|
131
|
-
export {
|
|
143
|
+
export { getCatbeeGlobalConfig, getCatbeeServerGlobalConfig, getConfig, setCatbeeGlobalConfig, setCatbeeServerGlobalConfig, setConfig };
|
package/context-store/index.d.ts
CHANGED
|
@@ -22,4 +22,195 @@
|
|
|
22
22
|
* SOFTWARE.
|
|
23
23
|
*/
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Type representing the store object used in AsyncLocalStorage.
|
|
29
|
+
* Keys must be unique symbols to ensure isolation and prevent collisions.
|
|
30
|
+
*/
|
|
31
|
+
interface Store {
|
|
32
|
+
[key: symbol]: unknown;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Predefined symbols used as keys in AsyncLocalStorage.
|
|
36
|
+
* Add new symbols here to avoid duplication.
|
|
37
|
+
*/
|
|
38
|
+
declare const StoreKeys: {
|
|
39
|
+
LOGGER: symbol;
|
|
40
|
+
REQUEST_ID: symbol;
|
|
41
|
+
USER: symbol;
|
|
42
|
+
SESSION: symbol;
|
|
43
|
+
TRANSACTION_ID: symbol;
|
|
44
|
+
USER_ID: symbol;
|
|
45
|
+
TENANT_ID: symbol;
|
|
46
|
+
TRACE_ID: symbol;
|
|
47
|
+
CORRELATION_ID: symbol;
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Retrieves the current request ID from the async context, if available.
|
|
51
|
+
*
|
|
52
|
+
* @returns {string | undefined} The request ID string or undefined if not present in the current context.
|
|
53
|
+
*/
|
|
54
|
+
declare function getRequestId(): string | undefined;
|
|
55
|
+
/**
|
|
56
|
+
* Type-safe getter for common context values.
|
|
57
|
+
*
|
|
58
|
+
* @param key The store key symbol
|
|
59
|
+
* @returns The typed value from the store
|
|
60
|
+
*/
|
|
61
|
+
declare function getFromContext<T>(key: symbol): T | undefined;
|
|
62
|
+
/**
|
|
63
|
+
* ContextStore manages per-request scoped context using AsyncLocalStorage.
|
|
64
|
+
* It allows storing and retrieving data across async calls (e.g., request ID, logger).
|
|
65
|
+
*
|
|
66
|
+
* Example (Express middleware):
|
|
67
|
+
* ```
|
|
68
|
+
* // Middleware to initialize context and logger
|
|
69
|
+
* app.use((req, res, next) => {
|
|
70
|
+
* const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
|
|
71
|
+
* ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
|
|
72
|
+
* ContextStore.set(StoreKeys.LOGGER, getLogger().child({ requestId }));
|
|
73
|
+
* next();
|
|
74
|
+
* });
|
|
75
|
+
* });
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
declare class ContextStore {
|
|
79
|
+
/**
|
|
80
|
+
* The underlying AsyncLocalStorage instance for context.
|
|
81
|
+
* @private
|
|
82
|
+
*/
|
|
83
|
+
private static readonly storage;
|
|
84
|
+
/**
|
|
85
|
+
* Returns the raw AsyncLocalStorage instance for advanced access.
|
|
86
|
+
*
|
|
87
|
+
* @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.
|
|
88
|
+
*/
|
|
89
|
+
static getInstance(): AsyncLocalStorage<Store>;
|
|
90
|
+
/**
|
|
91
|
+
* Retrieves a value from the async context store by symbol key.
|
|
92
|
+
*
|
|
93
|
+
* @typeParam T - The expected return type of the value.
|
|
94
|
+
* @param {symbol} key - Unique symbol used as the store key.
|
|
95
|
+
* @returns {T | undefined} The value found (typed) or undefined if not present.
|
|
96
|
+
*/
|
|
97
|
+
static get<T>(key: symbol): T | undefined;
|
|
98
|
+
/**
|
|
99
|
+
* Sets a value in the current context store by symbol key.
|
|
100
|
+
*
|
|
101
|
+
* @typeParam T - The value type to set.
|
|
102
|
+
* @param {symbol} key - Unique symbol key.
|
|
103
|
+
* @param {T} value - Value to set in context.
|
|
104
|
+
* @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).
|
|
105
|
+
*/
|
|
106
|
+
static set<T>(key: symbol, value: T): void;
|
|
107
|
+
/**
|
|
108
|
+
* Retrieves the entire context store object for the current async context.
|
|
109
|
+
*
|
|
110
|
+
* @returns {Store | undefined} The current store object or undefined if called outside a context.
|
|
111
|
+
*/
|
|
112
|
+
static getAll(): Store | undefined;
|
|
113
|
+
/**
|
|
114
|
+
* Initializes a new async context and executes a callback within it.
|
|
115
|
+
* This must be called at the beginning of a request or logical async flow.
|
|
116
|
+
*
|
|
117
|
+
* @typeParam T - The callback's return type.
|
|
118
|
+
* @param {Store} store - The initial key-value store object.
|
|
119
|
+
* @param {() => T} callback - The function to run within the new context.
|
|
120
|
+
* @returns {T} The result of the callback function.
|
|
121
|
+
*/
|
|
122
|
+
static run<T>(store: Store, callback: () => T): T;
|
|
123
|
+
/**
|
|
124
|
+
* Checks if a key exists in the current context store.
|
|
125
|
+
*
|
|
126
|
+
* @param {symbol} key - The symbol key to check.
|
|
127
|
+
* @returns {boolean} True if the key exists, false otherwise.
|
|
128
|
+
*/
|
|
129
|
+
static has(key: symbol): boolean;
|
|
130
|
+
/**
|
|
131
|
+
* Removes a value from the current context store by symbol key.
|
|
132
|
+
*
|
|
133
|
+
* @param {symbol} key - The symbol key to delete.
|
|
134
|
+
* @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.
|
|
135
|
+
* @throws {Error} If called outside an active context.
|
|
136
|
+
*/
|
|
137
|
+
static delete(key: symbol): boolean;
|
|
138
|
+
/**
|
|
139
|
+
* Updates multiple values in the current context store at once.
|
|
140
|
+
*
|
|
141
|
+
* @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.
|
|
142
|
+
* @throws {Error} If called outside an active context.
|
|
143
|
+
*/
|
|
144
|
+
static patch(values: Partial<Record<symbol, unknown>>): void;
|
|
145
|
+
/**
|
|
146
|
+
* Executes a callback with a temporary store value that only exists during execution.
|
|
147
|
+
* Original store is restored after callback completes.
|
|
148
|
+
*
|
|
149
|
+
* @typeParam T - The callback's return type.
|
|
150
|
+
* @param {symbol} key - The symbol key to temporarily set.
|
|
151
|
+
* @param {unknown} value - The temporary value.
|
|
152
|
+
* @param {() => T} callback - The function to execute with the temporary value.
|
|
153
|
+
* @returns {T} The result of the callback function.
|
|
154
|
+
* @throws {Error} If called outside an active context.
|
|
155
|
+
*/
|
|
156
|
+
static withValue<T>(key: symbol, value: unknown, callback: () => T): T;
|
|
157
|
+
/**
|
|
158
|
+
* Creates a new context that inherits values from the current context.
|
|
159
|
+
*
|
|
160
|
+
* @typeParam T - The callback's return type.
|
|
161
|
+
* @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.
|
|
162
|
+
* @param {() => T} callback - The function to execute in the new context.
|
|
163
|
+
* @returns {T} The result of the callback function.
|
|
164
|
+
*/
|
|
165
|
+
static extend<T>(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T;
|
|
166
|
+
/**
|
|
167
|
+
* Creates Express middleware that initializes a context for each request.
|
|
168
|
+
*
|
|
169
|
+
* @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.
|
|
170
|
+
* @returns Express middleware function.
|
|
171
|
+
*/
|
|
172
|
+
static createExpressMiddleware(initialValuesFactory?: (req: any) => Partial<Record<symbol, unknown>>): (req: any, _res: any, next: any) => void;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Type-safe wrapper for accessing and modifying context values with specific types.
|
|
176
|
+
*
|
|
177
|
+
* @typeParam T - The value type.
|
|
178
|
+
*/
|
|
179
|
+
declare class TypedContextKey<T> {
|
|
180
|
+
private readonly symbol;
|
|
181
|
+
private readonly defaultValue?;
|
|
182
|
+
/**
|
|
183
|
+
* Creates a new typed context key.
|
|
184
|
+
*
|
|
185
|
+
* @param symbol - The unique symbol for this key
|
|
186
|
+
* @param defaultValue - Optional default value if key is not found
|
|
187
|
+
*/
|
|
188
|
+
constructor(symbol: symbol, defaultValue?: T | undefined);
|
|
189
|
+
/**
|
|
190
|
+
* Gets the current value for this key.
|
|
191
|
+
*
|
|
192
|
+
* @returns The value or defaultValue if not found
|
|
193
|
+
*/
|
|
194
|
+
get(): T | undefined;
|
|
195
|
+
/**
|
|
196
|
+
* Sets the value for this key.
|
|
197
|
+
*
|
|
198
|
+
* @param value The value to set
|
|
199
|
+
*/
|
|
200
|
+
set(value: T): void;
|
|
201
|
+
/**
|
|
202
|
+
* Checks if this key exists in the context.
|
|
203
|
+
*
|
|
204
|
+
* @returns True if the key exists
|
|
205
|
+
*/
|
|
206
|
+
exists(): boolean;
|
|
207
|
+
/**
|
|
208
|
+
* Deletes this key from the context.
|
|
209
|
+
*
|
|
210
|
+
* @returns True if the key was deleted
|
|
211
|
+
*/
|
|
212
|
+
delete(): boolean;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export { ContextStore, StoreKeys, TypedContextKey, getFromContext, getRequestId };
|
|
216
|
+
export type { Store };
|
package/crypto/index.d.ts
CHANGED
|
@@ -22,4 +22,166 @@
|
|
|
22
22
|
* SOFTWARE.
|
|
23
23
|
*/
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
import { BinaryToTextEncoding, CipherGCMTypes } from 'node:crypto';
|
|
26
|
+
|
|
27
|
+
type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'utf-16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex';
|
|
28
|
+
/**
|
|
29
|
+
* Generates an HMAC digest using the specified algorithm and secret key.
|
|
30
|
+
*
|
|
31
|
+
* @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').
|
|
32
|
+
* @param {string} input - The string to hash.
|
|
33
|
+
* @param {string} secret - The secret key for HMAC.
|
|
34
|
+
* @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
|
|
35
|
+
* @returns {string} HMAC digest as a string.
|
|
36
|
+
*/
|
|
37
|
+
declare function hmac(algorithm: string, input: string, secret: string, encoding?: BinaryToTextEncoding): string;
|
|
38
|
+
/**
|
|
39
|
+
* Generates a hash digest using the specified algorithm.
|
|
40
|
+
*
|
|
41
|
+
* @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').
|
|
42
|
+
* @param {string} input - The string to hash.
|
|
43
|
+
* @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).
|
|
44
|
+
* @returns {string} Hash digest as a string.
|
|
45
|
+
*/
|
|
46
|
+
declare function hash(algorithm: string, input: string, encoding?: BinaryToTextEncoding): string;
|
|
47
|
+
/**
|
|
48
|
+
* Generates an HMAC-SHA256 digest.
|
|
49
|
+
*
|
|
50
|
+
* @param {string} input - The string to hash.
|
|
51
|
+
* @param {string} secret - The secret key.
|
|
52
|
+
* @returns {string} SHA-256 HMAC digest as a string.
|
|
53
|
+
*/
|
|
54
|
+
declare function sha256Hmac(input: string, secret: string): string;
|
|
55
|
+
/**
|
|
56
|
+
* Generates a SHA1 hash digest.
|
|
57
|
+
*
|
|
58
|
+
* @param {string} input - The string to hash.
|
|
59
|
+
* @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
|
|
60
|
+
* @returns {string} SHA-1 hash as a string.
|
|
61
|
+
*/
|
|
62
|
+
declare function sha1(input: string, encoding?: BinaryToTextEncoding): string;
|
|
63
|
+
/**
|
|
64
|
+
* Generates a SHA256 hash digest.
|
|
65
|
+
*
|
|
66
|
+
* @param {string} input - The string to hash.
|
|
67
|
+
* @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
|
|
68
|
+
* @returns {string} SHA-256 hash as a string.
|
|
69
|
+
*/
|
|
70
|
+
declare function sha256(input: string, encoding?: BinaryToTextEncoding): string;
|
|
71
|
+
/**
|
|
72
|
+
* Generates an MD5 hash digest.
|
|
73
|
+
*
|
|
74
|
+
* @param {string} input - The string to hash.
|
|
75
|
+
* @returns {string} MD5 hash as a string.
|
|
76
|
+
*/
|
|
77
|
+
declare function md5(input: string): string;
|
|
78
|
+
/**
|
|
79
|
+
* Generates a cryptographically strong random string by hashing a random UUID with SHA-256.
|
|
80
|
+
*
|
|
81
|
+
* @returns {string} Random string hashed with SHA-256 (hex encoding).
|
|
82
|
+
*/
|
|
83
|
+
declare function randomString(): string;
|
|
84
|
+
/**
|
|
85
|
+
* Generates a secure random buffer of specified byte length.
|
|
86
|
+
*
|
|
87
|
+
* @param {number} [byteLength=32] - Number of random bytes to generate.
|
|
88
|
+
* @returns {Buffer} Buffer containing random bytes.
|
|
89
|
+
*/
|
|
90
|
+
declare function generateRandomBytes(byteLength?: number): Buffer;
|
|
91
|
+
/**
|
|
92
|
+
* Generates a secure random string of specified byte length with specified encoding.
|
|
93
|
+
*
|
|
94
|
+
* @param {number} [byteLength=32] - Number of random bytes to generate.
|
|
95
|
+
* @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.
|
|
96
|
+
* @returns {string} Random string in specified encoding.
|
|
97
|
+
*/
|
|
98
|
+
declare function generateRandomBytesAsString(byteLength?: number, encoding?: BinaryToTextEncoding): string;
|
|
99
|
+
/**
|
|
100
|
+
* Generates a secure API key with a specified format.
|
|
101
|
+
*
|
|
102
|
+
* @param {string} [prefix=''] - Optional prefix for the key.
|
|
103
|
+
* @param {number} [byteLength=24] - Number of random bytes to generate.
|
|
104
|
+
* @returns {string} Formatted API key.
|
|
105
|
+
*/
|
|
106
|
+
declare function generateApiKey(prefix?: string, byteLength?: number): string;
|
|
107
|
+
/**
|
|
108
|
+
* Compares two strings, arrays, or buffers in constant time to prevent timing attacks.
|
|
109
|
+
*
|
|
110
|
+
* @param {string | Buffer | Uint8Array} a - First value to compare
|
|
111
|
+
* @param {string | Buffer | Uint8Array} b - Second value to compare
|
|
112
|
+
* @returns {boolean} True if values are equal
|
|
113
|
+
*/
|
|
114
|
+
declare function safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean;
|
|
115
|
+
/**
|
|
116
|
+
* Interface for encryption options
|
|
117
|
+
*/
|
|
118
|
+
interface EncryptionOptions {
|
|
119
|
+
/** Algorithm to use (default: aes-256-gcm) */
|
|
120
|
+
algorithm?: CipherGCMTypes;
|
|
121
|
+
/** Input encoding for plaintext if string (default: utf8) */
|
|
122
|
+
inputEncoding?: BufferEncoding;
|
|
123
|
+
/** Output encoding for ciphertext (default: hex) */
|
|
124
|
+
outputEncoding?: BinaryToTextEncoding;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Interface for decryption options
|
|
128
|
+
*/
|
|
129
|
+
interface DecryptionOptions {
|
|
130
|
+
/** Algorithm to use (default: aes-256-gcm) */
|
|
131
|
+
algorithm?: CipherGCMTypes;
|
|
132
|
+
/** Input encoding for ciphertext if string (default: hex) */
|
|
133
|
+
inputEncoding?: BinaryToTextEncoding;
|
|
134
|
+
/** Output encoding for plaintext (default: utf8) */
|
|
135
|
+
outputEncoding?: BufferEncoding;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Result of encryption operation including all data needed for decryption
|
|
139
|
+
*/
|
|
140
|
+
interface EncryptionResult {
|
|
141
|
+
/** Encrypted data (string or Buffer based on options) */
|
|
142
|
+
ciphertext: string | Buffer;
|
|
143
|
+
/** Initialization vector */
|
|
144
|
+
iv: Buffer;
|
|
145
|
+
/** Authentication tag (for GCM mode) */
|
|
146
|
+
authTag?: Buffer;
|
|
147
|
+
/** Algorithm used */
|
|
148
|
+
algorithm: string;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Encrypts data using a symmetric key with secure defaults (AES-256-GCM).
|
|
152
|
+
*
|
|
153
|
+
* @param {string | Buffer} data - Data to encrypt
|
|
154
|
+
* @param {string | Buffer} key - Encryption key or passphrase
|
|
155
|
+
* @param {EncryptionOptions} [options] - Encryption options
|
|
156
|
+
* @returns {Promise<EncryptionResult>} Encrypted data with metadata
|
|
157
|
+
*/
|
|
158
|
+
declare function encrypt(data: string | Buffer, key: string | Buffer, options?: EncryptionOptions): Promise<EncryptionResult>;
|
|
159
|
+
/**
|
|
160
|
+
* Decrypts data that was encrypted with the encrypt function.
|
|
161
|
+
*
|
|
162
|
+
* @param {EncryptionResult} encryptedData - The encrypted data and metadata
|
|
163
|
+
* @param {string | Buffer} key - Decryption key or passphrase
|
|
164
|
+
* @param {DecryptionOptions} [options] - Decryption options
|
|
165
|
+
* @returns {Promise<string | Buffer>} Decrypted data
|
|
166
|
+
*/
|
|
167
|
+
declare function decrypt(encryptedData: EncryptionResult, key: string | Buffer, options?: DecryptionOptions): Promise<string | Buffer>;
|
|
168
|
+
/**
|
|
169
|
+
* Creates a signed token with an expiration time and payload.
|
|
170
|
+
*
|
|
171
|
+
* @param {object} payload - Data to include in the token
|
|
172
|
+
* @param {string} secret - Secret key for signing
|
|
173
|
+
* @param {number} [expiresInSeconds=3600] - Token expiration in seconds
|
|
174
|
+
* @returns {string} Signed token string
|
|
175
|
+
*/
|
|
176
|
+
declare function createSignedToken(payload: Record<string, any>, secret: string, expiresInSeconds?: number): string;
|
|
177
|
+
/**
|
|
178
|
+
* Verifies and decodes a signed token.
|
|
179
|
+
*
|
|
180
|
+
* @param {string} token - The token to verify
|
|
181
|
+
* @param {string} secret - Secret key for verification
|
|
182
|
+
* @returns {object | null} Decoded payload if valid, null if invalid
|
|
183
|
+
*/
|
|
184
|
+
declare function verifySignedToken(token: string, secret: string): Record<string, any> | null;
|
|
185
|
+
|
|
186
|
+
export { createSignedToken, decrypt, encrypt, generateApiKey, generateRandomBytes, generateRandomBytesAsString, hash, hmac, md5, randomString, safeCompare, sha1, sha256, sha256Hmac, verifySignedToken };
|
|
187
|
+
export type { BufferEncoding, DecryptionOptions, EncryptionOptions, EncryptionResult };
|
package/date/index.cjs
CHANGED
|
@@ -88,7 +88,7 @@ function parseDate(input, fallback) {
|
|
|
88
88
|
}
|
|
89
89
|
try {
|
|
90
90
|
const date = new Date(input);
|
|
91
|
-
if (isNaN(date.getTime())) {
|
|
91
|
+
if (Number.isNaN(date.getTime())) {
|
|
92
92
|
return fallback || null;
|
|
93
93
|
}
|
|
94
94
|
return date;
|
|
@@ -281,6 +281,49 @@ function formatDuration(ms) {
|
|
|
281
281
|
return parts.join(" ");
|
|
282
282
|
}
|
|
283
283
|
__name(formatDuration, "formatDuration");
|
|
284
|
+
function parseDuration(value) {
|
|
285
|
+
const MAX_SAFE = Number.MAX_SAFE_INTEGER;
|
|
286
|
+
if (typeof value === "number" && Number.isFinite(value)) return Math.min(value, MAX_SAFE);
|
|
287
|
+
if (typeof value !== "string" || !value.trim()) return 0;
|
|
288
|
+
if (/^\d+$/.test(value)) return Math.min(Number(value), MAX_SAFE);
|
|
289
|
+
const val = value.replace(/\s+/g, "").toLowerCase();
|
|
290
|
+
const unitMap = {
|
|
291
|
+
y: 31536e6,
|
|
292
|
+
w: 6048e5,
|
|
293
|
+
d: 864e5,
|
|
294
|
+
h: 36e5,
|
|
295
|
+
m: 6e4,
|
|
296
|
+
s: 1e3,
|
|
297
|
+
ms: 1
|
|
298
|
+
};
|
|
299
|
+
const unitKeys = Object.keys(unitMap).sort((a, b) => b.length - a.length);
|
|
300
|
+
let total = 0;
|
|
301
|
+
let i = 0;
|
|
302
|
+
while (i < val.length) {
|
|
303
|
+
const start = i;
|
|
304
|
+
while (i < val.length && /\d/.test(val[i])) i++;
|
|
305
|
+
if (start === i) {
|
|
306
|
+
throw new Error(`Invalid duration at offset ${i} in "${value}"`);
|
|
307
|
+
}
|
|
308
|
+
const num = Number(val.slice(start, i));
|
|
309
|
+
if (!Number.isSafeInteger(num)) throw new Error(`Invalid number at offset ${start} in "${value}"`);
|
|
310
|
+
const unit = unitKeys.find((u) => val.startsWith(u, i));
|
|
311
|
+
if (!unit) throw new Error(`Unknown unit at offset ${i} in "${value}"`);
|
|
312
|
+
const add = num * unitMap[unit];
|
|
313
|
+
total = Math.min(total + add, MAX_SAFE);
|
|
314
|
+
i += unit.length;
|
|
315
|
+
}
|
|
316
|
+
return total;
|
|
317
|
+
}
|
|
318
|
+
__name(parseDuration, "parseDuration");
|
|
319
|
+
function getDateFromDuration(input) {
|
|
320
|
+
const ms = parseDuration(input);
|
|
321
|
+
if (ms <= 0) {
|
|
322
|
+
throw new Error(`Invalid duration: "${input}". Duration must be a positive value.`);
|
|
323
|
+
}
|
|
324
|
+
return new Date(Date.now() + ms);
|
|
325
|
+
}
|
|
326
|
+
__name(getDateFromDuration, "getDateFromDuration");
|
|
284
327
|
|
|
285
328
|
exports.addToDate = addToDate;
|
|
286
329
|
exports.dateDiff = dateDiff;
|
|
@@ -289,7 +332,9 @@ exports.endOf = endOf;
|
|
|
289
332
|
exports.formatDate = formatDate;
|
|
290
333
|
exports.formatDuration = formatDuration;
|
|
291
334
|
exports.formatRelativeTime = formatRelativeTime;
|
|
335
|
+
exports.getDateFromDuration = getDateFromDuration;
|
|
292
336
|
exports.isBetween = isBetween;
|
|
293
337
|
exports.isLeapYear = isLeapYear;
|
|
294
338
|
exports.parseDate = parseDate;
|
|
339
|
+
exports.parseDuration = parseDuration;
|
|
295
340
|
exports.startOf = startOf;
|