@catbee/utils 0.0.8-rc.1 → 0.0.8-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/{esnext → cjs}/config.d.ts +0 -1
- package/build/{src → cjs}/config.js +0 -1
- package/build/{esnext → cjs}/index.d.ts +0 -1
- package/build/{src → cjs}/index.js +0 -1
- package/build/{esnext → cjs}/servers/server.builder.d.ts +0 -1
- package/build/{src → cjs}/servers/server.builder.js +10 -13
- package/build/{src → cjs}/servers/server.d.ts +0 -1
- package/build/{src → cjs}/servers/server.js +83 -75
- package/build/{src → cjs}/types/api-response.d.ts +0 -1
- package/build/{src → cjs}/types/api-response.js +0 -1
- package/build/{src → cjs}/types/index.d.ts +0 -1
- package/build/{src → cjs}/types/index.js +0 -1
- package/build/{src → cjs}/types/server.d.ts +0 -1
- package/build/{src → cjs}/types/server.js +0 -1
- package/build/{src → cjs}/utils/array.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/array.utils.js +0 -1
- package/build/{src → cjs}/utils/async.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/async.utils.js +2 -3
- package/build/{esnext → cjs}/utils/cache.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/cache.utils.js +7 -6
- package/build/{esnext → cjs}/utils/context-store.utils.d.ts +1 -2
- package/build/{src → cjs}/utils/context-store.utils.js +10 -9
- package/build/{esnext → cjs}/utils/crypto.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/crypto.utils.js +5 -3
- package/build/{src → cjs}/utils/date.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/date.utils.js +1 -2
- package/build/{src → cjs}/utils/decorators.utils.d.ts +30 -27
- package/build/{src → cjs}/utils/decorators.utils.js +169 -30
- package/build/{esnext → cjs}/utils/dir.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/dir.utils.js +6 -7
- package/build/{esnext → cjs}/utils/env.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/env.utils.js +5 -8
- package/build/{src → cjs}/utils/exception.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/exception.utils.js +2 -1
- package/build/{src → cjs}/utils/fs.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/fs.utils.js +12 -13
- package/build/{esnext → cjs}/utils/http-status-codes.d.ts +0 -1
- package/build/{src → cjs}/utils/http-status-codes.js +0 -1
- package/build/{esnext → cjs}/utils/id.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/id.utils.js +0 -1
- package/build/{src → cjs}/utils/logger.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/logger.utils.js +10 -6
- package/build/{esnext → cjs}/utils/middleware.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/middleware.utils.js +16 -17
- package/build/{esnext → cjs}/utils/obj.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/obj.utils.js +1 -2
- package/build/{src → cjs}/utils/performance.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/performance.utils.js +6 -4
- package/build/{esnext → cjs}/utils/request.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/request.utils.js +7 -3
- package/build/{esnext → cjs}/utils/response.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/response.utils.js +42 -28
- package/build/{esnext → cjs}/utils/stream.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/stream.utils.js +0 -1
- package/build/{esnext → cjs}/utils/string.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/string.utils.js +0 -1
- package/build/{src → cjs}/utils/type.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/type.utils.js +2 -3
- package/build/{src → cjs}/utils/url.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/url.utils.js +8 -9
- package/build/{src → cjs}/utils/validate.utils.d.ts +0 -1
- package/build/{src → cjs}/utils/validate.utils.js +2 -3
- package/build/esm/config.d.ts +0 -1
- package/build/esm/config.js +6 -7
- package/build/esm/index.d.ts +0 -1
- package/build/esm/index.js +0 -1
- package/build/esm/servers/server.builder.d.ts +0 -1
- package/build/esm/servers/server.builder.js +99 -147
- package/build/esm/servers/server.d.ts +0 -1
- package/build/esm/servers/server.js +591 -876
- package/build/esm/types/api-response.d.ts +0 -1
- package/build/esm/types/api-response.js +0 -1
- package/build/esm/types/index.d.ts +0 -1
- package/build/esm/types/index.js +0 -1
- package/build/esm/types/server.d.ts +0 -1
- package/build/esm/types/server.js +0 -1
- package/build/esm/utils/array.utils.d.ts +0 -1
- package/build/esm/utils/array.utils.js +48 -86
- package/build/esm/utils/async.utils.d.ts +0 -1
- package/build/esm/utils/async.utils.js +247 -524
- package/build/esm/utils/cache.utils.d.ts +0 -1
- package/build/esm/utils/cache.utils.js +96 -301
- package/build/esm/utils/context-store.utils.d.ts +1 -2
- package/build/esm/utils/context-store.utils.js +62 -79
- package/build/esm/utils/crypto.utils.d.ts +0 -1
- package/build/esm/utils/crypto.utils.js +78 -175
- package/build/esm/utils/date.utils.d.ts +0 -1
- package/build/esm/utils/date.utils.js +47 -53
- package/build/esm/utils/decorators.utils.d.ts +30 -27
- package/build/esm/utils/decorators.utils.js +417 -461
- package/build/esm/utils/dir.utils.d.ts +0 -1
- package/build/esm/utils/dir.utils.js +264 -786
- package/build/esm/utils/env.utils.d.ts +0 -1
- package/build/esm/utils/env.utils.js +180 -271
- package/build/esm/utils/exception.utils.d.ts +0 -1
- package/build/esm/utils/exception.utils.js +112 -289
- package/build/esm/utils/fs.utils.d.ts +0 -1
- package/build/esm/utils/fs.utils.js +169 -401
- package/build/esm/utils/http-status-codes.d.ts +0 -1
- package/build/esm/utils/http-status-codes.js +0 -1
- package/build/esm/utils/id.utils.d.ts +0 -1
- package/build/esm/utils/id.utils.js +5 -9
- package/build/esm/utils/logger.utils.d.ts +0 -1
- package/build/esm/utils/logger.utils.js +34 -71
- package/build/esm/utils/middleware.utils.d.ts +0 -1
- package/build/esm/utils/middleware.utils.js +65 -155
- package/build/esm/utils/obj.utils.d.ts +0 -1
- package/build/esm/utils/obj.utils.js +69 -176
- package/build/esm/utils/performance.utils.d.ts +0 -1
- package/build/esm/utils/performance.utils.js +92 -195
- package/build/esm/utils/request.utils.d.ts +0 -1
- package/build/esm/utils/request.utils.js +41 -74
- package/build/esm/utils/response.utils.d.ts +0 -1
- package/build/esm/utils/response.utils.js +84 -107
- package/build/esm/utils/stream.utils.d.ts +0 -1
- package/build/esm/utils/stream.utils.js +38 -113
- package/build/esm/utils/string.utils.d.ts +0 -1
- package/build/esm/utils/string.utils.js +6 -11
- package/build/esm/utils/type.utils.d.ts +0 -1
- package/build/esm/utils/type.utils.js +8 -12
- package/build/esm/utils/url.utils.d.ts +0 -1
- package/build/esm/utils/url.utils.js +49 -127
- package/build/esm/utils/validate.utils.d.ts +0 -1
- package/build/esm/utils/validate.utils.js +23 -40
- package/package.json +288 -63
- package/build/esm/config.js.map +0 -1
- package/build/esm/index.js.map +0 -1
- package/build/esm/servers/server.builder.js.map +0 -1
- package/build/esm/servers/server.js.map +0 -1
- package/build/esm/types/api-response.js.map +0 -1
- package/build/esm/types/index.js.map +0 -1
- package/build/esm/types/server.js.map +0 -1
- package/build/esm/utils/array.utils.js.map +0 -1
- package/build/esm/utils/async.utils.js.map +0 -1
- package/build/esm/utils/cache.utils.js.map +0 -1
- package/build/esm/utils/context-store.utils.js.map +0 -1
- package/build/esm/utils/crypto.utils.js.map +0 -1
- package/build/esm/utils/date.utils.js.map +0 -1
- package/build/esm/utils/decorators.utils.js.map +0 -1
- package/build/esm/utils/dir.utils.js.map +0 -1
- package/build/esm/utils/env.utils.js.map +0 -1
- package/build/esm/utils/exception.utils.js.map +0 -1
- package/build/esm/utils/fs.utils.js.map +0 -1
- package/build/esm/utils/http-status-codes.js.map +0 -1
- package/build/esm/utils/id.utils.js.map +0 -1
- package/build/esm/utils/logger.utils.js.map +0 -1
- package/build/esm/utils/middleware.utils.js.map +0 -1
- package/build/esm/utils/obj.utils.js.map +0 -1
- package/build/esm/utils/performance.utils.js.map +0 -1
- package/build/esm/utils/request.utils.js.map +0 -1
- package/build/esm/utils/response.utils.js.map +0 -1
- package/build/esm/utils/stream.utils.js.map +0 -1
- package/build/esm/utils/string.utils.js.map +0 -1
- package/build/esm/utils/type.utils.js.map +0 -1
- package/build/esm/utils/url.utils.js.map +0 -1
- package/build/esm/utils/validate.utils.js.map +0 -1
- package/build/esnext/config.js +0 -133
- package/build/esnext/config.js.map +0 -1
- package/build/esnext/index.js +0 -50
- package/build/esnext/index.js.map +0 -1
- package/build/esnext/servers/server.builder.js +0 -657
- package/build/esnext/servers/server.builder.js.map +0 -1
- package/build/esnext/servers/server.d.ts +0 -256
- package/build/esnext/servers/server.js +0 -955
- package/build/esnext/servers/server.js.map +0 -1
- package/build/esnext/types/api-response.d.ts +0 -152
- package/build/esnext/types/api-response.js +0 -34
- package/build/esnext/types/api-response.js.map +0 -1
- package/build/esnext/types/index.d.ts +0 -125
- package/build/esnext/types/index.js +0 -25
- package/build/esnext/types/index.js.map +0 -1
- package/build/esnext/types/server.d.ts +0 -268
- package/build/esnext/types/server.js +0 -25
- package/build/esnext/types/server.js.map +0 -1
- package/build/esnext/utils/array.utils.d.ts +0 -168
- package/build/esnext/utils/array.utils.js +0 -345
- package/build/esnext/utils/array.utils.js.map +0 -1
- package/build/esnext/utils/async.utils.d.ts +0 -265
- package/build/esnext/utils/async.utils.js +0 -620
- package/build/esnext/utils/async.utils.js.map +0 -1
- package/build/esnext/utils/cache.utils.js +0 -293
- package/build/esnext/utils/cache.utils.js.map +0 -1
- package/build/esnext/utils/context-store.utils.js +0 -289
- package/build/esnext/utils/context-store.utils.js.map +0 -1
- package/build/esnext/utils/crypto.utils.js +0 -276
- package/build/esnext/utils/crypto.utils.js.map +0 -1
- package/build/esnext/utils/date.utils.d.ts +0 -159
- package/build/esnext/utils/date.utils.js +0 -384
- package/build/esnext/utils/date.utils.js.map +0 -1
- package/build/esnext/utils/decorators.utils.d.ts +0 -508
- package/build/esnext/utils/decorators.utils.js +0 -877
- package/build/esnext/utils/decorators.utils.js.map +0 -1
- package/build/esnext/utils/dir.utils.js +0 -477
- package/build/esnext/utils/dir.utils.js.map +0 -1
- package/build/esnext/utils/env.utils.js +0 -785
- package/build/esnext/utils/env.utils.js.map +0 -1
- package/build/esnext/utils/exception.utils.d.ts +0 -230
- package/build/esnext/utils/exception.utils.js +0 -381
- package/build/esnext/utils/exception.utils.js.map +0 -1
- package/build/esnext/utils/fs.utils.d.ts +0 -164
- package/build/esnext/utils/fs.utils.js +0 -349
- package/build/esnext/utils/fs.utils.js.map +0 -1
- package/build/esnext/utils/http-status-codes.js +0 -295
- package/build/esnext/utils/http-status-codes.js.map +0 -1
- package/build/esnext/utils/id.utils.js +0 -84
- package/build/esnext/utils/id.utils.js.map +0 -1
- package/build/esnext/utils/logger.utils.d.ts +0 -160
- package/build/esnext/utils/logger.utils.js +0 -300
- package/build/esnext/utils/logger.utils.js.map +0 -1
- package/build/esnext/utils/middleware.utils.js +0 -236
- package/build/esnext/utils/middleware.utils.js.map +0 -1
- package/build/esnext/utils/obj.utils.js +0 -413
- package/build/esnext/utils/obj.utils.js.map +0 -1
- package/build/esnext/utils/performance.utils.d.ts +0 -136
- package/build/esnext/utils/performance.utils.js +0 -271
- package/build/esnext/utils/performance.utils.js.map +0 -1
- package/build/esnext/utils/request.utils.js +0 -186
- package/build/esnext/utils/request.utils.js.map +0 -1
- package/build/esnext/utils/response.utils.js +0 -247
- package/build/esnext/utils/response.utils.js.map +0 -1
- package/build/esnext/utils/stream.utils.js +0 -210
- package/build/esnext/utils/stream.utils.js.map +0 -1
- package/build/esnext/utils/string.utils.js +0 -165
- package/build/esnext/utils/string.utils.js.map +0 -1
- package/build/esnext/utils/type.utils.d.ts +0 -90
- package/build/esnext/utils/type.utils.js +0 -187
- package/build/esnext/utils/type.utils.js.map +0 -1
- package/build/esnext/utils/url.utils.d.ts +0 -141
- package/build/esnext/utils/url.utils.js +0 -304
- package/build/esnext/utils/url.utils.js.map +0 -1
- package/build/esnext/utils/validate.utils.d.ts +0 -177
- package/build/esnext/utils/validate.utils.js +0 -320
- package/build/esnext/utils/validate.utils.js.map +0 -1
- package/build/src/config.d.ts +0 -122
- package/build/src/config.js.map +0 -1
- package/build/src/index.d.ts +0 -27
- package/build/src/index.js.map +0 -1
- package/build/src/servers/server.builder.d.ts +0 -508
- package/build/src/servers/server.builder.js.map +0 -1
- package/build/src/servers/server.js.map +0 -1
- package/build/src/types/api-response.js.map +0 -1
- package/build/src/types/index.js.map +0 -1
- package/build/src/types/server.js.map +0 -1
- package/build/src/utils/array.utils.js.map +0 -1
- package/build/src/utils/async.utils.js.map +0 -1
- package/build/src/utils/cache.utils.d.ts +0 -153
- package/build/src/utils/cache.utils.js.map +0 -1
- package/build/src/utils/context-store.utils.d.ts +0 -189
- package/build/src/utils/context-store.utils.js.map +0 -1
- package/build/src/utils/crypto.utils.d.ts +0 -160
- package/build/src/utils/crypto.utils.js.map +0 -1
- package/build/src/utils/date.utils.js.map +0 -1
- package/build/src/utils/decorators.utils.js.map +0 -1
- package/build/src/utils/dir.utils.d.ts +0 -196
- package/build/src/utils/dir.utils.js.map +0 -1
- package/build/src/utils/env.utils.d.ts +0 -377
- package/build/src/utils/env.utils.js.map +0 -1
- package/build/src/utils/exception.utils.js.map +0 -1
- package/build/src/utils/fs.utils.js.map +0 -1
- package/build/src/utils/http-status-codes.d.ts +0 -266
- package/build/src/utils/http-status-codes.js.map +0 -1
- package/build/src/utils/id.utils.d.ts +0 -36
- package/build/src/utils/id.utils.js.map +0 -1
- package/build/src/utils/logger.utils.js.map +0 -1
- package/build/src/utils/middleware.utils.d.ts +0 -100
- package/build/src/utils/middleware.utils.js.map +0 -1
- package/build/src/utils/obj.utils.d.ts +0 -124
- package/build/src/utils/obj.utils.js.map +0 -1
- package/build/src/utils/performance.utils.js.map +0 -1
- package/build/src/utils/request.utils.d.ts +0 -86
- package/build/src/utils/request.utils.js.map +0 -1
- package/build/src/utils/response.utils.d.ts +0 -163
- package/build/src/utils/response.utils.js.map +0 -1
- package/build/src/utils/stream.utils.d.ts +0 -88
- package/build/src/utils/stream.utils.js.map +0 -1
- package/build/src/utils/string.utils.d.ts +0 -93
- package/build/src/utils/string.utils.js.map +0 -1
- package/build/src/utils/type.utils.js.map +0 -1
- package/build/src/utils/url.utils.js.map +0 -1
- package/build/src/utils/validate.utils.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"obj.utils.js","sourceRoot":"","sources":["../../../src/utils/obj.utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;AAQH,gCAEC;AAWD,oBAEC;AAWD,oBAEC;AAUD,oCAkKC;AAQD,sCAKC;AAUD,sCAYC;AAUD,wCAUC;AAYD,wCAgCC;AASD,0BA4CC;AAUD,oCAKC;AAWD,8BAQC;AAUD,gCAaC;AAQD,4BAEC;AASD,kCAYC;AA9bD;;;;;GAKG;AACH,SAAgB,UAAU,CAAC,GAAqB;IAC9C,OAAO,CAAC,CAAC,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC;AAC3E,CAAC;AAED;;;;;;;;GAQG;AACH,SAAgB,IAAI,CAAsC,GAAM,EAAE,IAAS;IACzE,OAAO,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAe,CAAC;AAC5E,CAAC;AAED;;;;;;;;GAQG;AACH,SAAgB,IAAI,CAAsC,GAAM,EAAE,IAAS;IACzE,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAQ,CAAC,CAAC,CAAe,CAAC;AAC3G,CAAC;AAED;;;;;;;GAOG;AACH,SAAgB,Y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G,CAAC;AACb,CAAC;AAED;;;;;GAKG;AACH,SAAgB,QAAQ,CAAC,KAAc;IACrC,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,WAAW,CAAC,GAAwB,EAAE,aAAqB,EAAE;IAC3E,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,EAAE,CAAC;IAE9B,OAAO,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;QAClD,MAAM,WAAW,GAAG,UAAU,CAAC,CAAC,CAAC,GAAG,UAAU,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC;QAE9D,IAAI,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YACpB,OAAO,CAAC,WAAW,EAAE,GAAG,WAAW,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC;QAC3D,CAAC;QAED,OAAO,CAAC,WAAW,CAAC,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * Checks whether the object has no own enumerable properties.\n *\n * @param {Record<any, any>} obj - The object to check.\n * @returns {boolean} True if the object is empty, false otherwise.\n */\nexport function isObjEmpty(obj: Record<any, any>): boolean {\n return !!obj && typeof obj === 'object' && Object.keys(obj).length === 0;\n}\n\n/**\n * Returns a new object with only the specified keys picked.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to pick from the object.\n * @returns {Pick<T, K>} New object with picked keys.\n */\nexport function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {\n return Object.fromEntries(keys.map(key => [key, obj[key]])) as Pick<T, K>;\n}\n\n/**\n * Returns a new object with the specified keys omitted.\n *\n * @template T\n * @template K\n * @param {T} obj - The source object.\n * @param {K[]} keys - Keys to omit from the object.\n * @returns {Omit<T, K>} New object without omitted keys.\n */\nexport function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> {\n return Object.fromEntries(Object.entries(obj).filter(([key]) => !keys.includes(key as K))) as Omit<T, K>;\n}\n\n/**\n * Deeply merges multiple objects into the target object (mutates and returns the target object, not pure).\n *\n * @template T\n * @param {T} target - The object to merge into (will be mutated).\n * @param {...any[]} sources - The objects to merge from.\n * @returns {T} The merged object (same as target).\n */\nexport function deepObjMerge<T extends object>(target: T, ...sources: any[]): T {\n if (!sources.length) return target;\n\n const seen = new WeakMap();\n seen.set(target, target);\n\n for (const s of sources) {\n if (s && typeof s === 'object') {\n seen.set(s, target);\n }\n }\n\n function deepClone(value: any): any {\n if (value === null || typeof value !== 'object') return value;\n\n if (seen.has(value)) return seen.get(value);\n\n // Date\n if (value instanceof Date) {\n return new Date(value.getTime());\n }\n\n // Array\n if (Array.isArray(value)) {\n const clone: any[] = [];\n seen.set(value, clone);\n value.forEach((item, i) => (clone[i] = deepClone(item)));\n return clone;\n }\n\n // Set\n if (value instanceof Set) {\n const clone = new Set();\n seen.set(value, clone);\n value.forEach(item => clone.add(deepClone(item)));\n return clone;\n }\n\n // Map\n if (value instanceof Map) {\n const clone = new Map();\n seen.set(value, clone);\n value.forEach((val, key) => clone.set(key, deepClone(val)));\n return clone;\n }\n\n // RegExp\n if (value instanceof RegExp) {\n return new RegExp(value.source, value.flags);\n }\n\n // ArrayBuffer\n if (value instanceof ArrayBuffer) {\n return value.slice(0);\n }\n\n // TypedArrays\n if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {\n const typed = value as any; // cast for TS\n const ctor = typed.constructor;\n // List of standard TypedArray constructors\n const typedArrayCtors = [\n Int8Array,\n Uint8Array,\n Uint8ClampedArray,\n Int16Array,\n Uint16Array,\n Int32Array,\n Uint32Array,\n Float32Array,\n Float64Array,\n BigInt64Array,\n BigUint64Array\n ].filter(Boolean); // filter out undefined (for environments without BigInt)\n const typedArrayCtorSet = new Set(typedArrayCtors);\n if (typeof ctor === 'function' && typedArrayCtorSet.has(ctor)) {\n // Defensive: ensure buffer is an ArrayBuffer and slice is available\n const buffer = typed.buffer && typeof typed.buffer.slice === 'function' ? typed.buffer.slice(0) : typed.buffer;\n const clone = new ctor(buffer, typed.byteOffset, typed.length);\n seen.set(value, clone);\n return clone;\n } else if (typeof typed.slice === 'function') {\n // Fallback: try using slice if available (e.g., Node.js Buffer)\n const clone = typed.slice();\n seen.set(value, clone);\n return clone;\n } else {\n // Could not safely clone, throw an error for better debugging\n throw new Error(\n 'Cannot deep clone unknown TypedArray type: ' + (typed && typed.constructor && typed.constructor.name)\n );\n }\n }\n\n const clone = Object.create(Object.getPrototypeOf(value));\n seen.set(value, clone);\n\n Reflect.ownKeys(value).forEach(key => {\n const descriptor = Object.getOwnPropertyDescriptor(value, key)!;\n if (descriptor.get || descriptor.set) {\n Object.defineProperty(clone, key, descriptor);\n } else {\n (clone as any)[key] = deepClone((value as any)[key]);\n }\n });\n\n return clone;\n }\n\n function mergeProp(target: any, source: any, key: string | symbol): void {\n const targetValue = target[key];\n const sourceValue = source[key];\n\n // Ignore undefined in source\n if (sourceValue === undefined) return;\n\n // Primitives → overwrite directly\n if (sourceValue === null || typeof sourceValue !== 'object') {\n target[key] = sourceValue;\n return;\n }\n\n // Arrays → replace (lodash behavior)\n if (Array.isArray(sourceValue)) {\n target[key] = deepClone(sourceValue);\n return;\n }\n\n // Special cloneable objects\n if (\n sourceValue instanceof Date ||\n sourceValue instanceof RegExp ||\n sourceValue instanceof Set ||\n sourceValue instanceof Map ||\n sourceValue instanceof ArrayBuffer ||\n (ArrayBuffer.isView(sourceValue) && !(sourceValue instanceof DataView))\n ) {\n target[key] = deepClone(sourceValue);\n return;\n }\n\n // Plain objects → recursive merge\n if (isPlainObject(sourceValue) && isPlainObject(targetValue)) {\n for (const k of Reflect.ownKeys(sourceValue)) {\n mergeProp(targetValue, sourceValue, k);\n }\n return;\n }\n\n // Default → overwrite with clone\n target[key] = deepClone(sourceValue);\n }\n\n for (const source of sources) {\n if (source == null) continue;\n\n for (const key of Reflect.ownKeys(source)) {\n mergeProp(target, source, key);\n }\n }\n\n return target;\n}\n\n/**\n * Checks if a value is a plain object (i.e., not an array, null, or a built-in object).\n *\n * @param value - The value to check.\n * @returns True if the value is a plain object, false otherwise.\n */\nexport function isPlainObject(value: any): value is Record<string, any> {\n if (typeof value !== 'object' || value === null) return false;\n if (Array.isArray(value)) return false;\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Flattens a nested object using dot notation for keys (e.g., `{a: {b: 1}}` → `{ \"a.b\": 1 }`).\n *\n * @template T\n * @param {T} obj - The object to flatten.\n * @param {string} [prefix=\"\"] - Optional prefix for nested keys (used internally).\n * @returns {Record<string, any>} A new object with flattened keys.\n */\nexport function flattenObject<T extends Record<string, any>>(obj: T, prefix = ''): Record<string, any> {\n return Object.entries(obj).reduce((acc: Record<string, any>, [key, value]) => {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n Object.assign(acc, flattenObject(value, newKey));\n } else {\n acc[newKey] = value;\n }\n\n return acc;\n }, {});\n}\n\n/**\n * Safely gets the value of a deeply nested key in an object using dot/bracket notation path.\n *\n * @template T\n * @param {T} obj - The object to extract from.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @returns {any} The value at the given path, or undefined if not found.\n */\nexport function getValueByPath<T extends object>(obj: T, path: string) {\n if (!obj || typeof obj !== 'object') return undefined;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, '.$1') // convert [0] to .0\n .split('.')\n .filter(Boolean); // remove empty strings\n\n return parts.reduce((acc: any, key: string) => acc?.[key], obj);\n}\n\n/**\n * Sets a value at a deeply nested key in an object using dot/bracket notation path.\n * Creates intermediate objects and arrays as needed.\n *\n * @template T\n * @param {T} obj - The object to modify.\n * @param {string} path - String path using dot and/or bracket notation (e.g., 'user.friends[0].name').\n * @param {any} value - The value to set at the path.\n * @returns {T} The modified object.\n */\nexport function setValueByPath<T extends object>(obj: T, path: string, value: any): T {\n if (!obj || typeof obj !== 'object') return obj;\n\n // Convert path like \"a.b[0].c\" into [\"a\", \"b\", \"0\", \"c\"]\n const parts = path\n .replace(/\\[(\\d+)\\]/g, '.$1') // convert [0] to .0\n .split('.')\n .filter(Boolean); // remove empty strings\n\n // Handle empty path\n if (parts.length === 0) return obj;\n\n let current: any = obj;\n\n // Navigate to the parent of the target property\n for (let i = 0; i < parts.length - 1; i++) {\n const key = parts[i];\n const isArrayIndex = !isNaN(Number(parts[i + 1]));\n\n if (current[key] === undefined) {\n // Create intermediate object or array based on next key type\n current[key] = isArrayIndex ? [] : {};\n }\n\n current = current[key];\n }\n\n // Set the value at the final key\n const finalKey = parts[parts.length - 1];\n current[finalKey] = value;\n\n return obj;\n}\n\n/**\n * Performs a deep equality check between two objects.\n *\n * @param {any} a - First value to compare.\n * @param {any} b - Second value to compare.\n * @returns {boolean} True if values are deeply equal.\n */\nexport function isEqual(a: any, b: any): boolean {\n // Check if primitives or references to the same object\n if (a === b) return true;\n\n // Check if either is null/undefined or not an object\n if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') {\n return false;\n }\n\n // Handle Date objects\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n // If one is Date but the other isn't\n if (a instanceof Date || b instanceof Date) {\n return false;\n }\n\n // Handle arrays\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n\n // Check each element\n for (let i = 0; i < a.length; i++) {\n if (!isEqual(a[i], b[i])) return false;\n }\n\n return true;\n }\n\n // If one is Array but the other isn't\n if (Array.isArray(a) || Array.isArray(b)) {\n return false;\n }\n\n // Compare object keys\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n // Check if every key in A exists in B and has the same value\n return keysA.every(key => Object.prototype.hasOwnProperty.call(b, key) && isEqual(a[key], b[key]));\n}\n\n/**\n * Filters object properties based on a predicate function.\n *\n * @template T\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => boolean} predicate - Filter function.\n * @returns {Partial<T>} New object with filtered properties.\n */\nexport function filterObject<T extends object>(\n obj: T,\n predicate: (value: any, key: string, obj: T) => boolean\n): Partial<T> {\n return Object.fromEntries(Object.entries(obj).filter(([key, value]) => predicate(value, key, obj))) as Partial<T>;\n}\n\n/**\n * Maps object values to new values using a mapping function.\n *\n * @template T\n * @template U\n * @param {T} obj - The source object.\n * @param {(value: any, key: string, obj: T) => U} mapFn - Mapping function.\n * @returns {Record<keyof T, U>} New object with mapped values.\n */\nexport function mapObject<T extends object, U>(\n obj: T,\n mapFn: (value: any, key: string, obj: T) => U\n): Record<keyof T, U> {\n return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, mapFn(value, key, obj)])) as Record<\n keyof T,\n U\n >;\n}\n\n/**\n * Recursively freezes an object and all its properties.\n * Makes an object immutable.\n *\n * @template T\n * @param {T} obj - The object to freeze.\n * @returns {Readonly<T>} The frozen object.\n */\nexport function deepFreeze<T extends object>(obj: T): Readonly<T> {\n // Freeze primitive properties\n Object.freeze(obj);\n\n // Recursively freeze nested objects\n for (const prop of Object.getOwnPropertyNames(obj)) {\n const value = (obj as any)[prop];\n if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {\n deepFreeze(value);\n }\n }\n\n return obj;\n}\n\n/**\n * Safely checks if a value is an object (not null, not array).\n *\n * @param {unknown} value - Value to check.\n * @returns {boolean} True if value is a non-null, non-array object.\n */\nexport function isObject(value: unknown): value is Record<string, any> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Gets all paths in an object using dot notation.\n *\n * @param {Record<string, any>} obj - Object to analyze.\n * @param {string} [parentPath=\"\"] - Internal param for recursion.\n * @returns {string[]} Array of all paths in dot notation.\n */\nexport function getAllPaths(obj: Record<string, any>, parentPath: string = ''): string[] {\n if (!isObject(obj)) return [];\n\n return Object.entries(obj).flatMap(([key, value]) => {\n const currentPath = parentPath ? `${parentPath}.${key}` : key;\n\n if (isObject(value)) {\n return [currentPath, ...getAllPaths(value, currentPath)];\n }\n\n return [currentPath];\n });\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"performance.utils.js","sourceRoot":"","sources":["../../../src/utils/performance.utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;AAkDH,4BA6CC;AAoBD,8BAgDC;AAkBD,sBAsCC;AAqBD,0BAoCC;AASD,4CAgDC;AA3UD,+CAAyC;AACzC,iDAA2C;AA8B3C;;;;;;;;;;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K;YACL,YAAY,EAAE,YAAY;YAC1B,WAAW,EAAE,WAAW;YACxB,UAAU,EAAE,IAAI;SACjB,EACD,oBAAoB,KAAK,EAAE,CAC5B,CAAC;IACJ,CAAC;IAED,OAAO;QACL,MAAM;QACN,WAAW,EAAE;YACX,MAAM,EAAE,YAAY;YACpB,KAAK,EAAE,WAAW;YAClB,IAAI;SACL;KACF,CAAC;AACJ,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { TTLCache } from './cache.utils';\nimport { getLogger } from './logger.utils';\n\n/**\n * Options for timing function execution.\n */\nexport interface TimingOptions {\n /** Optional label for the timing (defaults to function name) */\n label?: string;\n /** Whether to log the timing (default: false) */\n log?: boolean;\n /** Log level to use if logging is enabled (default: 'debug') */\n logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error';\n}\n\n/**\n * Result of a timing operation.\n */\nexport interface TimingResult {\n /** Duration in milliseconds */\n durationMs: number;\n /** Duration in seconds */\n durationSec: number;\n /** Start timestamp */\n startTime: number;\n /** End timestamp */\n endTime: number;\n /** Label used for the timing */\n label: string;\n}\n\n/**\n * Measure the execution time of a synchronous function.\n *\n * @param fn - Function to measure\n * @param options - Timing options\n * @returns Result containing the return value and timing information\n *\n * @example\n * ```typescript\n * const { result, timing } = timeSync(() => {\n * // Some expensive operation\n * return computeResult();\n * }, { label: 'Computation', log: true });\n *\n * console.log(`Result: ${result}, took ${timing.durationMs}ms`);\n * ```\n */\nexport function timeSync<T>(fn: () => T, options: TimingOptions = {}): { result: T; timing: TimingResult } {\n const { label = fn.name || 'anonymous function', log = false, logLevel = 'debug' } = options;\n\n const startTime = performance.now();\n const result = fn();\n const endTime = performance.now();\n\n const durationMs = endTime - startTime;\n const durationSec = durationMs / 1000;\n\n const timing: TimingResult = {\n durationMs,\n durationSec,\n startTime,\n endTime,\n label\n };\n\n if (log) {\n const logger = getLogger();\n const message = `${label} completed in ${durationMs.toFixed(2)}ms`;\n\n switch (logLevel) {\n case 'trace':\n logger.trace({ timing }, message);\n break;\n case 'debug':\n logger.debug({ timing }, message);\n break;\n case 'info':\n logger.info({ timing }, message);\n break;\n case 'warn':\n logger.warn({ timing }, message);\n break;\n case 'error':\n logger.error({ timing }, message);\n break;\n default:\n logger.debug({ timing }, message);\n break;\n }\n }\n\n return { result, timing };\n}\n\n/**\n * Measure the execution time of an asynchronous function.\n *\n * @param fn - Async function to measure\n * @param options - Timing options\n * @returns Promise resolving to result and timing information\n *\n * @example\n * ```typescript\n * const { result, timing } = await timeAsync(async () => {\n * // Some expensive async operation\n * const data = await fetchData();\n * return processData(data);\n * }, { label: 'API Request', log: true });\n *\n * console.log(`Fetched ${result.length} items in ${timing.durationSec.toFixed(2)}s`);\n * ```\n */\nexport async function timeAsync<T>(\n fn: () => Promise<T>,\n options: TimingOptions = {}\n): Promise<{ result: T; timing: TimingResult }> {\n const { label = fn.name || 'anonymous async function', log = false, logLevel = 'debug' } = options;\n\n const startTime = performance.now();\n const result = await fn();\n const endTime = performance.now();\n\n const durationMs = endTime - startTime;\n const durationSec = durationMs / 1000;\n\n const timing: TimingResult = {\n durationMs,\n durationSec,\n startTime,\n endTime,\n label\n };\n\n if (log) {\n const logger = getLogger();\n const message = `${label} completed in ${durationMs.toFixed(2)}ms`;\n\n switch (logLevel) {\n case 'trace':\n logger.trace({ timing }, message);\n break;\n case 'debug':\n logger.debug({ timing }, message);\n break;\n case 'info':\n logger.info({ timing }, message);\n break;\n case 'warn':\n logger.warn({ timing }, message);\n break;\n case 'error':\n logger.error({ timing }, message);\n break;\n default:\n logger.debug({ timing }, message);\n break;\n }\n }\n\n return { result, timing };\n}\n\n/**\n * Create a timing decorator for class methods.\n *\n * @param options - Timing options\n * @returns Method decorator\n *\n * @example\n * ```typescript\n * class DataService {\n * @timed({ log: true, logLevel: 'info' })\n * async fetchData() {\n * // ...implementation\n * }\n * }\n * ```\n */\nexport function timed(options: TimingOptions = {}) {\n return function (target: any, propertyKeyOrContext: string | symbol | any, descriptor?: PropertyDescriptor): void {\n let propertyKey: string | symbol;\n let actualDescriptor: PropertyDescriptor;\n\n // ESNext decorator: second argument is context object\n if (typeof propertyKeyOrContext === 'object' && propertyKeyOrContext !== null && 'name' in propertyKeyOrContext) {\n propertyKey = propertyKeyOrContext.name;\n actualDescriptor = descriptor ?? Object.getOwnPropertyDescriptor(target, propertyKey)!;\n } else {\n // Legacy decorator: second argument is property key\n propertyKey = propertyKeyOrContext;\n actualDescriptor = descriptor ?? Object.getOwnPropertyDescriptor(target, propertyKey)!;\n }\n\n const originalMethod = actualDescriptor.value;\n\n actualDescriptor.value = function (...args: any[]) {\n const methodOptions = {\n ...options,\n label: options.label || `${target.constructor.name}.${String(propertyKey)}`\n };\n\n if (originalMethod.constructor.name === 'AsyncFunction') {\n return timeAsync(() => originalMethod.apply(this, args), methodOptions).then(({ result }) => result);\n } else {\n return timeSync(() => originalMethod.apply(this, args), methodOptions).result;\n }\n };\n\n // For legacy decorators, assign the new descriptor\n if (descriptor) {\n descriptor.value = actualDescriptor.value;\n } else {\n Object.defineProperty(target, propertyKey, actualDescriptor);\n }\n // No return needed for method decorators\n };\n}\n\n/**\n * Memoize function results with optional TTL and max cache size.\n *\n * @param fn - Function to memoize\n * @param options - Memoization options\n * @returns Memoized function\n *\n * @example\n * ```typescript\n * // Cache results for 30 seconds, with a maximum of 100 entries\n * const cachedFetch = memoize(\n * async (url) => {\n * const response = await fetch(url);\n * return response.json();\n * },\n * { ttl: 30000, maxSize: 100, cacheKey: (url) => url }\n * );\n * ```\n */\nexport function memoize<T, Args extends any[]>(\n fn: (...args: Args) => T,\n options: {\n /** Time-to-live in milliseconds (default: indefinite) */\n ttl?: number;\n /** Maximum cache size (default: unlimited) */\n maxSize?: number;\n /** Function to generate a cache key from arguments */\n cacheKey?: (...args: Args) => string;\n /** Auto-cleanup interval in milliseconds (default: disabled) */\n autoCleanupMs?: number;\n } = {}\n) {\n const { ttl, maxSize, autoCleanupMs, cacheKey = (...args) => JSON.stringify(args) } = options;\n\n // Create a properly configured TTLCache instance\n const cache = new TTLCache<string, T>({\n ttlMs: ttl,\n maxSize: maxSize,\n autoCleanupMs: autoCleanupMs\n });\n\n return function (...args: Args): T {\n const key = cacheKey(...args);\n\n // Try to get from cache first - TTLCache handles expiration internally\n const cachedValue = cache.get(key);\n if (cachedValue !== undefined) {\n return cachedValue;\n }\n\n // Calculate the value and store in cache with configured TTL\n const value = fn(...args);\n cache.set(key, value);\n return value;\n };\n}\n\n/**\n * Track memory usage for a function execution.\n *\n * @param fn - Function to track\n * @param options - Memory tracking options\n * @returns Result and memory usage information\n */\nexport function trackMemoryUsage<T>(\n fn: () => T,\n options: {\n /** Whether to log the memory usage (default: false) */\n log?: boolean;\n /** Label for the memory tracking (default: function name) */\n label?: string;\n } = {}\n): { result: T; memoryUsage: { before: NodeJS.MemoryUsage; after: NodeJS.MemoryUsage; diff: Record<string, number> } } {\n const { log = false, label = fn.name || 'anonymous function' } = options;\n\n // Collect garbage before measuring (optional)\n if (global.gc) {\n global.gc();\n }\n\n const beforeMemory = process.memoryUsage();\n const result = fn();\n const afterMemory = process.memoryUsage();\n\n // Calculate differences\n const diff: Record<string, number> = {};\n for (const key in afterMemory) {\n if (Object.prototype.hasOwnProperty.call(afterMemory, key)) {\n diff[key] = (afterMemory as any)[key] - (beforeMemory as any)[key];\n }\n }\n\n if (log) {\n getLogger().info(\n {\n label,\n memoryBefore: beforeMemory,\n memoryAfter: afterMemory,\n memoryDiff: diff\n },\n `Memory usage for ${label}`\n );\n }\n\n return {\n result,\n memoryUsage: {\n before: beforeMemory,\n after: afterMemory,\n diff\n }\n };\n}\n"]}
|
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
import { Request } from 'express';
|
|
2
|
-
import { WithPagination } from '../types/api-response';
|
|
3
|
-
/**
|
|
4
|
-
* Options for parsing and validating request parameters.
|
|
5
|
-
*/
|
|
6
|
-
export interface ValidationOptions {
|
|
7
|
-
/** Whether to throw an error on validation failure */
|
|
8
|
-
throwOnError?: boolean;
|
|
9
|
-
/** Custom error message for validation failures */
|
|
10
|
-
errorMessage?: string;
|
|
11
|
-
/** Default value to use if parameter is missing */
|
|
12
|
-
defaultValue?: any;
|
|
13
|
-
/** Whether the parameter is required */
|
|
14
|
-
required?: boolean;
|
|
15
|
-
}
|
|
16
|
-
/**
|
|
17
|
-
* Result of a parameter validation operation.
|
|
18
|
-
*/
|
|
19
|
-
export interface ValidationResult<T> {
|
|
20
|
-
/** Whether validation was successful */
|
|
21
|
-
isValid: boolean;
|
|
22
|
-
/** The validated and potentially transformed value */
|
|
23
|
-
value: T | null;
|
|
24
|
-
/** Error message if validation failed */
|
|
25
|
-
error?: string;
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Extracts pagination, sorting, and optional search params from a request.
|
|
29
|
-
*
|
|
30
|
-
* @param req - Express request
|
|
31
|
-
* @returns Object containing validated pagination, sorting, and additional query params
|
|
32
|
-
*/
|
|
33
|
-
export declare const getPaginationParams: <T = {}>(req: Request) => WithPagination<T>;
|
|
34
|
-
/**
|
|
35
|
-
* Safely parses a string parameter to a number.
|
|
36
|
-
*
|
|
37
|
-
* @param value - String value to parse
|
|
38
|
-
* @param options - Validation options
|
|
39
|
-
* @returns Validation result containing the parsed number or error
|
|
40
|
-
*/
|
|
41
|
-
export declare function parseNumberParam(value: string | undefined, options?: ValidationOptions): ValidationResult<number>;
|
|
42
|
-
/**
|
|
43
|
-
* Safely parses a string parameter to a boolean.
|
|
44
|
-
*
|
|
45
|
-
* @param value - String value to parse
|
|
46
|
-
* @param options - Validation options
|
|
47
|
-
* @returns Validation result containing the parsed boolean or error
|
|
48
|
-
*/
|
|
49
|
-
export declare function parseBooleanParam(value: string | undefined, options?: ValidationOptions): ValidationResult<boolean>;
|
|
50
|
-
/**
|
|
51
|
-
* Extracts pagination parameters from request query parameters.
|
|
52
|
-
*
|
|
53
|
-
* @param query - Query parameters object
|
|
54
|
-
* @param defaultPage - Default page number if not specified (defaults to 1)
|
|
55
|
-
* @param defaultLimit - Default per page size if not specified (defaults to 20)
|
|
56
|
-
* @param maxLimitSize - Maximum allowed per page size (defaults to 100)
|
|
57
|
-
* @returns Object containing validated page and limit
|
|
58
|
-
*/
|
|
59
|
-
export declare function extractPaginationParams(query: Record<string, string | string[]>, defaultPage?: number, defaultLimit?: number, maxLimitSize?: number): {
|
|
60
|
-
page: number;
|
|
61
|
-
limit: number;
|
|
62
|
-
};
|
|
63
|
-
/**
|
|
64
|
-
* Extracts sorting parameters from request query parameters.
|
|
65
|
-
*
|
|
66
|
-
* @param query - Query parameters object
|
|
67
|
-
* @param allowedFields - Array of field names that are allowed to be sorted
|
|
68
|
-
* @param defaultSort - Default sort configuration if not specified
|
|
69
|
-
* @returns Object containing sort field and direction
|
|
70
|
-
*/
|
|
71
|
-
export declare function extractSortParams(query: Record<string, string | string[]>, allowedFields: string[], defaultSort?: {
|
|
72
|
-
sortBy: string;
|
|
73
|
-
sortOrder: 'asc' | 'desc';
|
|
74
|
-
}): {
|
|
75
|
-
sortBy: string;
|
|
76
|
-
sortOrder: 'asc' | 'desc';
|
|
77
|
-
};
|
|
78
|
-
/**
|
|
79
|
-
* Extracts filter parameters from query parameters based on allowed filter fields.
|
|
80
|
-
*
|
|
81
|
-
* @param query - Query parameters object
|
|
82
|
-
* @param allowedFilters - Array of field names that are allowed to be used as filters
|
|
83
|
-
* @returns Object containing the filters as key-value pairs
|
|
84
|
-
*/
|
|
85
|
-
export declare function extractFilterParams(query: Record<string, string | string[]>, allowedFilters: string[]): Record<string, string | string[]>;
|
|
86
|
-
//# sourceMappingURL=request.utils.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"request.utils.js","sourceRoot":"","sources":["../../../src/utils/request.utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;AAsEH,4CA0BC;AASD,8CAiCC;AAWD,0DAoBC;AAUD,8CAmCC;AASD,kDAcC;AAzOD,uDAAwD;AAiCxD;;;;;GAKG;AACI,MAAM,mBAAmB,GAAG,CAAS,GAAY,EAAqB,EAAE;IAC7E,MAAM,KAAK,GAAG,GAAG,CAAC,KAA0C,CAAC;IAE7D,uBAAuB;IACvB,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,uBAAuB,CAAC,KAAK,EAAE,CAAC,EAAE,EAAE,EAAE,GAAG,CAAC,CAAC;IACnE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,iBAAiB,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IAE3D,wBAAwB;IACxB,MAAM,MAAM,GAAG,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;IAE3E,uCACM,KAAW,KACf,IAAI;QACJ,KAAK;QACL,MAAM,EACN,SAAS,EAAE,SAA0B,E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AAS,KAAK,QAAQ,EAAE,CAAC;QACxC,MAAM,KAAK,GAAG,KAAK,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC;QAC5C,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,MAAM,EAAE,CAAC;YACxC,SAAS,GAAG,KAAK,CAAC;QACpB,CAAC;IACH,CAAC;IAED,iBAAiB;IACjB,IAAI,aAAa,CAAC,MAAM,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QAC5D,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC;IAC9B,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;AAC/B,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,mBAAmB,CACjC,KAAwC,EACxC,cAAwB;IAExB,MAAM,OAAO,GAAsC,EAAE,CAAC;IAEtD,sCAAsC;IACtC,KAAK,MAAM,KAAK,IAAI,cAAc,EAAE,CAAC;QACnC,IAAI,KAAK,IAAI,KAAK,EAAE,CAAC;YACnB,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;QAChC,CAAC;IACH,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Request } from 'express';\nimport { SortDirection, WithPagination } from '../types/api-response';\nimport { BadRequestException } from './exception.utils';\n\n/**\n * Options for parsing and validating request parameters.\n */\nexport interface ValidationOptions {\n /** Whether to throw an error on validation failure */\n throwOnError?: boolean;\n\n /** Custom error message for validation failures */\n errorMessage?: string;\n\n /** Default value to use if parameter is missing */\n defaultValue?: any;\n\n /** Whether the parameter is required */\n required?: boolean;\n}\n\n/**\n * Result of a parameter validation operation.\n */\nexport interface ValidationResult<T> {\n /** Whether validation was successful */\n isValid: boolean;\n\n /** The validated and potentially transformed value */\n value: T | null;\n\n /** Error message if validation failed */\n error?: string;\n}\n\n/**\n * Extracts pagination, sorting, and optional search params from a request.\n *\n * @param req - Express request\n * @returns Object containing validated pagination, sorting, and additional query params\n */\nexport const getPaginationParams = <T = {}>(req: Request): WithPagination<T> => {\n const query = req.query as Record<string, string | string[]>;\n\n // Extract page & limit\n const { page, limit } = extractPaginationParams(query, 1, 20, 100);\n const { sortBy, sortOrder } = extractSortParams(query, []);\n\n // Optional search param\n const search = typeof query.search === 'string' ? query.search : undefined;\n\n return {\n ...(query as T),\n page,\n limit,\n sortBy,\n sortOrder: sortOrder as SortDirection,\n search\n };\n};\n\n/**\n * Safely parses a string parameter to a number.\n *\n * @param value - String value to parse\n * @param options - Validation options\n * @returns Validation result containing the parsed number or error\n */\nexport function parseNumberParam(value: string | undefined, options: ValidationOptions = {}): ValidationResult<number> {\n const { throwOnError = false, errorMessage = 'Invalid number parameter', defaultValue, required = false } = options;\n\n // Handle undefined case\n if (value === undefined) {\n if (required) {\n const error = `Required number parameter is missing`;\n if (throwOnError) throw new BadRequestException(error);\n return { isValid: false, value: null, error };\n }\n\n return {\n isValid: defaultValue !== undefined,\n value: defaultValue !== undefined ? defaultValue : null,\n error: defaultValue === undefined ? 'Missing parameter with no default' : undefined\n };\n }\n\n // Parse and validate the number\n const num = Number(value);\n if (isNaN(num)) {\n if (throwOnError) throw new BadRequestException(errorMessage);\n return { isValid: false, value: null, error: errorMessage };\n }\n\n return { isValid: true, value: num };\n}\n\n/**\n * Safely parses a string parameter to a boolean.\n *\n * @param value - String value to parse\n * @param options - Validation options\n * @returns Validation result containing the parsed boolean or error\n */\nexport function parseBooleanParam(\n value: string | undefined,\n options: ValidationOptions = {}\n): ValidationResult<boolean> {\n const { throwOnError = false, errorMessage = 'Invalid boolean parameter', defaultValue, required = false } = options;\n\n // Handle undefined case\n if (value === undefined) {\n if (required) {\n const error = `Required boolean parameter is missing`;\n if (throwOnError) throw new BadRequestException(error);\n return { isValid: false, value: null, error };\n }\n\n return {\n isValid: defaultValue !== undefined,\n value: defaultValue !== undefined ? defaultValue : null,\n error: defaultValue === undefined ? 'Missing parameter with no default' : undefined\n };\n }\n\n // Parse the boolean value with various allowed formats\n const lowercaseValue = value.toLowerCase();\n if (['true', 't', 'yes', 'y', '1'].includes(lowercaseValue)) {\n return { isValid: true, value: true };\n }\n\n if (['false', 'f', 'no', 'n', '0'].includes(lowercaseValue)) {\n return { isValid: true, value: false };\n }\n\n if (throwOnError) throw new BadRequestException(errorMessage);\n return { isValid: false, value: null, error: errorMessage };\n}\n\n/**\n * Extracts pagination parameters from request query parameters.\n *\n * @param query - Query parameters object\n * @param defaultPage - Default page number if not specified (defaults to 1)\n * @param defaultLimit - Default per page size if not specified (defaults to 20)\n * @param maxLimitSize - Maximum allowed per page size (defaults to 100)\n * @returns Object containing validated page and limit\n */\nexport function extractPaginationParams(\n query: Record<string, string | string[]>,\n defaultPage: number = 1,\n defaultLimit: number = 20,\n maxLimitSize: number = 100\n): { page: number; limit: number } {\n // Parse page parameter\n const pageParam = typeof query.page === 'string' ? query.page : undefined;\n const pageResult = parseNumberParam(pageParam, { defaultValue: defaultPage });\n\n // Parse limit parameter\n const limitParam = typeof query.limit === 'string' ? query.limit : undefined;\n const limitResult = parseNumberParam(limitParam, { defaultValue: defaultLimit });\n\n // Ensure valid values (handle 0 → fallback to default)\n const page = pageResult.value && pageResult.value > 0 ? pageResult.value : defaultPage;\n\n const limit = limitResult.value && limitResult.value > 0 ? Math.min(limitResult.value, maxLimitSize) : defaultLimit;\n\n return { page, limit };\n}\n\n/**\n * Extracts sorting parameters from request query parameters.\n *\n * @param query - Query parameters object\n * @param allowedFields - Array of field names that are allowed to be sorted\n * @param defaultSort - Default sort configuration if not specified\n * @returns Object containing sort field and direction\n */\nexport function extractSortParams(\n query: Record<string, string | string[]>,\n allowedFields: string[],\n defaultSort: { sortBy: string; sortOrder: 'asc' | 'desc' } = { sortBy: 'createdAt', sortOrder: 'desc' }\n): { sortBy: string; sortOrder: 'asc' | 'desc' } {\n let sortBy = defaultSort.sortBy;\n let sortOrder: 'asc' | 'desc' = defaultSort.sortOrder;\n\n // Extract from `sortBy` or `sort`\n if (typeof query.sortBy === 'string') {\n sortBy = query.sortBy;\n } else if (Array.isArray(query.sortBy)) {\n sortBy = query.sortBy[0];\n } else if (typeof query.sort === 'string') {\n sortBy = query.sort.startsWith('-') ? query.sort.slice(1) : query.sort;\n sortOrder = query.sort.startsWith('-') ? 'desc' : 'asc';\n } else if (Array.isArray(query.sort)) {\n sortBy = query.sort[0].startsWith('-') ? query.sort[0].slice(1) : query.sort[0];\n sortOrder = query.sort[0].startsWith('-') ? 'desc' : 'asc';\n }\n\n // Explicit sortOrder (overrides inferred one if valid)\n if (typeof query.sortOrder === 'string') {\n const order = query.sortOrder.toLowerCase();\n if (order === 'asc' || order === 'desc') {\n sortOrder = order;\n }\n }\n\n // Validate field\n if (allowedFields.length && !allowedFields.includes(sortBy)) {\n sortBy = defaultSort.sortBy;\n }\n\n return { sortBy, sortOrder };\n}\n\n/**\n * Extracts filter parameters from query parameters based on allowed filter fields.\n *\n * @param query - Query parameters object\n * @param allowedFilters - Array of field names that are allowed to be used as filters\n * @returns Object containing the filters as key-value pairs\n */\nexport function extractFilterParams(\n query: Record<string, string | string[]>,\n allowedFilters: string[]\n): Record<string, string | string[]> {\n const filters: Record<string, string | string[]> = {};\n\n // Find filter parameters in the query\n for (const field of allowedFilters) {\n if (field in query) {\n filters[field] = query[field];\n }\n }\n\n return filters;\n}\n"]}
|
|
@@ -1,163 +0,0 @@
|
|
|
1
|
-
import { Request } from 'express';
|
|
2
|
-
import { ApiErrorResponse, ApiResponse } from '../types/api-response';
|
|
3
|
-
/**
|
|
4
|
-
* Standard HTTP response wrapper for successful responses.
|
|
5
|
-
* Implements the `ApiResponse<T>` interface and sets default values.
|
|
6
|
-
*
|
|
7
|
-
* @typeParam T - The shape of the data returned in the response.
|
|
8
|
-
*/
|
|
9
|
-
export declare class SuccessResponse<T> implements ApiResponse<T> {
|
|
10
|
-
/** Message describing the result of the operation. */
|
|
11
|
-
message: string;
|
|
12
|
-
/** Whether the response is an error. Always false in success responses. */
|
|
13
|
-
error: boolean;
|
|
14
|
-
/** The payload returned from the API. */
|
|
15
|
-
data: T | null;
|
|
16
|
-
/** Timestamp when the response was generated, in ISO format. */
|
|
17
|
-
timestamp: string;
|
|
18
|
-
/** Unique identifier for this response, useful for request tracing. */
|
|
19
|
-
requestId: string;
|
|
20
|
-
/**
|
|
21
|
-
* Constructs a new success response.
|
|
22
|
-
*
|
|
23
|
-
* @param {string} message - Optional message to override the default.
|
|
24
|
-
* @param {T} [data] - Optional data payload.
|
|
25
|
-
*/
|
|
26
|
-
constructor(message: string, data?: T);
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* Wrapper for error responses that extends the native `Error` object.
|
|
30
|
-
* Implements `ApiResponse` but omits the `data` field (which should not be present in errors).
|
|
31
|
-
*/
|
|
32
|
-
export declare class ErrorResponse extends Error implements Omit<ApiResponse<never>, 'data'> {
|
|
33
|
-
/** HTTP status code associated with the error (e.g., 404, 500). */
|
|
34
|
-
status: number;
|
|
35
|
-
/** Indicates that this is an error. Always true. */
|
|
36
|
-
error: boolean;
|
|
37
|
-
/** Timestamp when the error occurred, in ISO format. */
|
|
38
|
-
timestamp: string;
|
|
39
|
-
/** Unique identifier for this error instance. */
|
|
40
|
-
requestId: string;
|
|
41
|
-
/**
|
|
42
|
-
* Constructs a new error response.
|
|
43
|
-
*
|
|
44
|
-
* @param {string} message - The error message to display or log.
|
|
45
|
-
* @param {number} [status=500] - Optional HTTP status code (defaults to 500).
|
|
46
|
-
*/
|
|
47
|
-
constructor(message: string, status?: number);
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* Response with paginated data extending the standard success response.
|
|
51
|
-
* Useful for APIs that return large collections of data.
|
|
52
|
-
*
|
|
53
|
-
* @typeParam T - The shape of each item in the paginated collection.
|
|
54
|
-
*/
|
|
55
|
-
export declare class PaginatedResponse<T> extends SuccessResponse<T[]> {
|
|
56
|
-
/** Total number of items across all pages */
|
|
57
|
-
total: number;
|
|
58
|
-
/** Current page number (1-based) */
|
|
59
|
-
page: number;
|
|
60
|
-
/** Number of items per page */
|
|
61
|
-
pageSize: number;
|
|
62
|
-
/** Total number of pages */
|
|
63
|
-
totalPages: number;
|
|
64
|
-
/** Whether there's a next page available */
|
|
65
|
-
hasNext: boolean;
|
|
66
|
-
/** Whether there's a previous page available */
|
|
67
|
-
hasPrevious: boolean;
|
|
68
|
-
/**
|
|
69
|
-
* Constructs a new paginated response.
|
|
70
|
-
*
|
|
71
|
-
* @param {T[]} items - The current page of items.
|
|
72
|
-
* @param {Object} pagination - Pagination information.
|
|
73
|
-
* @param {number} pagination.total - Total number of items across all pages.
|
|
74
|
-
* @param {number} pagination.page - Current page number (1-based).
|
|
75
|
-
* @param {number} pagination.pageSize - Number of items per page.
|
|
76
|
-
* @param {string} [message="Success"] - Optional custom message.
|
|
77
|
-
*/
|
|
78
|
-
constructor(items: T[], pagination: {
|
|
79
|
-
total: number;
|
|
80
|
-
page: number;
|
|
81
|
-
pageSize: number;
|
|
82
|
-
}, message?: string);
|
|
83
|
-
}
|
|
84
|
-
/**
|
|
85
|
-
* Specialized response for operations that don't return data (HTTP 204).
|
|
86
|
-
*/
|
|
87
|
-
export declare class NoContentResponse extends SuccessResponse<null> {
|
|
88
|
-
/**
|
|
89
|
-
* Constructs a new no-content response.
|
|
90
|
-
*
|
|
91
|
-
* @param {string} [message="Operation completed successfully"] - Optional custom message.
|
|
92
|
-
*/
|
|
93
|
-
constructor(message?: string);
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
|
-
* Specialized response for redirects.
|
|
97
|
-
*/
|
|
98
|
-
export declare class RedirectResponse {
|
|
99
|
-
/** The URL to redirect to */
|
|
100
|
-
redirectUrl: string;
|
|
101
|
-
/** HTTP status code for the redirect (301, 302, 303, 307, 308) */
|
|
102
|
-
statusCode: number;
|
|
103
|
-
/** Whether the response is a redirect */
|
|
104
|
-
isRedirect: boolean;
|
|
105
|
-
/** Unique identifier for this response */
|
|
106
|
-
requestId: string;
|
|
107
|
-
/**
|
|
108
|
-
* Constructs a new redirect response.
|
|
109
|
-
*
|
|
110
|
-
* @param {string} url - The URL to redirect to.
|
|
111
|
-
* @param {number} [statusCode=302] - HTTP status code for the redirect.
|
|
112
|
-
*/
|
|
113
|
-
constructor(url: string, statusCode?: number);
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* Creates a standard success response.
|
|
117
|
-
*
|
|
118
|
-
* @typeParam T - The shape of the data returned in the response.
|
|
119
|
-
* @param {T} data - The data to include in the response.
|
|
120
|
-
* @param {string} [message="Success"] - Optional custom message.
|
|
121
|
-
* @returns {SuccessResponse<T>} A properly formatted success response.
|
|
122
|
-
*/
|
|
123
|
-
export declare function createSuccessResponse<T>(data: T, message?: string): SuccessResponse<T>;
|
|
124
|
-
/**
|
|
125
|
-
* Creates a standard error response.
|
|
126
|
-
*
|
|
127
|
-
* @param {string} message - The error message.
|
|
128
|
-
* @param {number} [statusCode=500] - HTTP status code for the error.
|
|
129
|
-
* @returns {ErrorResponse} A properly formatted error response.
|
|
130
|
-
*/
|
|
131
|
-
export declare function createErrorResponse(message: string, statusCode?: number): ErrorResponse;
|
|
132
|
-
/**
|
|
133
|
-
* Creates a final error response with request information.
|
|
134
|
-
*
|
|
135
|
-
* @param req - The original request object.
|
|
136
|
-
* @param status - The HTTP status code.
|
|
137
|
-
* @param message - The error message.
|
|
138
|
-
* @param error - The original error object (optional).
|
|
139
|
-
* @param options - Additional options for the response (optional).
|
|
140
|
-
* @returns A properly formatted final error response.
|
|
141
|
-
*/
|
|
142
|
-
export declare function createFinalErrorResponse(req: Request, status: number, message: string, error?: any, options?: {
|
|
143
|
-
includeDetails?: boolean;
|
|
144
|
-
}): ApiErrorResponse;
|
|
145
|
-
/**
|
|
146
|
-
* Creates a paginated response from array data.
|
|
147
|
-
*
|
|
148
|
-
* @typeParam T - The shape of each item in the collection.
|
|
149
|
-
* @param {T[]} allItems - The complete array of items to paginate.
|
|
150
|
-
* @param {number} page - The requested page (1-based).
|
|
151
|
-
* @param {number} pageSize - The number of items per page.
|
|
152
|
-
* @param {string} [message="Success"] - Optional custom message.
|
|
153
|
-
* @returns {PaginatedResponse<T>} A properly formatted paginated response.
|
|
154
|
-
*/
|
|
155
|
-
export declare function createPaginatedResponse<T>(allItems: T[], page: number, pageSize: number, message?: string): PaginatedResponse<T>;
|
|
156
|
-
/**
|
|
157
|
-
* Adapter to convert API responses to Express.js response format.
|
|
158
|
-
*
|
|
159
|
-
* @param {any} res - Express response object.
|
|
160
|
-
* @param {SuccessResponse<any> | ErrorResponse | RedirectResponse} apiResponse - API response instance.
|
|
161
|
-
*/
|
|
162
|
-
export declare function sendResponse(res: any, apiResponse: SuccessResponse<any> | ErrorResponse | RedirectResponse): void;
|
|
163
|
-
//# sourceMappingURL=response.utils.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|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;IACT,CAAC;IAED,2BAA2B;IAC3B,MAAM,eAAe,GAAG,WAAmC,CAAC;IAE5D,2CAA2C;IAC3C,IAAI,eAAe,YAAY,iBAAiB,EAAE,CAAC;QACjD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC;QACtB,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;AACxC,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Request } from 'express';\nimport { ApiErrorResponse, ApiResponse } from '../types/api-response';\nimport { getRequestId } from './context-store.utils';\nimport { Env } from './env.utils';\nimport { uuid } from './id.utils';\n\n/**\n * Standard HTTP response wrapper for successful responses.\n * Implements the `ApiResponse<T>` interface and sets default values.\n *\n * @typeParam T - The shape of the data returned in the response.\n */\nexport class SuccessResponse<T> implements ApiResponse<T> {\n /** Message describing the result of the operation. */\n message: string = 'Success';\n\n /** Whether the response is an error. Always false in success responses. */\n error: boolean = false;\n\n /** The payload returned from the API. */\n data: T | null = null;\n\n /** Timestamp when the response was generated, in ISO format. */\n timestamp: string = new Date().toISOString();\n\n /** Unique identifier for this response, useful for request tracing. */\n requestId: string = getRequestId() ?? uuid();\n\n /**\n * Constructs a new success response.\n *\n * @param {string} message - Optional message to override the default.\n * @param {T} [data] - Optional data payload.\n */\n constructor(message: string, data?: T) {\n if (message) this.message = message;\n this.data = data ?? null;\n }\n}\n\n/**\n * Wrapper for error responses that extends the native `Error` object.\n * Implements `ApiResponse` but omits the `data` field (which should not be present in errors).\n */\nexport class ErrorResponse extends Error implements Omit<ApiResponse<never>, 'data'> {\n /** HTTP status code associated with the error (e.g., 404, 500). */\n status: number;\n\n /** Indicates that this is an error. Always true. */\n error: boolean = true;\n\n /** Timestamp when the error occurred, in ISO format. */\n timestamp: string = new Date().toISOString();\n\n /** Unique identifier for this error instance. */\n requestId: string = getRequestId() ?? uuid();\n\n /**\n * Constructs a new error response.\n *\n * @param {string} message - The error message to display or log.\n * @param {number} [status=500] - Optional HTTP status code (defaults to 500).\n */\n constructor(message: string, status: number = 500) {\n super(message);\n this.status = status;\n this.name = this.constructor.name;\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Response with paginated data extending the standard success response.\n * Useful for APIs that return large collections of data.\n *\n * @typeParam T - The shape of each item in the paginated collection.\n */\nexport class PaginatedResponse<T> extends SuccessResponse<T[]> {\n /** Total number of items across all pages */\n total: number;\n\n /** Current page number (1-based) */\n page: number;\n\n /** Number of items per page */\n pageSize: number;\n\n /** Total number of pages */\n totalPages: number;\n\n /** Whether there's a next page available */\n hasNext: boolean;\n\n /** Whether there's a previous page available */\n hasPrevious: boolean;\n\n /**\n * Constructs a new paginated response.\n *\n * @param {T[]} items - The current page of items.\n * @param {Object} pagination - Pagination information.\n * @param {number} pagination.total - Total number of items across all pages.\n * @param {number} pagination.page - Current page number (1-based).\n * @param {number} pagination.pageSize - Number of items per page.\n * @param {string} [message=\"Success\"] - Optional custom message.\n */\n constructor(items: T[], pagination: { total: number; page: number; pageSize: number }, message: string = 'Success') {\n super(message, items);\n\n this.total = pagination.total;\n this.page = pagination.page;\n this.pageSize = pagination.pageSize;\n\n this.totalPages = Math.ceil(this.total / this.pageSize);\n this.hasNext = this.page < this.totalPages;\n this.hasPrevious = this.page > 1;\n }\n}\n\n/**\n * Specialized response for operations that don't return data (HTTP 204).\n */\nexport class NoContentResponse extends SuccessResponse<null> {\n /**\n * Constructs a new no-content response.\n *\n * @param {string} [message=\"Operation completed successfully\"] - Optional custom message.\n */\n constructor(message: string = 'Operation completed successfully') {\n super(message, null);\n }\n}\n\n/**\n * Specialized response for redirects.\n */\nexport class RedirectResponse {\n /** The URL to redirect to */\n redirectUrl: string;\n\n /** HTTP status code for the redirect (301, 302, 303, 307, 308) */\n statusCode: number;\n\n /** Whether the response is a redirect */\n isRedirect: boolean = true;\n\n /** Unique identifier for this response */\n requestId: string = getRequestId() ?? uuid();\n\n /**\n * Constructs a new redirect response.\n *\n * @param {string} url - The URL to redirect to.\n * @param {number} [statusCode=302] - HTTP status code for the redirect.\n */\n constructor(url: string, statusCode: number = 302) {\n this.redirectUrl = url;\n this.statusCode = statusCode;\n }\n}\n\n/**\n * Creates a standard success response.\n *\n * @typeParam T - The shape of the data returned in the response.\n * @param {T} data - The data to include in the response.\n * @param {string} [message=\"Success\"] - Optional custom message.\n * @returns {SuccessResponse<T>} A properly formatted success response.\n */\nexport function createSuccessResponse<T>(data: T, message: string = 'Success'): SuccessResponse<T> {\n return new SuccessResponse<T>(message, data);\n}\n\n/**\n * Creates a standard error response.\n *\n * @param {string} message - The error message.\n * @param {number} [statusCode=500] - HTTP status code for the error.\n * @returns {ErrorResponse} A properly formatted error response.\n */\nexport function createErrorResponse(message: string, statusCode: number = 500): ErrorResponse {\n return new ErrorResponse(message, statusCode);\n}\n\n/**\n * Creates a final error response with request information.\n *\n * @param req - The original request object.\n * @param status - The HTTP status code.\n * @param message - The error message.\n * @param error - The original error object (optional).\n * @param options - Additional options for the response (optional).\n * @returns A properly formatted final error response.\n */\nexport function createFinalErrorResponse(\n req: Request,\n status: number,\n message: string,\n error?: any,\n options?: { includeDetails?: boolean }\n) {\n const isDev = Env.isDev();\n const includeDetails = options?.includeDetails && isDev;\n\n const response: ApiErrorResponse = {\n error: true,\n message,\n timestamp: new Date().toISOString(),\n requestId: error?.requestId || req?.id || uuid(),\n status,\n path: req.originalUrl || req.url\n };\n\n // Include stack trace in development mode if requested\n if (includeDetails && error?.stack) {\n response.stack = error.stack.split('\\n').map((line: string) => line.trim());\n }\n\n return response;\n}\n\n/**\n * Creates a paginated response from array data.\n *\n * @typeParam T - The shape of each item in the collection.\n * @param {T[]} allItems - The complete array of items to paginate.\n * @param {number} page - The requested page (1-based).\n * @param {number} pageSize - The number of items per page.\n * @param {string} [message=\"Success\"] - Optional custom message.\n * @returns {PaginatedResponse<T>} A properly formatted paginated response.\n */\nexport function createPaginatedResponse<T>(\n allItems: T[],\n page: number,\n pageSize: number,\n message: string = 'Success'\n): PaginatedResponse<T> {\n // Ensure valid pagination parameters\n const validPage = Math.max(1, page);\n const validPageSize = Math.max(1, pageSize);\n\n // Calculate slice indices\n const startIndex = (validPage - 1) * validPageSize;\n const endIndex = startIndex + validPageSize;\n\n // Get current page items\n const pageItems = allItems.slice(startIndex, endIndex);\n\n return new PaginatedResponse<T>(\n pageItems,\n {\n total: allItems.length,\n page: validPage,\n pageSize: validPageSize\n },\n message\n );\n}\n\n/**\n * Adapter to convert API responses to Express.js response format.\n *\n * @param {any} res - Express response object.\n * @param {SuccessResponse<any> | ErrorResponse | RedirectResponse} apiResponse - API response instance.\n */\nexport function sendResponse(res: any, apiResponse: SuccessResponse<any> | ErrorResponse | RedirectResponse): void {\n // Handle redirects\n if ('redirectUrl' in apiResponse) {\n res.redirect(apiResponse.statusCode, apiResponse.redirectUrl);\n return;\n }\n\n // Handle errors\n if ('error' in apiResponse && apiResponse.error) {\n const errorResponse = apiResponse as ErrorResponse;\n res.status(errorResponse.status).json({\n error: true,\n message: errorResponse.message,\n timestamp: errorResponse.timestamp,\n requestId: errorResponse.requestId\n });\n return;\n }\n\n // Handle success responses\n const successResponse = apiResponse as SuccessResponse<any>;\n\n // No content (204) shouldn't return a body\n if (successResponse instanceof NoContentResponse) {\n res.status(204).end();\n return;\n }\n\n res.status(200).json(successResponse);\n}\n"]}
|
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
import { Readable, Transform } from 'stream';
|
|
2
|
-
import { BufferEncoding } from './crypto.utils';
|
|
3
|
-
/**
|
|
4
|
-
* Convert a buffer or string to a readable stream.
|
|
5
|
-
*
|
|
6
|
-
* @param data - Buffer or string to convert
|
|
7
|
-
* @returns Readable stream containing the data
|
|
8
|
-
*
|
|
9
|
-
* @example
|
|
10
|
-
* ```typescript
|
|
11
|
-
* const stream = bufferToStream(Buffer.from('Hello world'));
|
|
12
|
-
* // or
|
|
13
|
-
* const stream = bufferToStream('Hello world');
|
|
14
|
-
* ```
|
|
15
|
-
*/
|
|
16
|
-
export declare function bufferToStream(data: Buffer | string): Readable;
|
|
17
|
-
/**
|
|
18
|
-
* Convert a readable stream to a buffer.
|
|
19
|
-
*
|
|
20
|
-
* @param stream - Readable stream to convert
|
|
21
|
-
* @returns Promise resolving to a buffer containing all stream data
|
|
22
|
-
*
|
|
23
|
-
* @example
|
|
24
|
-
* ```typescript
|
|
25
|
-
* const buffer = await streamToBuffer(fs.createReadStream('file.txt'));
|
|
26
|
-
* console.log(buffer.toString()); // Contents of file.txt
|
|
27
|
-
* ```
|
|
28
|
-
*/
|
|
29
|
-
export declare function streamToBuffer(stream: Readable): Promise<Buffer>;
|
|
30
|
-
/**
|
|
31
|
-
* Convert a readable stream to a string.
|
|
32
|
-
*
|
|
33
|
-
* @param stream - Readable stream to convert
|
|
34
|
-
* @param encoding - Character encoding (default: 'utf8')
|
|
35
|
-
* @returns Promise resolving to a string containing all stream data
|
|
36
|
-
*
|
|
37
|
-
* @example
|
|
38
|
-
* ```typescript
|
|
39
|
-
* const content = await streamToString(fs.createReadStream('file.txt'));
|
|
40
|
-
* console.log(content); // Contents of file.txt as string
|
|
41
|
-
* ```
|
|
42
|
-
*/
|
|
43
|
-
export declare function streamToString(stream: Readable, encoding?: BufferEncoding): Promise<string>;
|
|
44
|
-
/**
|
|
45
|
-
* Create a transform stream that limits the rate of data flow.
|
|
46
|
-
*
|
|
47
|
-
* @param bytesPerSecond - Maximum bytes per second
|
|
48
|
-
* @returns Transform stream that throttles data flow
|
|
49
|
-
*/
|
|
50
|
-
export declare function createThrottleStream(bytesPerSecond: number): Transform;
|
|
51
|
-
/**
|
|
52
|
-
* Create a transform stream that batches data into chunks of specified size.
|
|
53
|
-
*
|
|
54
|
-
* @param size - Size of each batch (items for object mode, bytes for binary mode)
|
|
55
|
-
* @param options - Stream options
|
|
56
|
-
* @returns Transform stream that batches data
|
|
57
|
-
*
|
|
58
|
-
* @example
|
|
59
|
-
* ```typescript
|
|
60
|
-
* // Batch lines from a file into arrays of 100 lines each
|
|
61
|
-
* createReadStream('large-file.txt')
|
|
62
|
-
* .pipe(createLineStream())
|
|
63
|
-
* .pipe(createBatchStream(100))
|
|
64
|
-
* .on('data', batch => console.log(`Processing batch of ${batch.length} lines`));
|
|
65
|
-
* ```
|
|
66
|
-
*/
|
|
67
|
-
export declare function createBatchStream(size: number, options?: {
|
|
68
|
-
objectMode?: boolean;
|
|
69
|
-
}): Transform;
|
|
70
|
-
/**
|
|
71
|
-
* Create a transform stream that splits text data by newlines.
|
|
72
|
-
*
|
|
73
|
-
* @param options - Options for the line stream
|
|
74
|
-
* @returns Transform stream that emits lines
|
|
75
|
-
*
|
|
76
|
-
* @example
|
|
77
|
-
* ```typescript
|
|
78
|
-
* // Process a file line by line
|
|
79
|
-
* createReadStream('file.txt')
|
|
80
|
-
* .pipe(createLineStream())
|
|
81
|
-
* .on('data', line => console.log(`Line: ${line}`));
|
|
82
|
-
* ```
|
|
83
|
-
*/
|
|
84
|
-
export declare function createLineStream(options?: {
|
|
85
|
-
encoding?: BufferEncoding;
|
|
86
|
-
includeNewlines?: boolean;
|
|
87
|
-
}): Transform;
|
|
88
|
-
//# sourceMappingURL=stream.utils.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"stream.utils.js","sourceRoot":"","sources":["../../../src/utils/stream.utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;AAkBH,wCAKC;AAcD,wCAOC;AAeD,wCAGC;AAQD,oDA0BC;AAkBD,8CAiDC;AAgBD,4CA8BC;AA/MD,mCAAgE;AAGhE;;;;;;;;;;;;GAYG;AACH,SAAgB,cAAc,CAAC,IAAqB;IAClD,MAAM,QAAQ,GAAG,IAAI,iBAAQ,EAAE,CAAC;IAChC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACpB,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,gBAAgB;IACrC,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,cAAc,CAAC,MAAgB;IACnD,OAAO,IAAI,OAAO,CAAS,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QAC7C,MAAM,MAAM,GAAa,EAAE,CAAC;QAC5B,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAC7F,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CA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AC,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;YACjF,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YACjC,MAAM,GAAG,KAAK,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC;YAE3B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;gBACzB,IAAI,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAClD,CAAC;YAED,QAAQ,EAAE,CAAC;QACb,CAAC;QAED,KAAK,CAAC,QAAQ;YACZ,IAAI,MAAM,EAAE,CAAC;gBACX,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACpB,CAAC;YACD,QAAQ,EAAE,CAAC;QACb,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { Readable, Transform, TransformCallback } from 'stream';\nimport { BufferEncoding } from './crypto.utils';\n\n/**\n * Convert a buffer or string to a readable stream.\n *\n * @param data - Buffer or string to convert\n * @returns Readable stream containing the data\n *\n * @example\n * ```typescript\n * const stream = bufferToStream(Buffer.from('Hello world'));\n * // or\n * const stream = bufferToStream('Hello world');\n * ```\n */\nexport function bufferToStream(data: Buffer | string): Readable {\n const readable = new Readable();\n readable.push(data);\n readable.push(null); // End of stream\n return readable;\n}\n\n/**\n * Convert a readable stream to a buffer.\n *\n * @param stream - Readable stream to convert\n * @returns Promise resolving to a buffer containing all stream data\n *\n * @example\n * ```typescript\n * const buffer = await streamToBuffer(fs.createReadStream('file.txt'));\n * console.log(buffer.toString()); // Contents of file.txt\n * ```\n */\nexport async function streamToBuffer(stream: Readable): Promise<Buffer> {\n return new Promise<Buffer>((resolve, reject) => {\n const chunks: Buffer[] = [];\n stream.on('data', chunk => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));\n stream.on('end', () => resolve(Buffer.concat(chunks)));\n stream.on('error', reject);\n });\n}\n\n/**\n * Convert a readable stream to a string.\n *\n * @param stream - Readable stream to convert\n * @param encoding - Character encoding (default: 'utf8')\n * @returns Promise resolving to a string containing all stream data\n *\n * @example\n * ```typescript\n * const content = await streamToString(fs.createReadStream('file.txt'));\n * console.log(content); // Contents of file.txt as string\n * ```\n */\nexport async function streamToString(stream: Readable, encoding: BufferEncoding = 'utf8'): Promise<string> {\n const buffer = await streamToBuffer(stream);\n return buffer.toString(encoding);\n}\n\n/**\n * Create a transform stream that limits the rate of data flow.\n *\n * @param bytesPerSecond - Maximum bytes per second\n * @returns Transform stream that throttles data flow\n */\nexport function createThrottleStream(bytesPerSecond: number): Transform {\n let bytesSent = 0;\n let startTime = Date.now();\n\n return new Transform({\n transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback) {\n const elapsedSeconds = (Date.now() - startTime) / 1000;\n const targetBytes = bytesPerSecond * elapsedSeconds;\n const chunkSize = chunk.length;\n\n // If we've sent fewer bytes than our target, just send the chunk\n if (bytesSent + chunkSize <= targetBytes) {\n bytesSent += chunkSize;\n callback(null, chunk);\n return;\n }\n\n // Otherwise we need to throttle\n const delay = ((bytesSent + chunkSize) / bytesPerSecond - elapsedSeconds) * 1000;\n\n setTimeout(() => {\n bytesSent += chunkSize;\n callback(null, chunk);\n }, delay);\n }\n });\n}\n\n/**\n * Create a transform stream that batches data into chunks of specified size.\n *\n * @param size - Size of each batch (items for object mode, bytes for binary mode)\n * @param options - Stream options\n * @returns Transform stream that batches data\n *\n * @example\n * ```typescript\n * // Batch lines from a file into arrays of 100 lines each\n * createReadStream('large-file.txt')\n * .pipe(createLineStream())\n * .pipe(createBatchStream(100))\n * .on('data', batch => console.log(`Processing batch of ${batch.length} lines`));\n * ```\n */\nexport function createBatchStream(size: number, options: { objectMode?: boolean } = {}): Transform {\n const objectMode = options.objectMode !== false;\n let batch: any[] = [];\n let buffers: Buffer[] = [];\n let bufferSize = 0;\n\n return new Transform({\n objectMode,\n transform(chunk, _encoding, callback) {\n if (objectMode) {\n batch.push(chunk);\n if (batch.length >= size) {\n this.push(batch);\n batch = [];\n }\n } else {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n buffers.push(buffer);\n bufferSize += buffer.length;\n\n // Emit batches of exact size\n let combined = Buffer.concat(buffers, bufferSize);\n while (combined.length >= size) {\n this.push(combined.slice(0, size));\n combined = combined.slice(size);\n }\n buffers = combined.length > 0 ? [combined] : [];\n bufferSize = combined.length;\n }\n\n callback();\n },\n\n flush(callback) {\n if (objectMode && batch.length > 0) {\n this.push(batch);\n } else if (!objectMode && buffers.length > 0 && bufferSize > 0) {\n let combined = Buffer.concat(buffers, bufferSize);\n while (combined.length >= size) {\n this.push(combined.slice(0, size));\n combined = combined.slice(size);\n }\n if (combined.length > 0) {\n this.push(combined);\n }\n }\n callback();\n }\n });\n}\n\n/**\n * Create a transform stream that splits text data by newlines.\n *\n * @param options - Options for the line stream\n * @returns Transform stream that emits lines\n *\n * @example\n * ```typescript\n * // Process a file line by line\n * createReadStream('file.txt')\n * .pipe(createLineStream())\n * .on('data', line => console.log(`Line: ${line}`));\n * ```\n */\nexport function createLineStream(\n options: {\n encoding?: BufferEncoding;\n includeNewlines?: boolean;\n } = {}\n): Transform {\n const { encoding = 'utf8', includeNewlines = false } = options;\n let buffer = '';\n\n return new Transform({\n objectMode: true,\n transform(chunk, _encoding, callback) {\n const str = buffer + (Buffer.isBuffer(chunk) ? chunk.toString(encoding) : chunk);\n const lines = str.split(/\\r?\\n/);\n buffer = lines.pop() || '';\n\n for (const line of lines) {\n this.push(includeNewlines ? line + '\\n' : line);\n }\n\n callback();\n },\n\n flush(callback) {\n if (buffer) {\n this.push(buffer);\n }\n callback();\n }\n });\n}\n"]}
|
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Capitalizes the first character of a string.
|
|
3
|
-
*
|
|
4
|
-
* @param {string} str - The input string.
|
|
5
|
-
* @returns {string} The string with the first character in uppercase.
|
|
6
|
-
*/
|
|
7
|
-
export declare function capitalize(str: string): string;
|
|
8
|
-
/**
|
|
9
|
-
* Converts a string to kebab-case (e.g., "FooBar test" → "foo-bar-test").
|
|
10
|
-
*
|
|
11
|
-
* @param {string} str - The input string.
|
|
12
|
-
* @returns {string} The kebab-cased string.
|
|
13
|
-
*/
|
|
14
|
-
export declare function toKebabCase(str: string): string;
|
|
15
|
-
/**
|
|
16
|
-
* Converts a kebab-case or snake_case string to camelCase.
|
|
17
|
-
*
|
|
18
|
-
* @param {string} str - The input string.
|
|
19
|
-
* @returns {string} The camelCased string.
|
|
20
|
-
*/
|
|
21
|
-
export declare function toCamelCase(str: string): string;
|
|
22
|
-
/**
|
|
23
|
-
* Converts a string to a URL-friendly slug (lowercase, dashes, alphanumeric).
|
|
24
|
-
*
|
|
25
|
-
* @param {string} str - The input string.
|
|
26
|
-
* @returns {string} The slugified string.
|
|
27
|
-
*/
|
|
28
|
-
export declare function slugify(str: string): string;
|
|
29
|
-
/**
|
|
30
|
-
* Truncates a string to a specific length, appending '...' if truncated.
|
|
31
|
-
*
|
|
32
|
-
* @param {string} str - The input string.
|
|
33
|
-
* @param {number} len - The maximum length.
|
|
34
|
-
* @returns {string} The truncated string.
|
|
35
|
-
*/
|
|
36
|
-
export declare function truncate(str: string, len: number): string;
|
|
37
|
-
/**
|
|
38
|
-
* Converts a string to PascalCase (e.g., "foo-bar" → "FooBar").
|
|
39
|
-
*
|
|
40
|
-
* @param {string} str - The input string.
|
|
41
|
-
* @returns {string} The PascalCased string.
|
|
42
|
-
*/
|
|
43
|
-
export declare function toPascalCase(str: string): string;
|
|
44
|
-
/**
|
|
45
|
-
* Converts a string to snake_case (e.g., "FooBar test" → "foo_bar_test").
|
|
46
|
-
*
|
|
47
|
-
* @param {string} str - The input string.
|
|
48
|
-
* @returns {string} The snake_cased string.
|
|
49
|
-
*/
|
|
50
|
-
export declare function toSnakeCase(str: string): string;
|
|
51
|
-
/**
|
|
52
|
-
* Masks a string by replacing characters with a mask character.
|
|
53
|
-
* Useful for hiding sensitive information like credit cards or passwords.
|
|
54
|
-
*
|
|
55
|
-
* @param {string} str - The string to mask.
|
|
56
|
-
* @param {number} [visibleStart=0] - Number of characters to show at start.
|
|
57
|
-
* @param {number} [visibleEnd=0] - Number of characters to show at end.
|
|
58
|
-
* @param {string} [maskChar="*"] - Character to use for masking.
|
|
59
|
-
* @returns {string} The masked string.
|
|
60
|
-
*/
|
|
61
|
-
export declare function mask(str: string, visibleStart?: number, visibleEnd?: number, maskChar?: string): string;
|
|
62
|
-
/**
|
|
63
|
-
* Removes all HTML tags from a string.
|
|
64
|
-
*
|
|
65
|
-
* @param {string} str - The HTML string to process.
|
|
66
|
-
* @returns {string} The string with HTML tags removed.
|
|
67
|
-
*/
|
|
68
|
-
export declare function stripHtml(str: string): string;
|
|
69
|
-
/**
|
|
70
|
-
* Performs case-insensitive string comparison.
|
|
71
|
-
*
|
|
72
|
-
* @param {string} a - First string.
|
|
73
|
-
* @param {string} b - Second string.
|
|
74
|
-
* @returns {boolean} True if the strings are equal ignoring case.
|
|
75
|
-
*/
|
|
76
|
-
export declare function equalsIgnoreCase(a: string, b: string): boolean;
|
|
77
|
-
/**
|
|
78
|
-
* Reverses a string.
|
|
79
|
-
*
|
|
80
|
-
* @param {string} str - The string to reverse.
|
|
81
|
-
* @returns {string} The reversed string.
|
|
82
|
-
*/
|
|
83
|
-
export declare function reverse(str: string): string;
|
|
84
|
-
/**
|
|
85
|
-
* Counts occurrences of a substring within a string.
|
|
86
|
-
*
|
|
87
|
-
* @param {string} str - The source string.
|
|
88
|
-
* @param {string} substring - The substring to count.
|
|
89
|
-
* @param {boolean} [caseSensitive=true] - Whether to perform case-sensitive counting.
|
|
90
|
-
* @returns {number} Number of occurrences.
|
|
91
|
-
*/
|
|
92
|
-
export declare function countOccurrences(str: string, substring: string, caseSensitive?: boolean): number;
|
|
93
|
-
//# sourceMappingURL=string.utils.d.ts.map
|