@catbee/utils 0.0.4 → 0.0.5
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 +693 -242
- package/build/esm/config.d.ts +20 -5
- package/build/esm/config.js +26 -6
- package/build/esm/config.js.map +1 -1
- package/build/esm/index.d.ts +2 -0
- package/build/esm/index.js +2 -0
- package/build/esm/index.js.map +1 -1
- package/build/esm/utils/cache.utils.js +16 -16
- package/build/esm/utils/cache.utils.js.map +1 -1
- package/build/esm/utils/context-store.utils.d.ts +1 -1
- package/build/esm/utils/context-store.utils.js +1 -1
- package/build/esm/utils/context-store.utils.js.map +1 -1
- package/build/esm/utils/crypto.utils.js +3 -2
- package/build/esm/utils/crypto.utils.js.map +1 -1
- package/build/esm/utils/decorators.utils.d.ts +291 -0
- package/build/esm/utils/decorators.utils.js +372 -40
- package/build/esm/utils/decorators.utils.js.map +1 -1
- package/build/esm/utils/env.utils.d.ts +186 -23
- package/build/esm/utils/env.utils.js +494 -91
- package/build/esm/utils/env.utils.js.map +1 -1
- package/build/esm/utils/logger.utils.d.ts +107 -0
- package/build/esm/utils/logger.utils.js +207 -14
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +27 -7
- package/build/esm/utils/middleware.utils.js +25 -9
- package/build/esm/utils/middleware.utils.js.map +1 -1
- package/build/esm/utils/request.utils.d.ts +77 -0
- package/build/esm/utils/request.utils.js +173 -0
- package/build/esm/utils/request.utils.js.map +1 -0
- package/build/esm/utils/response.utils.js +4 -4
- package/build/esm/utils/response.utils.js.map +1 -1
- package/build/esnext/config.d.ts +20 -5
- package/build/esnext/config.js +26 -6
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/index.d.ts +2 -0
- package/build/esnext/index.js +2 -0
- package/build/esnext/index.js.map +1 -1
- package/build/esnext/utils/cache.utils.js +16 -16
- package/build/esnext/utils/cache.utils.js.map +1 -1
- package/build/esnext/utils/context-store.utils.d.ts +1 -1
- package/build/esnext/utils/context-store.utils.js +1 -1
- package/build/esnext/utils/context-store.utils.js.map +1 -1
- package/build/esnext/utils/crypto.utils.js +3 -2
- package/build/esnext/utils/crypto.utils.js.map +1 -1
- package/build/esnext/utils/decorators.utils.d.ts +291 -0
- package/build/esnext/utils/decorators.utils.js +348 -21
- package/build/esnext/utils/decorators.utils.js.map +1 -1
- package/build/esnext/utils/env.utils.d.ts +186 -23
- package/build/esnext/utils/env.utils.js +445 -77
- package/build/esnext/utils/env.utils.js.map +1 -1
- package/build/esnext/utils/logger.utils.d.ts +107 -0
- package/build/esnext/utils/logger.utils.js +178 -14
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +27 -7
- package/build/esnext/utils/middleware.utils.js +25 -9
- package/build/esnext/utils/middleware.utils.js.map +1 -1
- package/build/esnext/utils/request.utils.d.ts +77 -0
- package/build/esnext/utils/request.utils.js +145 -0
- package/build/esnext/utils/request.utils.js.map +1 -0
- package/build/esnext/utils/response.utils.js +4 -4
- package/build/esnext/utils/response.utils.js.map +1 -1
- package/build/src/config.d.ts +20 -5
- package/build/src/config.js +29 -7
- package/build/src/config.js.map +1 -1
- package/build/src/index.d.ts +2 -0
- package/build/src/index.js +5 -0
- package/build/src/index.js.map +1 -1
- package/build/src/utils/cache.utils.js +15 -15
- package/build/src/utils/cache.utils.js.map +1 -1
- package/build/src/utils/context-store.utils.d.ts +1 -1
- package/build/src/utils/context-store.utils.js +1 -1
- package/build/src/utils/context-store.utils.js.map +1 -1
- package/build/src/utils/crypto.utils.js +2 -1
- package/build/src/utils/crypto.utils.js.map +1 -1
- package/build/src/utils/decorators.utils.d.ts +291 -0
- package/build/src/utils/decorators.utils.js +350 -21
- package/build/src/utils/decorators.utils.js.map +1 -1
- package/build/src/utils/env.utils.d.ts +186 -23
- package/build/src/utils/env.utils.js +444 -76
- package/build/src/utils/env.utils.js.map +1 -1
- package/build/src/utils/logger.utils.d.ts +107 -0
- package/build/src/utils/logger.utils.js +184 -14
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +27 -7
- package/build/src/utils/middleware.utils.js +24 -8
- package/build/src/utils/middleware.utils.js.map +1 -1
- package/build/src/utils/request.utils.d.ts +77 -0
- package/build/src/utils/request.utils.js +152 -0
- package/build/src/utils/request.utils.js.map +1 -0
- package/build/src/utils/response.utils.js +4 -4
- package/build/src/utils/response.utils.js.map +1 -1
- package/package.json +12 -7
package/build/esm/config.d.ts
CHANGED
|
@@ -2,8 +2,8 @@ type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silen
|
|
|
2
2
|
/**
|
|
3
3
|
* Application runtime configuration loaded from environment variables.
|
|
4
4
|
*/
|
|
5
|
-
export declare
|
|
6
|
-
|
|
5
|
+
export declare let config: {
|
|
6
|
+
logger: {
|
|
7
7
|
/**
|
|
8
8
|
* Logging level (e.g., 'info', 'debug', 'warn', 'error').
|
|
9
9
|
*/
|
|
@@ -11,20 +11,35 @@ export declare const Config: {
|
|
|
11
11
|
/**
|
|
12
12
|
* Name of the logger instance (defaults to npm package name).
|
|
13
13
|
*/
|
|
14
|
-
name: string
|
|
14
|
+
name: string;
|
|
15
|
+
/**
|
|
16
|
+
* Enables pretty-print logging in development.
|
|
17
|
+
* Has no effect in production.
|
|
18
|
+
*/
|
|
19
|
+
pretty: boolean;
|
|
15
20
|
};
|
|
16
|
-
|
|
21
|
+
http: {
|
|
17
22
|
/**
|
|
18
23
|
* Timeout for HTTP requests in milliseconds
|
|
19
24
|
*/
|
|
20
25
|
timeout: number;
|
|
21
26
|
};
|
|
22
|
-
|
|
27
|
+
cache: {
|
|
23
28
|
/**
|
|
24
29
|
* Default TTL (time to live) for cache entries in seconds
|
|
25
30
|
*/
|
|
26
31
|
defaultTtl: number;
|
|
27
32
|
};
|
|
28
33
|
};
|
|
34
|
+
/**
|
|
35
|
+
* Update the @catbee/utils configuration.
|
|
36
|
+
* @param value Partial configuration object.
|
|
37
|
+
*/
|
|
38
|
+
export declare function setConfig(value: Partial<typeof config>): void;
|
|
39
|
+
/**
|
|
40
|
+
* Get the current @catbee/utils configuration.
|
|
41
|
+
* @returns The current configuration object.
|
|
42
|
+
*/
|
|
43
|
+
export declare function getConfig(): typeof config;
|
|
29
44
|
export {};
|
|
30
45
|
//# sourceMappingURL=config.d.ts.map
|
package/build/esm/config.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { Env } from './utils/env.utils';
|
|
2
|
+
import { deepObjMerge } from './utils/obj.utils';
|
|
2
3
|
/**
|
|
3
4
|
* Application runtime configuration loaded from environment variables.
|
|
4
5
|
*/
|
|
5
|
-
export var
|
|
6
|
-
|
|
6
|
+
export var config = {
|
|
7
|
+
logger: {
|
|
7
8
|
/**
|
|
8
9
|
* Logging level (e.g., 'info', 'debug', 'warn', 'error').
|
|
9
10
|
*/
|
|
@@ -11,19 +12,38 @@ export var Config = {
|
|
|
11
12
|
/**
|
|
12
13
|
* Name of the logger instance (defaults to npm package name).
|
|
13
14
|
*/
|
|
14
|
-
name: Env.get('LOGGER_NAME', Env.get('npm_package_name', '@catbee/utils'))
|
|
15
|
+
name: Env.get('LOGGER_NAME', Env.get('npm_package_name', '@catbee/utils')),
|
|
16
|
+
/**
|
|
17
|
+
* Enables pretty-print logging in development.
|
|
18
|
+
* Has no effect in production.
|
|
19
|
+
*/
|
|
20
|
+
pretty: Env.getBoolean('LOGGER_PRETTY', true)
|
|
15
21
|
},
|
|
16
|
-
|
|
22
|
+
http: {
|
|
17
23
|
/**
|
|
18
24
|
* Timeout for HTTP requests in milliseconds
|
|
19
25
|
*/
|
|
20
26
|
timeout: Env.getNumber('HTTP_TIMEOUT', 30000)
|
|
21
27
|
},
|
|
22
|
-
|
|
28
|
+
cache: {
|
|
23
29
|
/**
|
|
24
30
|
* Default TTL (time to live) for cache entries in seconds
|
|
25
31
|
*/
|
|
26
|
-
defaultTtl: Env.getNumber('
|
|
32
|
+
defaultTtl: Env.getNumber('CACHE_DEFAULT_TTL_SECONDS', 3600) * 1000
|
|
27
33
|
}
|
|
28
34
|
};
|
|
35
|
+
/**
|
|
36
|
+
* Update the @catbee/utils configuration.
|
|
37
|
+
* @param value Partial configuration object.
|
|
38
|
+
*/
|
|
39
|
+
export function setConfig(value) {
|
|
40
|
+
deepObjMerge(config, value);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Get the current @catbee/utils configuration.
|
|
44
|
+
* @returns The current configuration object.
|
|
45
|
+
*/
|
|
46
|
+
export function getConfig() {
|
|
47
|
+
return config;
|
|
48
|
+
}
|
|
29
49
|
//# sourceMappingURL=config.js.map
|
package/build/esm/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAIjD;;GAEG;AACH,MAAM,CAAC,IAAI,MAAM,GAAG;IAClB,MAAM,EAAE;QACN;;WAEG;QACH,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,cAAc,EAAE,MAAM,CAAa;QAElD;;WAEG;QACH,IAAI,EAAE,GAAG,CAAC,GAAG,CAAC,aAAa,EAAE,GAAG,CAAC,GAAG,CAAC,kBAAkB,EAAE,eAAe,CAAC,CAAC;QAE1E;;;WAGG;QACH,MAAM,EAAE,GAAG,CAAC,UAAU,CAAC,eAAe,EAAE,IAAI,CAAC;KAC9C;IAED,IAAI,EAAE;QACJ;;WAEG;QACH,OAAO,EAAE,GAAG,CAAC,SAAS,CAAC,cAAc,EAAE,KAAK,CAAC;KAC9C;IAED,KAAK,EAAE;QACL;;WAEG;QACH,UAAU,EAAE,GAAG,CAAC,SAAS,CAAC,2BAA2B,EAAE,IAAI,CAAC,GAAG,IAAI;KACpE;CACF,CAAC;AAEF;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,KAA6B;IACrD,YAAY,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AAC9B,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,SAAS;IACvB,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Env } from './utils/env.utils';\nimport { deepObjMerge } from './utils/obj.utils';\n\ntype LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent';\n\n/**\n * Application runtime configuration loaded from environment variables.\n */\nexport let config = {\n logger: {\n /**\n * Logging level (e.g., 'info', 'debug', 'warn', 'error').\n */\n level: Env.get('LOGGER_LEVEL', 'info') as LogLevel,\n\n /**\n * Name of the logger instance (defaults to npm package name).\n */\n name: Env.get('LOGGER_NAME', Env.get('npm_package_name', '@catbee/utils')),\n\n /**\n * Enables pretty-print logging in development.\n * Has no effect in production.\n */\n pretty: Env.getBoolean('LOGGER_PRETTY', true)\n },\n\n http: {\n /**\n * Timeout for HTTP requests in milliseconds\n */\n timeout: Env.getNumber('HTTP_TIMEOUT', 30000)\n },\n\n cache: {\n /**\n * Default TTL (time to live) for cache entries in seconds\n */\n defaultTtl: Env.getNumber('CACHE_DEFAULT_TTL_SECONDS', 3600) * 1000\n }\n};\n\n/**\n * Update the @catbee/utils configuration.\n * @param value Partial configuration object.\n */\nexport function setConfig(value: Partial<typeof config>): void {\n deepObjMerge(config, value);\n}\n\n/**\n * Get the current @catbee/utils configuration.\n * @returns The current configuration object.\n */\nexport function getConfig(): typeof config {\n return config;\n}\n"]}
|
package/build/esm/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { setConfig, getConfig } from './config';
|
|
1
2
|
export * from './utils/array.utils';
|
|
2
3
|
export * from './utils/async.utils';
|
|
3
4
|
export * from './utils/cache.utils';
|
|
@@ -13,6 +14,7 @@ export * from './utils/id.utils';
|
|
|
13
14
|
export * from './utils/logger.utils';
|
|
14
15
|
export * from './utils/middleware.utils';
|
|
15
16
|
export * from './utils/obj.utils';
|
|
17
|
+
export * from './utils/request.utils';
|
|
16
18
|
export * from './utils/response.utils';
|
|
17
19
|
export * from './utils/string.utils';
|
|
18
20
|
export * from './utils/url.utils';
|
package/build/esm/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { setConfig, getConfig } from './config';
|
|
1
2
|
export * from './utils/array.utils';
|
|
2
3
|
export * from './utils/async.utils';
|
|
3
4
|
export * from './utils/cache.utils';
|
|
@@ -13,6 +14,7 @@ export * from './utils/id.utils';
|
|
|
13
14
|
export * from './utils/logger.utils';
|
|
14
15
|
export * from './utils/middleware.utils';
|
|
15
16
|
export * from './utils/obj.utils';
|
|
17
|
+
export * from './utils/request.utils';
|
|
16
18
|
export * from './utils/response.utils';
|
|
17
19
|
export * from './utils/string.utils';
|
|
18
20
|
export * from './utils/url.utils';
|
package/build/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,sBAAsB,CAAC;AACrC,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC;AACrC,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,mBAAmB,CAAC;AAClC,cAAc,wBAAwB,CAAC;AAEvC,cAAc,sBAAsB,CAAC","sourcesContent":["export * from './utils/array.utils';\nexport * from './utils/async.utils';\nexport * from './utils/cache.utils';\nexport * from './utils/context-store.utils';\nexport * from './utils/crypto.utils';\nexport * from './utils/decorators.utils';\nexport * from './utils/dir.utils';\nexport * from './utils/env.utils';\nexport * from './utils/exception.utils';\nexport * from './utils/fs.utils';\nexport * from './utils/http-status-codes';\nexport * from './utils/id.utils';\nexport * from './utils/logger.utils';\nexport * from './utils/middleware.utils';\nexport * from './utils/obj.utils';\nexport * from './utils/response.utils';\nexport * from './utils/string.utils';\nexport * from './utils/url.utils';\nexport * from './utils/validate.utils';\n\nexport * from './types/api-response';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAEhD,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,sBAAsB,CAAC;AACrC,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,cAAc,mBAAmB,CAAC;AAClC,cAAc,yBAAyB,CAAC;AACxC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC;AACrC,cAAc,0BAA0B,CAAC;AACzC,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC;AACtC,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,mBAAmB,CAAC;AAClC,cAAc,wBAAwB,CAAC;AAEvC,cAAc,sBAAsB,CAAC","sourcesContent":["export { setConfig, getConfig } from './config';\n\nexport * from './utils/array.utils';\nexport * from './utils/async.utils';\nexport * from './utils/cache.utils';\nexport * from './utils/context-store.utils';\nexport * from './utils/crypto.utils';\nexport * from './utils/decorators.utils';\nexport * from './utils/dir.utils';\nexport * from './utils/env.utils';\nexport * from './utils/exception.utils';\nexport * from './utils/fs.utils';\nexport * from './utils/http-status-codes';\nexport * from './utils/id.utils';\nexport * from './utils/logger.utils';\nexport * from './utils/middleware.utils';\nexport * from './utils/obj.utils';\nexport * from './utils/request.utils';\nexport * from './utils/response.utils';\nexport * from './utils/string.utils';\nexport * from './utils/url.utils';\nexport * from './utils/validate.utils';\n\nexport * from './types/api-response';\n"]}
|
|
@@ -61,7 +61,7 @@ var __read = (this && this.__read) || function (o, n) {
|
|
|
61
61
|
}
|
|
62
62
|
return ar;
|
|
63
63
|
};
|
|
64
|
-
import {
|
|
64
|
+
import { config } from '../config';
|
|
65
65
|
/**
|
|
66
66
|
* An in-memory cache with time-to-live (TTL) support for each entry.
|
|
67
67
|
*
|
|
@@ -82,7 +82,7 @@ var TTLCache = /** @class */ (function () {
|
|
|
82
82
|
var _this = this;
|
|
83
83
|
var _a;
|
|
84
84
|
this.cache = new Map();
|
|
85
|
-
this.ttlMs = (_a = options.ttlMs) !== null && _a !== void 0 ? _a :
|
|
85
|
+
this.ttlMs = (_a = options.ttlMs) !== null && _a !== void 0 ? _a : config.cache.defaultTtl;
|
|
86
86
|
this.maxSize = options.maxSize;
|
|
87
87
|
// Setup auto-cleanup if enabled
|
|
88
88
|
var autoCleanupMs = options.autoCleanupMs;
|
|
@@ -111,8 +111,10 @@ var TTLCache = /** @class */ (function () {
|
|
|
111
111
|
TTLCache.prototype.setWithTTL = function (key, value, ttlMs) {
|
|
112
112
|
var now = Date.now();
|
|
113
113
|
var expiresAt = now + ttlMs;
|
|
114
|
+
if (this.cache.has(key)) {
|
|
115
|
+
this.cache.delete(key); // remove old entry to maintain LRU order
|
|
116
|
+
}
|
|
114
117
|
this.cache.set(key, { value: value, expiresAt: expiresAt, lastAccessed: now });
|
|
115
|
-
// Enforce max size limit if configured
|
|
116
118
|
if (this.maxSize && this.cache.size > this.maxSize) {
|
|
117
119
|
this.evictLRU();
|
|
118
120
|
}
|
|
@@ -132,8 +134,11 @@ var TTLCache = /** @class */ (function () {
|
|
|
132
134
|
this.cache.delete(key);
|
|
133
135
|
return undefined;
|
|
134
136
|
}
|
|
135
|
-
// Update
|
|
137
|
+
// Update lastAccessed and move key to the end (most recently used)
|
|
136
138
|
entry.lastAccessed = now;
|
|
139
|
+
// Re-insert to end of Map to maintain LRU order
|
|
140
|
+
this.cache.delete(key);
|
|
141
|
+
this.cache.set(key, entry);
|
|
137
142
|
return entry.value;
|
|
138
143
|
};
|
|
139
144
|
/**
|
|
@@ -442,20 +447,13 @@ var TTLCache = /** @class */ (function () {
|
|
|
442
447
|
*/
|
|
443
448
|
TTLCache.prototype.evictLRU = function () {
|
|
444
449
|
var e_7, _a;
|
|
445
|
-
var
|
|
446
|
-
var oldestAccess = Infinity;
|
|
450
|
+
var now = Date.now();
|
|
447
451
|
try {
|
|
448
|
-
|
|
452
|
+
// Remove all expired items first
|
|
453
|
+
for (var _b = __values(Array.from(this.cache.entries())), _c = _b.next(); !_c.done; _c = _b.next()) {
|
|
449
454
|
var _d = __read(_c.value, 2), key = _d[0], entry = _d[1];
|
|
450
|
-
|
|
451
|
-
if (Date.now() > entry.expiresAt) {
|
|
455
|
+
if (now > entry.expiresAt) {
|
|
452
456
|
this.cache.delete(key);
|
|
453
|
-
return;
|
|
454
|
-
}
|
|
455
|
-
// Find the oldest accessed entry
|
|
456
|
-
if (entry.lastAccessed && entry.lastAccessed < oldestAccess) {
|
|
457
|
-
oldestAccess = entry.lastAccessed;
|
|
458
|
-
oldestKey = key;
|
|
459
457
|
}
|
|
460
458
|
}
|
|
461
459
|
}
|
|
@@ -466,7 +464,9 @@ var TTLCache = /** @class */ (function () {
|
|
|
466
464
|
}
|
|
467
465
|
finally { if (e_7) throw e_7.error; }
|
|
468
466
|
}
|
|
469
|
-
|
|
467
|
+
// Evict oldest entries until within max size
|
|
468
|
+
while (this.maxSize && this.cache.size > this.maxSize) {
|
|
469
|
+
var oldestKey = this.cache.keys().next().value;
|
|
470
470
|
this.cache.delete(oldestKey);
|
|
471
471
|
}
|
|
472
472
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache.utils.js","sourceRoot":"","sources":["../../../src/utils/cache.utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAuBnC;;;;;;;;;;GAUG;AACH;IAME;;OAEG;IACH,kBAAY,OAA6B;QAA7B,wBAAA,EAAA,YAA6B;QAAzC,iBAWC;;QAnBO,UAAK,GAAG,IAAI,GAAG,EAAoB,CAAC;QAS1C,IAAI,CAAC,KAAK,GAAG,MAAA,OAAO,CAAC,KAAK,mCAAI,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC;QACtD,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAE/B,gCAAgC;QAChC,IAAM,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;QAC5C,IAAI,aAAa,IAAI,aAAa,GAAG,CAAC,EAAE,CAAC;YACvC,IAAI,CAAC,eAAe,GAAG,WAAW,CAAC;gBACjC,KAAI,CAAC,OAAO,EAAE,CAAC;YACjB,CAAC,EAAE,aAAa,CAAC,CAAC;QACpB,CAAC;IACH,CAAC;IAED;;;;;OAKG;IACH,sBAAG,GAAH,UAAI,GAAM,EAAE,KAAQ;QAClB,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;IAED;;;;;;OAMG;IACH,6BAAU,GAAV,UAAW,GAAM,EAAE,KAAQ,EAAE,KAAa;QACxC,IAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,IAAM,SAAS,G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AAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACnC,CAAC;IACH,CAAC;IAED;;;OAGG;IACK,2BAAQ,GAAhB;;QACE,IAAI,SAAwB,CAAC;QAC7B,IAAI,YAAY,GAAG,QAAQ,CAAC;;YAE5B,KAA2B,IAAA,KAAA,SAAA,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAA,gBAAA,4BAAE,CAAC;gBAAvC,IAAA,KAAA,mBAAY,EAAX,GAAG,QAAA,EAAE,KAAK,QAAA;gBACpB,wCAAwC;gBACxC,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,SAAS,EAAE,CAAC;oBACjC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;oBACvB,OAAO;gBACT,CAAC;gBAED,iCAAiC;gBACjC,IAAI,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,YAAY,GAAG,YAAY,EAAE,CAAC;oBAC5D,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;oBAClC,SAAS,GAAG,GAAG,CAAC;gBAClB,CAAC;YACH,CAAC;;;;;;;;;QAED,IAAI,SAAS,EAAE,CAAC;YACd,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QAC/B,CAAC;IACH,CAAC;IACH,eAAC;AAAD,CAAC,AA7RD,IA6RC","sourcesContent":["import { Config } from '../config';\n\n/**\n * Represents a cached entry with a value and an expiration timestamp.\n */\ntype CacheEntry<T> = {\n value: T;\n expiresAt: number;\n lastAccessed?: number; // Track last access time for LRU functionality\n};\n\n/**\n * Options for configuring a TTLCache instance.\n */\nexport interface TTLCacheOptions {\n /** Default time-to-live in milliseconds for cache entries */\n ttlMs?: number;\n /** Maximum number of entries to keep in cache (uses LRU eviction policy) */\n maxSize?: number;\n /** Auto-cleanup interval in milliseconds (disabled if 0 or negative) */\n autoCleanupMs?: number;\n}\n\n/**\n * An in-memory cache with time-to-live (TTL) support for each entry.\n *\n * @typeParam K - Type of the key.\n * @typeParam V - Type of the value.\n *\n * @example\n * const cache = new TTLCache<string, number>({ ttlMs: 1000 });\n * cache.set(\"x\", 123);\n * const value = cache.get(\"x\"); // 123\n */\nexport class TTLCache<K, V> {\n private cache = new Map<K, CacheEntry<V>>();\n private ttlMs: number;\n private maxSize?: number;\n private cleanupInterval?: NodeJS.Timeout;\n\n /**\n * @param options - Configuration options for the cache\n */\n constructor(options: TTLCacheOptions = {}) {\n this.ttlMs = options.ttlMs ?? Config.Cache.defaultTtl;\n this.maxSize = options.maxSize;\n\n // Setup auto-cleanup if enabled\n const autoCleanupMs = options.autoCleanupMs;\n if (autoCleanupMs && autoCleanupMs > 0) {\n this.cleanupInterval = setInterval(() => {\n this.cleanup();\n }, autoCleanupMs);\n }\n }\n\n /**\n * Sets a key-value pair in the cache with the default TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n */\n set(key: K, value: V): void {\n this.setWithTTL(key, value, this.ttlMs);\n }\n\n /**\n * Sets a key-value pair in the cache with a custom TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n * @param ttlMs - Time-to-live in milliseconds.\n */\n setWithTTL(key: K, value: V, ttlMs: number): void {\n const now = Date.now();\n const expiresAt = now + ttlMs;\n this.cache.set(key, { value, expiresAt, lastAccessed: now });\n\n // Enforce max size limit if configured\n if (this.maxSize && this.cache.size > this.maxSize) {\n this.evictLRU();\n }\n }\n\n /**\n * Retrieves the value for a given key if it hasn't expired.\n *\n * @param key - The key to retrieve.\n * @returns The cached value, or undefined if not found or expired.\n */\n get(key: K): V | undefined {\n const entry = this.cache.get(key);\n if (!entry) return undefined;\n\n const now = Date.now();\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n return undefined;\n }\n\n // Update last access time for LRU tracking\n entry.lastAccessed = now;\n return entry.value;\n }\n\n /**\n * Retrieves or computes a value if it's not in the cache or has expired.\n *\n * @param key - The key to retrieve\n * @param producer - Function to generate the value if not cached\n * @param ttlMs - Optional custom TTL for the computed value\n * @returns The cached or computed value\n */\n async getOrCompute(key: K, producer: () => Promise<V>, ttlMs?: number): Promise<V> {\n const value = this.get(key);\n if (value !== undefined) return value;\n\n const newValue = await producer();\n this.setWithTTL(key, newValue, ttlMs ?? this.ttlMs);\n return newValue;\n }\n\n /**\n * Checks if the key exists and hasn't expired.\n *\n * @param key - The key to check.\n * @returns `true` if key exists and is valid, otherwise `false`.\n */\n has(key: K): boolean {\n return this.get(key) !== undefined;\n }\n\n /**\n * Deletes a key from the cache.\n *\n * @param key - The key to delete.\n * @returns `true` if the key existed and was removed, `false` otherwise.\n */\n delete(key: K): boolean {\n return this.cache.delete(key);\n }\n\n /**\n * Clears all entries from the cache.\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).\n *\n * @returns Number of items in the cache (may include expired keys).\n */\n size(): number {\n return this.cache.size;\n }\n\n /**\n * Set multiple key-value pairs at once with the default TTL.\n *\n * @param entries - Array of [key, value] tuples to set\n */\n setMany(entries: [K, V][]): void {\n for (const [key, value] of entries) {\n this.set(key, value);\n }\n }\n\n /**\n * Get multiple values at once.\n *\n * @param keys - Array of keys to retrieve\n * @returns Array of values (undefined for keys that don't exist or expired)\n */\n getMany(keys: K[]): (V | undefined)[] {\n return keys.map(key => this.get(key));\n }\n\n /**\n * Removes all expired entries from the cache.\n *\n * @returns Number of entries removed.\n */\n cleanup(): number {\n let removed = 0;\n const now = Date.now();\n for (const [key, entry] of this.cache.entries()) {\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n removed++;\n }\n }\n return removed;\n }\n\n /**\n * Returns an iterator of all current valid [key, value] pairs.\n *\n * @returns IterableIterator<[K, V]>\n */\n *entries(): IterableIterator<[K, V]> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield [key, entry.value];\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid keys.\n *\n * @returns IterableIterator<K>\n */\n *keys(): IterableIterator<K> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield key;\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid values.\n *\n * @returns IterableIterator<V>\n */\n *values(): IterableIterator<V> {\n for (const entry of this.cache.values()) {\n if (Date.now() <= entry.expiresAt) {\n yield entry.value;\n }\n }\n }\n\n /**\n * Extends the expiration of a key by the specified time or default TTL.\n *\n * @param key - The key to refresh\n * @param ttlMs - Optional new TTL in milliseconds (uses default if not specified)\n * @returns true if the key was found and refreshed, false otherwise\n */\n refresh(key: K, ttlMs?: number): boolean {\n const entry = this.cache.get(key);\n if (!entry) return false;\n\n const now = Date.now();\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n return false;\n }\n\n entry.expiresAt = now + (ttlMs ?? this.ttlMs);\n entry.lastAccessed = now;\n return true;\n }\n\n /**\n * Returns a snapshot of cache stats.\n *\n * @returns Object containing cache statistics\n */\n stats() {\n const now = Date.now();\n let expired = 0;\n let valid = 0;\n\n for (const entry of this.cache.values()) {\n if (now > entry.expiresAt) {\n expired++;\n } else {\n valid++;\n }\n }\n\n return {\n size: this.cache.size,\n validEntries: valid,\n expiredEntries: expired,\n maxSize: this.maxSize\n };\n }\n\n /**\n * Stop the auto-cleanup interval if it's running.\n */\n destroy() {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = undefined;\n }\n }\n\n /**\n * Evict the least recently used entry from the cache.\n * @private\n */\n private evictLRU(): void {\n let oldestKey: K | undefined;\n let oldestAccess = Infinity;\n\n for (const [key, entry] of this.cache.entries()) {\n // Skip entries that are already expired\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key);\n return;\n }\n\n // Find the oldest accessed entry\n if (entry.lastAccessed && entry.lastAccessed < oldestAccess) {\n oldestAccess = entry.lastAccessed;\n oldestKey = key;\n }\n }\n\n if (oldestKey) {\n this.cache.delete(oldestKey);\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"cache.utils.js","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,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACzB,aAAa,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;YACpC,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACnC,CAAC;IACH,CAAC;IAED;;;OAGG;IACK,2BAAQ,GAAhB;;QACE,IAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;;YAEvB,iCAAiC;YACjC,KAA2B,IAAA,KAAA,SAAA,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAA,gBAAA,4BAAE,CAAC;gBAAnD,IAAA,KAAA,mBAAY,EAAX,GAAG,QAAA,EAAE,KAAK,QAAA;gBACpB,IAAI,GAAG,GAAG,KAAK,CAAC,SAAS,EAAE,CAAC;oBAC1B,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBACzB,CAAC;YACH,CAAC;;;;;;;;;QAED,6CAA6C;QAC7C,OAAO,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;YACtD,IAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;YACjD,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,SAAc,CAAC,CAAC;QACpC,CAAC;IACH,CAAC;IACH,eAAC;AAAD,CAAC,AA/RD,IA+RC","sourcesContent":["import { config } from '../config';\n\n/**\n * Represents a cached entry with a value and an expiration timestamp.\n */\ntype CacheEntry<T> = {\n value: T;\n expiresAt: number;\n lastAccessed?: number; // Track last access time for LRU functionality\n};\n\n/**\n * Options for configuring a TTLCache instance.\n */\nexport interface TTLCacheOptions {\n /** Default time-to-live in milliseconds for cache entries */\n ttlMs?: number;\n /** Maximum number of entries to keep in cache (uses LRU eviction policy) */\n maxSize?: number;\n /** Auto-cleanup interval in milliseconds (disabled if 0 or negative) */\n autoCleanupMs?: number;\n}\n\n/**\n * An in-memory cache with time-to-live (TTL) support for each entry.\n *\n * @typeParam K - Type of the key.\n * @typeParam V - Type of the value.\n *\n * @example\n * const cache = new TTLCache<string, number>({ ttlMs: 1000 });\n * cache.set(\"x\", 123);\n * const value = cache.get(\"x\"); // 123\n */\nexport class TTLCache<K, V> {\n private cache = new Map<K, CacheEntry<V>>();\n private ttlMs: number;\n private maxSize?: number;\n private cleanupInterval?: NodeJS.Timeout;\n\n /**\n * @param options - Configuration options for the cache\n */\n constructor(options: TTLCacheOptions = {}) {\n this.ttlMs = options.ttlMs ?? config.cache.defaultTtl;\n this.maxSize = options.maxSize;\n\n // Setup auto-cleanup if enabled\n const autoCleanupMs = options.autoCleanupMs;\n if (autoCleanupMs && autoCleanupMs > 0) {\n this.cleanupInterval = setInterval(() => {\n this.cleanup();\n }, autoCleanupMs);\n }\n }\n\n /**\n * Sets a key-value pair in the cache with the default TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n */\n set(key: K, value: V): void {\n this.setWithTTL(key, value, this.ttlMs);\n }\n\n /**\n * Sets a key-value pair in the cache with a custom TTL.\n *\n * @param key - The key to set.\n * @param value - The value to associate with the key.\n * @param ttlMs - Time-to-live in milliseconds.\n */\n setWithTTL(key: K, value: V, ttlMs: number): void {\n const now = Date.now();\n const expiresAt = now + ttlMs;\n\n if (this.cache.has(key)) {\n this.cache.delete(key); // remove old entry to maintain LRU order\n }\n\n this.cache.set(key, { value, expiresAt, lastAccessed: now });\n\n if (this.maxSize && this.cache.size > this.maxSize) {\n this.evictLRU();\n }\n }\n\n /**\n * Retrieves the value for a given key if it hasn't expired.\n *\n * @param key - The key to retrieve.\n * @returns The cached value, or undefined if not found or expired.\n */\n get(key: K): V | undefined {\n const entry = this.cache.get(key);\n if (!entry) return undefined;\n\n const now = Date.now();\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n return undefined;\n }\n\n // Update lastAccessed and move key to the end (most recently used)\n entry.lastAccessed = now;\n // Re-insert to end of Map to maintain LRU order\n this.cache.delete(key);\n this.cache.set(key, entry);\n\n return entry.value;\n }\n\n /**\n * Retrieves or computes a value if it's not in the cache or has expired.\n *\n * @param key - The key to retrieve\n * @param producer - Function to generate the value if not cached\n * @param ttlMs - Optional custom TTL for the computed value\n * @returns The cached or computed value\n */\n async getOrCompute(key: K, producer: () => Promise<V>, ttlMs?: number): Promise<V> {\n const value = this.get(key);\n if (value !== undefined) return value;\n\n const newValue = await producer();\n this.setWithTTL(key, newValue, ttlMs ?? this.ttlMs);\n return newValue;\n }\n\n /**\n * Checks if the key exists and hasn't expired.\n *\n * @param key - The key to check.\n * @returns `true` if key exists and is valid, otherwise `false`.\n */\n has(key: K): boolean {\n return this.get(key) !== undefined;\n }\n\n /**\n * Deletes a key from the cache.\n *\n * @param key - The key to delete.\n * @returns `true` if the key existed and was removed, `false` otherwise.\n */\n delete(key: K): boolean {\n return this.cache.delete(key);\n }\n\n /**\n * Clears all entries from the cache.\n */\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).\n *\n * @returns Number of items in the cache (may include expired keys).\n */\n size(): number {\n return this.cache.size;\n }\n\n /**\n * Set multiple key-value pairs at once with the default TTL.\n *\n * @param entries - Array of [key, value] tuples to set\n */\n setMany(entries: [K, V][]): void {\n for (const [key, value] of entries) {\n this.set(key, value);\n }\n }\n\n /**\n * Get multiple values at once.\n *\n * @param keys - Array of keys to retrieve\n * @returns Array of values (undefined for keys that don't exist or expired)\n */\n getMany(keys: K[]): (V | undefined)[] {\n return keys.map(key => this.get(key));\n }\n\n /**\n * Removes all expired entries from the cache.\n *\n * @returns Number of entries removed.\n */\n cleanup(): number {\n let removed = 0;\n const now = Date.now();\n for (const [key, entry] of this.cache.entries()) {\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n removed++;\n }\n }\n return removed;\n }\n\n /**\n * Returns an iterator of all current valid [key, value] pairs.\n *\n * @returns IterableIterator<[K, V]>\n */\n *entries(): IterableIterator<[K, V]> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield [key, entry.value];\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid keys.\n *\n * @returns IterableIterator<K>\n */\n *keys(): IterableIterator<K> {\n for (const [key, entry] of this.cache.entries()) {\n if (Date.now() <= entry.expiresAt) {\n yield key;\n }\n }\n }\n\n /**\n * Returns an iterator of all current valid values.\n *\n * @returns IterableIterator<V>\n */\n *values(): IterableIterator<V> {\n for (const entry of this.cache.values()) {\n if (Date.now() <= entry.expiresAt) {\n yield entry.value;\n }\n }\n }\n\n /**\n * Extends the expiration of a key by the specified time or default TTL.\n *\n * @param key - The key to refresh\n * @param ttlMs - Optional new TTL in milliseconds (uses default if not specified)\n * @returns true if the key was found and refreshed, false otherwise\n */\n refresh(key: K, ttlMs?: number): boolean {\n const entry = this.cache.get(key);\n if (!entry) return false;\n\n const now = Date.now();\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n return false;\n }\n\n entry.expiresAt = now + (ttlMs ?? this.ttlMs);\n entry.lastAccessed = now;\n return true;\n }\n\n /**\n * Returns a snapshot of cache stats.\n *\n * @returns Object containing cache statistics\n */\n stats() {\n const now = Date.now();\n let expired = 0;\n let valid = 0;\n\n for (const entry of this.cache.values()) {\n if (now > entry.expiresAt) {\n expired++;\n } else {\n valid++;\n }\n }\n\n return {\n size: this.cache.size,\n validEntries: valid,\n expiredEntries: expired,\n maxSize: this.maxSize\n };\n }\n\n /**\n * Stop the auto-cleanup interval if it's running.\n */\n destroy() {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = undefined;\n }\n }\n\n /**\n * Evict the least recently used entry from the cache.\n * @private\n */\n private evictLRU(): void {\n const now = Date.now();\n\n // Remove all expired items first\n for (const [key, entry] of Array.from(this.cache.entries())) {\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n }\n }\n\n // Evict oldest entries until within max size\n while (this.maxSize && this.cache.size > this.maxSize) {\n const oldestKey = this.cache.keys().next().value;\n this.cache.delete(oldestKey as K);\n }\n }\n}\n"]}
|
|
@@ -41,7 +41,7 @@ export declare function getFromContext<T>(key: symbol): T | undefined;
|
|
|
41
41
|
* app.use((req, res, next) => {
|
|
42
42
|
* const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
|
|
43
43
|
* ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
|
|
44
|
-
* ContextStore.set(StoreKeys.LOGGER, getLogger().child({
|
|
44
|
+
* ContextStore.set(StoreKeys.LOGGER, getLogger().child({ requestId }));
|
|
45
45
|
* next();
|
|
46
46
|
* });
|
|
47
47
|
* });
|
|
@@ -49,7 +49,7 @@ export function getFromContext(key) {
|
|
|
49
49
|
* app.use((req, res, next) => {
|
|
50
50
|
* const requestId = req.headers["x-request-id"]?.toString() || crypto.randomUUID();
|
|
51
51
|
* ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {
|
|
52
|
-
* ContextStore.set(StoreKeys.LOGGER, getLogger().child({
|
|
52
|
+
* ContextStore.set(StoreKeys.LOGGER, getLogger().child({ requestId }));
|
|
53
53
|
* next();
|
|
54
54
|
* });
|
|
55
55
|
* });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-store.utils.js","sourceRoot":"","sources":["../../../src/utils/context-store.utils.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAUhD;;;GAGG;AACH,MAAM,CAAC,IAAM,SAAS,GAAG;IACvB,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC;IAC/B,OAAO,EAAE,MAAM,CAAC,QAAQ,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC,UAAU,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC,SAAS,CAAC;IAC3B,cAAc,EAAE,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GAIG;AACH;IACE;;;;;OAKG;IACH,yBACU,MAAc,EACd,YAAgB;QADhB,WAAM,GAAN,MAAM,CAAQ;QACd,iBAAY,GAAZ,YAAY,CAAI;IACvB,CAAC;IAEJ;;;;OAIG;IACH,6BAAG,GAAH;QACE,IAAM,KAAK,GAAG,YAAY,CAAC,GAAG,CAAI,IAAI,CAAC,MAAM,CAAC,CAAC;QAC/C,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC;IACzD,CAAC;IAED;;;;OAIG;IACH,6BAAG,GAAH,UAAI,KAAQ;QACV,YAAY,CAAC,GAAG,CAAI,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC1C,CAAC;IAED;;;;OAIG;IACH,gCAAM,GAAN;QACE,OAAO,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACvC,CAAC;IAED;;;;OAIG;IACH,gCAAM,GAAN;QACE,OAAO,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1C,CAAC;IACH,sBAAC;AAAD,CAAC,AAhDD,IAgDC","sourcesContent":["import { AsyncLocalStorage } from 'async_hooks';\n\n/**\n * Type representing the store object used in AsyncLocalStorage.\n * Keys must be unique symbols to ensure isolation and prevent collisions.\n */\nexport interface Store {\n [key: symbol]: unknown;\n}\n\n/**\n * Predefined symbols used as keys in AsyncLocalStorage.\n * Add new symbols here to avoid duplication.\n */\nexport const StoreKeys = {\n LOGGER: Symbol('logger'),\n REQUEST_ID: Symbol('requestId'),\n USER_ID: Symbol('userId'),\n TENANT_ID: Symbol('tenantId'),\n TRACE_ID: Symbol('traceId'),\n CORRELATION_ID: Symbol('correlationId')\n};\n\n/**\n * Retrieves the current request ID from the async context, if available.\n *\n * @returns {string | undefined} The request ID string or undefined if not present in the current context.\n */\nexport function getRequestId(): string | undefined {\n return ContextStore.get<string>(StoreKeys.REQUEST_ID);\n}\n\n/**\n * Type-safe getter for common context values.\n *\n * @param key The store key symbol\n * @returns The typed value from the store\n */\nexport function getFromContext<T>(key: symbol): T | undefined {\n return ContextStore.get<T>(key);\n}\n\n/**\n * ContextStore manages per-request scoped context using AsyncLocalStorage.\n * It allows storing and retrieving data across async calls (e.g., request ID, logger).\n *\n * Example (Express middleware):\n * ```\n * // Middleware to initialize context and logger\n * app.use((req, res, next) => {\n * const requestId = req.headers[\"x-request-id\"]?.toString() || crypto.randomUUID();\n * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ reqId: requestId }));\n * next();\n * });\n * });\n * ```\n */\nexport class ContextStore {\n /**\n * The underlying AsyncLocalStorage instance for context.\n * @private\n */\n private static readonly storage = new AsyncLocalStorage<Store>();\n\n /**\n * Returns the raw AsyncLocalStorage instance for advanced access.\n *\n * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.\n */\n static getInstance(): AsyncLocalStorage<Store> {\n return this.storage;\n }\n\n /**\n * Retrieves a value from the async context store by symbol key.\n *\n * @typeParam T - The expected return type of the value.\n * @param {symbol} key - Unique symbol used as the store key.\n * @returns {T | undefined} The value found (typed) or undefined if not present.\n */\n static get<T>(key: symbol): T | undefined {\n const store = this.storage.getStore();\n return store?.[key] as T | undefined;\n }\n\n /**\n * Sets a value in the current context store by symbol key.\n *\n * @typeParam T - The value type to set.\n * @param {symbol} key - Unique symbol key.\n * @param {T} value - Value to set in context.\n * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).\n */\n static set<T>(key: symbol, value: T): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to set ${String(key)}: AsyncLocalStorage store is not initialized.`);\n }\n store[key] = value;\n }\n\n /**\n * Retrieves the entire context store object for the current async context.\n *\n * @returns {Store | undefined} The current store object or undefined if called outside a context.\n */\n static getAll(): Store | undefined {\n return this.storage.getStore();\n }\n\n /**\n * Initializes a new async context and executes a callback within it.\n * This must be called at the beginning of a request or logical async flow.\n *\n * @typeParam T - The callback's return type.\n * @param {Store} store - The initial key-value store object.\n * @param {() => T} callback - The function to run within the new context.\n * @returns {T} The result of the callback function.\n */\n static run<T>(store: Store, callback: () => T): T {\n return this.storage.run(store, callback);\n }\n\n /**\n * Checks if a key exists in the current context store.\n *\n * @param {symbol} key - The symbol key to check.\n * @returns {boolean} True if the key exists, false otherwise.\n */\n static has(key: symbol): boolean {\n const store = this.storage.getStore();\n return store !== undefined && key in store;\n }\n\n /**\n * Removes a value from the current context store by symbol key.\n *\n * @param {symbol} key - The symbol key to delete.\n * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.\n * @throws {Error} If called outside an active context.\n */\n static delete(key: symbol): boolean {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to delete ${String(key)}: AsyncLocalStorage store is not initialized.`);\n }\n return delete store[key];\n }\n\n /**\n * Updates multiple values in the current context store at once.\n *\n * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.\n * @throws {Error} If called outside an active context.\n */\n static patch(values: Partial<Record<symbol, unknown>>): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error('Failed to patch: AsyncLocalStorage store is not initialized.');\n }\n Object.getOwnPropertySymbols(values).forEach(key => {\n store[key] = values[key];\n });\n }\n /**\n * Executes a callback with a temporary store value that only exists during execution.\n * Original store is restored after callback completes.\n *\n * @typeParam T - The callback's return type.\n * @param {symbol} key - The symbol key to temporarily set.\n * @param {unknown} value - The temporary value.\n * @param {() => T} callback - The function to execute with the temporary value.\n * @returns {T} The result of the callback function.\n * @throws {Error} If called outside an active context.\n */\n static withValue<T>(key: symbol, value: unknown, callback: () => T): T {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to set temporary value: AsyncLocalStorage store is not initialized.`);\n }\n\n // Save original value\n const hasOriginal = key in store;\n const originalValue = store[key];\n\n // Set temporary value\n store[key] = value;\n\n try {\n // Run callback\n return callback();\n } finally {\n // Restore original value\n if (hasOriginal) {\n store[key] = originalValue;\n } else {\n delete store[key];\n }\n }\n }\n\n /**\n * Creates a new context that inherits values from the current context.\n *\n * @typeParam T - The callback's return type.\n * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.\n * @param {() => T} callback - The function to execute in the new context.\n * @returns {T} The result of the callback function.\n */\n static extend<T>(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T {\n const currentStore = this.storage.getStore() || {};\n\n // Create new store with current values plus new ones\n const newStore: Store = { ...currentStore };\n\n // Add new values\n Object.getOwnPropertySymbols(newValues).forEach(key => {\n newStore[key] = newValues[key];\n });\n\n // Run with extended store\n return this.storage.run(newStore, callback);\n }\n\n /**\n * Creates Express middleware that initializes a context for each request.\n *\n * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.\n * @returns Express middleware function.\n */\n static createExpressMiddleware(initialValuesFactory: (req: any) => Partial<Record<symbol, unknown>> = () => ({})) {\n return (req: any, res: any, next: any) => {\n const initialValues = initialValuesFactory(req);\n ContextStore.run(initialValues as Store, next);\n };\n }\n}\n\n/**\n * Type-safe wrapper for accessing and modifying context values with specific types.\n *\n * @typeParam T - The value type.\n */\nexport class TypedContextKey<T> {\n /**\n * Creates a new typed context key.\n *\n * @param symbol - The unique symbol for this key\n * @param defaultValue - Optional default value if key is not found\n */\n constructor(\n private symbol: symbol,\n private defaultValue?: T\n ) {}\n\n /**\n * Gets the current value for this key.\n *\n * @returns The value or defaultValue if not found\n */\n get(): T | undefined {\n const value = ContextStore.get<T>(this.symbol);\n return value !== undefined ? value : this.defaultValue;\n }\n\n /**\n * Sets the value for this key.\n *\n * @param value The value to set\n */\n set(value: T): void {\n ContextStore.set<T>(this.symbol, value);\n }\n\n /**\n * Checks if this key exists in the context.\n *\n * @returns True if the key exists\n */\n exists(): boolean {\n return ContextStore.has(this.symbol);\n }\n\n /**\n * Deletes this key from the context.\n *\n * @returns True if the key was deleted\n */\n delete(): boolean {\n return ContextStore.delete(this.symbol);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context-store.utils.js","sourceRoot":"","sources":["../../../src/utils/context-store.utils.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAUhD;;;GAGG;AACH,MAAM,CAAC,IAAM,SAAS,GAAG;IACvB,MAAM,EAAE,MAAM,CAAC,QAAQ,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC;IAC/B,OAAO,EAAE,MAAM,CAAC,QAAQ,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC,UAAU,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC,SAAS,CAAC;IAC3B,cAAc,EAAE,MAAM,CAAC,eAAe,CAAC;CACxC,CAAC;AAEF;;;;GAIG;AACH,MAAM,UAAU,YAAY;IAC1B,OAAO,YAAY,CAAC,GAAG,CAAS,SAAS,CAAC,UAAU,CAAC,CAAC;AACxD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAI,GAAW;IAC3C,OAAO,YAAY,CAAC,GAAG,CAAI,GAAG,CAAC,CAAC;AAClC,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH;IAAA;IAmLA,CAAC;IA5KC;;;;OAIG;IACI,wBAAW,GAAlB;QACE,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;IAED;;;;;;OAMG;IACI,gBAAG,GAAV,UAAc,GAAW;QACvB,IAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;QACtC,OAAO,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAG,GAAG,CAAkB,CAAC;IACvC,CAAC;IAED;;;;;;;OAOG;IACI,gBAAG,GAAV,UAAc,GAAW,EAAE,KAAQ;QACjC,IAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;QACtC,IAAI,CAAC,KAAK,EAA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ocalStorage } from 'async_hooks';\n\n/**\n * Type representing the store object used in AsyncLocalStorage.\n * Keys must be unique symbols to ensure isolation and prevent collisions.\n */\nexport interface Store {\n [key: symbol]: unknown;\n}\n\n/**\n * Predefined symbols used as keys in AsyncLocalStorage.\n * Add new symbols here to avoid duplication.\n */\nexport const StoreKeys = {\n LOGGER: Symbol('logger'),\n REQUEST_ID: Symbol('requestId'),\n USER_ID: Symbol('userId'),\n TENANT_ID: Symbol('tenantId'),\n TRACE_ID: Symbol('traceId'),\n CORRELATION_ID: Symbol('correlationId')\n};\n\n/**\n * Retrieves the current request ID from the async context, if available.\n *\n * @returns {string | undefined} The request ID string or undefined if not present in the current context.\n */\nexport function getRequestId(): string | undefined {\n return ContextStore.get<string>(StoreKeys.REQUEST_ID);\n}\n\n/**\n * Type-safe getter for common context values.\n *\n * @param key The store key symbol\n * @returns The typed value from the store\n */\nexport function getFromContext<T>(key: symbol): T | undefined {\n return ContextStore.get<T>(key);\n}\n\n/**\n * ContextStore manages per-request scoped context using AsyncLocalStorage.\n * It allows storing and retrieving data across async calls (e.g., request ID, logger).\n *\n * Example (Express middleware):\n * ```\n * // Middleware to initialize context and logger\n * app.use((req, res, next) => {\n * const requestId = req.headers[\"x-request-id\"]?.toString() || crypto.randomUUID();\n * ContextStore.run({ [StoreKeys.REQUEST_ID]: requestId }, () => {\n * ContextStore.set(StoreKeys.LOGGER, getLogger().child({ requestId }));\n * next();\n * });\n * });\n * ```\n */\nexport class ContextStore {\n /**\n * The underlying AsyncLocalStorage instance for context.\n * @private\n */\n private static readonly storage = new AsyncLocalStorage<Store>();\n\n /**\n * Returns the raw AsyncLocalStorage instance for advanced access.\n *\n * @returns {AsyncLocalStorage<Store>} The AsyncLocalStorage instance.\n */\n static getInstance(): AsyncLocalStorage<Store> {\n return this.storage;\n }\n\n /**\n * Retrieves a value from the async context store by symbol key.\n *\n * @typeParam T - The expected return type of the value.\n * @param {symbol} key - Unique symbol used as the store key.\n * @returns {T | undefined} The value found (typed) or undefined if not present.\n */\n static get<T>(key: symbol): T | undefined {\n const store = this.storage.getStore();\n return store?.[key] as T | undefined;\n }\n\n /**\n * Sets a value in the current context store by symbol key.\n *\n * @typeParam T - The value type to set.\n * @param {symbol} key - Unique symbol key.\n * @param {T} value - Value to set in context.\n * @throws {Error} If called outside an active context (not within a .run call or in the wrong async boundaries).\n */\n static set<T>(key: symbol, value: T): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to set ${String(key)}: AsyncLocalStorage store is not initialized.`);\n }\n store[key] = value;\n }\n\n /**\n * Retrieves the entire context store object for the current async context.\n *\n * @returns {Store | undefined} The current store object or undefined if called outside a context.\n */\n static getAll(): Store | undefined {\n return this.storage.getStore();\n }\n\n /**\n * Initializes a new async context and executes a callback within it.\n * This must be called at the beginning of a request or logical async flow.\n *\n * @typeParam T - The callback's return type.\n * @param {Store} store - The initial key-value store object.\n * @param {() => T} callback - The function to run within the new context.\n * @returns {T} The result of the callback function.\n */\n static run<T>(store: Store, callback: () => T): T {\n return this.storage.run(store, callback);\n }\n\n /**\n * Checks if a key exists in the current context store.\n *\n * @param {symbol} key - The symbol key to check.\n * @returns {boolean} True if the key exists, false otherwise.\n */\n static has(key: symbol): boolean {\n const store = this.storage.getStore();\n return store !== undefined && key in store;\n }\n\n /**\n * Removes a value from the current context store by symbol key.\n *\n * @param {symbol} key - The symbol key to delete.\n * @returns {boolean} True if the key was deleted, false if the key wasn't found or no active context.\n * @throws {Error} If called outside an active context.\n */\n static delete(key: symbol): boolean {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to delete ${String(key)}: AsyncLocalStorage store is not initialized.`);\n }\n return delete store[key];\n }\n\n /**\n * Updates multiple values in the current context store at once.\n *\n * @param {Partial<Record<symbol, unknown>>} values - Object containing symbol keys and values to update.\n * @throws {Error} If called outside an active context.\n */\n static patch(values: Partial<Record<symbol, unknown>>): void {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error('Failed to patch: AsyncLocalStorage store is not initialized.');\n }\n Object.getOwnPropertySymbols(values).forEach(key => {\n store[key] = values[key];\n });\n }\n /**\n * Executes a callback with a temporary store value that only exists during execution.\n * Original store is restored after callback completes.\n *\n * @typeParam T - The callback's return type.\n * @param {symbol} key - The symbol key to temporarily set.\n * @param {unknown} value - The temporary value.\n * @param {() => T} callback - The function to execute with the temporary value.\n * @returns {T} The result of the callback function.\n * @throws {Error} If called outside an active context.\n */\n static withValue<T>(key: symbol, value: unknown, callback: () => T): T {\n const store = this.storage.getStore();\n if (!store) {\n throw new Error(`Failed to set temporary value: AsyncLocalStorage store is not initialized.`);\n }\n\n // Save original value\n const hasOriginal = key in store;\n const originalValue = store[key];\n\n // Set temporary value\n store[key] = value;\n\n try {\n // Run callback\n return callback();\n } finally {\n // Restore original value\n if (hasOriginal) {\n store[key] = originalValue;\n } else {\n delete store[key];\n }\n }\n }\n\n /**\n * Creates a new context that inherits values from the current context.\n *\n * @typeParam T - The callback's return type.\n * @param {Partial<Record<symbol, unknown>>} newValues - New values to add to or override in the context.\n * @param {() => T} callback - The function to execute in the new context.\n * @returns {T} The result of the callback function.\n */\n static extend<T>(newValues: Partial<Record<symbol, unknown>>, callback: () => T): T {\n const currentStore = this.storage.getStore() || {};\n\n // Create new store with current values plus new ones\n const newStore: Store = { ...currentStore };\n\n // Add new values\n Object.getOwnPropertySymbols(newValues).forEach(key => {\n newStore[key] = newValues[key];\n });\n\n // Run with extended store\n return this.storage.run(newStore, callback);\n }\n\n /**\n * Creates Express middleware that initializes a context for each request.\n *\n * @param {(req: any) => Partial<Record<symbol, unknown>>} initialValuesFactory - Function that returns initial context values.\n * @returns Express middleware function.\n */\n static createExpressMiddleware(initialValuesFactory: (req: any) => Partial<Record<symbol, unknown>> = () => ({})) {\n return (req: any, res: any, next: any) => {\n const initialValues = initialValuesFactory(req);\n ContextStore.run(initialValues as Store, next);\n };\n }\n}\n\n/**\n * Type-safe wrapper for accessing and modifying context values with specific types.\n *\n * @typeParam T - The value type.\n */\nexport class TypedContextKey<T> {\n /**\n * Creates a new typed context key.\n *\n * @param symbol - The unique symbol for this key\n * @param defaultValue - Optional default value if key is not found\n */\n constructor(\n private symbol: symbol,\n private defaultValue?: T\n ) {}\n\n /**\n * Gets the current value for this key.\n *\n * @returns The value or defaultValue if not found\n */\n get(): T | undefined {\n const value = ContextStore.get<T>(this.symbol);\n return value !== undefined ? value : this.defaultValue;\n }\n\n /**\n * Sets the value for this key.\n *\n * @param value The value to set\n */\n set(value: T): void {\n ContextStore.set<T>(this.symbol, value);\n }\n\n /**\n * Checks if this key exists in the context.\n *\n * @returns True if the key exists\n */\n exists(): boolean {\n return ContextStore.has(this.symbol);\n }\n\n /**\n * Deletes this key from the context.\n *\n * @returns True if the key was deleted\n */\n delete(): boolean {\n return ContextStore.delete(this.symbol);\n }\n}\n"]}
|
|
@@ -61,8 +61,9 @@ var __read = (this && this.__read) || function (o, n) {
|
|
|
61
61
|
}
|
|
62
62
|
return ar;
|
|
63
63
|
};
|
|
64
|
-
import { createHmac, createHash,
|
|
64
|
+
import { createHmac, createHash, randomBytes, createCipheriv, createDecipheriv, scrypt, timingSafeEqual } from 'crypto';
|
|
65
65
|
import { promisify } from 'util';
|
|
66
|
+
import { uuid } from './id.utils';
|
|
66
67
|
/**
|
|
67
68
|
* Generates an HMAC digest using the specified algorithm and secret key.
|
|
68
69
|
*
|
|
@@ -135,7 +136,7 @@ export function md5(input) {
|
|
|
135
136
|
* @returns {string} Random string hashed with SHA-256 (hex encoding).
|
|
136
137
|
*/
|
|
137
138
|
export function randomString() {
|
|
138
|
-
return sha256(
|
|
139
|
+
return sha256(uuid());
|
|
139
140
|
}
|
|
140
141
|
/**
|
|
141
142
|
* Generates a secure random buffer of specified byte length.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crypto.utils.js","sourceRoot":"","sources":["../../../src/utils/crypto.utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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IAAI,OAAO,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;YAC/D,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n createHmac,\n createHash,\n BinaryToTextEncoding,\n randomUUID,\n randomBytes,\n createCipheriv,\n createDecipheriv,\n scrypt,\n timingSafeEqual,\n CipherGCMTypes\n} from 'crypto';\nimport { promisify } from 'util';\n\nexport type BufferEncoding =\n | 'ascii'\n | 'utf8'\n | 'utf-8'\n | 'utf16le'\n | 'utf-16le'\n | 'ucs2'\n | 'ucs-2'\n | 'base64'\n | 'base64url'\n | 'latin1'\n | 'binary'\n | 'hex';\n\n/**\n * Generates an HMAC digest using the specified algorithm and secret key.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key for HMAC.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} HMAC digest as a string.\n */\nexport function hmac(algorithm: string, input: string, secret: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return createHmac(algorithm, secret).update(input).digest(encoding);\n}\n\n/**\n * Generates a hash digest using the specified algorithm.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} Hash digest as a string.\n */\nexport function hash(algorithm: string, input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return createHash(algorithm).update(input).digest(encoding);\n}\n\n/**\n * Generates an HMAC-SHA256 digest.\n *\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key.\n * @returns {string} SHA-256 HMAC digest as a string.\n */\nexport function sha256Hmac(input: string, secret: string): string {\n return hmac('sha256', input, secret);\n}\n\n/**\n * Generates a SHA1 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-1 hash as a string.\n */\nexport function sha1(input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return hash('sha1', input, encoding);\n}\n\n/**\n * Generates a SHA256 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-256 hash as a string.\n */\nexport function sha256(input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return hash('sha256', input, encoding);\n}\n\n/**\n * Generates an MD5 hash digest.\n *\n * @param {string} input - The string to hash.\n * @returns {string} MD5 hash as a string.\n */\nexport function md5(input: string): string {\n return hash('md5', input);\n}\n\n/**\n * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.\n *\n * @returns {string} Random string hashed with SHA-256 (hex encoding).\n */\nexport function randomString(): string {\n return sha256(randomUUID());\n}\n\n/**\n * Generates a secure random buffer of specified byte length.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @returns {Buffer} Buffer containing random bytes.\n */\nexport function generateRandomBytes(byteLength: number = 32): Buffer {\n return randomBytes(byteLength);\n}\n\n/**\n * Generates a secure random string of specified byte length with specified encoding.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} Random string in specified encoding.\n */\nexport function generateRandomBytesAsString(byteLength: number = 32, encoding: BinaryToTextEncoding = 'hex'): string {\n return randomBytes(byteLength).toString(encoding);\n}\n\n/**\n * Generates a secure API key with a specified format.\n *\n * @param {string} [prefix=''] - Optional prefix for the key.\n * @param {number} [byteLength=24] - Number of random bytes to generate.\n * @returns {string} Formatted API key.\n */\nexport function generateApiKey(prefix: string = '', byteLength: number = 24): string {\n const randomString = generateRandomBytesAsString(byteLength, 'base64');\n const key = randomString\n .replace(/[+/=]/g, '') // Remove non-URL-safe characters\n .substring(0, 32); // Limit length\n\n return prefix ? `${prefix}_${key}` : key;\n}\n\n/**\n * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.\n *\n * @param {string | Buffer | Uint8Array} a - First value to compare\n * @param {string | Buffer | Uint8Array} b - Second value to compare\n * @returns {boolean} True if values are equal\n */\nexport function safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean {\n if (typeof a === 'string' && typeof b === 'string') {\n // Convert strings to buffers\n const bufA = Buffer.from(a);\n const bufB = Buffer.from(b);\n\n // Compare lengths first (not constant time, but prevents timing attack on contents)\n if (bufA.length !== bufB.length) return false;\n\n return timingSafeEqual(bufA, bufB);\n } else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {\n // Compare lengths first\n if (a.length !== b.length) return false;\n\n return timingSafeEqual(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));\n }\n\n throw new Error('Cannot compare: inputs must be strings, Buffers, or Uint8Arrays');\n}\n\n/**\n * Interface for encryption options\n */\nexport interface EncryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for plaintext if string (default: utf8) */\n inputEncoding?: BufferEncoding;\n /** Output encoding for ciphertext (default: hex) */\n outputEncoding?: BinaryToTextEncoding;\n}\n\n/**\n * Interface for decryption options\n */\nexport interface DecryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for ciphertext if string (default: hex) */\n inputEncoding?: BinaryToTextEncoding;\n /** Output encoding for plaintext (default: utf8) */\n outputEncoding?: BufferEncoding;\n}\n\n/**\n * Result of encryption operation including all data needed for decryption\n */\nexport interface EncryptionResult {\n /** Encrypted data (string or Buffer based on options) */\n ciphertext: string | Buffer;\n /** Initialization vector */\n iv: Buffer;\n /** Authentication tag (for GCM mode) */\n authTag?: Buffer;\n /** Algorithm used */\n algorithm: string;\n}\n\n// Promisified version of scrypt for key derivation\nconst scryptAsync = promisify<string | Buffer, string | Buffer, number, Buffer>(scrypt);\n\n/**\n * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).\n *\n * @param {string | Buffer} data - Data to encrypt\n * @param {string | Buffer} key - Encryption key or passphrase\n * @param {EncryptionOptions} [options] - Encryption options\n * @returns {Promise<EncryptionResult>} Encrypted data with metadata\n */\nexport async function encrypt(\n data: string | Buffer,\n key: string | Buffer,\n options: EncryptionOptions = {}\n): Promise<EncryptionResult> {\n const algorithm = options.algorithm || 'aes-256-gcm';\n const inputEncoding = options.inputEncoding || 'utf8';\n const outputEncoding = options.outputEncoding || 'hex';\n\n // Generate a random IV\n const iv = randomBytes(16);\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey = typeof key === 'string' ? await scryptAsync(key, iv.slice(0, 8), 32) : key;\n\n // Create cipher\n const cipher = createCipheriv(algorithm, derivedKey, iv);\n\n // Encrypt the data\n let ciphertext: string | Buffer;\n\n if (typeof data === 'string') {\n ciphertext = cipher.update(data, inputEncoding, outputEncoding as BufferEncoding);\n ciphertext += cipher.final(outputEncoding as BufferEncoding);\n } else {\n const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);\n ciphertext = outputEncoding ? encrypted.toString(outputEncoding) : encrypted;\n }\n\n // Get authentication tag if using GCM mode\n const authTag = algorithm.includes('gcm') ? (cipher as any).getAuthTag() : undefined;\n\n return {\n ciphertext,\n iv,\n authTag,\n algorithm\n };\n}\n\n/**\n * Decrypts data that was encrypted with the encrypt function.\n *\n * @param {EncryptionResult} encryptedData - The encrypted data and metadata\n * @param {string | Buffer} key - Decryption key or passphrase\n * @param {DecryptionOptions} [options] - Decryption options\n * @returns {Promise<string | Buffer>} Decrypted data\n */\nexport async function decrypt(\n encryptedData: EncryptionResult,\n key: string | Buffer,\n options: DecryptionOptions = {}\n): Promise<string | Buffer> {\n const algorithm = options.algorithm || encryptedData.algorithm || 'aes-256-gcm';\n const inputEncoding = options.inputEncoding || 'hex';\n const outputEncoding = options.outputEncoding || 'utf8';\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey = typeof key === 'string' ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;\n\n // Create decipher\n const decipher = createDecipheriv(algorithm, derivedKey, encryptedData.iv);\n\n // Set auth tag if using GCM mode\n if (encryptedData.authTag && algorithm.includes('gcm')) {\n (decipher as any).setAuthTag(encryptedData.authTag);\n }\n\n // Decrypt the data\n let decrypted: string | Buffer;\n\n if (typeof encryptedData.ciphertext === 'string') {\n decrypted = decipher.update(encryptedData.ciphertext, inputEncoding as BufferEncoding, outputEncoding);\n decrypted += decipher.final(outputEncoding);\n } else {\n const result = Buffer.concat([decipher.update(encryptedData.ciphertext), decipher.final()]);\n decrypted = outputEncoding ? result.toString(outputEncoding) : result;\n }\n\n return decrypted;\n}\n\n/**\n * Creates a signed token with an expiration time and payload.\n *\n * @param {object} payload - Data to include in the token\n * @param {string} secret - Secret key for signing\n * @param {number} [expiresInSeconds=3600] - Token expiration in seconds\n * @returns {string} Signed token string\n */\nexport function createSignedToken(\n payload: Record<string, any>,\n secret: string,\n expiresInSeconds: number = 3600\n): string {\n // Create payload with expiration\n const tokenPayload = {\n ...payload,\n exp: Math.floor(Date.now() / 1000) + expiresInSeconds\n };\n\n // Convert to string\n const payloadStr = JSON.stringify(tokenPayload);\n\n // Base64 encode the payload\n const base64Payload = Buffer.from(payloadStr).toString('base64url');\n\n // Create signature\n const signature = hmac('sha256', base64Payload, secret, 'base64url');\n\n // Combine payload and signature\n return `${base64Payload}.${signature}`;\n}\n\n/**\n * Verifies and decodes a signed token.\n *\n * @param {string} token - The token to verify\n * @param {string} secret - Secret key for verification\n * @returns {object | null} Decoded payload if valid, null if invalid\n */\nexport function verifySignedToken(token: string, secret: string): Record<string, any> | null {\n try {\n // Split token into parts\n const [payloadB64, signature] = token.split('.');\n\n if (!payloadB64 || !signature) return null;\n\n // Verify signature\n const expectedSignature = hmac('sha256', payloadB64, secret, 'base64url');\n if (!safeCompare(signature, expectedSignature)) return null;\n\n // Decode payload\n const payloadStr = Buffer.from(payloadB64, 'base64url').toString('utf8');\n const payload = JSON.parse(payloadStr);\n\n // Check expiration\n if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {\n return null;\n }\n\n return payload;\n } catch {\n return null;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"crypto.utils.js","sourceRoot":"","sources":["../../../src/utils/crypto.utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EACL,UAAU,EACV,UAAU,EAEV,WAAW,EACX,cAAc,EACd,gBAAgB,EAChB,MAAM,EACN,eAAe,EAEhB,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAgBlC;;;;;;;;GAQG;AACH,MAAM,UAAU,IAAI,CAAC,SAAiB,EAAE,KAAa,EAAE,MAAc,EAAE,QAAsC;IAAtC,yBAAA,EAAA,gBAAsC;IAC3G,OAAO,UAAU,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACtE,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,IAAI,CAAC,SAAiB,EAAE,KAAa,EAAE,QAAsC;IAAtC,yBAAA,EAAA,gBAAsC;IAC3F,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AAC9D,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CAAC,KAAa,EAAE,MAAc;IACtD,OAAO,IAAI,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,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I,CAAC;QAE3C,mBAAmB;QACnB,IAAM,iBAAiB,GAAG,IAAI,CAAC,QAAQ,EAAE,UAAU,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QAC1E,IAAI,CAAC,WAAW,CAAC,SAAS,EAAE,iBAAiB,CAAC;YAAE,OAAO,IAAI,CAAC;QAE5D,iBAAiB;QACjB,IAAM,UAAU,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QACzE,IAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAEvC,mBAAmB;QACnB,IAAI,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;YAC/D,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAAC,WAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n createHmac,\n createHash,\n BinaryToTextEncoding,\n randomBytes,\n createCipheriv,\n createDecipheriv,\n scrypt,\n timingSafeEqual,\n CipherGCMTypes\n} from 'crypto';\nimport { promisify } from 'util';\nimport { uuid } from './id.utils';\n\nexport type BufferEncoding =\n | 'ascii'\n | 'utf8'\n | 'utf-8'\n | 'utf16le'\n | 'utf-16le'\n | 'ucs2'\n | 'ucs-2'\n | 'base64'\n | 'base64url'\n | 'latin1'\n | 'binary'\n | 'hex';\n\n/**\n * Generates an HMAC digest using the specified algorithm and secret key.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'sha1').\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key for HMAC.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} HMAC digest as a string.\n */\nexport function hmac(algorithm: string, input: string, secret: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return createHmac(algorithm, secret).update(input).digest(encoding);\n}\n\n/**\n * Generates a hash digest using the specified algorithm.\n *\n * @param {string} algorithm - The hashing algorithm (e.g., 'sha256', 'md5').\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding ('hex', 'base64', etc).\n * @returns {string} Hash digest as a string.\n */\nexport function hash(algorithm: string, input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return createHash(algorithm).update(input).digest(encoding);\n}\n\n/**\n * Generates an HMAC-SHA256 digest.\n *\n * @param {string} input - The string to hash.\n * @param {string} secret - The secret key.\n * @returns {string} SHA-256 HMAC digest as a string.\n */\nexport function sha256Hmac(input: string, secret: string): string {\n return hmac('sha256', input, secret);\n}\n\n/**\n * Generates a SHA1 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-1 hash as a string.\n */\nexport function sha1(input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return hash('sha1', input, encoding);\n}\n\n/**\n * Generates a SHA256 hash digest.\n *\n * @param {string} input - The string to hash.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} SHA-256 hash as a string.\n */\nexport function sha256(input: string, encoding: BinaryToTextEncoding = 'hex'): string {\n return hash('sha256', input, encoding);\n}\n\n/**\n * Generates an MD5 hash digest.\n *\n * @param {string} input - The string to hash.\n * @returns {string} MD5 hash as a string.\n */\nexport function md5(input: string): string {\n return hash('md5', input);\n}\n\n/**\n * Generates a cryptographically strong random string by hashing a random UUID with SHA-256.\n *\n * @returns {string} Random string hashed with SHA-256 (hex encoding).\n */\nexport function randomString(): string {\n return sha256(uuid());\n}\n\n/**\n * Generates a secure random buffer of specified byte length.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @returns {Buffer} Buffer containing random bytes.\n */\nexport function generateRandomBytes(byteLength: number = 32): Buffer {\n return randomBytes(byteLength);\n}\n\n/**\n * Generates a secure random string of specified byte length with specified encoding.\n *\n * @param {number} [byteLength=32] - Number of random bytes to generate.\n * @param {BinaryToTextEncoding} [encoding='hex'] - Output encoding.\n * @returns {string} Random string in specified encoding.\n */\nexport function generateRandomBytesAsString(byteLength: number = 32, encoding: BinaryToTextEncoding = 'hex'): string {\n return randomBytes(byteLength).toString(encoding);\n}\n\n/**\n * Generates a secure API key with a specified format.\n *\n * @param {string} [prefix=''] - Optional prefix for the key.\n * @param {number} [byteLength=24] - Number of random bytes to generate.\n * @returns {string} Formatted API key.\n */\nexport function generateApiKey(prefix: string = '', byteLength: number = 24): string {\n const randomString = generateRandomBytesAsString(byteLength, 'base64');\n const key = randomString\n .replace(/[+/=]/g, '') // Remove non-URL-safe characters\n .substring(0, 32); // Limit length\n\n return prefix ? `${prefix}_${key}` : key;\n}\n\n/**\n * Compares two strings, arrays, or buffers in constant time to prevent timing attacks.\n *\n * @param {string | Buffer | Uint8Array} a - First value to compare\n * @param {string | Buffer | Uint8Array} b - Second value to compare\n * @returns {boolean} True if values are equal\n */\nexport function safeCompare(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean {\n if (typeof a === 'string' && typeof b === 'string') {\n // Convert strings to buffers\n const bufA = Buffer.from(a);\n const bufB = Buffer.from(b);\n\n // Compare lengths first (not constant time, but prevents timing attack on contents)\n if (bufA.length !== bufB.length) return false;\n\n return timingSafeEqual(bufA, bufB);\n } else if ((a instanceof Buffer || a instanceof Uint8Array) && (b instanceof Buffer || b instanceof Uint8Array)) {\n // Compare lengths first\n if (a.length !== b.length) return false;\n\n return timingSafeEqual(a instanceof Buffer ? a : Buffer.from(a), b instanceof Buffer ? b : Buffer.from(b));\n }\n\n throw new Error('Cannot compare: inputs must be strings, Buffers, or Uint8Arrays');\n}\n\n/**\n * Interface for encryption options\n */\nexport interface EncryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for plaintext if string (default: utf8) */\n inputEncoding?: BufferEncoding;\n /** Output encoding for ciphertext (default: hex) */\n outputEncoding?: BinaryToTextEncoding;\n}\n\n/**\n * Interface for decryption options\n */\nexport interface DecryptionOptions {\n /** Algorithm to use (default: aes-256-gcm) */\n algorithm?: CipherGCMTypes;\n /** Input encoding for ciphertext if string (default: hex) */\n inputEncoding?: BinaryToTextEncoding;\n /** Output encoding for plaintext (default: utf8) */\n outputEncoding?: BufferEncoding;\n}\n\n/**\n * Result of encryption operation including all data needed for decryption\n */\nexport interface EncryptionResult {\n /** Encrypted data (string or Buffer based on options) */\n ciphertext: string | Buffer;\n /** Initialization vector */\n iv: Buffer;\n /** Authentication tag (for GCM mode) */\n authTag?: Buffer;\n /** Algorithm used */\n algorithm: string;\n}\n\n// Promisified version of scrypt for key derivation\nconst scryptAsync = promisify<string | Buffer, string | Buffer, number, Buffer>(scrypt);\n\n/**\n * Encrypts data using a symmetric key with secure defaults (AES-256-GCM).\n *\n * @param {string | Buffer} data - Data to encrypt\n * @param {string | Buffer} key - Encryption key or passphrase\n * @param {EncryptionOptions} [options] - Encryption options\n * @returns {Promise<EncryptionResult>} Encrypted data with metadata\n */\nexport async function encrypt(\n data: string | Buffer,\n key: string | Buffer,\n options: EncryptionOptions = {}\n): Promise<EncryptionResult> {\n const algorithm = options.algorithm || 'aes-256-gcm';\n const inputEncoding = options.inputEncoding || 'utf8';\n const outputEncoding = options.outputEncoding || 'hex';\n\n // Generate a random IV\n const iv = randomBytes(16);\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey = typeof key === 'string' ? await scryptAsync(key, iv.slice(0, 8), 32) : key;\n\n // Create cipher\n const cipher = createCipheriv(algorithm, derivedKey, iv);\n\n // Encrypt the data\n let ciphertext: string | Buffer;\n\n if (typeof data === 'string') {\n ciphertext = cipher.update(data, inputEncoding, outputEncoding as BufferEncoding);\n ciphertext += cipher.final(outputEncoding as BufferEncoding);\n } else {\n const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);\n ciphertext = outputEncoding ? encrypted.toString(outputEncoding) : encrypted;\n }\n\n // Get authentication tag if using GCM mode\n const authTag = algorithm.includes('gcm') ? (cipher as any).getAuthTag() : undefined;\n\n return {\n ciphertext,\n iv,\n authTag,\n algorithm\n };\n}\n\n/**\n * Decrypts data that was encrypted with the encrypt function.\n *\n * @param {EncryptionResult} encryptedData - The encrypted data and metadata\n * @param {string | Buffer} key - Decryption key or passphrase\n * @param {DecryptionOptions} [options] - Decryption options\n * @returns {Promise<string | Buffer>} Decrypted data\n */\nexport async function decrypt(\n encryptedData: EncryptionResult,\n key: string | Buffer,\n options: DecryptionOptions = {}\n): Promise<string | Buffer> {\n const algorithm = options.algorithm || encryptedData.algorithm || 'aes-256-gcm';\n const inputEncoding = options.inputEncoding || 'hex';\n const outputEncoding = options.outputEncoding || 'utf8';\n\n // Derive key using scrypt if key is a string (passphrase)\n const derivedKey = typeof key === 'string' ? await scryptAsync(key, encryptedData.iv.slice(0, 8), 32) : key;\n\n // Create decipher\n const decipher = createDecipheriv(algorithm, derivedKey, encryptedData.iv);\n\n // Set auth tag if using GCM mode\n if (encryptedData.authTag && algorithm.includes('gcm')) {\n (decipher as any).setAuthTag(encryptedData.authTag);\n }\n\n // Decrypt the data\n let decrypted: string | Buffer;\n\n if (typeof encryptedData.ciphertext === 'string') {\n decrypted = decipher.update(encryptedData.ciphertext, inputEncoding as BufferEncoding, outputEncoding);\n decrypted += decipher.final(outputEncoding);\n } else {\n const result = Buffer.concat([decipher.update(encryptedData.ciphertext), decipher.final()]);\n decrypted = outputEncoding ? result.toString(outputEncoding) : result;\n }\n\n return decrypted;\n}\n\n/**\n * Creates a signed token with an expiration time and payload.\n *\n * @param {object} payload - Data to include in the token\n * @param {string} secret - Secret key for signing\n * @param {number} [expiresInSeconds=3600] - Token expiration in seconds\n * @returns {string} Signed token string\n */\nexport function createSignedToken(\n payload: Record<string, any>,\n secret: string,\n expiresInSeconds: number = 3600\n): string {\n // Create payload with expiration\n const tokenPayload = {\n ...payload,\n exp: Math.floor(Date.now() / 1000) + expiresInSeconds\n };\n\n // Convert to string\n const payloadStr = JSON.stringify(tokenPayload);\n\n // Base64 encode the payload\n const base64Payload = Buffer.from(payloadStr).toString('base64url');\n\n // Create signature\n const signature = hmac('sha256', base64Payload, secret, 'base64url');\n\n // Combine payload and signature\n return `${base64Payload}.${signature}`;\n}\n\n/**\n * Verifies and decodes a signed token.\n *\n * @param {string} token - The token to verify\n * @param {string} secret - Secret key for verification\n * @returns {object | null} Decoded payload if valid, null if invalid\n */\nexport function verifySignedToken(token: string, secret: string): Record<string, any> | null {\n try {\n // Split token into parts\n const [payloadB64, signature] = token.split('.');\n\n if (!payloadB64 || !signature) return null;\n\n // Verify signature\n const expectedSignature = hmac('sha256', payloadB64, secret, 'base64url');\n if (!safeCompare(signature, expectedSignature)) return null;\n\n // Decode payload\n const payloadStr = Buffer.from(payloadB64, 'base64url').toString('utf8');\n const payload = JSON.parse(payloadStr);\n\n // Check expiration\n if (payload.exp && payload.exp < Math.floor(Date.now() / 1000)) {\n return null;\n }\n\n return payload;\n } catch {\n return null;\n }\n}\n"]}
|