@germondai/ts-utils 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,15 @@
1
+ # @germondai/ts-utils
2
+
3
+ To install dependencies:
4
+
5
+ ```bash
6
+ bun install
7
+ ```
8
+
9
+ To run:
10
+
11
+ ```bash
12
+ bun run index.ts
13
+ ```
14
+
15
+ This project was created using `bun init` in bun v1.2.2. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
@@ -0,0 +1 @@
1
+ export * from './runtime';
package/dist/module.js ADDED
@@ -0,0 +1,244 @@
1
+ // src/runtime/collection.ts
2
+ var hasDuplicates = (array, keyExtractor) => {
3
+ const seen = new Set;
4
+ for (const item of array) {
5
+ const key = keyExtractor ? keyExtractor(item) : item;
6
+ if (seen.has(key))
7
+ return true;
8
+ seen.add(key);
9
+ }
10
+ return false;
11
+ };
12
+ var uniqueArray = (array) => [...new Set(array)];
13
+ // src/runtime/constants.ts
14
+ var SUPPORTED_DISPLAYABLE_MEDIA_TYPES = {
15
+ images: [
16
+ "image/jpeg",
17
+ "image/png",
18
+ "image/gif",
19
+ "image/webp",
20
+ "image/svg+xml",
21
+ "image/avif",
22
+ "image/apng"
23
+ ],
24
+ videos: [
25
+ "video/mp4",
26
+ "video/webm",
27
+ "video/ogg",
28
+ "video/quicktime"
29
+ ]
30
+ };
31
+ // src/runtime/convertor.ts
32
+ var toCamelCase = (input) => {
33
+ const words = input.toLowerCase().split(/[\s_-]+/).filter(Boolean);
34
+ return words.map((word, index) => index === 0 ? word : word.charAt(0).toUpperCase() + word.slice(1)).join("");
35
+ };
36
+ var toPascalCase = (input) => input.toLowerCase().split(/[\s_-]+/).filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
37
+ var toSnakeCase = (input) => input.toLowerCase().split(/[\s-]+/).filter(Boolean).join("_");
38
+ var toKebabCase = (input) => input.toLowerCase().split(/[\s_]+/).filter(Boolean).join("-");
39
+ var toTitleCase = (input) => input.toLowerCase().split(/\s+/).filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
40
+ var toSentenceCase = (input) => {
41
+ const lower = input.toLowerCase();
42
+ return lower.charAt(0).toUpperCase() + lower.slice(1);
43
+ };
44
+ var toConstantCase = (input) => toSnakeCase(input).toUpperCase();
45
+ var toggleCase = (input) => input.split("").map((char) => char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase()).join("");
46
+ var capitalize = (str) => str.length > 0 ? str.charAt(0).toUpperCase() + str.slice(1).toLowerCase() : str;
47
+ var truncate = (text, maxLength, ellipsis = false) => {
48
+ if (text.length <= maxLength)
49
+ return text;
50
+ return ellipsis ? text.slice(0, maxLength - 3) + "..." : text.slice(0, maxLength);
51
+ };
52
+ var slugify = (title, length = 64) => title.toString().normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim().replace(/\s+/g, "-").replace(/[^\w-]+/g, "").replace(/--+/g, "-").replace(/^-+/, "").replace(/-+$/, "").slice(0, length);
53
+ var stripTags = (html) => html.replace(/<\/?[^>]+(>|$)/g, "");
54
+ var escapeHTML = (str) => {
55
+ const escapeMap = {
56
+ "&": "&amp;",
57
+ "<": "&lt;",
58
+ ">": "&gt;",
59
+ '"': "&quot;",
60
+ "'": "&#039;"
61
+ };
62
+ return str.replace(/[&<>"']/g, (char) => escapeMap[char] || char);
63
+ };
64
+ // src/runtime/data.ts
65
+ var clone = (data) => JSON.parse(JSON.stringify(data));
66
+ // src/runtime/errors.ts
67
+ var catchError = (promise, errorsToCatch) => promise().then((data) => ({ data, ok: true })).catch((error) => {
68
+ if (errorsToCatch === undefined || errorsToCatch.some((e) => error instanceof e))
69
+ return { error, ok: false };
70
+ throw error;
71
+ });
72
+ // src/runtime/math.ts
73
+ var rand = (n, m = 0) => Math.floor(Math.random() * (m - n + 1)) + n;
74
+ var percentage = (value, maxValue, decimalPlaces = 2) => {
75
+ if (maxValue === 0)
76
+ return 0;
77
+ const percent = value / maxValue * 100;
78
+ return Number(percent.toFixed(decimalPlaces));
79
+ };
80
+ var clamp = (num, min, max) => Math.min(Math.max(num, min), max);
81
+ var formatNumber = (num) => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
82
+ // src/runtime/media.ts
83
+ var isSupportedDisplayableMedia = (mime, type = { image: true, video: true }) => type.image && SUPPORTED_DISPLAYABLE_MEDIA_TYPES.images.includes(mime) || type.video && SUPPORTED_DISPLAYABLE_MEDIA_TYPES.videos.includes(mime);
84
+ // src/runtime/promise.ts
85
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
86
+ // src/runtime/regex.ts
87
+ var isEmail = (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
88
+ var isUrl = (value) => /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/.test(value);
89
+ var isPhoneNumber = (value) => /^\+?(\d{1,3})?[-. (]*\d{1,4}[-. )]*\d{1,4}[-. ]*\d{1,9}$/.test(value);
90
+ var isHex = (value) => /^[A-Fa-f0-9]+$/.test(value);
91
+ var isHexColor = (value) => /^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{6})$/.test(value);
92
+ var isIPv4 = (value) => /^(25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|1?[0-9][0-9]?)$/.test(value);
93
+ var isIPv6 = (value) => /^(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}$/i.test(value);
94
+ var isMacAddress = (value) => /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/.test(value);
95
+ var isUUID = (value) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
96
+ var isCreditCard = (value) => /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9]{2})[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/.test(value);
97
+ var isDomain = (value) => /^(?!:\/\/)([a-zA-Z0-9-_]{1,63}\.)+[a-zA-Z]{2,63}$/.test(value);
98
+ var isPostalCode = (value) => /^[A-Za-z0-9\s-]{3,10}$/.test(value);
99
+ var isISODate = (value) => /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/.test(value);
100
+ var isJson = (value) => {
101
+ try {
102
+ JSON.parse(value);
103
+ return true;
104
+ } catch {
105
+ return false;
106
+ }
107
+ };
108
+ var isBase64 = (value) => /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value);
109
+ var isSlug = (value) => /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value);
110
+ // src/runtime/size.ts
111
+ var formatBytes = (bytes, decimals = 2) => {
112
+ if (bytes === 0)
113
+ return "0 Bytes";
114
+ const k = 1024;
115
+ const dm = decimals < 0 ? 0 : decimals;
116
+ const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"];
117
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
118
+ const size = parseFloat((bytes / Math.pow(k, i)).toFixed(dm));
119
+ return `${size} ${sizes[i]}`;
120
+ };
121
+ // src/runtime/time.ts
122
+ var formatTime = (seconds) => {
123
+ const hours = Math.floor(seconds / 3600);
124
+ const minutes = Math.floor(seconds % 3600 / 60);
125
+ const secs = seconds % 60;
126
+ const minutesStr = minutes.toString().padStart(2, "0");
127
+ const secsStr = secs.toString().padStart(2, "0");
128
+ if (hours > 0)
129
+ return `${hours}:${minutesStr}:${secsStr}`;
130
+ if (minutes > 0)
131
+ return `${minutes}:${secsStr}`;
132
+ return `0:${secsStr}`;
133
+ };
134
+ var formatDuration = (ms) => {
135
+ const sec = Math.floor(ms / 1000);
136
+ const min = Math.floor(sec / 60);
137
+ const hrs = Math.floor(min / 60);
138
+ const days = Math.floor(hrs / 24);
139
+ if (days > 0)
140
+ return `${days}d ${hrs % 24}h`;
141
+ if (hrs > 0)
142
+ return `${hrs}h ${min % 60}m`;
143
+ if (min > 0)
144
+ return `${min}m ${sec % 60}s`;
145
+ return `${sec}s`;
146
+ };
147
+ // src/runtime/type.ts
148
+ var isPrimitive = (value) => value === null || value === undefined || typeof value !== "object" && typeof value !== "function";
149
+ var isObject = (value) => value !== null && typeof value === "object" && value.constructor === Object;
150
+ var isArray = (value) => Array.isArray(value);
151
+ var isEmpty = (value) => {
152
+ if (value === undefined || value === null)
153
+ return true;
154
+ if (isArray(value) || typeof value === "string")
155
+ return value.length === 0;
156
+ if (isObject(value))
157
+ return Object.keys(value).length === 0;
158
+ return false;
159
+ };
160
+ // src/runtime/url.ts
161
+ var getQueryParams = (urlString) => {
162
+ const url = new URL(urlString);
163
+ const params = {};
164
+ url.searchParams.forEach((value, key) => {
165
+ params[key] = value;
166
+ });
167
+ return params;
168
+ };
169
+ var updateQueryParam = (urlString, key, value) => {
170
+ const url = new URL(urlString);
171
+ url.searchParams.set(key, value);
172
+ return url.toString();
173
+ };
174
+ var removeQueryParam = (urlString, key) => {
175
+ const url = new URL(urlString);
176
+ url.searchParams.delete(key);
177
+ return url.toString();
178
+ };
179
+ var buildUrl = (baseUrl, path, queryParams) => {
180
+ const url = new URL(baseUrl);
181
+ if (path) {
182
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
183
+ url.pathname = `${url.pathname.replace(/\/$/, "")}${normalizedPath}`;
184
+ }
185
+ if (queryParams) {
186
+ Object.entries(queryParams).forEach(([key, value]) => {
187
+ url.searchParams.set(key, String(value));
188
+ });
189
+ }
190
+ return url.toString();
191
+ };
192
+ export {
193
+ updateQueryParam,
194
+ uniqueArray,
195
+ truncate,
196
+ toggleCase,
197
+ toTitleCase,
198
+ toSnakeCase,
199
+ toSentenceCase,
200
+ toPascalCase,
201
+ toKebabCase,
202
+ toConstantCase,
203
+ toCamelCase,
204
+ stripTags,
205
+ slugify,
206
+ sleep,
207
+ removeQueryParam,
208
+ rand,
209
+ percentage,
210
+ isUrl,
211
+ isUUID,
212
+ isSupportedDisplayableMedia,
213
+ isSlug,
214
+ isPrimitive,
215
+ isPostalCode,
216
+ isPhoneNumber,
217
+ isObject,
218
+ isMacAddress,
219
+ isJson,
220
+ isISODate,
221
+ isIPv6,
222
+ isIPv4,
223
+ isHexColor,
224
+ isHex,
225
+ isEmpty,
226
+ isEmail,
227
+ isDomain,
228
+ isCreditCard,
229
+ isBase64,
230
+ isArray,
231
+ hasDuplicates,
232
+ getQueryParams,
233
+ formatTime,
234
+ formatNumber,
235
+ formatDuration,
236
+ formatBytes,
237
+ escapeHTML,
238
+ clone,
239
+ clamp,
240
+ catchError,
241
+ capitalize,
242
+ buildUrl,
243
+ SUPPORTED_DISPLAYABLE_MEDIA_TYPES
244
+ };
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Converts a string to camelCase.
3
+ * Example: "hello world" → "helloWorld"
4
+ * @param input The input string.
5
+ * @returns The camelCase version of the input.
6
+ */
7
+ export declare const toCamelCase: (input: string) => string;
8
+ /**
9
+ * Converts a string to PascalCase.
10
+ * Example: "hello world" → "HelloWorld"
11
+ * @param input The input string.
12
+ * @returns The PascalCase version of the input.
13
+ */
14
+ export declare const toPascalCase: (input: string) => string;
15
+ /**
16
+ * Converts a string to snake_case.
17
+ * Example: "hello world" → "hello_world"
18
+ * @param input The input string.
19
+ * @returns The snake_case version of the input.
20
+ */
21
+ export declare const toSnakeCase: (input: string) => string;
22
+ /**
23
+ * Converts a string to kebab-case.
24
+ * Example: "hello world" → "hello-world"
25
+ * @param input The input string.
26
+ * @returns The kebab-case version of the input.
27
+ */
28
+ export declare const toKebabCase: (input: string) => string;
29
+ /**
30
+ * Converts a string to title case.
31
+ * Example: "hello world" → "Hello World"
32
+ * Splits the input by whitespace, lowercases it, then capitalizes each word.
33
+ * @param input The input string.
34
+ * @returns The title-cased string.
35
+ */
36
+ export declare const toTitleCase: (input: string) => string;
37
+ /**
38
+ * Converts a string to sentence case.
39
+ * Example: "hello world" → "Hello world"
40
+ * Lowercases the entire string then capitalizes only the first letter.
41
+ * @param input The input string.
42
+ * @returns The sentence-cased string.
43
+ */
44
+ export declare const toSentenceCase: (input: string) => string;
45
+ /**
46
+ * Toggles the case of each character in the string.
47
+ * Example: "Hello" → "hELLO"
48
+ * For each character, if it's uppercase it becomes lowercase, and vice versa.
49
+ * @param input The input string.
50
+ * @returns The string with toggled character cases.
51
+ */
52
+ export declare const toggleCase: (input: string) => string;
53
+ /**
54
+ * Converts a string to constant case (screaming snake case).
55
+ * Example: "hello world" → "HELLO_WORLD"
56
+ * This builds on the snake_case conversion and then converts the result to uppercase.
57
+ * @param input The input string.
58
+ * @returns The constant-cased string.
59
+ */
60
+ export declare const toConstantCase: (input: string) => string;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Checks if an array contains duplicate values.
3
+ *
4
+ * @param array - The array to check for duplicates.
5
+ * @returns True if the array contains duplicates, false otherwise.
6
+ *
7
+ * @example
8
+ * hasDuplicates([1, 2, 3, 4, 1]); // true
9
+ * hasDuplicates(['a', 'b', 'c']); // false
10
+ * hasDuplicates([{ id: 1 }, { id: 2 }, { id: 1 }], (item) => item.id); // true
11
+ */
12
+ export declare const hasDuplicates: <T>(array: T[], keyExtractor?: (item: T) => unknown) => boolean;
13
+ /**
14
+ * Removes duplicates from an array.
15
+ *
16
+ * @param array - The array to process.
17
+ * @returns A new array without duplicates.
18
+ */
19
+ export declare const uniqueArray: <T>(array: T[]) => T[];
@@ -0,0 +1,4 @@
1
+ export declare const SUPPORTED_DISPLAYABLE_MEDIA_TYPES: {
2
+ images: string[];
3
+ videos: string[];
4
+ };
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Converts a string to camelCase.
3
+ * Example: "hello world" → "helloWorld"
4
+ * @param input The input string.
5
+ * @returns The camelCase version of the input.
6
+ */
7
+ export declare const toCamelCase: (input: string) => string;
8
+ /**
9
+ * Converts a string to PascalCase.
10
+ * Example: "hello world" → "HelloWorld"
11
+ * @param input The input string.
12
+ * @returns The PascalCase version of the input.
13
+ */
14
+ export declare const toPascalCase: (input: string) => string;
15
+ /**
16
+ * Converts a string to snake_case.
17
+ * Example: "hello world" → "hello_world"
18
+ * @param input The input string.
19
+ * @returns The snake_case version of the input.
20
+ */
21
+ export declare const toSnakeCase: (input: string) => string;
22
+ /**
23
+ * Converts a string to kebab-case.
24
+ * Example: "hello world" → "hello-world"
25
+ * @param input The input string.
26
+ * @returns The kebab-case version of the input.
27
+ */
28
+ export declare const toKebabCase: (input: string) => string;
29
+ /**
30
+ * Converts a string to title case.
31
+ * Example: "hello world" → "Hello World"
32
+ * Splits the input by whitespace, lowercases it, then capitalizes each word.
33
+ * @param input The input string.
34
+ * @returns The title-cased string.
35
+ */
36
+ export declare const toTitleCase: (input: string) => string;
37
+ /**
38
+ * Converts a string to sentence case.
39
+ * Example: "hello world" → "Hello world"
40
+ * Lowercases the entire string then capitalizes only the first letter.
41
+ * @param input The input string.
42
+ * @returns The sentence-cased string.
43
+ */
44
+ export declare const toSentenceCase: (input: string) => string;
45
+ /**
46
+ * Converts a string to constant case (screaming snake case).
47
+ * Example: "hello world" → "HELLO_WORLD"
48
+ * This builds on the snake_case conversion and then converts the result to uppercase.
49
+ * @param input The input string.
50
+ * @returns The constant-cased string.
51
+ */
52
+ export declare const toConstantCase: (input: string) => string;
53
+ /**
54
+ * Toggles the case of each character in the string.
55
+ * Example: "Hello" → "hELLO"
56
+ * For each character, if it's uppercase it becomes lowercase, and vice versa.
57
+ * @param input The input string.
58
+ * @returns The string with toggled character cases.
59
+ */
60
+ export declare const toggleCase: (input: string) => string;
61
+ /**
62
+ * Capitalizes the first character of a string and lowercases the remainder.
63
+ *
64
+ * @param str - The string to capitalize.
65
+ * @returns The capitalized string.
66
+ */
67
+ export declare const capitalize: (str: string) => string;
68
+ /**
69
+ * Truncates a string to a maximum length.
70
+ *
71
+ * If the string exceeds the maximum length, it will be cut off.
72
+ * Optionally, an ellipsis ("...") is appended.
73
+ *
74
+ * @param text - The text to truncate.
75
+ * @param maxLength - The maximum allowed length.
76
+ * @param ellipsis - Whether to append "..." if truncated (default is false).
77
+ * @returns The truncated string.
78
+ */
79
+ export declare const truncate: (text: string, maxLength: number, ellipsis?: boolean) => string;
80
+ /**
81
+ * Generates a URL-friendly slug from a given string.
82
+ *
83
+ * The function normalizes accented characters, converts the string to lowercase,
84
+ * trims whitespace, replaces spaces with hyphens, removes invalid characters,
85
+ * and limits the slug length.
86
+ *
87
+ * @param title - The input string to slugify.
88
+ * @param length - Maximum length of the slug (default is 64).
89
+ * @returns The slugified string.
90
+ */
91
+ export declare const slugify: (title: string, length?: number) => string;
92
+ /**
93
+ * Strips HTML tags from a string.
94
+ *
95
+ * @param html - The HTML string.
96
+ * @returns The string without HTML tags.
97
+ */
98
+ export declare const stripTags: (html: string) => string;
99
+ /**
100
+ * Escapes special characters in a string to make it safe for inclusion in HTML.
101
+ * Converts characters like `<`, `>`, `&`, `"`, and `'` into their HTML entity equivalents.
102
+ *
103
+ * @param str - The input string to escape.
104
+ * @returns The HTML-escaped string.
105
+ */
106
+ export declare const escapeHTML: (str: string) => string;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Creates a deep clone of the given data using JSON serialization.
3
+ *
4
+ * **Note:** This method does not support cloning functions, dates, or undefined values.
5
+ *
6
+ * @param data - The data to clone.
7
+ * @returns A deep copy of the data.
8
+ */
9
+ export declare const clone: <T>(data: T) => T;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Formats a duration in seconds into a human-readable time string.
3
+ *
4
+ * - If the duration is one hour or more: "H:MM:SS"
5
+ * - If the duration is less than an hour but at least one minute: "M:SS"
6
+ * - Otherwise: "0:SS"
7
+ *
8
+ * @param seconds - The total number of seconds.
9
+ * @returns The formatted time string.
10
+ */
11
+ export declare const formatTime: (seconds: number) => string;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Wraps a promise and catches specified errors.
3
+ *
4
+ * Returns an object containing the resolved data or the caught error.
5
+ * If the error is not one of the specified errors to catch, it is re-thrown.
6
+ *
7
+ * @template T - The type of data returned by the promise.
8
+ * @template E - The error type(s) to catch.
9
+ * @param promise - A function that returns a promise.
10
+ * @param errorsToCatch - Optional array of error constructors to catch.
11
+ * @returns A promise resolving to an object with either the data or an error.
12
+ */
13
+ export declare const catchError: <T, E extends new (message?: string) => Error>(promise: () => Promise<T>, errorsToCatch?: E[]) => Promise<{
14
+ data?: T;
15
+ ok: boolean;
16
+ error?: InstanceType<E>;
17
+ }>;
@@ -0,0 +1,13 @@
1
+ export * from './collection';
2
+ export * from './constants';
3
+ export * from './convertor';
4
+ export * from './data';
5
+ export * from './errors';
6
+ export * from './math';
7
+ export * from './media';
8
+ export * from './promise';
9
+ export * from './regex';
10
+ export * from './size';
11
+ export * from './time';
12
+ export * from './type';
13
+ export * from './url';
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Generates a random integer between n and m (inclusive).
3
+ *
4
+ * **Note:** Ensure that `m` is greater than or equal to `n`.
5
+ *
6
+ * @param n - The lower bound.
7
+ * @param m - The upper bound (default is 0).
8
+ * @returns A random integer between n and m.
9
+ */
10
+ export declare const rand: (n: number, m?: number) => number;
11
+ /**
12
+ * Calculates the percentage of a number relative to a maximum number.
13
+ *
14
+ * @param value - The current value.
15
+ * @param maxValue - The maximum possible value.
16
+ * @param decimalPlaces - Number of decimal places to round to (default: 2).
17
+ * @returns The calculated percentage, or 0 if maxValue is 0.
18
+ */
19
+ export declare const percentage: (value: number, maxValue: number, decimalPlaces?: number) => number;
20
+ /**
21
+ * Clamps a number within a specified range.
22
+ *
23
+ * @param num - The number to clamp.
24
+ * @param min - The minimum value.
25
+ * @param max - The maximum value.
26
+ * @returns The clamped value.
27
+ */
28
+ export declare const clamp: (num: number, min: number, max: number) => number;
29
+ /**
30
+ * Formats a number with commas for thousands.
31
+ *
32
+ * @param num - The number to format.
33
+ * @returns A string with formatted number (e.g., "1,234,567").
34
+ */
35
+ export declare const formatNumber: (num: number) => string;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Checks if a given MIME type is supported as displayable media.
3
+ *
4
+ * Uses the SUPPORTED_DISPLAYABLE_MEDIA_TYPES constant from './constants'.
5
+ *
6
+ * @param mime - The MIME type of the file.
7
+ * @param type - An object specifying if images and/or videos should be checked (default is both).
8
+ * @returns True if the MIME type is supported, false otherwise.
9
+ */
10
+ export declare const isSupportedDisplayableMedia: (mime: File["type"], type?: {
11
+ image?: boolean;
12
+ video?: boolean;
13
+ }) => boolean | undefined;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Waits for a given number of milliseconds.
3
+ *
4
+ * @param ms - The number of milliseconds to wait.
5
+ * @returns A promise that resolves after the delay.
6
+ */
7
+ export declare const sleep: (ms: number) => Promise<void>;
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Checks if a given string is a valid email address.
3
+ *
4
+ * @param value - The string to validate.
5
+ * @returns True if the string is a valid email, false otherwise.
6
+ *
7
+ * @example
8
+ * isEmail('test@example.com'); // true
9
+ * isEmail('invalid-email'); // false
10
+ */
11
+ export declare const isEmail: (value: string) => boolean;
12
+ /**
13
+ * Checks if a given string is a valid URL.
14
+ *
15
+ * @param value - The string to validate.
16
+ * @returns True if the string is a valid URL, false otherwise.
17
+ *
18
+ * @example
19
+ * isUrl('https://example.com'); // true
20
+ * isUrl('ftp://files.example.com'); // true
21
+ * isUrl('invalid-url'); // false
22
+ */
23
+ export declare const isUrl: (value: string) => boolean;
24
+ /**
25
+ * Checks if a given string is a valid phone number (supports various formats).
26
+ *
27
+ * @param value - The string to validate.
28
+ * @returns True if the string is a valid phone number, false otherwise.
29
+ *
30
+ * @example
31
+ * isPhoneNumber('+1 (555) 555-5555'); // true
32
+ * isPhoneNumber('123456'); // false
33
+ */
34
+ export declare const isPhoneNumber: (value: string) => boolean;
35
+ /**
36
+ * Checks if a given string is a valid hexadecimal string.
37
+ *
38
+ * @param value - The string to validate.
39
+ * @returns True if the string is a valid hexadecimal, false otherwise.
40
+ *
41
+ * @example
42
+ * isHex('1A3F'); // true
43
+ * isHex('XYZ'); // false
44
+ */
45
+ export declare const isHex: (value: string) => boolean;
46
+ /**
47
+ * Checks if a given string is a valid hex color code.
48
+ *
49
+ * @param value - The string to validate.
50
+ * @returns True if the string is a valid hex color, false otherwise.
51
+ *
52
+ * @example
53
+ * isHexColor('#ff5733'); // true
54
+ * isHexColor('rgb(255, 87, 51)'); // false
55
+ */
56
+ export declare const isHexColor: (value: string) => boolean;
57
+ /**
58
+ * Checks if a given string is a valid IPv4 address.
59
+ *
60
+ * @param value - The string to validate.
61
+ * @returns True if the string is a valid IPv4 address, false otherwise.
62
+ *
63
+ * @example
64
+ * isIPv4('192.168.1.1'); // true
65
+ * isIPv4('999.999.999.999'); // false
66
+ */
67
+ export declare const isIPv4: (value: string) => boolean;
68
+ /**
69
+ * Checks if a given string is a valid IPv6 address.
70
+ *
71
+ * @param value - The string to validate.
72
+ * @returns True if the string is a valid IPv6 address, false otherwise.
73
+ *
74
+ * @example
75
+ * isIPv6('2001:0db8:85a3:0000:0000:8a2e:0370:7334'); // true
76
+ * isIPv6('InvalidIPv6'); // false
77
+ */
78
+ export declare const isIPv6: (value: string) => boolean;
79
+ /**
80
+ * Checks if a given string is a valid MAC address.
81
+ *
82
+ * @param value - The string to validate.
83
+ * @returns True if the string is a valid MAC address, false otherwise.
84
+ *
85
+ * @example
86
+ * isMacAddress('00:1A:2B:3C:4D:5E'); // true
87
+ * isMacAddress('invalid-mac'); // false
88
+ */
89
+ export declare const isMacAddress: (value: string) => boolean;
90
+ /**
91
+ * Checks if a given string is a valid UUID (v4 format).
92
+ *
93
+ * @param value - The string to validate.
94
+ * @returns True if the string is a valid UUID, false otherwise.
95
+ *
96
+ * @example
97
+ * isUUID('123e4567-e89b-12d3-a456-426614174000'); // true
98
+ * isUUID('invalid-uuid'); // false
99
+ */
100
+ export declare const isUUID: (value: string) => boolean;
101
+ /**
102
+ * Checks if a given string is a valid credit card number (basic validation).
103
+ *
104
+ * @param value - The string to validate.
105
+ * @returns True if the string is a valid credit card number, false otherwise.
106
+ *
107
+ * @example
108
+ * isCreditCard('4111 1111 1111 1111'); // true
109
+ * isCreditCard('1234567890123456'); // false
110
+ */
111
+ export declare const isCreditCard: (value: string) => boolean;
112
+ /**
113
+ * Checks if a given string is a valid domain name.
114
+ *
115
+ * @param value - The string to validate.
116
+ * @returns True if the string is a valid domain, false otherwise.
117
+ *
118
+ * @example
119
+ * isDomain('example.com'); // true
120
+ * isDomain('sub.example.co.uk'); // true
121
+ * isDomain('invalid_domain'); // false
122
+ */
123
+ export declare const isDomain: (value: string) => boolean;
124
+ /**
125
+ * Checks if a given string is a valid postal/ZIP code (supports various formats).
126
+ *
127
+ * @param value - The string to validate.
128
+ * @returns True if the string is a valid postal code, false otherwise.
129
+ *
130
+ * @example
131
+ * isPostalCode('12345'); // true (US)
132
+ * isPostalCode('12345-6789'); // true (US extended)
133
+ * isPostalCode('SW1A 1AA'); // true (UK)
134
+ * isPostalCode('invalid_code'); // false
135
+ */
136
+ export declare const isPostalCode: (value: string) => boolean;
137
+ /**
138
+ * Checks if a given string is a valid date in YYYY-MM-DD format.
139
+ *
140
+ * @param value - The string to validate.
141
+ * @returns True if the string is a valid date, false otherwise.
142
+ *
143
+ * @example
144
+ * isISODate('2024-02-12'); // true
145
+ * isISODate('2024-13-01'); // false
146
+ */
147
+ export declare const isISODate: (value: string) => boolean;
148
+ /**
149
+ * Checks if a given string is a valid JSON string.
150
+ *
151
+ * @param value - The string to validate.
152
+ * @returns True if the string is valid JSON, false otherwise.
153
+ *
154
+ * @example
155
+ * isJson('{"name": "John"}'); // true
156
+ * isJson('{invalid}'); // false
157
+ */
158
+ export declare const isJson: (value: string) => boolean;
159
+ /**
160
+ * Checks if a given string is a valid Base64-encoded string.
161
+ *
162
+ * @param value - The string to validate.
163
+ * @returns True if the string is valid Base64, false otherwise.
164
+ *
165
+ * @example
166
+ * isBase64('U29tZSB0ZXh0'); // true
167
+ * isBase64('Invalid!'); // false
168
+ */
169
+ export declare const isBase64: (value: string) => boolean;
170
+ /**
171
+ * Checks if a given string is a valid slug.
172
+ *
173
+ * @param value - The string to validate.
174
+ * @returns True if the string is a valid slug, false otherwise.
175
+ *
176
+ * @example
177
+ * isSlug('valid-slug-123'); // true
178
+ * isSlug('Invalid Slug!'); // false
179
+ */
180
+ export declare const isSlug: (value: string) => boolean;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Converts a file size in bytes into a human-readable string with appropriate units.
3
+ *
4
+ * The function supports sizes in Bytes, KB, MB, GB, TB, and PB.
5
+ *
6
+ * @param bytes - The file size in bytes.
7
+ * @param decimals - The number of decimal places to round to (default is 2).
8
+ * @returns A string representing the file size (e.g., "1.23 MB").
9
+ */
10
+ export declare const formatBytes: (bytes: number, decimals?: number) => string;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Capitalizes the first character of a string and lowercases the remainder.
3
+ *
4
+ * @param str - The string to capitalize.
5
+ * @returns The capitalized string.
6
+ */
7
+ export declare const capitalize: (str: string) => string;
8
+ /**
9
+ * Truncates a string to a maximum length.
10
+ *
11
+ * If the string exceeds the maximum length, it will be cut off.
12
+ * Optionally, an ellipsis ("...") is appended.
13
+ *
14
+ * @param text - The text to truncate.
15
+ * @param maxLength - The maximum allowed length.
16
+ * @param ellipsis - Whether to append "..." if truncated (default is false).
17
+ * @returns The truncated string.
18
+ */
19
+ export declare const truncate: (text: string, maxLength: number, ellipsis?: boolean) => string;
20
+ /**
21
+ * Generates a URL-friendly slug from a given string.
22
+ *
23
+ * The function normalizes accented characters, converts the string to lowercase,
24
+ * trims whitespace, replaces spaces with hyphens, removes invalid characters,
25
+ * and limits the slug length.
26
+ *
27
+ * @param title - The input string to slugify.
28
+ * @param length - Maximum length of the slug (default is 64).
29
+ * @returns The slugified string.
30
+ */
31
+ export declare const slugify: (title: string, length?: number) => string;
32
+ /**
33
+ * Strips HTML tags from a string.
34
+ *
35
+ * @param html - The HTML string.
36
+ * @returns The string without HTML tags.
37
+ */
38
+ export declare const stripTags: (html: string) => string;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Formats a duration in seconds into a human-readable time string.
3
+ *
4
+ * - If the duration is one hour or more: "H:MM:SS"
5
+ * - If the duration is less than an hour but at least one minute: "M:SS"
6
+ * - Otherwise: "0:SS"
7
+ *
8
+ * @param seconds - The total number of seconds.
9
+ * @returns The formatted time string.
10
+ */
11
+ export declare const formatTime: (seconds: number) => string;
12
+ /**
13
+ * Converts milliseconds to a human-readable time format.
14
+ *
15
+ * @param ms - The number of milliseconds.
16
+ * @returns A formatted string (e.g., "2h 15m 30s").
17
+ */
18
+ export declare const formatDuration: (ms: number) => string;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Determines whether a value is a primitive.
3
+ *
4
+ * A primitive is defined here as one of:
5
+ * string, number, boolean, bigint, symbol, undefined, or null.
6
+ *
7
+ * @param value - The value to check.
8
+ * @returns True if the value is primitive, false otherwise.
9
+ */
10
+ export declare const isPrimitive: (value: unknown) => value is string | number | boolean | bigint | symbol | null | undefined;
11
+ /**
12
+ * Determines whether a value is a plain object.
13
+ *
14
+ * A plain object is an object whose constructor is Object.
15
+ *
16
+ * @param value - The value to check.
17
+ * @returns True if the value is a plain object, false otherwise.
18
+ */
19
+ export declare const isObject: (value: unknown) => value is Record<string, unknown>;
20
+ /**
21
+ * Determines whether a value is an array.
22
+ *
23
+ * @param value - The value to check.
24
+ * @returns True if the value is an array, false otherwise.
25
+ */
26
+ export declare const isArray: <T>(value: unknown) => value is T[];
27
+ /**
28
+ * Checks if a value is empty.
29
+ *
30
+ * For arrays and strings, it checks if the length is 0.
31
+ * For plain objects, it checks if there are no enumerable keys.
32
+ *
33
+ * @param value - The value to check.
34
+ * @returns True if the value is empty, false otherwise.
35
+ */
36
+ export declare const isEmpty: (value: unknown) => boolean;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Parses the query parameters from a URL string into an object.
3
+ *
4
+ * @param urlString - The URL string to parse.
5
+ * @returns An object where keys are query parameter names and values are query parameter values.
6
+ *
7
+ * @example
8
+ * // returns { search: 'test', page: '2' }
9
+ * getQueryParams('https://example.com/?search=test&page=2');
10
+ */
11
+ export declare const getQueryParams: (urlString: string) => Record<string, string>;
12
+ /**
13
+ * Updates (or adds) a query parameter in a given URL string.
14
+ *
15
+ * @param urlString - The original URL string.
16
+ * @param key - The query parameter key to update.
17
+ * @param value - The new value for the query parameter.
18
+ * @returns The updated URL string.
19
+ *
20
+ * @example
21
+ * // returns 'https://example.com/?search=new'
22
+ * updateQueryParam('https://example.com/?search=test', 'search', 'new');
23
+ */
24
+ export declare const updateQueryParam: (urlString: string, key: string, value: string) => string;
25
+ /**
26
+ * Removes a query parameter from a given URL string.
27
+ *
28
+ * @param urlString - The original URL string.
29
+ * @param key - The query parameter key to remove.
30
+ * @returns The updated URL string with the specified query parameter removed.
31
+ *
32
+ * @example
33
+ * // returns 'https://example.com/'
34
+ * removeQueryParam('https://example.com/?search=test', 'search');
35
+ */
36
+ export declare const removeQueryParam: (urlString: string, key: string) => string;
37
+ /**
38
+ * Builds a URL from a base URL, an optional path, and optional query parameters.
39
+ *
40
+ * @param baseUrl - The base URL (e.g., "https://example.com").
41
+ * @param path - Optional path to append to the base URL (e.g., "/api/v1/resource").
42
+ * @param queryParams - Optional object representing query parameters, where keys are parameter names and values are parameter values.
43
+ * @returns The constructed URL as a string.
44
+ *
45
+ * @example
46
+ * // returns 'https://example.com/api/v1/resource?search=test&page=2'
47
+ * buildUrl('https://example.com', '/api/v1/resource', { search: 'test', page: 2 });
48
+ */
49
+ export declare const buildUrl: (baseUrl: string, path?: string, queryParams?: Record<string, string | number | boolean>) => string;
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@germondai/ts-utils",
3
+ "version": "0.0.1",
4
+ "description": "Germond's TypeScript Utilities",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/germondai/ts-utils.git"
8
+ },
9
+ "author": "germondai",
10
+ "license": "MIT",
11
+ "type": "module",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/module.d.ts",
15
+ "import": "./dist/module.js",
16
+ "require": "./dist/module.js"
17
+ }
18
+ },
19
+ "main": "./dist/module.js",
20
+ "types": "./dist/module.d.ts",
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "scripts": {
25
+ "prepack": "bun run build",
26
+ "build": "bun build --target=node ./src/module.ts --outfile=dist/module.js && bun run build:types",
27
+ "build:types": "tsc --emitDeclarationOnly --project tsconfig.types.json",
28
+ "release": "bun fmt && bun prepack && changelogen --release && bun publish && git push --follow-tags",
29
+ "prettier": "prettier --check .",
30
+ "prettier:fix": "prettier --write --list-different .",
31
+ "fmt": "bun prettier:fix"
32
+ },
33
+ "devDependencies": {
34
+ "@types/bun": "latest",
35
+ "prettier": "^3.5.0"
36
+ },
37
+ "peerDependencies": {
38
+ "typescript": "^5.7.3"
39
+ }
40
+ }