@entrolytics/utilities 2.1.0 → 2.3.0

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/dist/index.js CHANGED
@@ -1,300 +1,372 @@
1
- // src/string.ts
2
- function truncate(str, maxLength, suffix = "...") {
3
- if (str.length <= maxLength) return str;
4
- return str.slice(0, maxLength - suffix.length) + suffix;
5
- }
6
- function capitalize(str) {
7
- return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
8
- }
9
- function toKebabCase(str) {
10
- return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
11
- }
12
- function toCamelCase(str) {
13
- return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (_, chr) => chr.toUpperCase());
14
- }
15
- function toSnakeCase(str) {
16
- return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[\s-]+/g, "_").toLowerCase();
17
- }
18
- function randomString(length) {
19
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
20
- let result = "";
21
- for (let i = 0; i < length; i++) {
22
- result += chars.charAt(Math.floor(Math.random() * chars.length));
23
- }
24
- return result;
25
- }
26
- function slugify(str) {
27
- return str.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
28
- }
29
-
30
- // src/date.ts
1
+ //#region src/date.ts
2
+ /**
3
+ * Date utility functions
4
+ */
5
+ /**
6
+ * Format date to ISO string
7
+ */
31
8
  function toISOString(date) {
32
- return new Date(date).toISOString();
9
+ return new Date(date).toISOString();
33
10
  }
11
+ /**
12
+ * Format date to YYYY-MM-DD
13
+ */
34
14
  function toDateString(date) {
35
- const d = new Date(date);
36
- const year = d.getFullYear();
37
- const month = String(d.getMonth() + 1).padStart(2, "0");
38
- const day = String(d.getDate()).padStart(2, "0");
39
- return `${year}-${month}-${day}`;
15
+ const d = new Date(date);
16
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
40
17
  }
18
+ /**
19
+ * Get date range for the last N days
20
+ */
41
21
  function getLastNDays(n) {
42
- const endDate = /* @__PURE__ */ new Date();
43
- const startDate = /* @__PURE__ */ new Date();
44
- startDate.setDate(startDate.getDate() - n);
45
- return { startDate, endDate };
22
+ const endDate = /* @__PURE__ */ new Date();
23
+ const startDate = /* @__PURE__ */ new Date();
24
+ startDate.setDate(startDate.getDate() - n);
25
+ return {
26
+ startDate,
27
+ endDate
28
+ };
46
29
  }
30
+ /**
31
+ * Check if a date is today
32
+ */
47
33
  function isToday(date) {
48
- const d = new Date(date);
49
- const today = /* @__PURE__ */ new Date();
50
- return d.toDateString() === today.toDateString();
34
+ const d = new Date(date);
35
+ const today = /* @__PURE__ */ new Date();
36
+ return d.toDateString() === today.toDateString();
51
37
  }
38
+ /**
39
+ * Add days to a date
40
+ */
52
41
  function addDays(date, days) {
53
- const result = new Date(date);
54
- result.setDate(result.getDate() + days);
55
- return result;
42
+ const result = new Date(date);
43
+ result.setDate(result.getDate() + days);
44
+ return result;
56
45
  }
46
+ /**
47
+ * Get start of day
48
+ */
57
49
  function startOfDay(date) {
58
- const result = new Date(date);
59
- result.setHours(0, 0, 0, 0);
60
- return result;
50
+ const result = new Date(date);
51
+ result.setHours(0, 0, 0, 0);
52
+ return result;
61
53
  }
54
+ /**
55
+ * Get end of day
56
+ */
62
57
  function endOfDay(date) {
63
- const result = new Date(date);
64
- result.setHours(23, 59, 59, 999);
65
- return result;
58
+ const result = new Date(date);
59
+ result.setHours(23, 59, 59, 999);
60
+ return result;
66
61
  }
62
+ /**
63
+ * Get difference in days between two dates
64
+ */
67
65
  function daysDifference(date1, date2) {
68
- const oneDay = 24 * 60 * 60 * 1e3;
69
- return Math.round(Math.abs((date1.getTime() - date2.getTime()) / oneDay));
66
+ return Math.round(Math.abs((date1.getTime() - date2.getTime()) / (1440 * 60 * 1e3)));
70
67
  }
