@catbee/utils 0.0.8-rc.3 → 0.0.8-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/build/index.cjs +6591 -0
  2. package/build/index.d.ts +5131 -0
  3. package/build/index.mjs +6321 -0
  4. package/package.json +13 -292
  5. package/build/cjs/config.d.ts +0 -121
  6. package/build/cjs/config.js +0 -137
  7. package/build/cjs/index.d.ts +0 -26
  8. package/build/cjs/index.js +0 -68
  9. package/build/cjs/servers/server.builder.d.ts +0 -507
  10. package/build/cjs/servers/server.builder.js +0 -658
  11. package/build/cjs/servers/server.d.ts +0 -255
  12. package/build/cjs/servers/server.js +0 -970
  13. package/build/cjs/types/api-response.d.ts +0 -151
  14. package/build/cjs/types/api-response.js +0 -36
  15. package/build/cjs/types/index.d.ts +0 -124
  16. package/build/cjs/types/index.js +0 -25
  17. package/build/cjs/types/server.d.ts +0 -267
  18. package/build/cjs/types/server.js +0 -25
  19. package/build/cjs/utils/array.utils.d.ts +0 -167
  20. package/build/cjs/utils/array.utils.js +0 -363
  21. package/build/cjs/utils/async.utils.d.ts +0 -264
  22. package/build/cjs/utils/async.utils.js +0 -640
  23. package/build/cjs/utils/cache.utils.d.ts +0 -152
  24. package/build/cjs/utils/cache.utils.js +0 -298
  25. package/build/cjs/utils/context-store.utils.d.ts +0 -188
  26. package/build/cjs/utils/context-store.utils.js +0 -297
  27. package/build/cjs/utils/crypto.utils.d.ts +0 -159
  28. package/build/cjs/utils/crypto.utils.js +0 -295
  29. package/build/cjs/utils/date.utils.d.ts +0 -158
  30. package/build/cjs/utils/date.utils.js +0 -395
  31. package/build/cjs/utils/decorators.utils.d.ts +0 -511
  32. package/build/cjs/utils/decorators.utils.js +0 -1035
  33. package/build/cjs/utils/dir.utils.d.ts +0 -195
  34. package/build/cjs/utils/dir.utils.js +0 -500
  35. package/build/cjs/utils/env.utils.d.ts +0 -376
  36. package/build/cjs/utils/env.utils.js +0 -786
  37. package/build/cjs/utils/exception.utils.d.ts +0 -229
  38. package/build/cjs/utils/exception.utils.js +0 -408
  39. package/build/cjs/utils/fs.utils.d.ts +0 -163
  40. package/build/cjs/utils/fs.utils.js +0 -371
  41. package/build/cjs/utils/http-status-codes.d.ts +0 -265
  42. package/build/cjs/utils/http-status-codes.js +0 -297
  43. package/build/cjs/utils/id.utils.d.ts +0 -35
  44. package/build/cjs/utils/id.utils.js +0 -90
  45. package/build/cjs/utils/logger.utils.d.ts +0 -159
  46. package/build/cjs/utils/logger.utils.js +0 -350
  47. package/build/cjs/utils/middleware.utils.d.ts +0 -99
  48. package/build/cjs/utils/middleware.utils.js +0 -243
  49. package/build/cjs/utils/obj.utils.d.ts +0 -123
  50. package/build/cjs/utils/obj.utils.js +0 -428
  51. package/build/cjs/utils/performance.utils.d.ts +0 -135
  52. package/build/cjs/utils/performance.utils.js +0 -280
  53. package/build/cjs/utils/request.utils.d.ts +0 -85
  54. package/build/cjs/utils/request.utils.js +0 -199
  55. package/build/cjs/utils/response.utils.d.ts +0 -162
  56. package/build/cjs/utils/response.utils.js +0 -274
  57. package/build/cjs/utils/stream.utils.d.ts +0 -87
  58. package/build/cjs/utils/stream.utils.js +0 -217
  59. package/build/cjs/utils/string.utils.d.ts +0 -92
  60. package/build/cjs/utils/string.utils.js +0 -178
  61. package/build/cjs/utils/type.utils.d.ts +0 -89
  62. package/build/cjs/utils/type.utils.js +0 -195
  63. package/build/cjs/utils/url.utils.d.ts +0 -140
  64. package/build/cjs/utils/url.utils.js +0 -316
  65. package/build/cjs/utils/validate.utils.d.ts +0 -176
  66. package/build/cjs/utils/validate.utils.js +0 -344
  67. package/build/esm/config.d.ts +0 -121
  68. package/build/esm/config.js +0 -132
  69. package/build/esm/index.d.ts +0 -26
  70. package/build/esm/index.js +0 -49
  71. package/build/esm/servers/server.builder.d.ts +0 -507
  72. package/build/esm/servers/server.builder.js +0 -654
  73. package/build/esm/servers/server.d.ts +0 -255
  74. package/build/esm/servers/server.js +0 -963
  75. package/build/esm/types/api-response.d.ts +0 -151
  76. package/build/esm/types/api-response.js +0 -33
  77. package/build/esm/types/index.d.ts +0 -124
  78. package/build/esm/types/index.js +0 -24
  79. package/build/esm/types/server.d.ts +0 -267
  80. package/build/esm/types/server.js +0 -24
  81. package/build/esm/utils/array.utils.d.ts +0 -167
  82. package/build/esm/utils/array.utils.js +0 -344
  83. package/build/esm/utils/async.utils.d.ts +0 -264
  84. package/build/esm/utils/async.utils.js +0 -619
  85. package/build/esm/utils/cache.utils.d.ts +0 -152
  86. package/build/esm/utils/cache.utils.js +0 -294
  87. package/build/esm/utils/context-store.utils.d.ts +0 -188
  88. package/build/esm/utils/context-store.utils.js +0 -290
  89. package/build/esm/utils/crypto.utils.d.ts +0 -159
  90. package/build/esm/utils/crypto.utils.js +0 -278
  91. package/build/esm/utils/date.utils.d.ts +0 -158
  92. package/build/esm/utils/date.utils.js +0 -383
  93. package/build/esm/utils/decorators.utils.d.ts +0 -511
  94. package/build/esm/utils/decorators.utils.js +0 -1013
  95. package/build/esm/utils/dir.utils.d.ts +0 -195
  96. package/build/esm/utils/dir.utils.js +0 -476
  97. package/build/esm/utils/env.utils.d.ts +0 -376
  98. package/build/esm/utils/env.utils.js +0 -782
  99. package/build/esm/utils/exception.utils.d.ts +0 -229
  100. package/build/esm/utils/exception.utils.js +0 -382
  101. package/build/esm/utils/fs.utils.d.ts +0 -163
  102. package/build/esm/utils/fs.utils.js +0 -348
  103. package/build/esm/utils/http-status-codes.d.ts +0 -265
  104. package/build/esm/utils/http-status-codes.js +0 -294
  105. package/build/esm/utils/id.utils.d.ts +0 -35
  106. package/build/esm/utils/id.utils.js +0 -83
  107. package/build/esm/utils/logger.utils.d.ts +0 -159
  108. package/build/esm/utils/logger.utils.js +0 -304
  109. package/build/esm/utils/middleware.utils.d.ts +0 -99
  110. package/build/esm/utils/middleware.utils.js +0 -235
  111. package/build/esm/utils/obj.utils.d.ts +0 -123
  112. package/build/esm/utils/obj.utils.js +0 -412
  113. package/build/esm/utils/performance.utils.d.ts +0 -135
  114. package/build/esm/utils/performance.utils.js +0 -273
  115. package/build/esm/utils/request.utils.d.ts +0 -85
  116. package/build/esm/utils/request.utils.js +0 -190
  117. package/build/esm/utils/response.utils.d.ts +0 -162
  118. package/build/esm/utils/response.utils.js +0 -261
  119. package/build/esm/utils/stream.utils.d.ts +0 -87
  120. package/build/esm/utils/stream.utils.js +0 -209
  121. package/build/esm/utils/string.utils.d.ts +0 -92
  122. package/build/esm/utils/string.utils.js +0 -164
  123. package/build/esm/utils/type.utils.d.ts +0 -89
  124. package/build/esm/utils/type.utils.js +0 -186
  125. package/build/esm/utils/url.utils.d.ts +0 -140
  126. package/build/esm/utils/url.utils.js +0 -303
  127. package/build/esm/utils/validate.utils.d.ts +0 -176
  128. package/build/esm/utils/validate.utils.js +0 -319
