@catbee/utils 0.0.6 → 0.0.7

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.
Files changed (122) hide show
  1. package/README.md +51 -1106
  2. package/build/esm/config.d.ts +5 -13
  3. package/build/esm/config.js +0 -12
  4. package/build/esm/config.js.map +1 -1
  5. package/build/esm/servers/server.builder.d.ts +1 -118
  6. package/build/esm/servers/server.builder.js +0 -20
  7. package/build/esm/servers/server.builder.js.map +1 -1
  8. package/build/esm/servers/server.d.ts +2 -2
  9. package/build/esm/servers/server.js +3 -13
  10. package/build/esm/servers/server.js.map +1 -1
  11. package/build/esm/types/api-response.d.ts +28 -0
  12. package/build/esm/types/api-response.js +10 -1
  13. package/build/esm/types/api-response.js.map +1 -1
  14. package/build/esm/types/server.d.ts +0 -17
  15. package/build/esm/types/server.js.map +1 -1
  16. package/build/esm/utils/async.utils.d.ts +91 -0
  17. package/build/esm/utils/async.utils.js +244 -0
  18. package/build/esm/utils/async.utils.js.map +1 -1
  19. package/build/esm/utils/context-store.utils.d.ts +3 -0
  20. package/build/esm/utils/context-store.utils.js +9 -6
  21. package/build/esm/utils/context-store.utils.js.map +1 -1
  22. package/build/esm/utils/date.utils.d.ts +159 -0
  23. package/build/esm/utils/date.utils.js +389 -0
  24. package/build/esm/utils/date.utils.js.map +1 -0
  25. package/build/esm/utils/logger.utils.d.ts +3 -9
  26. package/build/esm/utils/logger.utils.js +3 -9
  27. package/build/esm/utils/logger.utils.js.map +1 -1
  28. package/build/esm/utils/middleware.utils.js +2 -1
  29. package/build/esm/utils/middleware.utils.js.map +1 -1
  30. package/build/esm/utils/performance.utils.d.ts +136 -0
  31. package/build/esm/utils/performance.utils.js +376 -0
  32. package/build/esm/utils/performance.utils.js.map +1 -0
  33. package/build/esm/utils/request.utils.d.ts +9 -0
  34. package/build/esm/utils/request.utils.js +32 -5
  35. package/build/esm/utils/request.utils.js.map +1 -1
  36. package/build/esm/utils/stream.utils.d.ts +88 -0
  37. package/build/esm/utils/stream.utils.js +284 -0
  38. package/build/esm/utils/stream.utils.js.map +1 -0
  39. package/build/esm/utils/type.utils.d.ts +90 -0
  40. package/build/esm/utils/type.utils.js +190 -0
  41. package/build/esm/utils/type.utils.js.map +1 -0
  42. package/build/esnext/config.d.ts +5 -13
  43. package/build/esnext/config.js +0 -12
  44. package/build/esnext/config.js.map +1 -1
  45. package/build/esnext/servers/server.builder.d.ts +1 -118
  46. package/build/esnext/servers/server.builder.js +0 -20
  47. package/build/esnext/servers/server.builder.js.map +1 -1
  48. package/build/esnext/servers/server.d.ts +2 -2
  49. package/build/esnext/servers/server.js +3 -13
  50. package/build/esnext/servers/server.js.map +1 -1
  51. package/build/esnext/types/api-response.d.ts +28 -0
  52. package/build/esnext/types/api-response.js +10 -1
  53. package/build/esnext/types/api-response.js.map +1 -1
  54. package/build/esnext/types/server.d.ts +0 -17
  55. package/build/esnext/types/server.js.map +1 -1
  56. package/build/esnext/utils/async.utils.d.ts +91 -0
  57. package/build/esnext/utils/async.utils.js +190 -0
  58. package/build/esnext/utils/async.utils.js.map +1 -1
  59. package/build/esnext/utils/context-store.utils.d.ts +3 -0
  60. package/build/esnext/utils/context-store.utils.js +9 -6
  61. package/build/esnext/utils/context-store.utils.js.map +1 -1
  62. package/build/esnext/utils/date.utils.d.ts +159 -0
  63. package/build/esnext/utils/date.utils.js +384 -0
  64. package/build/esnext/utils/date.utils.js.map +1 -0
  65. package/build/esnext/utils/logger.utils.d.ts +3 -9
  66. package/build/esnext/utils/logger.utils.js +3 -9
  67. package/build/esnext/utils/logger.utils.js.map +1 -1
  68. package/build/esnext/utils/middleware.utils.js +2 -1
  69. package/build/esnext/utils/middleware.utils.js.map +1 -1
  70. package/build/esnext/utils/performance.utils.d.ts +136 -0
  71. package/build/esnext/utils/performance.utils.js +271 -0
  72. package/build/esnext/utils/performance.utils.js.map +1 -0
  73. package/build/esnext/utils/request.utils.d.ts +9 -0
  74. package/build/esnext/utils/request.utils.js +23 -5
  75. package/build/esnext/utils/request.utils.js.map +1 -1
  76. package/build/esnext/utils/stream.utils.d.ts +88 -0
  77. package/build/esnext/utils/stream.utils.js +210 -0
  78. package/build/esnext/utils/stream.utils.js.map +1 -0
  79. package/build/esnext/utils/type.utils.d.ts +90 -0
  80. package/build/esnext/utils/type.utils.js +187 -0
  81. package/build/esnext/utils/type.utils.js.map +1 -0
  82. package/build/src/config.d.ts +5 -13
  83. package/build/src/config.js +0 -12
  84. package/build/src/config.js.map +1 -1
  85. package/build/src/servers/server.builder.d.ts +1 -118
  86. package/build/src/servers/server.builder.js +0 -20
  87. package/build/src/servers/server.builder.js.map +1 -1
  88. package/build/src/servers/server.d.ts +2 -2
  89. package/build/src/servers/server.js +2 -12
  90. package/build/src/servers/server.js.map +1 -1
  91. package/build/src/types/api-response.d.ts +28 -0
  92. package/build/src/types/api-response.js +11 -0
  93. package/build/src/types/api-response.js.map +1 -1
  94. package/build/src/types/server.d.ts +0 -17
  95. package/build/src/types/server.js.map +1 -1
  96. package/build/src/utils/async.utils.d.ts +91 -0
  97. package/build/src/utils/async.utils.js +194 -0
  98. package/build/src/utils/async.utils.js.map +1 -1
  99. package/build/src/utils/context-store.utils.d.ts +3 -0
  100. package/build/src/utils/context-store.utils.js +9 -6
  101. package/build/src/utils/context-store.utils.js.map +1 -1
  102. package/build/src/utils/date.utils.d.ts +159 -0
  103. package/build/src/utils/date.utils.js +396 -0
  104. package/build/src/utils/date.utils.js.map +1 -0
  105. package/build/src/utils/logger.utils.d.ts +3 -9
  106. package/build/src/utils/logger.utils.js +4 -10
  107. package/build/src/utils/logger.utils.js.map +1 -1
  108. package/build/src/utils/middleware.utils.js +2 -1
  109. package/build/src/utils/middleware.utils.js.map +1 -1
  110. package/build/src/utils/performance.utils.d.ts +136 -0
  111. package/build/src/utils/performance.utils.js +278 -0
  112. package/build/src/utils/performance.utils.js.map +1 -0
  113. package/build/src/utils/request.utils.d.ts +9 -0
  114. package/build/src/utils/request.utils.js +25 -5
  115. package/build/src/utils/request.utils.js.map +1 -1
  116. package/build/src/utils/stream.utils.d.ts +88 -0
  117. package/build/src/utils/stream.utils.js +218 -0
  118. package/build/src/utils/stream.utils.js.map +1 -0
  119. package/build/src/utils/type.utils.d.ts +90 -0
  120. package/build/src/utils/type.utils.js +196 -0
  121. package/build/src/utils/type.utils.js.map +1 -0
  122. package/package.json +6 -2