71
68
 
72
- // src/url.ts
73
- function parseQueryParams(url) {
74
- const params = {};
75
- const urlObj = new URL(url);
76
- urlObj.searchParams.forEach((value, key) => {
77
- params[key] = value;
78
- });
79
- return params;
80
- }
81
- function buildQueryString(params) {
82
- const searchParams = new URLSearchParams();
83
- Object.entries(params).forEach(([key, value]) => {
84
- if (value !== null && value !== void 0) {
85
- searchParams.append(key, String(value));
86
- }
87
- });
88
- return searchParams.toString();
89
- }
90
- function getDomain(url) {
91
- try {
92
- const urlObj = new URL(url);
93
- return urlObj.hostname;
94
- } catch {
95
- return "";
96
- }
97
- }
98
- function getPathname(url) {
99
- try {
100
- const urlObj = new URL(url);
101
- return urlObj.pathname;
102
- } catch {
103
- return "";
104
- }
105
- }
106
- function isValidUrl(url) {
107
- try {
108
- new URL(url);
109
- return true;
110
- } catch {
111
- return false;
112
- }
113
- }
114
- function combineUrl(base, ...paths) {
115
- let url = base.replace(/\/+$/, "");
116
- for (const path of paths) {
117
- url += "/" + path.replace(/^\/+/, "");
118
- }
119
- return url;
69
+ //#endregion
70
+ //#region src/debounce.ts
71
+ /**
72
+ * Debounce utility
73
+ */
74
+ function debounce(func, waitMs) {
75
+ let timeoutId = null;
76
+ return function debounced(...args) {
77
+ if (timeoutId !== null) clearTimeout(timeoutId);
78
+ timeoutId = setTimeout(() => {
79
+ func(...args);
80
+ }, waitMs);
81
+ };
120
82
  }
121
83
 
122
- // src/hash.ts
84
+ //#endregion
85
+ //#region src/hash.ts
86
+ /**
87
+ * Hashing utility functions
88
+ */
89
+ /**
90
+ * Simple hash function for strings (non-cryptographic)
91
+ */
123
92
  function simpleHash(str) {
124
- let hash = 0;
125
- for (let i = 0; i < str.length; i++) {
126
- const char = str.charCodeAt(i);
127
- hash = (hash << 5) - hash + char;
128
- hash |= 0;
129
- }
130
- return Math.abs(hash);
93
+ let hash = 0;
94
+ for (let i = 0; i < str.length; i++) {
95
+ const char = str.charCodeAt(i);
96
+ hash = (hash << 5) - hash + char;
97
+ hash |= 0;
98
+ }
99
+ return Math.abs(hash);
131
100
  }
101
+ /**
102
+ * Generate a simple hash string from input
103
+ */
132
104
  function hashString(str) {
133
- return simpleHash(str).toString(36);
105
+ return simpleHash(str).toString(36);
134
106
  }
107
+ /**
108
+ * Generate a deterministic ID from multiple values
109
+ */
135
110
  function generateId(...values) {
136
- const combined = values.join("|");
137
- return hashString(combined);
111
+ return hashString(values.join("|"));
138
112
  }
139
113
 
140
- // src/retry.ts
114
+ //#endregion
115
+ //#region src/retry.ts
116
+ /**
117
+ * Retry a function with exponential backoff
118
+ */
141
119
  async function retry(fn, options = {}) {
142
- const {
143
- maxAttempts = 3,
144
- delayMs = 1e3,
145
- backoffMultiplier = 2,
146
- maxDelayMs = 3e4,
147
- onRetry
148
- } = options;
149
- let lastError;
150
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
151
- try {
152
- return await fn();
153
- } catch (error) {
154
- lastError = error;
155
- if (attempt === maxAttempts) {
156
- throw lastError;
157
- }
158
- const delay = Math.min(delayMs * Math.pow(backoffMultiplier, attempt - 1), maxDelayMs);
159
- if (onRetry) {
160
- onRetry(lastError, attempt);
161
- }
162
- await new Promise((resolve) => setTimeout(resolve, delay));
163
- }
164
- }
165
- throw lastError;
120
+ const { maxAttempts = 3, delayMs = 1e3, backoffMultiplier = 2, maxDelayMs = 3e4, onRetry } = options;
121
+ let lastError;
122
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) try {
123
+ return await fn();
124
+ } catch (error) {
125
+ lastError = error;
126
+ if (attempt === maxAttempts) throw lastError;
127
+ const delay = Math.min(delayMs * backoffMultiplier ** (attempt - 1), maxDelayMs);
128
+ if (onRetry) onRetry(lastError, attempt);
129
+ await new Promise((resolve) => setTimeout(resolve, delay));
130
+ }
131
+ throw lastError;
166
132
  }
