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