@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.cjs CHANGED
@@ -1,302 +1,375 @@
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
+ get(key, defaultValue) {
146
+ if (typeof window === "undefined") return defaultValue ?? null;
147
+ try {
148
+ const item = window.localStorage.getItem(key);
149
+ return item ? JSON.parse(item) : defaultValue ?? null;
150
+ } catch {
151
+ return defaultValue ?? null;
152
+ }
153
+ },
154
+ set(key, value) {
155
+ if (typeof window === "undefined") return;
156
+ try {
157
+ window.localStorage.setItem(key, JSON.stringify(value));
158
+ } catch (error) {
159
+ console.error("Failed to set localStorage item:", error);
160
+ }
161
+ },
162
+ remove(key) {
163
+ if (typeof window === "undefined") return;
164
+ try {
165
+ window.localStorage.removeItem(key);
166
+ } catch (error) {
167
+ console.error("Failed to remove localStorage item:", error);
168
+ }
169
+ },
170
+ clear() {
171
+ if (typeof window === "undefined") return;
172
+ try {
173
+ window.localStorage.clear();
174
+ } catch (error) {
175
+ console.error("Failed to clear localStorage:", error);
176
+ }
177
+ }
178
+ };
179
+ /**
180
+ * Safe sessionStorage wrapper
181
+ */
182
+ const sessionStorage = {
183
+ get(key, defaultValue) {
184
+ if (typeof window === "undefined") return defaultValue ?? null;
185
+ try {
186
+ const item = window.sessionStorage.getItem(key);
187
+ return item ? JSON.parse(item) : defaultValue ?? null;
188
+ } catch {
189
+ return defaultValue ?? null;
190
+ }
191
+ },
192
+ set(key, value) {
193
+ if (typeof window === "undefined") return;
194
+ try {
195
+ window.sessionStorage.setItem(key, JSON.stringify(value));
196
+ } catch (error) {
197
+ console.error("Failed to set sessionStorage item:", error);
198
+ }
199
+ },
200
+ remove(key) {
201
+ if (typeof window === "undefined") return;
202
+ try {
203
+ window.sessionStorage.removeItem(key);
204
+ } catch (error) {
205
+ console.error("Failed to remove sessionStorage item:", error);
206
+ }
207
+ },
208
+ clear() {
209
+ if (typeof window === "undefined") return;
210
+ try {
211
+ window.sessionStorage.clear();
212
+ } catch (error) {
213
+ console.error("Failed to clear sessionStorage:", error);
214
+ }
215
+ }
216
+ };
217
+
218
+ //#endregion
219
+ //#region src/string.ts
220
+ /**
221
+ * String utility functions
222
+ */
223
+ /**
224
+ * Truncate a string to a maximum length
225
+ */
226
+ function truncate(str, maxLength, suffix = "...") {
227
+ if (str.length <= maxLength) return str;
228
+ return str.slice(0, maxLength - suffix.length) + suffix;
229
+ }
230
+ /**
231
+ * Capitalize the first letter of a string
232
+ */
233
+ function capitalize(str) {
234
+ return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
235
+ }
236
+ /**
237
+ * Convert string to kebab-case
238
+ */
239
+ function toKebabCase(str) {
240
+ return str.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
241
+ }
242
+ /**
243
+ * Convert string to camelCase
244
+ */
245
+ function toCamelCase(str) {
246
+ return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (_, chr) => chr.toUpperCase());
247
+ }
248
+ /**
249
+ * Convert string to snake_case
250
+ */
251
+ function toSnakeCase(str) {
252
+ return str.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[\s-]+/g, "_").toLowerCase();
253
+ }
254
+ /**
255
+ * Generate a random alphanumeric string
256
+ */
257
+ function randomString(length) {
258
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
259
+ let result = "";
260
+ for (let i = 0; i < length; i++) result += chars.charAt(Math.floor(Math.random() * 62));
261
+ return result;
262
+ }
263
+ /**
264
+ * Slugify a string for URLs
265
+ */
266
+ function slugify(str) {
267
+ return str.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
181
268
  }
182
269
 
183
- // src/throttle.ts
270
+ //#endregion
271
+ //#region src/throttle.ts
272
+ /**
273
+ * Throttle utility
274
+ */
184
275
  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
- };
276
+ let inThrottle = false;
277
+ let lastArgs = null;
278
+ return function throttled(...args) {
279
+ if (!inThrottle) {
280
+ func(...args);
281
+ inThrottle = true;
282
+ setTimeout(() => {
283
+ inThrottle = false;
284
+ if (lastArgs !== null) {
285
+ throttled(...lastArgs);
286
+ lastArgs = null;
287
+ }
288
+ }, limitMs);
289
+ } else lastArgs = args;
290
+ };
202
291
  }
203
292
 
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
- };
293
+ //#endregion
294
+ //#region src/url.ts
295
+ /**
296
+ * URL utility functions
297
+ */
298
+ /**
299
+ * Parse query parameters from URL
300
+ */
301
+ function parseQueryParams(url) {
302
+ const params = {};
303
+ new URL(url).searchParams.forEach((value, key) => {
304
+ params[key] = value;
305
+ });
306
+ return params;
307
+ }
308
+ /**
309
+ * Build query string from object
310
+ */
311
+ function buildQueryString(params) {
312
+ const searchParams = new URLSearchParams();
313
+ Object.entries(params).forEach(([key, value]) => {
314
+ if (value !== null && value !== void 0) {
315
+ if (typeof value === "string") {
316
+ searchParams.append(key, value);
317
+ return;
318
+ }
319
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
320
+ searchParams.append(key, String(value));
321
+ return;
322
+ }
323
+ if (value instanceof Date) {
324
+ searchParams.append(key, value.toISOString());
325
+ return;
326
+ }
327
+ searchParams.append(key, JSON.stringify(value));
328
+ }
329
+ });
330
+ return searchParams.toString();
331
+ }
332
+ /**
333
+ * Get domain from URL
334
+ */
335
+ function getDomain(url) {
336
+ try {
337
+ return new URL(url).hostname;
338
+ } catch {
339
+ return "";
340
+ }
341
+ }
342
+ /**
343
+ * Get pathname from URL
344
+ */
345
+ function getPathname(url) {
346
+ try {
347
+ return new URL(url).pathname;
348
+ } catch {
349
+ return "";
350
+ }
351
+ }
352
+ /**
353
+ * Validate URL
354
+ */
355
+ function isValidUrl(url) {
356
+ try {
357
+ new URL(url);
358
+ return true;
359
+ } catch {
360
+ return false;
361
+ }
362
+ }
363
+ /**
364
+ * Combine URL parts
365
+ */
366
+ function combineUrl(base, ...paths) {
367
+ let url = base.replace(/\/+$/, "");
368
+ for (const path of paths) url += "/" + path.replace(/^\/+/, "");
369
+ return url;
370
+ }
299
371
 
372
+ //#endregion
300
373
  exports.addDays = addDays;
301
374
  exports.buildQueryString = buildQueryString;
302
375
  exports.capitalize = capitalize;
@@ -326,5 +399,4 @@ exports.toISOString = toISOString;
326
399
  exports.toKebabCase = toKebabCase;
327
400
  exports.toSnakeCase = toSnakeCase;
328
401
  exports.truncate = truncate;
329
- //# sourceMappingURL=index.cjs.map
330
402
  //# sourceMappingURL=index.cjs.map