167
133
 
168
- // src/debounce.ts
169
- function debounce(func, waitMs) {
170
- let timeoutId = null;
171
- return function debounced(...args) {
172
- if (timeoutId !== null) {
173
- clearTimeout(timeoutId);
174
- }
175
- timeoutId = setTimeout(() => {
176
- func(...args);
177
- }, waitMs);
178
- };
134
+ //#endregion
135
+ //#region src/storage.ts
136
+ /**
137
+ * Storage utility functions for browser localStorage/sessionStorage
138
+ */
139
+ /**
140
+ * Safe localStorage wrapper
141
+ */
142
+ const storage = {
143
+ get(key, defaultValue) {
144
+ if (typeof window === "undefined") return defaultValue ?? null;
145
+ try {
146
+ const item = window.localStorage.getItem(key);
147
+ return item ? JSON.parse(item) : defaultValue ?? null;
148
+ } catch {
149
+ return defaultValue ?? null;
150
+ }
151
+ },
152
+ set(key, value) {
153
+ if (typeof window === "undefined") return;
154
+ try {
155
+ window.localStorage.setItem(key, JSON.stringify(value));
156
+ } catch (error) {
157
+ console.error("Failed to set localStorage item:", error);
158
+ }
159
+ },
160
+ remove(key) {
161
+ if (typeof window === "undefined") return;
162
+ try {
163
+ window.localStorage.removeItem(key);
164
+ } catch (error) {
165
+ console.error("Failed to remove localStorage item:", error);
166
+ }
167
+ },
168
+ clear() {
169
+ if (typeof window === "undefined") return;
170
+ try {
171
+ window.localStorage.clear();
172
+ } catch (error) {
173
+ console.error("Failed to clear localStorage:", error);
174
+ }
175
+ }
176
+ };
177
+ /**
178
+ * Safe sessionStorage wrapper
179
+ */
180
+ const sessionStorage = {
181
+ get(key, defaultValue) {
182
+ if (typeof window === "undefined") return defaultValue ?? null;
183
+ try {
184
+ const item = window.sessionStorage.getItem(key);
185
+ return item ? JSON.parse(item) : defaultValue ?? null;
186
+ } catch {
187
+ return defaultValue ?? null;
188
+ }
189
+ },
190
+ set(key, value) {
191
+ if (typeof window === "undefined") return;
192
+ try {
193
+ window.sessionStorage.setItem(key, JSON.stringify(value));
194
+ } catch (error) {
195
+ console.error("Failed to set sessionStorage item:", error);
196
+ }
197
+ },
198
+ remove(key) {
199
+ if (typeof window === "undefined") return;
200
+ try {
201
+ window.sessionStorage.removeItem(key);
202
+ } catch (error) {
203
+ console.error("Failed to remove sessionStorage item:", error);
204
+ }
205
+ },
206
+ clear() {
207
+ if (typeof window === "undefined") return;
208
+ try {
209
+ window.sessionStorage.clear();
210
+ } catch (error) {
211
+ console.error("Failed to clear sessionStorage:", error);
212
+ }
213
+ }
214
+ };
215
+
216
+ //#endregion
217
+ //#region src/string.ts
218
+ /**
219
+ * String utility functions
220
+ */
221
+ /**
222
+ * Truncate a string to a maximum length
223
+ */
224
+ function truncate(str, maxLength, suffix = "...") {
225
+ if (str.length <= maxLength) return str;
226
+ return str.slice(0, maxLength - suffix.length) + suffix;
227
+ }
228
+ /**
229
+ * Capitalize the first letter of a string
230
+ */
231
+ function capitalize(str) {
232
+ return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
233
+ }
234
+ /**
235
+ * Convert string to kebab-case
236
+ */
237
+ function toKebabCase(str) {
238
+ return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
239
+ }
240
+ /**
241
+ * Convert string to camelCase
242
+ */
243
+ function toCamelCase(str) {
244
+ return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (_, chr) => chr.toUpperCase());
245
+ }
246
+ /**
247
+ * Convert string to snake_case
248
+ */
249
+ function toSnakeCase(str) {
250
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[\s-]+/g, "_").toLowerCase();
251
+ }
252
+ /**
253
+ * Generate a random alphanumeric string
254
+ */
255
+ function randomString(length) {
256
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
257
+ let result = "";
258
+ for (let i = 0; i < length; i++) result += chars.charAt(Math.floor(Math.random() * 62));
259
+ return result;
260
+ }
261
+ /**
262
+ * Slugify a string for URLs
263
+ */
264
+ function slugify(str) {
265
+ return str.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
179
266
  }