@@ -1,186 +0,0 @@
1
- /*
2
- * The MIT License
3
- *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
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
- */
24
- /**
25
- * Check if a value is of a specific primitive type.
26
- *
27
- * @param value - Value to check
28
- * @param type - Type to check against
29
- * @returns Whether the value is of the specified type
30
- *
31
- * @example
32
- * ```typescript
33
- * isPrimitiveType('hello', 'string'); // true
34
- * isPrimitiveType(42, 'number'); // true
35
- * isPrimitiveType(true, 'boolean'); // true
36
- * isPrimitiveType(null, 'null'); // true
37
- * isPrimitiveType(undefined, 'undefined'); // true
38
- * isPrimitiveType({}, 'object'); // true
39
- * isPrimitiveType([], 'array'); // true
40
- * ```
41
- */
42
- export function isPrimitiveType(value, type) {
43
- if (type === 'array') {
44
- return Array.isArray(value);
45
- }
46
- if (type === 'null') {
47
- return value === null;
48
- }
49
- if (type === 'undefined') {
50
- return value === undefined;
51
- }
52
- if (type === 'object') {
53
- // Only plain objects, not arrays or null
54
- return typeof value === 'object' && value !== null && !Array.isArray(value);
55
- }
56
- return typeof value === type;
57
- }
58
- /**
59
- * Get the primitive type of a value as a string.
60
- *
61
- * @param value - Value to get the type of
62
- * @returns String representing the type
63
- *
64
- * @example
65
- * ```typescript
66
- * getTypeOf('hello'); // 'string'
67
- * getTypeOf(42); // 'number'
68
- * getTypeOf([]); // 'array'
69
- * getTypeOf(null); // 'null'
70
- * ```
71
- */
72
- export function getTypeOf(value) {
73
- if (value === null)
74
- return 'null';
75
- if (value === undefined)
76
- return 'undefined';
77
- if (Array.isArray(value))
78
- return 'array';
79
- return typeof value;
80
- }
81
- /**
82
- * Type guard for checking if a value is an array of a specific type.
83
- *
84
- * @param value - Value to check
85
- * @param itemTypeGuard - Function that checks if items are of the expected type
86
- * @returns True if the value is an array with items of the expected type
87
- *
88
- * @example
89
- * ```typescript
90
- * isArrayOf([1, 2, 3], (item): item is number => typeof item === 'number'); // true
91
- * isArrayOf(['a', 'b', 'c'], (item): item is string => typeof item === 'string'); // true
92
- * isArrayOf([1, '2', 3], (item): item is number => typeof item === 'number'); // false
93
- * ```
94
- */
95
- export function isArrayOf(value, itemTypeGuard) {
96
- if (!Array.isArray(value))
97
- return false;
98
- return value.every(item => itemTypeGuard(item));
99
- }
100
- /**
101
- * Convert a value to a string.
102
- *
103
- * @param value - Value to convert
104
- * @param defaultValue - Default value if conversion fails
105
- * @returns String representation of the value
106
- */
107
- export function toStr(value, defaultValue = '') {
108
- if (value === null || value === undefined)
109
- return defaultValue;
110
- try {
111
- if (typeof value === 'object') {
112
- return JSON.stringify(value);
113
- }
114
- return String(value);
115
- }
116
- catch {
117
- return defaultValue;
118
- }
119
- }
120
- /**
121
- * Convert a value to a number.
122
- *
123
- * @param value - Value to convert
124
- * @param defaultValue - Default value if conversion fails
125
- * @returns Numeric representation of the value
126
- */
127
- export function toNum(value, defaultValue = 0) {
128
- if (value === null || value === undefined)
129
- return defaultValue;
130
- if (typeof value === 'number')
131
- return value;
132
- try {
133
- const num = Number(value);
134
- return isNaN(num) ? defaultValue : num;
135
- }
136
- catch {
137
- return defaultValue;
138
- }
139
- }
140
- /**
141
- * Convert a value to a boolean.
142
- *
143
- * @param value - Value to convert
144
- * @param defaultValue - Default value if conversion fails
145
- * @returns Boolean representation of the value
146
- */
147
- export function toBool(value, defaultValue = false) {
148
- if (value === null || value === undefined)
149
- return defaultValue;
150
- if (typeof value === 'boolean')
151
- return value;
152
- if (typeof value === 'string') {
153
- const lowercased = value.toLowerCase();
154
- if (lowercased === 'true' || lowercased === 'yes' || lowercased === 'y' || lowercased === '1') {
155
- return true;
156
- }
157
- if (lowercased === 'false' || lowercased === 'no' || lowercased === 'n' || lowercased === '0') {
158
- return false;
159
- }
160
- }
161
- if (typeof value === 'number') {
162
- return value !== 0;
163
- }
164
- return defaultValue;
165
- }
166
- /**
167
- * Ensure a value matches the expected type, or provide a default.
168
- *
169
- * @param value - Value to check
170
- * @param expectedType - Expected primitive type
171
- * @param defaultValue - Default value to use if type doesn't match
172
- * @returns The value if it matches the type, otherwise the default
173
- *
174
- * @example
175
- * ```typescript
176
- * ensureType(42, 'number', 0); // 42
177
- * ensureType('42', 'number', 0); // 0
178
- * ensureType(undefined, 'string', 'default'); // 'default'
179
- * ```
180
- */
181
- export function ensureType(value, expectedType, defaultValue) {
182
- if (getTypeOf(value) === expectedType) {
183
- return value;
184
- }
185
- return defaultValue;
186
- }
@@ -1,140 +0,0 @@
1
- /**
2
- * Appends query parameters to a given URL.
3
- *
4
- * @param {string} url - The base URL to which query parameters will be appended.
5
- * @param {Record<string, string | number>} params - Key-value pairs to add as query parameters.
6
- * @returns {string} The new URL string with query parameters appended.
7
- *
8
- * @example
9
- * appendQueryParams('https://example.com', { page: 1, limit: 10 });
10
- * // → 'https://example.com/?page=1&limit=10'
11
- */
12
- export declare function appendQueryParams(url: string, params: Record<string, string | number>): string;
13
- /**
14
- * Parses a query string into a key-value object.
15
- *
16
- * @param {string} query - The query string (with or without leading '?').
17
- * @returns {Record<string, string>} Object representing parsed query parameters.
18
- *
19
- * @example
20
- * parseQueryString('?page=1&limit=10');
21
- * // → { page: '1', limit: '10' }
22
- */
23
- export declare function parseQueryString(query: string): Record<string, string>;
24
- /**
25
- * Validates if a string is a valid URL.
26
- *
27
- * @param {string} url - The URL string to validate.
28
- * @param {boolean} [requireHttps=false] - If true, requires the URL to use HTTPS.
29
- * @returns {boolean} True if the URL is valid, false otherwise.
30
- */
31
- export declare function isValidUrl(url: string, requireHttps?: boolean): boolean;
32
- /**
33
- * Extracts the domain name from a URL.
34
- *
35
- * @param {string} url - The URL to extract the domain from.
36
- * @param {boolean} [removeSubdomains=false] - If true, removes subdomains (returns root domain only).
37
- * @returns {string} The domain name.
38
- *
39
- * @example
40
- * getDomain('https://api.example.com/path');
41
- * // → 'api.example.com'
42
- *
43
- * getDomain('https://api.example.com/path', true);
44
- * // → 'example.com'
45
- */
46
- export declare function getDomain(url: string, removeSubdomains?: boolean): string;
47
- /**
48
- * Joins URL paths properly handling slashes.
49
- *
50
- * @param {...string[]} segments - URL path segments to join.
51
- * @returns {string} Joined URL path.
52
- *
53
- * @example
54
- * joinPaths('https://example.com/', '/api/', '/users');
55
- * // → 'https://example.com/api/users'
56
- */
57
- export declare function joinPaths(...segments: string[]): string;
58
- /**
59
- * Normalizes a URL by resolving relative paths, handling protocol-relative URLs, etc.
60
- *
61
- * @param {string} url - The URL to normalize.
62
- * @param {string} [base] - Optional base URL for resolving relative URLs.
63
- * @returns {string} Normalized URL.
64
- *
65
- * @example
66
- * normalizeUrl('HTTP://Example.COM/foo/../bar');
67
- * // → 'http://example.com/bar'
68
- */
69
- export declare function normalizeUrl(url: string, base?: string): string;
70
- /**
71
- * Creates a URL builder for constructing URLs with a base URL.
72
- *
73
- * @param {string} baseUrl - The base URL to build upon.
74
- * @returns {Object} URL builder methods.
75
- *
76
- * @example
77
- * const api = createUrlBuilder('https://api.example.com');
78
- * api.path('/users', { active: true });
79
- * // → 'https://api.example.com/users?active=true'
80
- */
81
- export declare function createUrlBuilder(baseUrl: string): {
82
- /**
83
- * Creates a full URL with the given path and query parameters.
84
- *
85
- * @param {string} path - The path to append to the base URL.
86
- * @param {Record<string, any>} [params] - Query parameters to add.
87
- * @returns {string} The complete URL.
88
- */
89
- path(path: string, params?: Record<string, any>): string;
90
- /**
91
- * Creates a full URL with query parameters but no additional path.
92
- *
93
- * @param {Record<string, any>} params - Query parameters to add.
94
- * @returns {string} The complete URL with query parameters.
95
- */
96
- query(params: Record<string, any>): string;
97
- };
98
- /**
99
- * Extracts specific query parameters from a URL.
100
- *
101
- * @param {string} url - The URL to extract parameters from.
102
- * @param {string[]} paramNames - Names of parameters to extract.
103
- * @returns {Record<string, string>} Object containing the extracted parameters.
104
- */
105
- export declare function extractQueryParams(url: string, paramNames: string[]): Record<string, string>;
106
- /**
107
- * Removes specified query parameters from a URL.
108
- *
109
- * @param {string} url - The URL to modify.
110
- * @param {string[]} paramsToRemove - Names of parameters to remove.
111
- * @returns {string} URL with parameters removed.
112
- */
113
- export declare function removeQueryParams(url: string, paramsToRemove: string[]): string;
114
- /**
115
- * Gets the file extension from a URL path.
116
- *
117
- * @param {string} url - The URL to examine.
118
- * @returns {string} The file extension (without dot) or empty string if none found.
119
- *
120
- * @example
121
- * getExtension('https://example.com/document.pdf?v=1');
122
- * // → 'pdf'
123
- */
124
- export declare function getExtension(url: string): string;
125
- /**
126
- * Parses URL query parameters into a strongly-typed object.
127
- *
128
- * @template T Expected type of the query parameters
129
- * @param {string} url - The URL to parse.
130
- * @param {Record<keyof T, (val: string) => any>} [converters] - Type converters for params.
131
- * @returns {Partial<T>} Typed query parameters.
132
- *
133
- * @example
134
- * parseTypedQueryParams<{page: number, q: string}>('https://example.com?page=2&q=test', {
135
- * page: Number,
136
- * q: String
137
- * });
138
- * // → { page: 2, q: 'test' }
139
- */
140
- export declare function parseTypedQueryParams<T extends Record<string, any>>(url: string, converters?: Record<keyof T, (val: string) => any>): Partial<T>;
@@ -1,303 +0,0 @@
1
- /*
2
- * The MIT License
3
- *
4
- * Copyright (c) 2025 Catbee Technologies. https://catbee-utils.npm.hprasath.com/license
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
- */
24
- import { URL, URLSearchParams } from 'url';
25
- /**
26
- * Appends query parameters to a given URL.
27
- *
28
- * @param {string} url - The base URL to which query parameters will be appended.
29
- * @param {Record<string, string | number>} params - Key-value pairs to add as query parameters.
30
- * @returns {string} The new URL string with query parameters appended.
31
- *
32
- * @example
33
- * appendQueryParams('https://example.com', { page: 1, limit: 10 });
34
- * // → 'https://example.com/?page=1&limit=10'
35
- */
36
- export function appendQueryParams(url, params) {
37
- const urlObj = new URL(url);
38
- for (const [key, value] of Object.entries(params)) {
39
- urlObj.searchParams.set(key, value.toString());
40
- }
41
- return urlObj.toString();
42
- }
43
- /**
44
- * Parses a query string into a key-value object.
45
- *
46
- * @param {string} query - The query string (with or without leading '?').
47
- * @returns {Record<string, string>} Object representing parsed query parameters.
48
- *
49
- * @example
50
- * parseQueryString('?page=1&limit=10');
51
- * // → { page: '1', limit: '10' }
52
- */
53
- export function parseQueryString(query) {
54
- const cleanQuery = query.startsWith('?') ? query.slice(1) : query;
55
- // Object.fromEntries guarantees string values in result
56
- return Object.fromEntries(new URLSearchParams(cleanQuery));
57
- }
58
- /**
59
- * Validates if a string is a valid URL.
60
- *
61
- * @param {string} url - The URL string to validate.
62
- * @param {boolean} [requireHttps=false] - If true, requires the URL to use HTTPS.
63
- * @returns {boolean} True if the URL is valid, false otherwise.
64
- */
65
- export function isValidUrl(url, requireHttps = false) {
66
- try {
67
- const parsedUrl = new URL(url);
68
- if (!parsedUrl.protocol || !parsedUrl.hostname)
69
- return false;
70
- if (requireHttps && parsedUrl.protocol !== 'https:')
71
- return false;
72
- return true;
73
- }
74
- catch {
75
- return false;
76
- }
77
- }
78
- /**
79
- * Extracts the domain name from a URL.
80
- *
81
- * @param {string} url - The URL to extract the domain from.
82
- * @param {boolean} [removeSubdomains=false] - If true, removes subdomains (returns root domain only).
83
- * @returns {string} The domain name.
84
- *
85
- * @example
86
- * getDomain('https://api.example.com/path');
87
- * // → 'api.example.com'
88
- *
89
- * getDomain('https://api.example.com/path', true);
90
- * // → 'example.com'
91
- */
92
- export function getDomain(url, removeSubdomains = false) {
93
- try {
94
- const { hostname } = new URL(url);
95
- if (!removeSubdomains) {
96
- return hostname;
97
- }
98
- // Extract root domain (remove subdomains)
99
- const parts = hostname.split('.');
100
- if (parts.length <= 2)
101
- return hostname;
102
- // Handle special cases like co.in, com.au
103
- const secondLevelDomains = ['co', 'com', 'org', 'net', 'gov', 'edu', 'ac'];
104
- const sld = parts[parts.length - 2];
105
- if (secondLevelDomains.includes(sld) && parts.length > 2) {
106
- return parts.slice(-3).join('.');
107
- }
108
- return parts.slice(-2).join('.');
109
- }
110
- catch {
111
- return '';
112
- }
113
- }
114
- /**
115
- * Joins URL paths properly handling slashes.
116
- *
117
- * @param {...string[]} segments - URL path segments to join.
118
- * @returns {string} Joined URL path.
119
- *
120
- * @example
121
- * joinPaths('https://example.com/', '/api/', '/users');
122
- * // → 'https://example.com/api/users'
123
- */
124
- export function joinPaths(...segments) {
125
- let result = segments
126
- .filter(s => s !== undefined && s !== null)
127
- .map((segment, index) => {
128
- if (index === 0)
129
- return segment.replace(/\/+$/, '');
130
- return segment.replace(/^\/+|\/+$/g, '');
131
- })
132
- .filter(Boolean)
133
- .join('/');
134
- if (segments[0] === '' && !result.startsWith('/'))
135
- result = '/' + result;
136
- return result;
137
- }
138
- /**
139
- * Normalizes a URL by resolving relative paths, handling protocol-relative URLs, etc.
140
- *
141
- * @param {string} url - The URL to normalize.
142
- * @param {string} [base] - Optional base URL for resolving relative URLs.
143
- * @returns {string} Normalized URL.
144
- *
145
- * @example
146
- * normalizeUrl('HTTP://Example.COM/foo/../bar');
147
- * // → 'http://example.com/bar'
148
- */
149
- export function normalizeUrl(url, base) {
150
- try {
151
- // Handle protocol-relative URLs
152
- if (url.startsWith('//')) {
153
- url = `https:${url}`;
154
- }
155
- // Resolve relative URLs against a base
156
- const parsedUrl = base ? new URL(url, base) : new URL(url);
157
- // Normalize
158
- parsedUrl.pathname = parsedUrl.pathname.replace(/\/+/g, '/'); // Collapse multiple slashes
159
- parsedUrl.pathname = parsedUrl.pathname.replace(/\/+$/, ''); // Remove trailing slash
160
- parsedUrl.hostname = parsedUrl.hostname.toLowerCase();
161
- return parsedUrl.toString();
162
- }
163
- catch {
164
- return url; // Return original if invalid
165
- }
166
- }
167
- /**
168
- * Creates a URL builder for constructing URLs with a base URL.
169
- *
170
- * @param {string} baseUrl - The base URL to build upon.
171
- * @returns {Object} URL builder methods.
172
- *
173
- * @example
174
- * const api = createUrlBuilder('https://api.example.com');
175
- * api.path('/users', { active: true });
176
- * // → 'https://api.example.com/users?active=true'
177
- */
178
- export function createUrlBuilder(baseUrl) {
179
- return {
180
- /**
181
- * Creates a full URL with the given path and query parameters.
182
- *
183
- * @param {string} path - The path to append to the base URL.
184
- * @param {Record<string, any>} [params] - Query parameters to add.
185
- * @returns {string} The complete URL.
186
- */
187
- path(path, params) {
188
- const url = joinPaths(baseUrl, path);
189
- return params ? appendQueryParams(url, params) : url;
190
- },
191
- /**
192
- * Creates a full URL with query parameters but no additional path.
193
- *
194
- * @param {Record<string, any>} params - Query parameters to add.
195
- * @returns {string} The complete URL with query parameters.
196
- */
197
- query(params) {
198
- return appendQueryParams(baseUrl, params);
199
- }
200
- };
201
- }
202
- /**
203
- * Extracts specific query parameters from a URL.
204
- *
205
- * @param {string} url - The URL to extract parameters from.
206
- * @param {string[]} paramNames - Names of parameters to extract.
207
- * @returns {Record<string, string>} Object containing the extracted parameters.
208
- */
209
- export function extractQueryParams(url, paramNames) {
210
- try {
211
- const parsedUrl = new URL(url);
212
- const result = {};
213
- for (const name of paramNames) {
214
- const value = parsedUrl.searchParams.get(name);
215
- if (value !== null) {
216
- result[name] = value;
217
- }
218
- }
219
- return result;
220
- }
221
- catch {
222
- return {};
223
- }
224
- }
225
- /**
226
- * Removes specified query parameters from a URL.
227
- *
228
- * @param {string} url - The URL to modify.
229
- * @param {string[]} paramsToRemove - Names of parameters to remove.
230
- * @returns {string} URL with parameters removed.
231
- */
232
- export function removeQueryParams(url, paramsToRemove) {
233
- try {
234
- const parsedUrl = new URL(url);
235
- for (const param of paramsToRemove) {
236
- parsedUrl.searchParams.delete(param);
237
- }
238
- return parsedUrl.toString();
239
- }
240
- catch {
241
- return url;
242
- }
243
- }
244
- /**
245
- * Gets the file extension from a URL path.
246
- *
247
- * @param {string} url - The URL to examine.
248
- * @returns {string} The file extension (without dot) or empty string if none found.
249
- *
250
- * @example
251
- * getExtension('https://example.com/document.pdf?v=1');
252
- * // → 'pdf'
253
- */
254
- export function getExtension(url) {
255
- try {
256
- const { pathname } = new URL(url);
257
- const match = pathname.match(/\.([^./\\?#]+)$/);
258
- return match ? match[1].toLowerCase() : '';
259
- }
260
- catch {
261
- // If URL parsing fails, try a simpler approach
262
- const match = url.match(/\.([^./\\?#]+)$/);
263
- return match ? match[1].toLowerCase() : '';
264
- }
265
- }
266
- /**
267
- * Parses URL query parameters into a strongly-typed object.
268
- *
269
- * @template T Expected type of the query parameters
270
- * @param {string} url - The URL to parse.
271
- * @param {Record<keyof T, (val: string) => any>} [converters] - Type converters for params.
272
- * @returns {Partial<T>} Typed query parameters.
273
- *
274
- * @example
275
- * parseTypedQueryParams<{page: number, q: string}>('https://example.com?page=2&q=test', {
276
- * page: Number,
277
- * q: String
278
- * });
279
- * // → { page: 2, q: 'test' }
280
- */
281
- export function parseTypedQueryParams(url, converters) {
282
- try {
283
- const { searchParams } = new URL(url);
284
- const result = {};
285
- for (const [key, value] of searchParams.entries()) {
286
- if (converters && key in converters) {
287
- try {
288
- result[key] = converters[key](value);
289
- }
290
- catch {
291
- // Skip on conversion error
292
- }
293
- }
294
- else {
295
- result[key] = value;
296
- }
297
- }
298
- return result;
299
- }
300
- catch {
301
- return {};
302
- }
303
- }