@catbee/utils 0.0.5 → 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.
- package/LICENSE +21 -201
- package/README.md +51 -888
- package/build/esm/config.d.ts +84 -7
- package/build/esm/config.js +89 -5
- package/build/esm/config.js.map +1 -1
- package/build/esm/index.d.ts +4 -0
- package/build/esm/index.js +27 -0
- package/build/esm/index.js.map +1 -1
- package/build/esm/servers/server.builder.d.ts +508 -0
- package/build/esm/servers/server.builder.js +702 -0
- package/build/esm/servers/server.builder.js.map +1 -0
- package/build/esm/servers/server.d.ts +256 -0
- package/build/esm/servers/server.js +1201 -0
- package/build/esm/servers/server.js.map +1 -0
- package/build/esm/types/api-response.d.ts +33 -7
- package/build/esm/types/api-response.js +33 -1
- package/build/esm/types/api-response.js.map +1 -1
- package/build/esm/types/index.d.ts +125 -0
- package/build/esm/types/index.js +25 -0
- package/build/esm/types/index.js.map +1 -0
- package/build/esm/types/server.d.ts +268 -0
- package/build/esm/types/server.js +25 -0
- package/build/esm/types/server.js.map +1 -0
- package/build/esm/utils/array.utils.js +23 -0
- package/build/esm/utils/array.utils.js.map +1 -1
- package/build/esm/utils/async.utils.d.ts +91 -0
- package/build/esm/utils/async.utils.js +267 -0
- package/build/esm/utils/async.utils.js.map +1 -1
- package/build/esm/utils/cache.utils.js +23 -0
- package/build/esm/utils/cache.utils.js.map +1 -1
- package/build/esm/utils/context-store.utils.d.ts +3 -0
- package/build/esm/utils/context-store.utils.js +32 -6
- package/build/esm/utils/context-store.utils.js.map +1 -1
- package/build/esm/utils/crypto.utils.js +23 -0
- package/build/esm/utils/crypto.utils.js.map +1 -1
- package/build/esm/utils/date.utils.d.ts +159 -0
- package/build/esm/utils/date.utils.js +389 -0
- package/build/esm/utils/date.utils.js.map +1 -0
- package/build/esm/utils/decorators.utils.js +23 -1
- package/build/esm/utils/decorators.utils.js.map +1 -1
- package/build/esm/utils/dir.utils.js +23 -0
- package/build/esm/utils/dir.utils.js.map +1 -1
- package/build/esm/utils/env.utils.js +23 -0
- package/build/esm/utils/env.utils.js.map +1 -1
- package/build/esm/utils/exception.utils.js +31 -8
- package/build/esm/utils/exception.utils.js.map +1 -1
- package/build/esm/utils/fs.utils.js +23 -0
- package/build/esm/utils/fs.utils.js.map +1 -1
- package/build/esm/utils/http-status-codes.js +23 -0
- package/build/esm/utils/http-status-codes.js.map +1 -1
- package/build/esm/utils/id.utils.js +23 -0
- package/build/esm/utils/id.utils.js.map +1 -1
- package/build/esm/utils/logger.utils.d.ts +5 -0
- package/build/esm/utils/logger.utils.js +40 -3
- package/build/esm/utils/logger.utils.js.map +1 -1
- package/build/esm/utils/middleware.utils.d.ts +2 -0
- package/build/esm/utils/middleware.utils.js +61 -50
- package/build/esm/utils/middleware.utils.js.map +1 -1
- package/build/esm/utils/obj.utils.d.ts +10 -3
- package/build/esm/utils/obj.utils.js +225 -15
- package/build/esm/utils/obj.utils.js.map +1 -1
- package/build/esm/utils/performance.utils.d.ts +136 -0
- package/build/esm/utils/performance.utils.js +376 -0
- package/build/esm/utils/performance.utils.js.map +1 -0
- package/build/esm/utils/request.utils.d.ts +9 -0
- package/build/esm/utils/request.utils.js +55 -5
- package/build/esm/utils/request.utils.js.map +1 -1
- package/build/esm/utils/response.utils.d.ts +15 -1
- package/build/esm/utils/response.utils.js +51 -0
- package/build/esm/utils/response.utils.js.map +1 -1
- package/build/esm/utils/stream.utils.d.ts +88 -0
- package/build/esm/utils/stream.utils.js +284 -0
- package/build/esm/utils/stream.utils.js.map +1 -0
- package/build/esm/utils/string.utils.js +23 -0
- package/build/esm/utils/string.utils.js.map +1 -1
- package/build/esm/utils/type.utils.d.ts +90 -0
- package/build/esm/utils/type.utils.js +190 -0
- package/build/esm/utils/type.utils.js.map +1 -0
- package/build/esm/utils/url.utils.js +23 -0
- package/build/esm/utils/url.utils.js.map +1 -1
- package/build/esm/utils/validate.utils.d.ts +7 -0
- package/build/esm/utils/validate.utils.js +35 -2
- package/build/esm/utils/validate.utils.js.map +1 -1
- package/build/esnext/config.d.ts +84 -7
- package/build/esnext/config.js +89 -5
- package/build/esnext/config.js.map +1 -1
- package/build/esnext/index.d.ts +4 -0
- package/build/esnext/index.js +27 -0
- package/build/esnext/index.js.map +1 -1
- package/build/esnext/servers/server.builder.d.ts +508 -0
- package/build/esnext/servers/server.builder.js +657 -0
- package/build/esnext/servers/server.builder.js.map +1 -0
- package/build/esnext/servers/server.d.ts +256 -0
- package/build/esnext/servers/server.js +908 -0
- package/build/esnext/servers/server.js.map +1 -0
- package/build/esnext/types/api-response.d.ts +33 -7
- package/build/esnext/types/api-response.js +33 -1
- package/build/esnext/types/api-response.js.map +1 -1
- package/build/esnext/types/index.d.ts +125 -0
- package/build/esnext/types/index.js +25 -0
- package/build/esnext/types/index.js.map +1 -0
- package/build/esnext/types/server.d.ts +268 -0
- package/build/esnext/types/server.js +25 -0
- package/build/esnext/types/server.js.map +1 -0
- package/build/esnext/utils/array.utils.js +23 -0
- package/build/esnext/utils/array.utils.js.map +1 -1
- package/build/esnext/utils/async.utils.d.ts +91 -0
- package/build/esnext/utils/async.utils.js +213 -0
- package/build/esnext/utils/async.utils.js.map +1 -1
- package/build/esnext/utils/cache.utils.js +23 -0
- package/build/esnext/utils/cache.utils.js.map +1 -1
- package/build/esnext/utils/context-store.utils.d.ts +3 -0
- package/build/esnext/utils/context-store.utils.js +32 -6
- package/build/esnext/utils/context-store.utils.js.map +1 -1
- package/build/esnext/utils/crypto.utils.js +23 -0
- package/build/esnext/utils/crypto.utils.js.map +1 -1
- package/build/esnext/utils/date.utils.d.ts +159 -0
- package/build/esnext/utils/date.utils.js +384 -0
- package/build/esnext/utils/date.utils.js.map +1 -0
- package/build/esnext/utils/decorators.utils.js +23 -1
- package/build/esnext/utils/decorators.utils.js.map +1 -1
- package/build/esnext/utils/dir.utils.js +23 -0
- package/build/esnext/utils/dir.utils.js.map +1 -1
- package/build/esnext/utils/env.utils.js +23 -0
- package/build/esnext/utils/env.utils.js.map +1 -1
- package/build/esnext/utils/exception.utils.js +30 -7
- package/build/esnext/utils/exception.utils.js.map +1 -1
- package/build/esnext/utils/fs.utils.js +23 -0
- package/build/esnext/utils/fs.utils.js.map +1 -1
- package/build/esnext/utils/http-status-codes.js +23 -0
- package/build/esnext/utils/http-status-codes.js.map +1 -1
- package/build/esnext/utils/id.utils.js +23 -0
- package/build/esnext/utils/id.utils.js.map +1 -1
- package/build/esnext/utils/logger.utils.d.ts +5 -0
- package/build/esnext/utils/logger.utils.js +40 -3
- package/build/esnext/utils/logger.utils.js.map +1 -1
- package/build/esnext/utils/middleware.utils.d.ts +2 -0
- package/build/esnext/utils/middleware.utils.js +57 -50
- package/build/esnext/utils/middleware.utils.js.map +1 -1
- package/build/esnext/utils/obj.utils.d.ts +10 -3
- package/build/esnext/utils/obj.utils.js +176 -12
- package/build/esnext/utils/obj.utils.js.map +1 -1
- package/build/esnext/utils/performance.utils.d.ts +136 -0
- package/build/esnext/utils/performance.utils.js +271 -0
- package/build/esnext/utils/performance.utils.js.map +1 -0
- package/build/esnext/utils/request.utils.d.ts +9 -0
- package/build/esnext/utils/request.utils.js +46 -5
- package/build/esnext/utils/request.utils.js.map +1 -1
- package/build/esnext/utils/response.utils.d.ts +15 -1
- package/build/esnext/utils/response.utils.js +51 -0
- package/build/esnext/utils/response.utils.js.map +1 -1
- package/build/esnext/utils/stream.utils.d.ts +88 -0
- package/build/esnext/utils/stream.utils.js +210 -0
- package/build/esnext/utils/stream.utils.js.map +1 -0
- package/build/esnext/utils/string.utils.js +23 -0
- package/build/esnext/utils/string.utils.js.map +1 -1
- package/build/esnext/utils/type.utils.d.ts +90 -0
- package/build/esnext/utils/type.utils.js +187 -0
- package/build/esnext/utils/type.utils.js.map +1 -0
- package/build/esnext/utils/url.utils.js +23 -0
- package/build/esnext/utils/url.utils.js.map +1 -1
- package/build/esnext/utils/validate.utils.d.ts +7 -0
- package/build/esnext/utils/validate.utils.js +33 -0
- package/build/esnext/utils/validate.utils.js.map +1 -1
- package/build/src/config.d.ts +84 -7
- package/build/src/config.js +90 -6
- package/build/src/config.js.map +1 -1
- package/build/src/index.d.ts +4 -0
- package/build/src/index.js +27 -0
- package/build/src/index.js.map +1 -1
- package/build/src/servers/server.builder.d.ts +508 -0
- package/build/src/servers/server.builder.js +661 -0
- package/build/src/servers/server.builder.js.map +1 -0
- package/build/src/servers/server.d.ts +256 -0
- package/build/src/servers/server.js +948 -0
- package/build/src/servers/server.js.map +1 -0
- package/build/src/types/api-response.d.ts +33 -7
- package/build/src/types/api-response.js +34 -0
- package/build/src/types/api-response.js.map +1 -1
- package/build/src/types/index.d.ts +125 -0
- package/build/src/types/index.js +26 -0
- package/build/src/types/index.js.map +1 -0
- package/build/src/types/server.d.ts +268 -0
- package/build/src/types/server.js +26 -0
- package/build/src/types/server.js.map +1 -0
- package/build/src/utils/array.utils.js +23 -0
- package/build/src/utils/array.utils.js.map +1 -1
- package/build/src/utils/async.utils.d.ts +91 -0
- package/build/src/utils/async.utils.js +217 -0
- package/build/src/utils/async.utils.js.map +1 -1
- package/build/src/utils/cache.utils.js +23 -0
- package/build/src/utils/cache.utils.js.map +1 -1
- package/build/src/utils/context-store.utils.d.ts +3 -0
- package/build/src/utils/context-store.utils.js +32 -6
- package/build/src/utils/context-store.utils.js.map +1 -1
- package/build/src/utils/crypto.utils.js +23 -0
- package/build/src/utils/crypto.utils.js.map +1 -1
- package/build/src/utils/date.utils.d.ts +159 -0
- package/build/src/utils/date.utils.js +396 -0
- package/build/src/utils/date.utils.js.map +1 -0
- package/build/src/utils/decorators.utils.js +23 -1
- package/build/src/utils/decorators.utils.js.map +1 -1
- package/build/src/utils/dir.utils.js +23 -0
- package/build/src/utils/dir.utils.js.map +1 -1
- package/build/src/utils/env.utils.js +23 -0
- package/build/src/utils/env.utils.js.map +1 -1
- package/build/src/utils/exception.utils.js +30 -7
- package/build/src/utils/exception.utils.js.map +1 -1
- package/build/src/utils/fs.utils.js +23 -0
- package/build/src/utils/fs.utils.js.map +1 -1
- package/build/src/utils/http-status-codes.js +23 -0
- package/build/src/utils/http-status-codes.js.map +1 -1
- package/build/src/utils/id.utils.js +23 -0
- package/build/src/utils/id.utils.js.map +1 -1
- package/build/src/utils/logger.utils.d.ts +5 -0
- package/build/src/utils/logger.utils.js +41 -4
- package/build/src/utils/logger.utils.js.map +1 -1
- package/build/src/utils/middleware.utils.d.ts +2 -0
- package/build/src/utils/middleware.utils.js +56 -49
- package/build/src/utils/middleware.utils.js.map +1 -1
- package/build/src/utils/obj.utils.d.ts +10 -3
- package/build/src/utils/obj.utils.js +177 -12
- package/build/src/utils/obj.utils.js.map +1 -1
- package/build/src/utils/performance.utils.d.ts +136 -0
- package/build/src/utils/performance.utils.js +278 -0
- package/build/src/utils/performance.utils.js.map +1 -0
- package/build/src/utils/request.utils.d.ts +9 -0
- package/build/src/utils/request.utils.js +48 -5
- package/build/src/utils/request.utils.js.map +1 -1
- package/build/src/utils/response.utils.d.ts +15 -1
- package/build/src/utils/response.utils.js +52 -0
- package/build/src/utils/response.utils.js.map +1 -1
- package/build/src/utils/stream.utils.d.ts +88 -0
- package/build/src/utils/stream.utils.js +218 -0
- package/build/src/utils/stream.utils.js.map +1 -0
- package/build/src/utils/string.utils.js +23 -0
- package/build/src/utils/string.utils.js.map +1 -1
- package/build/src/utils/type.utils.d.ts +90 -0
- package/build/src/utils/type.utils.js +196 -0
- package/build/src/utils/type.utils.js.map +1 -0
- package/build/src/utils/url.utils.js +23 -0
- package/build/src/utils/url.utils.js.map +1 -1
- package/build/src/utils/validate.utils.d.ts +7 -0
- package/build/src/utils/validate.utils.js +36 -2
- package/build/src/utils/validate.utils.js.map +1 -1
- package/package.json +39 -9
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"date.utils.js","sourceRoot":"","sources":["../../../src/utils/date.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAcH;;;;;;;;;;;;;;;;;;GAkBG;AACH,MA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ereby 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 * Format options for the formatDate function\n */\nexport interface DateFormatOptions {\n /** Date format pattern (default: 'yyyy-MM-dd') */\n format?: string;\n /** Locale to use for formatting (default: system locale) */\n locale?: string | string[];\n /** Time zone to use (default: system time zone) */\n timeZone?: string;\n}\n\n/**\n * Format a date according to the specified format pattern.\n *\n * @param date - Date to format\n * @param options - Formatting options\n * @returns Formatted date string\n *\n * @example\n * ```typescript\n * // Format as ISO date\n * formatDate(new Date(), { format: 'yyyy-MM-dd' }); // '2023-05-15'\n *\n * // Format with time\n * formatDate(new Date(), { format: 'yyyy-MM-dd HH:mm:ss' }); // '2023-05-15 14:30:22'\n *\n * // Format with locale\n * formatDate(new Date(), { format: 'PPPP', locale: 'fr-FR' }); // 'lundi 15 mai 2023'\n * ```\n */\nexport function formatDate(date: Date | number, options: DateFormatOptions = {}): string {\n const { format = 'yyyy-MM-dd', locale, timeZone } = options;\n const d = date instanceof Date ? date : new Date(date);\n\n // Custom formatter for common patterns\n if (format === 'yyyy-MM-dd') {\n const yyyy = d.getFullYear();\n const mm = String(d.getMonth() + 1).padStart(2, '0');\n const dd = String(d.getDate()).padStart(2, '0');\n return `${yyyy}-${mm}-${dd}`;\n }\n if (format === 'yyyy-MM-dd HH:mm:ss') {\n const yyyy = d.getFullYear();\n const mm = String(d.getMonth() + 1).padStart(2, '0');\n const dd = String(d.getDate()).padStart(2, '0');\n const HH = String(d.getHours()).padStart(2, '0');\n const MM = String(d.getMinutes()).padStart(2, '0');\n const SS = String(d.getSeconds()).padStart(2, '0');\n return `${yyyy}-${mm}-${dd} ${HH}:${MM}:${SS}`;\n }\n if (format === 'relative') {\n return formatRelativeTime(date);\n }\n\n // Fallback to Intl.DateTimeFormat for other formats\n return new Intl.DateTimeFormat(locale, {\n timeZone,\n year: format.includes('yyyy') || format.includes('y') ? 'numeric' : undefined,\n month: format.includes('MM') || format.includes('M') ? 'numeric' : undefined,\n day: format.includes('dd') || format.includes('d') ? 'numeric' : undefined,\n hour: format.includes('HH') || format.includes('H') ? 'numeric' : undefined,\n minute: format.includes('mm') || format.includes('m') ? 'numeric' : undefined,\n second: format.includes('ss') || format.includes('s') ? 'numeric' : undefined,\n hour12: !format.includes('HH') && !format.includes('H')\n }).format(d);\n}\n\n/**\n * Format a date as relative time (e.g., \"5 minutes ago\", \"in 3 days\").\n *\n * @param date - Date to format\n * @param now - Reference date (default: current time)\n * @param locale - Locale to use for formatting\n * @returns Formatted relative time string\n */\nexport function formatRelativeTime(\n date: Date | number,\n now: Date | number = new Date(),\n locale?: string | string[]\n): string {\n const d1 = date instanceof Date ? date : new Date(date);\n const d2 = now instanceof Date ? now : new Date(now);\n\n const diffMs = d1.getTime() - d2.getTime();\n const diffSecs = Math.round(diffMs / 1000);\n const diffMins = Math.round(diffSecs / 60);\n const diffHours = Math.round(diffMins / 60);\n const diffDays = Math.round(diffHours / 24);\n const diffMonths = Math.round(diffDays / 30);\n const diffYears = Math.round(diffDays / 365);\n\n const formatter = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });\n\n if (Math.abs(diffSecs) < 60) return formatter.format(diffSecs, 'second');\n if (Math.abs(diffMins) < 60) return formatter.format(diffMins, 'minute');\n if (Math.abs(diffHours) < 24) return formatter.format(diffHours, 'hour');\n if (Math.abs(diffDays) < 30) return formatter.format(diffDays, 'day');\n if (Math.abs(diffMonths) < 12) return formatter.format(diffMonths, 'month');\n return formatter.format(diffYears, 'year');\n}\n\n/**\n * Parse a date string or timestamp into a Date object.\n *\n * @param input - Date string or timestamp to parse\n * @param fallback - Fallback date if parsing fails\n * @returns Parsed Date object or fallback\n *\n * @example\n * ```typescript\n * parseDate('2023-05-15'); // Date object for May 15, 2023\n * parseDate('invalid', new Date()); // Returns current date as fallback\n * ```\n */\nexport function parseDate(input: string | number, fallback?: Date): Date | null {\n if (typeof input === 'number') {\n return new Date(input);\n }\n\n try {\n const date = new Date(input);\n // Check if date is valid\n if (isNaN(date.getTime())) {\n return fallback || null;\n }\n return date;\n } catch {\n return fallback || null;\n }\n}\n\n/**\n * Calculate the difference between two dates in the specified unit.\n *\n * @param date1 - First date\n * @param date2 - Second date (default: current time)\n * @param unit - Unit of time for the difference\n * @returns Difference in the specified unit\n *\n * @example\n * ```typescript\n * // Get difference in days\n * dateDiff(new Date('2023-05-15'), new Date('2023-05-10'), 'days'); // 5\n *\n * // Get difference in hours\n * dateDiff(new Date('2023-05-15T10:00:00'), new Date('2023-05-15T06:00:00'), 'hours'); // 4\n * ```\n */\nexport function dateDiff(\n date1: Date | number,\n date2: Date | number = new Date(),\n unit: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years' = 'days'\n): number {\n const d1 = date1 instanceof Date ? date1 : new Date(date1);\n const d2 = date2 instanceof Date ? date2 : new Date(date2);\n\n const diffMs = d1.getTime() - d2.getTime();\n\n switch (unit) {\n case 'milliseconds':\n return diffMs;\n case 'seconds':\n return diffMs / 1000;\n case 'minutes':\n return diffMs / (1000 * 60);\n case 'hours':\n return diffMs / (1000 * 60 * 60);\n case 'days':\n return diffMs / (1000 * 60 * 60 * 24);\n case 'months':\n return (d1.getFullYear() - d2.getFullYear()) * 12 + d1.getMonth() - d2.getMonth();\n case 'years':\n return d1.getFullYear() - d2.getFullYear();\n default:\n throw new Error(`Unsupported unit: ${unit}`);\n }\n}\n\n/**\n * Add a specified amount of time to a date.\n *\n * @param date - Base date\n * @param amount - Amount to add (can be negative)\n * @param unit - Unit of time to add\n * @returns New date with the addition\n *\n * @example\n * ```typescript\n * // Add 5 days\n * addToDate(new Date('2023-05-15'), 5, 'days'); // Date for May 20, 2023\n *\n * // Subtract 2 hours\n * addToDate(new Date('2023-05-15T10:00:00'), -2, 'hours'); // Date for May 15, 2023 08:00:00\n * ```\n */\nexport function addToDate(\n date: Date | number,\n amount: number,\n unit: 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days' | 'months' | 'years'\n): Date {\n const d = date instanceof Date ? new Date(date) : new Date(date);\n\n switch (unit) {\n case 'milliseconds':\n d.setMilliseconds(d.getMilliseconds() + amount);\n break;\n case 'seconds':\n d.setSeconds(d.getSeconds() + amount);\n break;\n case 'minutes':\n d.setMinutes(d.getMinutes() + amount);\n break;\n case 'hours':\n d.setHours(d.getHours() + amount);\n break;\n case 'days':\n d.setDate(d.getDate() + amount);\n break;\n case 'months': {\n const origDate = d.getDate();\n const origMonth = d.getMonth();\n d.setDate(1); // Prevent overflow\n d.setMonth(origMonth + amount);\n const lastDay = new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();\n d.setDate(Math.min(origDate, lastDay));\n break;\n }\n case 'years':\n d.setFullYear(d.getFullYear() + amount);\n break;\n default:\n throw new Error(`Unsupported unit: ${unit}`);\n }\n\n return d;\n}\n\n/**\n * Get the start of a time period containing the specified date.\n *\n * @param date - Date to get the start from\n * @param unit - Time unit\n * @returns Date object representing the start of the time unit\n *\n * @example\n * ```typescript\n * // Get start of day (midnight)\n * startOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 00:00:00\n *\n * // Get start of month\n * startOf(new Date('2023-05-15'), 'month'); // Date for May 1, 2023\n * ```\n */\nexport function startOf(\n date: Date | number,\n unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'\n): Date {\n const d = date instanceof Date ? new Date(date) : new Date(date);\n\n switch (unit) {\n case 'second':\n d.setMilliseconds(0);\n break;\n case 'minute':\n d.setSeconds(0, 0);\n break;\n case 'hour':\n d.setMinutes(0, 0, 0);\n break;\n case 'day':\n d.setHours(0, 0, 0, 0);\n break;\n case 'week':\n d.setHours(0, 0, 0, 0);\n d.setDate(d.getDate() - d.getDay());\n break;\n case 'month':\n d.setDate(1);\n d.setHours(0, 0, 0, 0);\n break;\n case 'quarter':\n d.setMonth(Math.floor(d.getMonth() / 3) * 3, 1);\n d.setHours(0, 0, 0, 0);\n break;\n case 'year':\n d.setMonth(0, 1);\n d.setHours(0, 0, 0, 0);\n break;\n default:\n throw new Error(`Unsupported unit: ${unit}`);\n }\n\n return d;\n}\n\n/**\n * Get the end of a time period containing the specified date.\n *\n * @param date - Date to get the end from\n * @param unit - Time unit\n * @returns Date object representing the end of the time unit\n *\n * @example\n * ```typescript\n * // Get end of day (23:59:59.999)\n * endOf(new Date('2023-05-15T14:30:00'), 'day'); // Date for May 15, 2023 23:59:59.999\n *\n * // Get end of month\n * endOf(new Date('2023-05-15'), 'month'); // Date for May 31, 2023 23:59:59.999\n * ```\n */\nexport function endOf(\n date: Date | number,\n unit: 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'\n): Date {\n const d = date instanceof Date ? new Date(date) : new Date(date);\n\n switch (unit) {\n case 'second':\n d.setMilliseconds(999);\n break;\n case 'minute':\n d.setSeconds(59, 999);\n break;\n case 'hour':\n d.setMinutes(59, 59, 999);\n break;\n case 'day':\n d.setHours(23, 59, 59, 999);\n break;\n case 'week':\n d.setDate(d.getDate() - d.getDay() + 6);\n d.setHours(23, 59, 59, 999);\n break;\n case 'month':\n d.setMonth(d.getMonth() + 1, 0);\n d.setHours(23, 59, 59, 999);\n break;\n case 'quarter':\n d.setMonth(Math.floor(d.getMonth() / 3) * 3 + 3, 0);\n d.setHours(23, 59, 59, 999);\n break;\n case 'year':\n d.setMonth(11, 31);\n d.setHours(23, 59, 59, 999);\n break;\n default:\n throw new Error(`Unsupported unit: ${unit}`);\n }\n\n return d;\n}\n\n/**\n * Check if a date is between two other dates.\n *\n * @param date - Date to check\n * @param start - Start date of the range\n * @param end - End date of the range\n * @param inclusive - Whether the comparison should be inclusive of start/end\n * @returns True if the date is within the range\n *\n * @example\n * ```typescript\n * const date = new Date('2023-05-15');\n * const start = new Date('2023-05-10');\n * const end = new Date('2023-05-20');\n *\n * isBetween(date, start, end); // true\n * ```\n */\nexport function isBetween(\n date: Date | number,\n start: Date | number,\n end: Date | number,\n inclusive: boolean = true\n): boolean {\n const d = date instanceof Date ? date.getTime() : date;\n const s = start instanceof Date ? start.getTime() : start;\n const e = end instanceof Date ? end.getTime() : end;\n\n return inclusive ? d >= s && d <= e : d > s && d < e;\n}\n\n/**\n * Check if a year is a leap year.\n *\n * @param year - Year to check (or date object)\n * @returns True if the year is a leap year\n */\nexport function isLeapYear(year: number | Date): boolean {\n const y = year instanceof Date ? year.getFullYear() : year;\n return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;\n}\n\n/**\n * Get the number of days in a month.\n *\n * @param year - Year\n * @param month - Month (0-11)\n * @returns Number of days in the month\n */\nexport function daysInMonth(year: number | Date, month?: number): number {\n if (year instanceof Date) {\n month = year.getMonth();\n year = year.getFullYear();\n }\n\n if (month === undefined) {\n throw new Error('Month is required when year is a number');\n }\n\n return new Date(year, month + 1, 0).getDate();\n}\n"]}
|
|
@@ -1,4 +1,26 @@
|
|
|
1
|
-
/*
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2025 Catbee Technologies
|
|
5
|
+
*
|
|
6
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
* in the Software without restriction, including without limitation the rights
|
|
9
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
* furnished to do so, subject to the following conditions:
|
|
12
|
+
*
|
|
13
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
* copies or substantial portions of the Software.
|
|
15
|
+
*
|
|
16
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
* SOFTWARE.
|
|
23
|
+
*/
|
|
2
24
|
import 'reflect-metadata';
|
|
3
25
|
import { HttpStatusCodes } from './http-status-codes';
|
|
4
26
|
import { ForbiddenException } from './exception.utils';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorators.utils.js","sourceRoot":"","sources":["../../../src/utils/decorators.utils.ts"],"names":[],"mappings":"AAAA,sDAAsD;AAGtD,OAAO,kBAAkB,CAAC;AAC1B,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAEvD,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;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B;oBAC3B,IAAI,QAAQ,IAAI,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,KAAK,IAAI,OAAO,EAAE,CAAC;wBAC3E,MAAM,WAAW,GAAG,OAAO,CAAC,GAAa,CAAC;wBAC1C,MAAM,cAAc,GAAI,OAAO,CAAC,UAAqB,IAAI,QAAQ,CAAC,UAAU,CAAC;wBAC7E,OAAO,GAAG,CAAC,QAAQ,CAAC,cAAc,EAAE,WAAW,CAAC,CAAC;oBACnD,CAAC;oBAED,IAAI,CAAC,GAAG,CAAC,WAAW,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE,CAAC;wBACvD,IAAI,QAAQ;4BAAE,MAAA,GAAG,CAAC,MAAM,oDAAG,QAAQ,CAAC,CAAC;wBACrC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;4BAAE,MAAA,GAAG,CAAC,GAAG,oDAAG,CAAC,EAAE,CAAC,CAAC,CAAC;wBAC9D,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;oBACpB,CAAC;oBACD,KAAK,MAAM,EAAE,IAAI,UAAU;wBAAE,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;gBAC3D,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,CAAC,GAAG,CAAC,CAAC;gBACZ,CAAC;YACH,CAAC,CAAC;YAED,MAAc,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,IAAI,EAAE,GAAG,WAAW,EAAE,OAAO,CAAC,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport type { RequestHandler, Router } from 'express';\nimport 'reflect-metadata';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { ForbiddenException } from './exception.utils';\n\n// Metadata keys\nconst ROUTES_KEY = Symbol('routes');\nconst MIDDLEWARE_KEY = Symbol('middlewares');\nconst PARAMS_KEY = Symbol('params');\nconst HTTP_CODE_KEY = Symbol('httpCode');\nconst HEADER_KEY = Symbol('headers');\nconst BEFORE_KEY = Symbol('before');\nconst AFTER_KEY = Symbol('after');\nconst ROLES_KEY = Symbol('roles');\nconst REDIRECT_KEY = Symbol('redirect');\n\n/**\n * Supported HTTP methods for route decorators\n */\ntype HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'head' | 'trace' | 'connect';\n\n/**\n * Represents a route definition for controller methods\n */\ninterface RouteDefinition {\n /** The URL path for this route */\n path: string;\n /** HTTP method for this route */\n method: HttpMethod;\n /** Name of the handler method in the controller class */\n handlerName: string;\n}\n\n/**\n * Parameter decoration definition for method parameters\n */\ninterface ParamDefinition {\n /** Parameter position in method signature */\n index: number;\n /** Type of parameter (query, body, etc.) */\n type: 'query' | 'param' | 'body' | 'req' | 'res';\n /** Optional key for extracting specific property */\n key?: string;\n}\n\n/**\n * Factory function that creates HTTP method decorators.\n *\n * @param method - HTTP method to create decorator for\n * @returns A method decorator function\n */\nfunction createRouteDecorator(method: HttpMethod) {\n return (path: string): MethodDecorator => {\n return (target, propertyKey, descriptor) => {\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, target.constructor) || [];\n routes.push({\n path,\n method,\n handlerName: propertyKey as string\n });\n Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);\n };\n };\n}\n\n/**\n * Decorator for GET HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/users')\n * getUsers() {\n * return this.userService.findAll();\n * }\n * ```\n */\nexport const Get = createRouteDecorator('get');\n\n/**\n * Decorator for POST HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Post('/users')\n * createUser(@Body() userData: any) {\n * return this.userService.create(userData);\n * }\n * ```\n */\nexport const Post = createRouteDecorator('post');\n\n/**\n * Decorator for PUT HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Put = createRouteDecorator('put');\n\n/**\n * Decorator for PATCH HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Patch = createRouteDecorator('patch');\n\n/**\n * Decorator for DELETE HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Delete = createRouteDecorator('delete');\n\n/**\n * Decorator for OPTIONS HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Options = createRouteDecorator('options');\n\n/**\n * Decorator for HEAD HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Head = createRouteDecorator('head');\n\n/**\n * Decorator for TRACE HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Trace = createRouteDecorator('trace');\n\n/**\n * Decorator for CONNECT HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Connect = createRouteDecorator('connect');\n\n/**\n * Decorator that marks a class as a controller with a base path.\n * Used as the entry point for routing configuration.\n *\n * @param basePath - Base URL path for all routes in this controller\n * @returns Class decorator\n *\n * @example\n * ```ts\n * @Controller('/api/users')\n * class UserController {\n * // Controller methods...\n * }\n * ```\n */\nexport function Controller(basePath: string): ClassDecorator {\n return target => {\n Reflect.defineMetadata('basePath', basePath, target);\n };\n}\n\n/**\n * Decorator that applies middleware to a controller method.\n * Multiple middlewares can be applied and will execute in order.\n *\n * @param middlewares - Express middleware functions to apply\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/protected')\n * @Use(authMiddleware, loggingMiddleware)\n * getProtectedResource() {\n * // This route is protected by auth middleware\n * }\n * ```\n */\nexport function Use(...middlewares: RequestHandler[]): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const existing: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey as string) || [];\n Reflect.defineMetadata(MIDDLEWARE_KEY, [...existing, ...middlewares], target, propertyKey as string);\n };\n}\n\n/**\n * Factory function that creates parameter decorators.\n *\n * @param type - Parameter type to extract from request\n * @param key - Optional fixed key for extraction\n * @returns Parameter decorator function\n */\nfunction createParamDecorator(type: ParamDefinition['type'], key?: string) {\n return (paramKey?: string): ParameterDecorator => {\n return (target, propertyKey, parameterIndex) => {\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, target, propertyKey as string) || [];\n // Ensure parameters are ordered by index\n params.push({ index: parameterIndex, type, key: paramKey || key });\n params.sort((a, b) => a.index - b.index);\n Reflect.defineMetadata(PARAMS_KEY, params, target, propertyKey as string);\n };\n };\n}\n\n/**\n * Decorator that extracts query parameters from request.\n *\n * @param paramKey - Optional key to extract specific query parameter\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/search')\n * search(@Query('term') searchTerm: string) {\n * // searchTerm will contain the value of req.query.term\n * }\n * ```\n */\nexport const Query = createParamDecorator('query');\n\n/**\n * Decorator that extracts route parameters from request.\n *\n * @param paramKey - Optional key to extract specific route parameter\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/users/:id')\n * getUser(@Param('id') userId: string) {\n * // userId will contain the value of req.params.id\n * }\n * ```\n */\nexport const Param = createParamDecorator('param');\n\n/**\n * Decorator that extracts body or body property from request.\n *\n * @param paramKey - Optional key to extract specific body property\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Post('/users')\n * createUser(@Body() userData: any) {\n * // userData will contain the entire req.body\n * }\n *\n * @Post('/update')\n * updateName(@Body('name') name: string) {\n * // name will contain the value of req.body.name\n * }\n * ```\n */\nexport const Body = createParamDecorator('body');\n\n/**\n * Decorator that injects the entire request object.\n *\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/complex')\n * complex(@Req() req: Request) {\n * // Access the full request object\n * console.log(req.headers);\n * }\n * ```\n */\nexport const Req = createParamDecorator('req');\n\n/**\n * Decorator that injects the response object.\n *\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/custom')\n * custom(@Res() res: Response) {\n * // Direct access to response object\n * return res.status(201).send('Created');\n * }\n * ```\n */\nexport const Res = createParamDecorator('res');\n\n/**\n * Decorator that sets a custom HTTP status code for a response.\n *\n * @param status - HTTP status code to use\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Post('/users')\n * @HttpCode(201)\n * createUser(@Body() userData: any) {\n * // Response will have 201 Created status code\n * return { id: '123', ...userData };\n * }\n * ```\n */\nexport function HttpCode(status: number): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that adds a custom HTTP header to the response.\n *\n * @param name - Header name\n * @param value - Header value\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/data')\n * @Header('Cache-Control', 'max-age=60')\n * getData() {\n * // Response will include the Cache-Control header\n * return { data: '...' };\n * }\n * ```\n */\nexport function Header(name: string, value: string): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, target, propertyKey as string) || {};\n headers[name] = value;\n Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that registers a function to run before route handler execution.\n * Useful for pre-processing or logging.\n *\n * @param fn - Function to execute before the handler\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/users/:id')\n * @Before((req, res) => console.log(`Accessing user ${req.params.id}`))\n * getUser(@Param('id') id: string) {\n * // Function will log before this handler runs\n * }\n * ```\n */\nexport function Before(fn: Function): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(BEFORE_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that registers a function to run after route handler execution.\n * Can access the handler's result.\n *\n * @param fn - Function to execute after the handler\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/users/:id')\n * @After((req, res, result) => console.log(`User data sent: ${JSON.stringify(result)}`))\n * getUser(@Param('id') id: string) {\n * // After this handler, the function will log the returned data\n * return { id, name: 'Example' };\n * }\n * ```\n */\nexport function After(fn: Function): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(AFTER_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that requires specific roles for accessing a route.\n * Must be used with authentication middleware.\n *\n * @param roles - List of roles that can access this route\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/admin/settings')\n * @Roles('admin', 'superuser')\n * getSettings() {\n * // Only admins and superusers can access\n * return { settings: [...] };\n * }\n * ```\n */\nexport function Roles(...roles: string[]): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n Reflect.defineMetadata(ROLES_KEY, roles, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that redirects to another URL.\n *\n * @param url - URL to redirect to (can be absolute or relative)\n * @param statusCode - HTTP status code for redirect (default: 302)\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/old-path')\n * @Redirect('/new-path', 301)\n * redirectToNewPath() {\n * // This method won't be executed; automatic redirect happens\n * }\n *\n * @Get('/dynamic-redirect')\n * @Redirect()\n * getDynamicRedirect() {\n * // Return an object with url and optionally statusCode\n * return { url: '/calculated-path', statusCode: 307 };\n * }\n * ```\n */\nexport function Redirect(url?: string, statusCode: number = 302): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n // Store the redirect information in metadata\n Reflect.defineMetadata(REDIRECT_KEY, { url, statusCode }, target, propertyKey as string);\n return descriptor;\n };\n}\n\n/**\n * Registers all controller classes with the provided router.\n * This function processes all decorators and sets up the Express routes.\n *\n * @param router - Express router instance\n * @param controllers - Array of controller classes\n */\nexport function registerControllers(router: Router, controllers: any[]) {\n controllers.forEach(ControllerClass => {\n const instance = new ControllerClass();\n const basePath: string = Reflect.getMetadata('basePath', ControllerClass) || '';\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];\n\n routes.forEach(({ path, method, handlerName }) => {\n const middlewares: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, instance, handlerName) || [];\n\n const httpCode: number | undefined = Reflect.getMetadata(HTTP_CODE_KEY, instance, handlerName);\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};\n const beforeHooks: Function[] = Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];\n const afterHooks: Function[] = Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];\n const roles: string[] = Reflect.getMetadata(ROLES_KEY, instance, handlerName) || [];\n const redirect: { url?: string; statusCode: number } | undefined = Reflect.getMetadata(\n REDIRECT_KEY,\n instance,\n handlerName\n );\n\n const handler: RequestHandler = async (req, res, next) => {\n try {\n // Handle roles-based access control\n if (roles.length && !(req as any)?.user?.roles?.some((role: string) => roles.includes(role))) {\n res.status(HttpStatusCodes.FORBIDDEN).json(new ForbiddenException('Forbidden Insufficient Roles'));\n return;\n }\n\n // Process static redirect if configured\n if (redirect && redirect.url) {\n return res.redirect(redirect.statusCode, redirect.url);\n }\n\n for (const fn of beforeHooks) await fn(req, res);\n const args: any[] = [];\n if (params.length) {\n params.forEach(({ index, type, key }) => {\n switch (type) {\n case 'query':\n args[index] = key ? req.query[key] : req.query;\n break;\n case 'param':\n args[index] = key ? req.params[key] : req.params;\n break;\n case 'body':\n args[index] = key ? req.body?.[key] : req.body;\n break;\n case 'req':\n args[index] = req;\n break;\n case 'res':\n args[index] = res;\n break;\n }\n });\n }\n const result = (instance as any)[handlerName](...args);\n // Support both sync and async handlers\n const awaited = result instanceof Promise ? await result : result;\n\n // Handle dynamic redirects\n if (redirect && awaited && typeof awaited === 'object' && 'url' in awaited) {\n const redirectUrl = awaited.url as string;\n const redirectStatus = (awaited.statusCode as number) || redirect.statusCode;\n return res.redirect(redirectStatus, redirectUrl);\n }\n\n if (!res.headersSent && typeof awaited !== 'undefined') {\n if (httpCode) res.status?.(httpCode);\n for (const [k, v] of Object.entries(headers)) res.set?.(k, v);\n res.json(awaited);\n }\n for (const fn of afterHooks) await fn(req, res, awaited);\n } catch (err) {\n next(err);\n }\n };\n\n (router as any)[method](basePath + path, ...middlewares, handler);\n });\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"decorators.utils.js","sourceRoot":"","sources":["../../../src/utils/decorators.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAKH,OAAO,kBAAkB,CAAC;AAC1B,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAEvD,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,cAAc,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC7C,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,aAAa,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;AACzC,MAAM,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AACrC,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;AAClC,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;AAClC,MAAM,YAAY,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;AA+BxC;;;;;GAKG;AACH,SAAS,oBAAoB,CAAC,MAAkB;IAC9C,OAAO,CAAC,IAAY,EAAmB,EAAE;QACvC,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE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,MAAA,GAAG,CAAC,GAAG,oDAAG,CAAC,EAAE,CAAC,CAAC,CAAC;wBAC9D,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;oBACpB,CAAC;oBACD,KAAK,MAAM,EAAE,IAAI,UAAU;wBAAE,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;gBAC3D,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,CAAC,GAAG,CAAC,CAAC;gBACZ,CAAC;YACH,CAAC,CAAC;YAED,MAAc,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,IAAI,EAAE,GAAG,WAAW,EAAE,OAAO,CAAC,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC,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\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport type { RequestHandler, Router } from 'express';\nimport 'reflect-metadata';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { ForbiddenException } from './exception.utils';\n\n// Metadata keys\nconst ROUTES_KEY = Symbol('routes');\nconst MIDDLEWARE_KEY = Symbol('middlewares');\nconst PARAMS_KEY = Symbol('params');\nconst HTTP_CODE_KEY = Symbol('httpCode');\nconst HEADER_KEY = Symbol('headers');\nconst BEFORE_KEY = Symbol('before');\nconst AFTER_KEY = Symbol('after');\nconst ROLES_KEY = Symbol('roles');\nconst REDIRECT_KEY = Symbol('redirect');\n\n/**\n * Supported HTTP methods for route decorators\n */\ntype HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'head' | 'trace' | 'connect';\n\n/**\n * Represents a route definition for controller methods\n */\ninterface RouteDefinition {\n /** The URL path for this route */\n path: string;\n /** HTTP method for this route */\n method: HttpMethod;\n /** Name of the handler method in the controller class */\n handlerName: string;\n}\n\n/**\n * Parameter decoration definition for method parameters\n */\ninterface ParamDefinition {\n /** Parameter position in method signature */\n index: number;\n /** Type of parameter (query, body, etc.) */\n type: 'query' | 'param' | 'body' | 'req' | 'res';\n /** Optional key for extracting specific property */\n key?: string;\n}\n\n/**\n * Factory function that creates HTTP method decorators.\n *\n * @param method - HTTP method to create decorator for\n * @returns A method decorator function\n */\nfunction createRouteDecorator(method: HttpMethod) {\n return (path: string): MethodDecorator => {\n return (target, propertyKey, descriptor) => {\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, target.constructor) || [];\n routes.push({\n path,\n method,\n handlerName: propertyKey as string\n });\n Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);\n };\n };\n}\n\n/**\n * Decorator for GET HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/users')\n * getUsers() {\n * return this.userService.findAll();\n * }\n * ```\n */\nexport const Get = createRouteDecorator('get');\n\n/**\n * Decorator for POST HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Post('/users')\n * createUser(@Body() userData: any) {\n * return this.userService.create(userData);\n * }\n * ```\n */\nexport const Post = createRouteDecorator('post');\n\n/**\n * Decorator for PUT HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Put = createRouteDecorator('put');\n\n/**\n * Decorator for PATCH HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Patch = createRouteDecorator('patch');\n\n/**\n * Decorator for DELETE HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Delete = createRouteDecorator('delete');\n\n/**\n * Decorator for OPTIONS HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Options = createRouteDecorator('options');\n\n/**\n * Decorator for HEAD HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Head = createRouteDecorator('head');\n\n/**\n * Decorator for TRACE HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Trace = createRouteDecorator('trace');\n\n/**\n * Decorator for CONNECT HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Connect = createRouteDecorator('connect');\n\n/**\n * Decorator that marks a class as a controller with a base path.\n * Used as the entry point for routing configuration.\n *\n * @param basePath - Base URL path for all routes in this controller\n * @returns Class decorator\n *\n * @example\n * ```ts\n * @Controller('/api/users')\n * class UserController {\n * // Controller methods...\n * }\n * ```\n */\nexport function Controller(basePath: string): ClassDecorator {\n return target => {\n Reflect.defineMetadata('basePath', basePath, target);\n };\n}\n\n/**\n * Decorator that applies middleware to a controller method.\n * Multiple middlewares can be applied and will execute in order.\n *\n * @param middlewares - Express middleware functions to apply\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/protected')\n * @Use(authMiddleware, loggingMiddleware)\n * getProtectedResource() {\n * // This route is protected by auth middleware\n * }\n * ```\n */\nexport function Use(...middlewares: RequestHandler[]): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const existing: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey as string) || [];\n Reflect.defineMetadata(MIDDLEWARE_KEY, [...existing, ...middlewares], target, propertyKey as string);\n };\n}\n\n/**\n * Factory function that creates parameter decorators.\n *\n * @param type - Parameter type to extract from request\n * @param key - Optional fixed key for extraction\n * @returns Parameter decorator function\n */\nfunction createParamDecorator(type: ParamDefinition['type'], key?: string) {\n return (paramKey?: string): ParameterDecorator => {\n return (target, propertyKey, parameterIndex) => {\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, target, propertyKey as string) || [];\n // Ensure parameters are ordered by index\n params.push({ index: parameterIndex, type, key: paramKey || key });\n params.sort((a, b) => a.index - b.index);\n Reflect.defineMetadata(PARAMS_KEY, params, target, propertyKey as string);\n };\n };\n}\n\n/**\n * Decorator that extracts query parameters from request.\n *\n * @param paramKey - Optional key to extract specific query parameter\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/search')\n * search(@Query('term') searchTerm: string) {\n * // searchTerm will contain the value of req.query.term\n * }\n * ```\n */\nexport const Query = createParamDecorator('query');\n\n/**\n * Decorator that extracts route parameters from request.\n *\n * @param paramKey - Optional key to extract specific route parameter\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/users/:id')\n * getUser(@Param('id') userId: string) {\n * // userId will contain the value of req.params.id\n * }\n * ```\n */\nexport const Param = createParamDecorator('param');\n\n/**\n * Decorator that extracts body or body property from request.\n *\n * @param paramKey - Optional key to extract specific body property\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Post('/users')\n * createUser(@Body() userData: any) {\n * // userData will contain the entire req.body\n * }\n *\n * @Post('/update')\n * updateName(@Body('name') name: string) {\n * // name will contain the value of req.body.name\n * }\n * ```\n */\nexport const Body = createParamDecorator('body');\n\n/**\n * Decorator that injects the entire request object.\n *\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/complex')\n * complex(@Req() req: Request) {\n * // Access the full request object\n * console.log(req.headers);\n * }\n * ```\n */\nexport const Req = createParamDecorator('req');\n\n/**\n * Decorator that injects the response object.\n *\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/custom')\n * custom(@Res() res: Response) {\n * // Direct access to response object\n * return res.status(201).send('Created');\n * }\n * ```\n */\nexport const Res = createParamDecorator('res');\n\n/**\n * Decorator that sets a custom HTTP status code for a response.\n *\n * @param status - HTTP status code to use\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Post('/users')\n * @HttpCode(201)\n * createUser(@Body() userData: any) {\n * // Response will have 201 Created status code\n * return { id: '123', ...userData };\n * }\n * ```\n */\nexport function HttpCode(status: number): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that adds a custom HTTP header to the response.\n *\n * @param name - Header name\n * @param value - Header value\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/data')\n * @Header('Cache-Control', 'max-age=60')\n * getData() {\n * // Response will include the Cache-Control header\n * return { data: '...' };\n * }\n * ```\n */\nexport function Header(name: string, value: string): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, target, propertyKey as string) || {};\n headers[name] = value;\n Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that registers a function to run before route handler execution.\n * Useful for pre-processing or logging.\n *\n * @param fn - Function to execute before the handler\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/users/:id')\n * @Before((req, res) => console.log(`Accessing user ${req.params.id}`))\n * getUser(@Param('id') id: string) {\n * // Function will log before this handler runs\n * }\n * ```\n */\nexport function Before(fn: Function): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(BEFORE_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that registers a function to run after route handler execution.\n * Can access the handler's result.\n *\n * @param fn - Function to execute after the handler\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/users/:id')\n * @After((req, res, result) => console.log(`User data sent: ${JSON.stringify(result)}`))\n * getUser(@Param('id') id: string) {\n * // After this handler, the function will log the returned data\n * return { id, name: 'Example' };\n * }\n * ```\n */\nexport function After(fn: Function): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(AFTER_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that requires specific roles for accessing a route.\n * Must be used with authentication middleware.\n *\n * @param roles - List of roles that can access this route\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/admin/settings')\n * @Roles('admin', 'superuser')\n * getSettings() {\n * // Only admins and superusers can access\n * return { settings: [...] };\n * }\n * ```\n */\nexport function Roles(...roles: string[]): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n Reflect.defineMetadata(ROLES_KEY, roles, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that redirects to another URL.\n *\n * @param url - URL to redirect to (can be absolute or relative)\n * @param statusCode - HTTP status code for redirect (default: 302)\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/old-path')\n * @Redirect('/new-path', 301)\n * redirectToNewPath() {\n * // This method won't be executed; automatic redirect happens\n * }\n *\n * @Get('/dynamic-redirect')\n * @Redirect()\n * getDynamicRedirect() {\n * // Return an object with url and optionally statusCode\n * return { url: '/calculated-path', statusCode: 307 };\n * }\n * ```\n */\nexport function Redirect(url?: string, statusCode: number = 302): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n // Store the redirect information in metadata\n Reflect.defineMetadata(REDIRECT_KEY, { url, statusCode }, target, propertyKey as string);\n return descriptor;\n };\n}\n\n/**\n * Registers all controller classes with the provided router.\n * This function processes all decorators and sets up the Express routes.\n *\n * @param router - Express router instance\n * @param controllers - Array of controller classes\n */\nexport function registerControllers(router: Router, controllers: any[]) {\n controllers.forEach(ControllerClass => {\n const instance = new ControllerClass();\n const basePath: string = Reflect.getMetadata('basePath', ControllerClass) || '';\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];\n\n routes.forEach(({ path, method, handlerName }) => {\n const middlewares: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, instance, handlerName) || [];\n\n const httpCode: number | undefined = Reflect.getMetadata(HTTP_CODE_KEY, instance, handlerName);\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};\n const beforeHooks: Function[] = Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];\n const afterHooks: Function[] = Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];\n const roles: string[] = Reflect.getMetadata(ROLES_KEY, instance, handlerName) || [];\n const redirect: { url?: string; statusCode: number } | undefined = Reflect.getMetadata(\n REDIRECT_KEY,\n instance,\n handlerName\n );\n\n const handler: RequestHandler = async (req, res, next) => {\n try {\n // Handle roles-based access control\n if (roles.length && !(req as any)?.user?.roles?.some((role: string) => roles.includes(role))) {\n res.status(HttpStatusCodes.FORBIDDEN).json(new ForbiddenException('Forbidden Insufficient Roles'));\n return;\n }\n\n // Process static redirect if configured\n if (redirect && redirect.url) {\n return res.redirect(redirect.statusCode, redirect.url);\n }\n\n for (const fn of beforeHooks) await fn(req, res);\n const args: any[] = [];\n if (params.length) {\n params.forEach(({ index, type, key }) => {\n switch (type) {\n case 'query':\n args[index] = key ? req.query[key] : req.query;\n break;\n case 'param':\n args[index] = key ? req.params[key] : req.params;\n break;\n case 'body':\n args[index] = key ? req.body?.[key] : req.body;\n break;\n case 'req':\n args[index] = req;\n break;\n case 'res':\n args[index] = res;\n break;\n }\n });\n }\n const result = (instance as any)[handlerName](...args);\n // Support both sync and async handlers\n const awaited = result instanceof Promise ? await result : result;\n\n // Handle dynamic redirects\n if (redirect && awaited && typeof awaited === 'object' && 'url' in awaited) {\n const redirectUrl = awaited.url as string;\n const redirectStatus = (awaited.statusCode as number) || redirect.statusCode;\n return res.redirect(redirectStatus, redirectUrl);\n }\n\n if (!res.headersSent && typeof awaited !== 'undefined') {\n if (httpCode) res.status?.(httpCode);\n for (const [k, v] of Object.entries(headers)) res.set?.(k, v);\n res.json(awaited);\n }\n for (const fn of afterHooks) await fn(req, res, awaited);\n } catch (err) {\n next(err);\n }\n };\n\n (router as any)[method](basePath + path, ...middlewares, handler);\n });\n });\n}\n"]}
|
|
@@ -1,3 +1,26 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2025 Catbee Technologies
|
|
5
|
+
*
|
|
6
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
* in the Software without restriction, including without limitation the rights
|
|
9
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
* furnished to do so, subject to the following conditions:
|
|
12
|
+
*
|
|
13
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
* copies or substantial portions of the Software.
|
|
15
|
+
*
|
|
16
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
* SOFTWARE.
|
|
23
|
+
*/
|
|
1
24
|
import os from 'os';
|
|
2
25
|
import fs from 'fs';
|
|
3
26
|
import fsp from 'fs/promises';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dir.utils.js","sourceRoot":"","sources":["../../../src/utils/dir.utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,GAAG,MAAM,aAAa,CAAC;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AAErC;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,OAAe;IAC7C,MAAM,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;AAChD,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,OAAe,EAAE,SAAS,GAAG,KAAK;IAChE,MAAM,OAAO,GAAG,MAAM,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC;IACpE,MAAM,KAAK,GAAa,EAAE,CAAC;IAE3B,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;QAEhD,IAAI,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC;YACnB,KAAK,CAAC,IAAI,CAAC,QAAQ,C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sourcesContent":["import os from 'os';\nimport fs from 'fs';\nimport fsp from 'fs/promises';\nimport path from 'path';\nimport { glob } from 'glob';\nimport { randomBytes } from 'crypto';\n\n/**\n * Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).\n *\n * @param {string} dirPath - The directory path to ensure.\n * @returns {Promise<void>} Resolves when the directory exists.\n * @throws {Error} If directory cannot be created.\n */\nexport async function ensureDir(dirPath: string): Promise<void> {\n await fsp.mkdir(dirPath, { recursive: true });\n}\n\n/**\n * Recursively lists all files in a directory.\n *\n * @param {string} dirPath - The base directory.\n * @param {boolean} [recursive=false] - Whether to recurse into subdirectories.\n * @returns {Promise<string[]>} Array of absolute file paths.\n * @throws {Error} If the directory cannot be read.\n */\nexport async function listFiles(dirPath: string, recursive = false): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const files: string[] = [];\n\n for (const entry of entries) {\n const fullPath = path.join(dirPath, entry.name);\n\n if (entry.isFile()) {\n files.push(fullPath);\n } else if (recursive && entry.isDirectory()) {\n const nestedFiles = await listFiles(fullPath, true);\n files.push(...nestedFiles);\n }\n }\n\n return files;\n}\n\n/**\n * Deletes a directory and all its contents recursively (like `rm -rf`).\n *\n * @param {string} dirPath - Directory to delete.\n * @returns {Promise<void>} Resolves when deletion is complete.\n * @throws {Error} If deletion fails.\n */\nexport async function deleteDirRecursive(dirPath: string): Promise<void> {\n await fsp.rm(dirPath, { recursive: true, force: true });\n}\n\n/**\n * Checks whether a given path is a directory.\n *\n * @param {string} pathStr - Path to check.\n * @returns {Promise<boolean>} True if the path is a directory, else false.\n */\nexport async function isDirectory(pathStr: string): Promise<boolean> {\n try {\n const stat = await fsp.stat(pathStr);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Recursively copies a directory and all its contents to a destination.\n *\n * @param {string} src - Source directory path.\n * @param {string} dest - Destination directory path.\n * @returns {Promise<void>} Resolves when copy is complete.\n * @throws {Error} If source does not exist or copy fails.\n */\nexport async function copyDir(src: string, dest: string): Promise<void> {\n await ensureDir(dest);\n const entries = await fsp.readdir(src, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await copyDir(srcPath, destPath);\n } else {\n await fsp.copyFile(srcPath, destPath);\n }\n }\n}\n\n/**\n * Moves a directory to a new location by copying and deleting the original.\n *\n * @param {string} src - Source directory path.\n * @param {string} dest - Destination directory path.\n * @returns {Promise<void>} Resolves when move is complete.\n * @throws {Error} If copy or deletion fails.\n */\nexport async function moveDir(src: string, dest: string): Promise<void> {\n await copyDir(src, dest);\n await deleteDirRecursive(src);\n}\n\n/**\n * Empties a directory by deleting all files and subdirectories inside it.\n *\n * @param {string} dirPath - Path to the directory to empty.\n * @returns {Promise<void>} Resolves when the directory has been emptied.\n * @throws {Error} If files or subdirectories cannot be removed.\n */\nexport async function emptyDir(dirPath: string): Promise<void> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n\n if (entry.isDirectory()) {\n await fsp.rm(entryPath, { recursive: true, force: true });\n } else {\n await fsp.unlink(entryPath);\n }\n }\n}\n\n/**\n * Calculates the total size (in bytes) of all files in a directory (recursive).\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<number>} Total size in bytes.\n * @throws {Error} If any file stats cannot be read.\n */\nexport async function getDirSize(dirPath: string): Promise<number> {\n let total = 0;\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n if (entry.isDirectory()) {\n total += await getDirSize(entryPath);\n } else {\n const stat = await fsp.stat(entryPath);\n total += stat.size;\n }\n }\n\n return total;\n}\n\n/**\n * Watches a directory for file changes and calls a callback on each event.\n *\n * @param {string} dirPath - Directory path to watch.\n * @param {(eventType: \"rename\" | \"change\", filename: string | null) => void} callback - Callback for each change event.\n * @returns {() => void} A function to stop watching the directory.\n */\nexport function watchDir(\n dirPath: string,\n callback: (eventType: 'rename' | 'change', filename: string | null) => void\n): () => void {\n const watcher = fs.watch(dirPath, (eventType, filename) => {\n callback(eventType, filename);\n });\n\n return () => watcher.close();\n}\n\n/**\n * Finds files matching a glob pattern.\n *\n * @param {string} pattern - Glob pattern to match files.\n * @param {object} [options] - Options for glob pattern matching.\n * @param {string} [options.cwd] - Current working directory for relative patterns.\n * @param {boolean} [options.dot=false] - Include dotfiles in matches.\n * @param {boolean} [options.nodir=true] - Only match files, not directories.\n * @returns {Promise<string[]>} Array of matched file paths.\n * @throws {Error} If pattern matching fails.\n */\nexport async function findFilesByPattern(\n pattern: string,\n options: { cwd?: string; dot?: boolean; nodir?: boolean } = {}\n): Promise<string[]> {\n const defaultOptions = { nodir: true, ...options };\n return glob(pattern, defaultOptions);\n}\n\n/**\n * Gets all subdirectories in a directory.\n *\n * @param {string} dirPath - The directory to search in.\n * @param {boolean} [recursive=false] - Whether to include subdirectories recursively.\n * @returns {Promise<string[]>} Array of absolute subdirectory paths.\n * @throws {Error} If directory cannot be read.\n */\nexport async function getSubdirectories(dirPath: string, recursive = false): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const dirs = entries.filter(entry => entry.isDirectory()).map(entry => path.join(dirPath, entry.name));\n\n if (recursive && dirs.length > 0) {\n const nestedDirs = await Promise.all(dirs.map(dir => getSubdirectories(dir, true)));\n return [...dirs, ...nestedDirs.flat()];\n }\n\n return dirs;\n}\n\n/**\n * Ensures a directory exists and is empty.\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<void>} Resolves when the directory exists and is empty.\n * @throws {Error} If directory cannot be created or emptied.\n */\nexport async function ensureEmptyDir(dirPath: string): Promise<void> {\n if (await isDirectory(dirPath)) {\n await emptyDir(dirPath);\n } else {\n try {\n await fsp.unlink(dirPath);\n } catch (error) {\n // Ignore if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n await ensureDir(dirPath);\n }\n}\n\n/**\n * Creates a temporary directory with optional auto-cleanup.\n *\n * @param {object} [options] - Options for the temporary directory.\n * @param {string} [options.prefix='tmp-'] - Prefix for the directory name.\n * @param {string} [options.parentDir=os.tmpdir()] - Parent directory.\n * @param {boolean} [options.cleanup=false] - Whether to register cleanup on process exit.\n * @returns {Promise<{ path: string, cleanup: () => Promise<void> }>} Object with directory path and cleanup function.\n * @throws {Error} If directory cannot be created.\n */\nexport async function createTempDir(\n options: { prefix?: string; parentDir?: string; cleanup?: boolean } = {}\n): Promise<{ path: string; cleanup: () => Promise<void> }> {\n const prefix = options.prefix || 'tmp-';\n const parentDir = options.parentDir || os.tmpdir();\n const dirName = `${prefix}${randomBytes(6).toString('hex')}`;\n const tempDirPath = path.join(parentDir, dirName);\n\n await ensureDir(tempDirPath);\n\n const cleanup = async () => {\n try {\n await deleteDirRecursive(tempDirPath);\n } catch {\n // Ignore cleanup errors\n }\n };\n\n if (options.cleanup) {\n process.once('exit', () => {\n try {\n fs.rmSync(tempDirPath, { recursive: true, force: true });\n } catch {\n // Ignore cleanup errors on exit\n }\n });\n\n // Handle signals for better cleanup\n ['SIGINT', 'SIGTERM', 'SIGUSR1', 'SIGUSR2'].forEach(signal => {\n process.once(signal as NodeJS.Signals, () => {\n cleanup().then(() => process.exit());\n });\n });\n }\n\n return { path: tempDirPath, cleanup };\n}\n\n/**\n * Finds the newest file in a directory.\n *\n * @param {string} dirPath - Directory to search.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string | null>} Path to the newest file or null if no files.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findNewestFile(dirPath: string, recursive = false): Promise<string | null> {\n const files = await listFiles(dirPath, recursive);\n if (files.length === 0) return null;\n\n const stats = await Promise.all(\n files.map(async file => ({\n path: file,\n mtime: (await fsp.stat(file)).mtime\n }))\n );\n\n return stats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime())[0].path;\n}\n\n/**\n * Finds the oldest file in a directory.\n *\n * @param {string} dirPath - Directory to search.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string | null>} Path to the oldest file or null if no files.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findOldestFile(dirPath: string, recursive = false): Promise<string | null> {\n const files = await listFiles(dirPath, recursive);\n if (files.length === 0) return null;\n\n const stats = await Promise.all(\n files.map(async file => ({\n path: file,\n mtime: (await fsp.stat(file)).mtime\n }))\n );\n\n return stats.sort((a, b) => a.mtime.getTime() - b.mtime.getTime())[0].path;\n}\n\n/**\n * Finds files or directories in a directory matching a predicate function.\n *\n * @param {string} dirPath - Directory to search.\n * @param {(path: string, stat: fs.Stats) => boolean | Promise<boolean>} predicate - Function to test each path.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string[]>} Array of matching paths.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findInDir(\n dirPath: string,\n predicate: (path: string, stat: fs.Stats) => boolean | Promise<boolean>,\n recursive = false\n): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const results: string[] = [];\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n const stat = await fsp.stat(entryPath);\n\n if (await predicate(entryPath, stat)) {\n results.push(entryPath);\n }\n\n if (recursive && entry.isDirectory()) {\n const nestedResults = await findInDir(entryPath, predicate, true);\n results.push(...nestedResults);\n }\n }\n\n return results;\n}\n\n/**\n * Watches a directory recursively for file changes.\n *\n * @param {string} dirPath - Base directory path to watch.\n * @param {(eventType: \"rename\" | \"change\", filename: string) => void} callback - Callback for each change event.\n * @param {boolean} [includeSubdirs=true] - Whether to watch subdirectories.\n * @returns {Promise<() => void>} A function to stop watching the directory.\n * @throws {Error} If directory cannot be watched.\n */\nexport async function watchDirRecursive(\n dirPath: string,\n callback: (eventType: 'rename' | 'change', filename: string) => void,\n includeSubdirs = true\n): Promise<() => void> {\n // Normalize the path to ensure consistent path separators\n const normalizedBasePath = path.normalize(dirPath);\n\n // Create watchers for the base dir and all subdirectories\n const watchers: fs.FSWatcher[] = [];\n\n // Helper function to add a watcher for a directory\n const addWatcher = (dir: string) => {\n try {\n const watcher = fs.watch(dir, (eventType, filename) => {\n if (!filename) return;\n\n const fullPath = path.join(dir, filename);\n // Make the path relative to the base directory\n const relativePath = path.relative(normalizedBasePath, fullPath);\n callback(eventType, relativePath);\n\n // If a new directory is created, we should watch it\n if (eventType === 'rename' && includeSubdirs) {\n setTimeout(async () => {\n try {\n if (await isDirectory(fullPath)) {\n addWatcher(fullPath);\n }\n } catch {\n // Ignore errors checking newly created items\n }\n }, 100);\n }\n });\n watchers.push(watcher);\n } catch {\n // Silently ignore directories we can't watch\n }\n };\n\n // Add watcher for the base directory\n addWatcher(normalizedBasePath);\n\n // If watching subdirectories, add watchers for all existing subdirectories\n if (includeSubdirs) {\n const subdirs = await getSubdirectories(normalizedBasePath, true);\n for (const subdir of subdirs) {\n addWatcher(subdir);\n }\n }\n\n // Return a function to close all watchers\n return () => {\n watchers.forEach(watcher => watcher.close());\n };\n}\n\n/**\n * Gets detailed directory statistics including file count, directory count, and size.\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<{ fileCount: number, dirCount: number, totalSize: number }>} Directory statistics.\n * @throws {Error} If directory cannot be read.\n */\nexport async function getDirStats(\n dirPath: string\n): Promise<{ fileCount: number; dirCount: number; totalSize: number }> {\n let fileCount = 0;\n let dirCount = 0;\n let totalSize = 0;\n\n async function processDir(currentPath: string): Promise<void> {\n const entries = await fsp.readdir(currentPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(currentPath, entry.name);\n\n if (entry.isDirectory()) {\n dirCount++;\n await processDir(entryPath);\n } else if (entry.isFile()) {\n fileCount++;\n const stat = await fsp.stat(entryPath);\n totalSize += stat.size;\n }\n }\n }\n\n await processDir(dirPath);\n\n return { fileCount, dirCount, totalSize };\n}\n\n/**\n * Walks through a directory hierarchy, calling a visitor function for each entry.\n *\n * @param {string} dirPath - Starting directory path.\n * @param {object} options - Options for walking the directory.\n * @param {(entry: { path: string, name: string, isDirectory: boolean, stats: fs.Stats }) => boolean | void | Promise<boolean | void>} options.visitorFn -\n * Function called for each file/directory. Return false to skip a directory.\n * @param {'pre' | 'post'} [options.traversalOrder='pre'] - Whether to visit directories before or after their contents.\n * @throws {Error} If directory cannot be read.\n */\nexport async function walkDir(\n dirPath: string,\n options: {\n visitorFn: (entry: {\n path: string;\n name: string;\n isDirectory: boolean;\n stats: fs.Stats;\n }) => boolean | void | Promise<boolean | void>;\n traversalOrder?: 'pre' | 'post';\n }\n): Promise<void> {\n const traversalOrder = options.traversalOrder || 'pre';\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n const stats = await fsp.stat(entryPath);\n const entryInfo = {\n path: entryPath,\n name: entry.name,\n isDirectory: entry.isDirectory(),\n stats\n };\n\n if (entry.isDirectory()) {\n // Pre-order: visit directory before its contents\n if (traversalOrder === 'pre') {\n const shouldContinue = await options.visitorFn(entryInfo);\n // If the visitor returns false, don't recurse into this directory\n if (shouldContinue !== false) {\n await walkDir(entryPath, options);\n }\n } else {\n // Post-order: visit directory after its contents\n await walkDir(entryPath, options);\n await options.visitorFn(entryInfo);\n }\n } else {\n // Files are always visited when encountered\n await options.visitorFn(entryInfo);\n }\n }\n\n if (traversalOrder === 'post') {\n // Only visit the root if this is the top-level call (not for subdirectories)\n // But since this function is always called recursively, always visit after children\n const stats = await fsp.stat(dirPath);\n const entryInfo = {\n path: dirPath,\n name: path.basename(dirPath),\n isDirectory: true,\n stats\n };\n await options.visitorFn(entryInfo);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"dir.utils.js","sourceRoot":"","sources":["../../../src/utils/dir.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,MAAM,IA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,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;gBAC1D,kEAAkE;gBAClE,IAAI,cAAc,KAAK,KAAK,EAAE,CAAC;oBAC7B,MAAM,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;gBACpC,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,iDAAiD;gBACjD,MAAM,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;gBAClC,MAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;YACrC,CAAC;QACH,CAAC;aAAM,CAAC;YACN,4CAA4C;YAC5C,MAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;QACrC,CAAC;IACH,CAAC;IAED,IAAI,cAAc,KAAK,MAAM,EAAE,CAAC;QAC9B,6EAA6E;QAC7E,oFAAoF;QACpF,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACtC,MAAM,SAAS,GAAG;YAChB,IAAI,EAAE,OAAO;YACb,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC;YAC5B,WAAW,EAAE,IAAI;YACjB,KAAK;SACN,CAAC;QACF,MAAM,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;IACrC,CAAC;AACH,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 os from 'os';\nimport fs from 'fs';\nimport fsp from 'fs/promises';\nimport path from 'path';\nimport { glob } from 'glob';\nimport { randomBytes } from 'crypto';\n\n/**\n * Ensures that a directory exists, creating parent directories if needed (like `mkdir -p`).\n *\n * @param {string} dirPath - The directory path to ensure.\n * @returns {Promise<void>} Resolves when the directory exists.\n * @throws {Error} If directory cannot be created.\n */\nexport async function ensureDir(dirPath: string): Promise<void> {\n await fsp.mkdir(dirPath, { recursive: true });\n}\n\n/**\n * Recursively lists all files in a directory.\n *\n * @param {string} dirPath - The base directory.\n * @param {boolean} [recursive=false] - Whether to recurse into subdirectories.\n * @returns {Promise<string[]>} Array of absolute file paths.\n * @throws {Error} If the directory cannot be read.\n */\nexport async function listFiles(dirPath: string, recursive = false): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const files: string[] = [];\n\n for (const entry of entries) {\n const fullPath = path.join(dirPath, entry.name);\n\n if (entry.isFile()) {\n files.push(fullPath);\n } else if (recursive && entry.isDirectory()) {\n const nestedFiles = await listFiles(fullPath, true);\n files.push(...nestedFiles);\n }\n }\n\n return files;\n}\n\n/**\n * Deletes a directory and all its contents recursively (like `rm -rf`).\n *\n * @param {string} dirPath - Directory to delete.\n * @returns {Promise<void>} Resolves when deletion is complete.\n * @throws {Error} If deletion fails.\n */\nexport async function deleteDirRecursive(dirPath: string): Promise<void> {\n await fsp.rm(dirPath, { recursive: true, force: true });\n}\n\n/**\n * Checks whether a given path is a directory.\n *\n * @param {string} pathStr - Path to check.\n * @returns {Promise<boolean>} True if the path is a directory, else false.\n */\nexport async function isDirectory(pathStr: string): Promise<boolean> {\n try {\n const stat = await fsp.stat(pathStr);\n return stat.isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Recursively copies a directory and all its contents to a destination.\n *\n * @param {string} src - Source directory path.\n * @param {string} dest - Destination directory path.\n * @returns {Promise<void>} Resolves when copy is complete.\n * @throws {Error} If source does not exist or copy fails.\n */\nexport async function copyDir(src: string, dest: string): Promise<void> {\n await ensureDir(dest);\n const entries = await fsp.readdir(src, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = path.join(src, entry.name);\n const destPath = path.join(dest, entry.name);\n\n if (entry.isDirectory()) {\n await copyDir(srcPath, destPath);\n } else {\n await fsp.copyFile(srcPath, destPath);\n }\n }\n}\n\n/**\n * Moves a directory to a new location by copying and deleting the original.\n *\n * @param {string} src - Source directory path.\n * @param {string} dest - Destination directory path.\n * @returns {Promise<void>} Resolves when move is complete.\n * @throws {Error} If copy or deletion fails.\n */\nexport async function moveDir(src: string, dest: string): Promise<void> {\n await copyDir(src, dest);\n await deleteDirRecursive(src);\n}\n\n/**\n * Empties a directory by deleting all files and subdirectories inside it.\n *\n * @param {string} dirPath - Path to the directory to empty.\n * @returns {Promise<void>} Resolves when the directory has been emptied.\n * @throws {Error} If files or subdirectories cannot be removed.\n */\nexport async function emptyDir(dirPath: string): Promise<void> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n\n if (entry.isDirectory()) {\n await fsp.rm(entryPath, { recursive: true, force: true });\n } else {\n await fsp.unlink(entryPath);\n }\n }\n}\n\n/**\n * Calculates the total size (in bytes) of all files in a directory (recursive).\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<number>} Total size in bytes.\n * @throws {Error} If any file stats cannot be read.\n */\nexport async function getDirSize(dirPath: string): Promise<number> {\n let total = 0;\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n if (entry.isDirectory()) {\n total += await getDirSize(entryPath);\n } else {\n const stat = await fsp.stat(entryPath);\n total += stat.size;\n }\n }\n\n return total;\n}\n\n/**\n * Watches a directory for file changes and calls a callback on each event.\n *\n * @param {string} dirPath - Directory path to watch.\n * @param {(eventType: \"rename\" | \"change\", filename: string | null) => void} callback - Callback for each change event.\n * @returns {() => void} A function to stop watching the directory.\n */\nexport function watchDir(\n dirPath: string,\n callback: (eventType: 'rename' | 'change', filename: string | null) => void\n): () => void {\n const watcher = fs.watch(dirPath, (eventType, filename) => {\n callback(eventType, filename);\n });\n\n return () => watcher.close();\n}\n\n/**\n * Finds files matching a glob pattern.\n *\n * @param {string} pattern - Glob pattern to match files.\n * @param {object} [options] - Options for glob pattern matching.\n * @param {string} [options.cwd] - Current working directory for relative patterns.\n * @param {boolean} [options.dot=false] - Include dotfiles in matches.\n * @param {boolean} [options.nodir=true] - Only match files, not directories.\n * @returns {Promise<string[]>} Array of matched file paths.\n * @throws {Error} If pattern matching fails.\n */\nexport async function findFilesByPattern(\n pattern: string,\n options: { cwd?: string; dot?: boolean; nodir?: boolean } = {}\n): Promise<string[]> {\n const defaultOptions = { nodir: true, ...options };\n return glob(pattern, defaultOptions);\n}\n\n/**\n * Gets all subdirectories in a directory.\n *\n * @param {string} dirPath - The directory to search in.\n * @param {boolean} [recursive=false] - Whether to include subdirectories recursively.\n * @returns {Promise<string[]>} Array of absolute subdirectory paths.\n * @throws {Error} If directory cannot be read.\n */\nexport async function getSubdirectories(dirPath: string, recursive = false): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const dirs = entries.filter(entry => entry.isDirectory()).map(entry => path.join(dirPath, entry.name));\n\n if (recursive && dirs.length > 0) {\n const nestedDirs = await Promise.all(dirs.map(dir => getSubdirectories(dir, true)));\n return [...dirs, ...nestedDirs.flat()];\n }\n\n return dirs;\n}\n\n/**\n * Ensures a directory exists and is empty.\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<void>} Resolves when the directory exists and is empty.\n * @throws {Error} If directory cannot be created or emptied.\n */\nexport async function ensureEmptyDir(dirPath: string): Promise<void> {\n if (await isDirectory(dirPath)) {\n await emptyDir(dirPath);\n } else {\n try {\n await fsp.unlink(dirPath);\n } catch (error) {\n // Ignore if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n await ensureDir(dirPath);\n }\n}\n\n/**\n * Creates a temporary directory with optional auto-cleanup.\n *\n * @param {object} [options] - Options for the temporary directory.\n * @param {string} [options.prefix='tmp-'] - Prefix for the directory name.\n * @param {string} [options.parentDir=os.tmpdir()] - Parent directory.\n * @param {boolean} [options.cleanup=false] - Whether to register cleanup on process exit.\n * @returns {Promise<{ path: string, cleanup: () => Promise<void> }>} Object with directory path and cleanup function.\n * @throws {Error} If directory cannot be created.\n */\nexport async function createTempDir(\n options: { prefix?: string; parentDir?: string; cleanup?: boolean } = {}\n): Promise<{ path: string; cleanup: () => Promise<void> }> {\n const prefix = options.prefix || 'tmp-';\n const parentDir = options.parentDir || os.tmpdir();\n const dirName = `${prefix}${randomBytes(6).toString('hex')}`;\n const tempDirPath = path.join(parentDir, dirName);\n\n await ensureDir(tempDirPath);\n\n const cleanup = async () => {\n try {\n await deleteDirRecursive(tempDirPath);\n } catch {\n // Ignore cleanup errors\n }\n };\n\n if (options.cleanup) {\n process.once('exit', () => {\n try {\n fs.rmSync(tempDirPath, { recursive: true, force: true });\n } catch {\n // Ignore cleanup errors on exit\n }\n });\n\n // Handle signals for better cleanup\n ['SIGINT', 'SIGTERM', 'SIGUSR1', 'SIGUSR2'].forEach(signal => {\n process.once(signal as NodeJS.Signals, () => {\n cleanup().then(() => process.exit());\n });\n });\n }\n\n return { path: tempDirPath, cleanup };\n}\n\n/**\n * Finds the newest file in a directory.\n *\n * @param {string} dirPath - Directory to search.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string | null>} Path to the newest file or null if no files.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findNewestFile(dirPath: string, recursive = false): Promise<string | null> {\n const files = await listFiles(dirPath, recursive);\n if (files.length === 0) return null;\n\n const stats = await Promise.all(\n files.map(async file => ({\n path: file,\n mtime: (await fsp.stat(file)).mtime\n }))\n );\n\n return stats.sort((a, b) => b.mtime.getTime() - a.mtime.getTime())[0].path;\n}\n\n/**\n * Finds the oldest file in a directory.\n *\n * @param {string} dirPath - Directory to search.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string | null>} Path to the oldest file or null if no files.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findOldestFile(dirPath: string, recursive = false): Promise<string | null> {\n const files = await listFiles(dirPath, recursive);\n if (files.length === 0) return null;\n\n const stats = await Promise.all(\n files.map(async file => ({\n path: file,\n mtime: (await fsp.stat(file)).mtime\n }))\n );\n\n return stats.sort((a, b) => a.mtime.getTime() - b.mtime.getTime())[0].path;\n}\n\n/**\n * Finds files or directories in a directory matching a predicate function.\n *\n * @param {string} dirPath - Directory to search.\n * @param {(path: string, stat: fs.Stats) => boolean | Promise<boolean>} predicate - Function to test each path.\n * @param {boolean} [recursive=false] - Whether to search subdirectories.\n * @returns {Promise<string[]>} Array of matching paths.\n * @throws {Error} If directory cannot be read.\n */\nexport async function findInDir(\n dirPath: string,\n predicate: (path: string, stat: fs.Stats) => boolean | Promise<boolean>,\n recursive = false\n): Promise<string[]> {\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n const results: string[] = [];\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n const stat = await fsp.stat(entryPath);\n\n if (await predicate(entryPath, stat)) {\n results.push(entryPath);\n }\n\n if (recursive && entry.isDirectory()) {\n const nestedResults = await findInDir(entryPath, predicate, true);\n results.push(...nestedResults);\n }\n }\n\n return results;\n}\n\n/**\n * Watches a directory recursively for file changes.\n *\n * @param {string} dirPath - Base directory path to watch.\n * @param {(eventType: \"rename\" | \"change\", filename: string) => void} callback - Callback for each change event.\n * @param {boolean} [includeSubdirs=true] - Whether to watch subdirectories.\n * @returns {Promise<() => void>} A function to stop watching the directory.\n * @throws {Error} If directory cannot be watched.\n */\nexport async function watchDirRecursive(\n dirPath: string,\n callback: (eventType: 'rename' | 'change', filename: string) => void,\n includeSubdirs = true\n): Promise<() => void> {\n // Normalize the path to ensure consistent path separators\n const normalizedBasePath = path.normalize(dirPath);\n\n // Create watchers for the base dir and all subdirectories\n const watchers: fs.FSWatcher[] = [];\n\n // Helper function to add a watcher for a directory\n const addWatcher = (dir: string) => {\n try {\n const watcher = fs.watch(dir, (eventType, filename) => {\n if (!filename) return;\n\n const fullPath = path.join(dir, filename);\n // Make the path relative to the base directory\n const relativePath = path.relative(normalizedBasePath, fullPath);\n callback(eventType, relativePath);\n\n // If a new directory is created, we should watch it\n if (eventType === 'rename' && includeSubdirs) {\n setTimeout(async () => {\n try {\n if (await isDirectory(fullPath)) {\n addWatcher(fullPath);\n }\n } catch {\n // Ignore errors checking newly created items\n }\n }, 100);\n }\n });\n watchers.push(watcher);\n } catch {\n // Silently ignore directories we can't watch\n }\n };\n\n // Add watcher for the base directory\n addWatcher(normalizedBasePath);\n\n // If watching subdirectories, add watchers for all existing subdirectories\n if (includeSubdirs) {\n const subdirs = await getSubdirectories(normalizedBasePath, true);\n for (const subdir of subdirs) {\n addWatcher(subdir);\n }\n }\n\n // Return a function to close all watchers\n return () => {\n watchers.forEach(watcher => watcher.close());\n };\n}\n\n/**\n * Gets detailed directory statistics including file count, directory count, and size.\n *\n * @param {string} dirPath - Path to the directory.\n * @returns {Promise<{ fileCount: number, dirCount: number, totalSize: number }>} Directory statistics.\n * @throws {Error} If directory cannot be read.\n */\nexport async function getDirStats(\n dirPath: string\n): Promise<{ fileCount: number; dirCount: number; totalSize: number }> {\n let fileCount = 0;\n let dirCount = 0;\n let totalSize = 0;\n\n async function processDir(currentPath: string): Promise<void> {\n const entries = await fsp.readdir(currentPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(currentPath, entry.name);\n\n if (entry.isDirectory()) {\n dirCount++;\n await processDir(entryPath);\n } else if (entry.isFile()) {\n fileCount++;\n const stat = await fsp.stat(entryPath);\n totalSize += stat.size;\n }\n }\n }\n\n await processDir(dirPath);\n\n return { fileCount, dirCount, totalSize };\n}\n\n/**\n * Walks through a directory hierarchy, calling a visitor function for each entry.\n *\n * @param {string} dirPath - Starting directory path.\n * @param {object} options - Options for walking the directory.\n * @param {(entry: { path: string, name: string, isDirectory: boolean, stats: fs.Stats }) => boolean | void | Promise<boolean | void>} options.visitorFn -\n * Function called for each file/directory. Return false to skip a directory.\n * @param {'pre' | 'post'} [options.traversalOrder='pre'] - Whether to visit directories before or after their contents.\n * @throws {Error} If directory cannot be read.\n */\nexport async function walkDir(\n dirPath: string,\n options: {\n visitorFn: (entry: {\n path: string;\n name: string;\n isDirectory: boolean;\n stats: fs.Stats;\n }) => boolean | void | Promise<boolean | void>;\n traversalOrder?: 'pre' | 'post';\n }\n): Promise<void> {\n const traversalOrder = options.traversalOrder || 'pre';\n const entries = await fsp.readdir(dirPath, { withFileTypes: true });\n\n for (const entry of entries) {\n const entryPath = path.join(dirPath, entry.name);\n const stats = await fsp.stat(entryPath);\n const entryInfo = {\n path: entryPath,\n name: entry.name,\n isDirectory: entry.isDirectory(),\n stats\n };\n\n if (entry.isDirectory()) {\n // Pre-order: visit directory before its contents\n if (traversalOrder === 'pre') {\n const shouldContinue = await options.visitorFn(entryInfo);\n // If the visitor returns false, don't recurse into this directory\n if (shouldContinue !== false) {\n await walkDir(entryPath, options);\n }\n } else {\n // Post-order: visit directory after its contents\n await walkDir(entryPath, options);\n await options.visitorFn(entryInfo);\n }\n } else {\n // Files are always visited when encountered\n await options.visitorFn(entryInfo);\n }\n }\n\n if (traversalOrder === 'post') {\n // Only visit the root if this is the top-level call (not for subdirectories)\n // But since this function is always called recursively, always visit after children\n const stats = await fsp.stat(dirPath);\n const entryInfo = {\n path: dirPath,\n name: path.basename(dirPath),\n isDirectory: true,\n stats\n };\n await options.visitorFn(entryInfo);\n }\n}\n"]}
|
|
@@ -1,3 +1,26 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The MIT License
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2025 Catbee Technologies
|
|
5
|
+
*
|
|
6
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
* of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
* in the Software without restriction, including without limitation the rights
|
|
9
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
* copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
* furnished to do so, subject to the following conditions:
|
|
12
|
+
*
|
|
13
|
+
* The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
* copies or substantial portions of the Software.
|
|
15
|
+
*
|
|
16
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
* SOFTWARE.
|
|
23
|
+
*/
|
|
1
24
|
/* eslint-disable n/no-process-env */
|
|
2
25
|
import { existsSync, readFileSync } from 'fs';
|
|
3
26
|
import { isAbsolute, resolve } from 'path';
|