180
267
 
181
- // src/throttle.ts
268
+ //#endregion
269
+ //#region src/throttle.ts
270
+ /**
271
+ * Throttle utility
272
+ */
182
273
  function throttle(func, limitMs) {
183
- let inThrottle = false;
184
- let lastArgs = null;
185
- return function throttled(...args) {
186
- if (!inThrottle) {
187
- func(...args);
188
- inThrottle = true;
189
- setTimeout(() => {
190
- inThrottle = false;
191
- if (lastArgs !== null) {
192
- throttled(...lastArgs);
193
- lastArgs = null;
194
- }
195
- }, limitMs);
196
- } else {
197
- lastArgs = args;
198
- }
199
- };
274
+ let inThrottle = false;
275
+ let lastArgs = null;
276
+ return function throttled(...args) {
277
+ if (!inThrottle) {
278
+ func(...args);
279
+ inThrottle = true;
280
+ setTimeout(() => {
281
+ inThrottle = false;
282
+ if (lastArgs !== null) {
283
+ throttled(...lastArgs);
284
+ lastArgs = null;
285
+ }
286
+ }, limitMs);
287
+ } else lastArgs = args;
288
+ };
200
289
  }
201
290
 
202
- // src/storage.ts
203
- var storage = {
204
- /**
205
- * Get item from localStorage with JSON parsing
206
- */
207
- get(key, defaultValue) {
208
- if (typeof window === "undefined") return defaultValue ?? null;
209
- try {
210
- const item = window.localStorage.getItem(key);
211
- return item ? JSON.parse(item) : defaultValue ?? null;
212
- } catch {
213
- return defaultValue ?? null;
214
- }
215
- },
216
- /**
217
- * Set item in localStorage with JSON stringification
218
- */
219
- set(key, value) {
220
- if (typeof window === "undefined") return;
221
- try {
222
- window.localStorage.setItem(key, JSON.stringify(value));
223
- } catch (error) {
224
- console.error("Failed to set localStorage item:", error);
225
- }
226
- },
227
- /**
228
- * Remove item from localStorage
229
- */
230
- remove(key) {
231
- if (typeof window === "undefined") return;
232
- try {
233
- window.localStorage.removeItem(key);
234
- } catch (error) {
235
- console.error("Failed to remove localStorage item:", error);
236
- }
237
- },
238
- /**
239
- * Clear all localStorage
240
- */
241
- clear() {
242
- if (typeof window === "undefined") return;
243
- try {
244
- window.localStorage.clear();
245
- } catch (error) {
246
- console.error("Failed to clear localStorage:", error);
247
- }
248
- }
249
- };
250
- var sessionStorage = {
251
- /**
252
- * Get item from sessionStorage with JSON parsing
253
- */
254
- get(key, defaultValue) {
255
- if (typeof window === "undefined") return defaultValue ?? null;
256
- try {
257
- const item = window.sessionStorage.getItem(key);
258
- return item ? JSON.parse(item) : defaultValue ?? null;
259
- } catch {
260
- return defaultValue ?? null;
261
- }
262
- },
263
- /**
264
- * Set item in sessionStorage with JSON stringification
265
- */
266
- set(key, value) {
267
- if (typeof window === "undefined") return;
268
- try {
269
- window.sessionStorage.setItem(key, JSON.stringify(value));
270
- } catch (error) {
271
- console.error("Failed to set sessionStorage item:", error);
272
- }
273
- },
274
- /**
275
- * Remove item from sessionStorage
276
- */
277
- remove(key) {
278
- if (typeof window === "undefined") return;
279
- try {
280
- window.sessionStorage.removeItem(key);
281
- } catch (error) {
282
- console.error("Failed to remove sessionStorage item:", error);
283
- }
284
- },
285
- /**
286
- * Clear all sessionStorage
287
- */
288
- clear() {
289
- if (typeof window === "undefined") return;
290
- try {
291
- window.sessionStorage.clear();
292
- } catch (error) {
293
- console.error("Failed to clear sessionStorage:", error);
294
- }
295
- }
296
- };
291
+ //#endregion
292
+ //#region src/url.ts
293
+ /**
294
+ * URL utility functions
295
+ */
296
+ /**
297
+ * Parse query parameters from URL
298
+ */
299
+ function parseQueryParams(url) {
300
+ const params = {};
301
+ new URL(url).searchParams.forEach((value, key) => {
302
+ params[key] = value;
303
+ });
304
+ return params;
305
+ }
306
+ /**
307
+ * Build query string from object
308
+ */
309
+ function buildQueryString(params) {
310
+ const searchParams = new URLSearchParams();
311
+ Object.entries(params).forEach(([key, value]) => {
312
+ if (value !== null && value !== void 0) {
313
+ if (typeof value === "string") {
314
+ searchParams.append(key, value);
315
+ return;
316
+ }
317
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
318
+ searchParams.append(key, String(value));
319
+ return;
320
+ }
321
+ if (value instanceof Date) {
322
+ searchParams.append(key, value.toISOString());
323
+ return;
324
+ }
325
+ searchParams.append(key, JSON.stringify(value));
326
+ }
327
+ });
328
+ return searchParams.toString();
329
+ }
330
+ /**
331
+ * Get domain from URL
332
+ */
333
+ function getDomain(url) {
334
+ try {
335
+ return new URL(url).hostname;
336
+ } catch {
337
+ return "";
338
+ }
339
+ }
340
+ /**
341
+ * Get pathname from URL
342
+ */
343
+ function getPathname(url) {
344
+ try {
345
+ return new URL(url).pathname;
346
+ } catch {
347
+ return "";
348
+ }
349
+ }
350
+ /**
351
+ * Validate URL
352
+ */
353
+ function isValidUrl(url) {
354
+ try {
355
+ new URL(url);
356
+ return true;
357
+ } catch {
358
+ return false;
359
+ }
360
+ }
361
+ /**
362
+ * Combine URL parts
363
+ */
364
+ function combineUrl(base, ...paths) {
365
+ let url = base.replace(/\/+$/, "");
366
+ for (const path of paths) url += "/" + path.replace(/^\/+/, "");
367
+ return url;
368
+ }
297
369
 
370
+ //#endregion
298
371
  export { addDays, buildQueryString, capitalize, combineUrl, daysDifference, debounce, endOfDay, generateId, getDomain, getLastNDays, getPathname, hashString, isToday, isValidUrl, parseQueryParams, randomString, retry, sessionStorage, simpleHash, slugify, startOfDay, storage, throttle, toCamelCase, toDateString, toISOString, toKebabCase, toSnakeCase, truncate };
299
- //# sourceMappingURL=index.js.map
300
372
  //# sourceMappingURL=index.js.map