@@ -1 +1 @@
1
- {"version":3,"file":"request.utils.js","sourceRoot":"","sources":["../../../src/utils/request.utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;AAwCH,4CA0BC;AASD,8CAiCC;AAWD,0DAoBC;AAUD,8CAmCC;AASD,kDAcC;AA9KD;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAAC,KAAyB,EAAE,UAA6B,EAAE;IACzF,MAAM,EAAE,YAAY,GAAG,KAAK,EAAE,YAAY,GAAG,0BAA0B,EAAE,YAAY,EAAE,QAAQ,GAAG,KAAK,EAAE,GAAG,OAAO,CAAC;IAEpH,wBAAwB;IACxB,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACxB,IAAI,QAAQ,EAAE,CAAC;YACb,MAAM,KAAK,GAAG,sCAAsC,CAAC;YACrD,IAAI,YAAY;gBAAE,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;YACzC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;QAChD,CAAC;QAED,OAAO;YACL,OAAO,EAAE,YAAY,KAAK,SAAS;YACnC,KAAK,EAAE,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI;YACvD,KAAK,EAAE,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,mCAAmC,CAAC,CAAC,CAAC,SAAS;SACpF,CAAC;IACJ,CAAC;IAED,gCAAgC;IAChC,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;IAC1B,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C,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAChF,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC;IAC7D,CAAC;IAED,uDAAuD;IACvD,IAAI,OAAO,KAAK,CAAC,SAAS,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,CAAC,aAAa,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QACpC,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\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 * 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 * 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 Error(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 Error(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 Error(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 Error(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.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
+ {"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,EACrC,MAAM,IACN;AACJ,CAAC,CAAC;AAlBW,QAAA,mBAAmB,uBAkB9B;AAEF;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAAC,KAAyB,EAAE,UAA6B,EAAE;IACzF,MAAM,EAAE,YAAY,GAAG,KAAK,EAAE,YAAY,GAAG,0BAA0B,EAAE,YAAY,EAAE,QAAQ,GAAG,KAAK,EAAE,GAAG,OAAO,CAAC;IAEpH,wBAAwB;IACxB,IAAI,KAAK,KAAK,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AM,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\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"]}
@@ -0,0 +1,88 @@
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
@@ -0,0 +1,218 @@
1
+ "use strict";
2
+ /*
3
+ * The MIT License
4
+ *
5
+ * Copyright (c) 2025 Catbee Technologies
6
+ *
7
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ * of this software and associated documentation files (the "Software"), to deal
9
+ * in the Software without restriction, including without limitation the rights
10
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ * copies of the Software, and to permit persons to whom the Software is
12
+ * furnished to do so, subject to the following conditions:
13
+ *
14
+ * The above copyright notice and this permission notice shall be included in all
15
+ * copies or substantial portions of the Software.
16
+ *
17
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ * SOFTWARE.
24
+ */
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.bufferToStream = bufferToStream;
27
+ exports.streamToBuffer = streamToBuffer;
28
+ exports.streamToString = streamToString;
29
+ exports.createThrottleStream = createThrottleStream;
30
+ exports.createBatchStream = createBatchStream;
31
+ exports.createLineStream = createLineStream;
32
+ const stream_1 = require("stream");
33
+ /**
34
+ * Convert a buffer or string to a readable stream.
35
+ *
36
+ * @param data - Buffer or string to convert
37
+ * @returns Readable stream containing the data
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * const stream = bufferToStream(Buffer.from('Hello world'));
42
+ * // or
43
+ * const stream = bufferToStream('Hello world');
44
+ * ```
45
+ */
46
+ function bufferToStream(data) {
47
+ const readable = new stream_1.Readable();
48
+ readable.push(data);
49
+ readable.push(null); // End of stream
50
+ return readable;
51
+ }
52
+ /**
53
+ * Convert a readable stream to a buffer.
54
+ *
55
+ * @param stream - Readable stream to convert
56
+ * @returns Promise resolving to a buffer containing all stream data
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * const buffer = await streamToBuffer(fs.createReadStream('file.txt'));
61
+ * console.log(buffer.toString()); // Contents of file.txt
62
+ * ```
63
+ */
64
+ async function streamToBuffer(stream) {
65
+ return new Promise((resolve, reject) => {
66
+ const chunks = [];
67
+ stream.on('data', chunk => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
68
+ stream.on('end', () => resolve(Buffer.concat(chunks)));
69
+ stream.on('error', reject);
70
+ });
71
+ }
72
+ /**
73
+ * Convert a readable stream to a string.
74
+ *
75
+ * @param stream - Readable stream to convert
76
+ * @param encoding - Character encoding (default: 'utf8')
77
+ * @returns Promise resolving to a string containing all stream data
78
+ *
79
+ * @example
80
+ * ```typescript
81
+ * const content = await streamToString(fs.createReadStream('file.txt'));
82
+ * console.log(content); // Contents of file.txt as string
83
+ * ```
84
+ */
85
+ async function streamToString(stream, encoding = 'utf8') {
86
+ const buffer = await streamToBuffer(stream);
87
+ return buffer.toString(encoding);
88
+ }
89
+ /**
90
+ * Create a transform stream that limits the rate of data flow.
91
+ *
92
+ * @param bytesPerSecond - Maximum bytes per second
93
+ * @returns Transform stream that throttles data flow
94
+ */
95
+ function createThrottleStream(bytesPerSecond) {
96
+ let bytesSent = 0;
97
+ let startTime = Date.now();
98
+ return new stream_1.Transform({
99
+ transform(chunk, _encoding, callback) {
100
+ const elapsedSeconds = (Date.now() - startTime) / 1000;
101
+ const targetBytes = bytesPerSecond * elapsedSeconds;
102
+ const chunkSize = chunk.length;
103
+ // If we've sent fewer bytes than our target, just send the chunk
104
+ if (bytesSent + chunkSize <= targetBytes) {
105
+ bytesSent += chunkSize;
106
+ callback(null, chunk);
107
+ return;
108
+ }
109
+ // Otherwise we need to throttle
110
+ const delay = ((bytesSent + chunkSize) / bytesPerSecond - elapsedSeconds) * 1000;
111
+ setTimeout(() => {
112
+ bytesSent += chunkSize;
113
+ callback(null, chunk);
114
+ }, delay);
115
+ }
116
+ });
117
+ }
118
+ /**
119
+ * Create a transform stream that batches data into chunks of specified size.
120
+ *
121
+ * @param size - Size of each batch (items for object mode, bytes for binary mode)
122
+ * @param options - Stream options
123
+ * @returns Transform stream that batches data
124
+ *
125
+ * @example
126
+ * ```typescript
127
+ * // Batch lines from a file into arrays of 100 lines each
128
+ * createReadStream('large-file.txt')
129
+ * .pipe(createLineStream())
130
+ * .pipe(createBatchStream(100))
131
+ * .on('data', batch => console.log(`Processing batch of ${batch.length} lines`));
132
+ * ```
133
+ */
134
+ function createBatchStream(size, options = {}) {
135
+ const objectMode = options.objectMode !== false;
136
+ let batch = [];
137
+ let buffers = [];
138
+ let bufferSize = 0;
139
+ return new stream_1.Transform({
140
+ objectMode,
141
+ transform(chunk, _encoding, callback) {
142
+ if (objectMode) {
143
+ batch.push(chunk);
144
+ if (batch.length >= size) {
145
+ this.push(batch);
146
+ batch = [];
147
+ }
148
+ }
149
+ else {
150
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
151
+ buffers.push(buffer);
152
+ bufferSize += buffer.length;
153
+ // Emit batches of exact size
154
+ let combined = Buffer.concat(buffers, bufferSize);
155
+ while (combined.length >= size) {
156
+ this.push(combined.slice(0, size));
157
+ combined = combined.slice(size);
158
+ }
159
+ buffers = combined.length > 0 ? [combined] : [];
160
+ bufferSize = combined.length;
161
+ }
162
+ callback();
163
+ },
164
+ flush(callback) {
165
+ if (objectMode && batch.length > 0) {
166
+ this.push(batch);
167
+ }
168
+ else if (!objectMode && buffers.length > 0 && bufferSize > 0) {
169
+ let combined = Buffer.concat(buffers, bufferSize);
170
+ while (combined.length >= size) {
171
+ this.push(combined.slice(0, size));
172
+ combined = combined.slice(size);
173
+ }
174
+ if (combined.length > 0) {
175
+ this.push(combined);
176
+ }
177
+ }
178
+ callback();
179
+ }
180
+ });
181
+ }
182
+ /**
183
+ * Create a transform stream that splits text data by newlines.
184
+ *
185
+ * @param options - Options for the line stream
186
+ * @returns Transform stream that emits lines
187
+ *
188
+ * @example
189
+ * ```typescript
190
+ * // Process a file line by line
191
+ * createReadStream('file.txt')
192
+ * .pipe(createLineStream())
193
+ * .on('data', line => console.log(`Line: ${line}`));
194
+ * ```
195
+ */
196
+ function createLineStream(options = {}) {
197
+ const { encoding = 'utf8', includeNewlines = false } = options;
198
+ let buffer = '';
199
+ return new stream_1.Transform({
200
+ objectMode: true,
201
+ transform(chunk, _encoding, callback) {
202
+ const str = buffer + (Buffer.isBuffer(chunk) ? chunk.toString(encoding) : chunk);
203
+ const lines = str.split(/\r?\n/);
204
+ buffer = lines.pop() || '';
205
+ for (const line of lines) {
206
+ this.push(includeNewlines ? line + '\n' : line);
207
+ }
208
+ callback();
209
+ },
210
+ flush(callback) {
211
+ if (buffer) {
212
+ this.push(buffer);
213
+ }
214
+ callback();
215
+ }
216
+ });
217
+ }
218
+ //# sourceMappingURL=stream.utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream.utils.js","sourceRoot":"","sources":["../../../src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I,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\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"]}
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Check if a value is of a specific primitive type.
3
+ *
4
+ * @param value - Value to check
5
+ * @param type - Type to check against
6
+ * @returns Whether the value is of the specified type
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * isPrimitiveType('hello', 'string'); // true
11
+ * isPrimitiveType(42, 'number'); // true
12
+ * isPrimitiveType(true, 'boolean'); // true
13
+ * isPrimitiveType(null, 'null'); // true
14
+ * isPrimitiveType(undefined, 'undefined'); // true
15
+ * isPrimitiveType({}, 'object'); // true
16
+ * isPrimitiveType([], 'array'); // true
17
+ * ```
18
+ */
19
+ export declare function isPrimitiveType(value: unknown, type: 'string' | 'number' | 'boolean' | 'symbol' | 'bigint' | 'function' | 'object' | 'array' | 'null' | 'undefined'): boolean;
20
+ /**
21
+ * Get the primitive type of a value as a string.
22
+ *
23
+ * @param value - Value to get the type of
24
+ * @returns String representing the type
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * getTypeOf('hello'); // 'string'
29
+ * getTypeOf(42); // 'number'
30
+ * getTypeOf([]); // 'array'
31
+ * getTypeOf(null); // 'null'
32
+ * ```
33
+ */
34
+ export declare function getTypeOf(value: unknown): string;
35
+ /**
36
+ * Type guard for checking if a value is an array of a specific type.
37
+ *
38
+ * @param value - Value to check
39
+ * @param itemTypeGuard - Function that checks if items are of the expected type
40
+ * @returns True if the value is an array with items of the expected type
41
+ *
42
+ * @example
43
+ * ```typescript
44
+ * isArrayOf([1, 2, 3], (item): item is number => typeof item === 'number'); // true
45
+ * isArrayOf(['a', 'b', 'c'], (item): item is string => typeof item === 'string'); // true
46
+ * isArrayOf([1, '2', 3], (item): item is number => typeof item === 'number'); // false
47
+ * ```
48
+ */
49
+ export declare function isArrayOf<T>(value: unknown, itemTypeGuard: (item: unknown) => item is T): value is T[];
50
+ /**
51
+ * Convert a value to a string.
52
+ *
53
+ * @param value - Value to convert
54
+ * @param defaultValue - Default value if conversion fails
55
+ * @returns String representation of the value
56
+ */
57
+ export declare function toStr(value: unknown, defaultValue?: string): string;
58
+ /**
59
+ * Convert a value to a number.
60
+ *
61
+ * @param value - Value to convert
62
+ * @param defaultValue - Default value if conversion fails
63
+ * @returns Numeric representation of the value
64
+ */
65
+ export declare function toNum(value: unknown, defaultValue?: number): number;
66
+ /**
67
+ * Convert a value to a boolean.
68
+ *
69
+ * @param value - Value to convert
70
+ * @param defaultValue - Default value if conversion fails
71
+ * @returns Boolean representation of the value
72
+ */
73
+ export declare function toBool(value: unknown, defaultValue?: boolean): boolean;
74
+ /**
75
+ * Ensure a value matches the expected type, or provide a default.
76
+ *
77
+ * @param value - Value to check
78
+ * @param expectedType - Expected primitive type
79
+ * @param defaultValue - Default value to use if type doesn't match
80
+ * @returns The value if it matches the type, otherwise the default
81
+ *
82
+ * @example
83
+ * ```typescript
84
+ * ensureType(42, 'number', 0); // 42
85
+ * ensureType('42', 'number', 0); // 0
86
+ * ensureType(undefined, 'string', 'default'); // 'default'
87
+ * ```
88
+ */
89
+ export declare function ensureType<T>(value: unknown, expectedType: string, defaultValue: T): T;
90
+ //# sourceMappingURL=type.utils.d.ts.map