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