@welshman/lib 0.0.34 → 0.0.35

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.
Files changed (48) hide show
  1. package/build/src/Context.d.ts +1 -1
  2. package/build/src/{Context.mjs → Context.js} +1 -1
  3. package/build/src/Context.js.map +1 -0
  4. package/build/src/{Deferred.mjs → Deferred.js} +1 -1
  5. package/build/src/Deferred.js.map +1 -0
  6. package/build/src/Emitter.d.ts +1 -1
  7. package/build/src/{Emitter.mjs → Emitter.js} +3 -3
  8. package/build/src/Emitter.js.map +1 -0
  9. package/build/src/{LRUCache.mjs → LRUCache.js} +5 -4
  10. package/build/src/LRUCache.js.map +1 -0
  11. package/build/src/Tools.d.ts +4 -4
  12. package/build/src/{Tools.mjs → Tools.js} +23 -15
  13. package/build/src/Tools.js.map +1 -0
  14. package/build/src/Worker.js +97 -0
  15. package/build/src/Worker.js.map +1 -0
  16. package/build/src/index.d.ts +11 -7
  17. package/build/src/index.js +8 -0
  18. package/build/src/index.js.map +1 -0
  19. package/build/src/normalize-url/{index.mjs → index.js} +7 -8
  20. package/build/src/normalize-url/index.js.map +1 -0
  21. package/build/tsconfig.tsbuildinfo +1 -0
  22. package/package.json +5 -10
  23. package/build/src/Context.cjs +0 -24
  24. package/build/src/Context.cjs.map +0 -1
  25. package/build/src/Context.mjs.map +0 -1
  26. package/build/src/Deferred.cjs +0 -26
  27. package/build/src/Deferred.cjs.map +0 -1
  28. package/build/src/Deferred.mjs.map +0 -1
  29. package/build/src/Emitter.cjs +0 -22
  30. package/build/src/Emitter.cjs.map +0 -1
  31. package/build/src/Emitter.mjs.map +0 -1
  32. package/build/src/LRUCache.cjs +0 -67
  33. package/build/src/LRUCache.cjs.map +0 -1
  34. package/build/src/LRUCache.mjs.map +0 -1
  35. package/build/src/Tools.cjs +0 -1008
  36. package/build/src/Tools.cjs.map +0 -1
  37. package/build/src/Tools.mjs.map +0 -1
  38. package/build/src/Worker.cjs +0 -119
  39. package/build/src/Worker.cjs.map +0 -1
  40. package/build/src/Worker.mjs +0 -115
  41. package/build/src/Worker.mjs.map +0 -1
  42. package/build/src/index.cjs +0 -29
  43. package/build/src/index.cjs.map +0 -1
  44. package/build/src/index.mjs +0 -8
  45. package/build/src/index.mjs.map +0 -1
  46. package/build/src/normalize-url/index.cjs +0 -254
  47. package/build/src/normalize-url/index.cjs.map +0 -1
  48. package/build/src/normalize-url/index.mjs.map +0 -1
@@ -1,1008 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.without = exports.remove = exports.difference = exports.intersection = exports.union = exports.append = exports.concat = exports.sleep = exports.displayDomain = exports.displayUrl = exports.stripProtocol = exports.randomId = exports.randomInt = exports.within = exports.between = exports.mergeRight = exports.mergeLeft = exports.mapVals = exports.mapKeys = exports.range = exports.pick = exports.omitVals = exports.omit = exports.take = exports.drop = exports.avg = exports.sum = exports.min = exports.max = exports.gte = exports.gt = exports.lte = exports.lt = exports.dec = exports.inc = exports.div = exports.mul = exports.sub = exports.add = exports.num = exports.complement = exports.not = exports.always = exports.identity = exports.last = exports.ffirst = exports.first = exports.noop = exports.ifLet = exports.isNil = void 0;
4
- exports.pushToMapKey = exports.addToMapKey = exports.pushToKey = exports.addToKey = exports.batcher = exports.batch = exports.throttleWithValue = exports.throttle = exports.memoize = exports.once = exports.chunks = exports.chunk = exports.initArray = exports.indexBy = exports.groupBy = exports.sortBy = exports.sort = exports.uniqBy = exports.uniq = exports.partition = exports.flatten = exports.fromPairs = exports.pluck = exports.ensureNumber = exports.ensurePlural = exports.toIterable = exports.isIterable = exports.sample = exports.shuffle = exports.choice = exports.insert = exports.splitAt = exports.hash = exports.assoc = exports.prop = exports.ne = exports.eq = exports.spec = exports.nthNe = exports.nthEq = exports.nth = exports.equals = exports.isPojo = exports.ellipsize = exports.tryCatch = exports.setJson = exports.getJson = exports.parseJson = exports.clamp = exports.toggle = void 0;
5
- exports.bech32ToHex = exports.hexToBech32 = exports.uploadFile = exports.postJson = exports.fetchJson = exports.ms = exports.ago = exports.now = exports.int = exports.YEAR = exports.QUARTER = exports.MONTH = exports.WEEK = exports.DAY = exports.HOUR = exports.MINUTE = exports.switcher = void 0;
6
- const base_1 = require("@scure/base");
7
- /** Checks if a value is null or undefined */
8
- const isNil = (x) => [null, undefined].includes(x);
9
- exports.isNil = isNil;
10
- /**
11
- * Executes a function if the value is defined
12
- * @param x - The value to check
13
- * @param f - Function to execute if x is defined
14
- * @returns Result of f(x) if x is defined, undefined otherwise
15
- */
16
- const ifLet = (x, f) => x === undefined ? undefined : f(x);
17
- exports.ifLet = ifLet;
18
- /** Function that does nothing and returns undefined */
19
- const noop = (...args) => undefined;
20
- exports.noop = noop;
21
- /**
22
- * Returns the first element of an array
23
- * @param xs - The array
24
- * @returns First element or undefined
25
- */
26
- const first = (xs, ...args) => xs[0];
27
- exports.first = first;
28
- /**
29
- * Returns the first element of the first array in a nested array
30
- * @param xs - Array of arrays
31
- * @returns First element of first array or undefined
32
- */
33
- const ffirst = (xs, ...args) => xs[0][0];
34
- exports.ffirst = ffirst;
35
- /**
36
- * Returns the last element of an array
37
- * @param xs - The array
38
- * @returns Last element or undefined
39
- */
40
- const last = (xs, ...args) => xs[xs.length - 1];
41
- exports.last = last;
42
- /**
43
- * Returns the input value unchanged
44
- * @param x - Any value
45
- * @returns The same value
46
- */
47
- const identity = (x, ...args) => x;
48
- exports.identity = identity;
49
- /**
50
- * Creates a function that always returns the same value
51
- * @param x - Value to return
52
- * @returns Function that returns x
53
- */
54
- const always = (x, ...args) => () => x;
55
- exports.always = always;
56
- /**
57
- * Returns the logical NOT of a value
58
- * @param x - Value to negate
59
- * @returns !x
60
- */
61
- const not = (x, ...args) => !x;
62
- exports.not = not;
63
- /** Returns a function that returns the boolean negation of the given function */
64
- const complement = (f) => (...args) => !f(...args);
65
- exports.complement = complement;
66
- /** Converts a Maybe<number> to a number, defaulting to 0 */
67
- const num = (x) => x || 0;
68
- exports.num = num;
69
- /** Adds two numbers, handling undefined values */
70
- const add = (x, y) => (0, exports.num)(x) + (0, exports.num)(y);
71
- exports.add = add;
72
- /** Subtracts two numbers, handling undefined values */
73
- const sub = (x, y) => (0, exports.num)(x) - (0, exports.num)(y);
74
- exports.sub = sub;
75
- /** Multiplies two numbers, handling undefined values */
76
- const mul = (x, y) => (0, exports.num)(x) * (0, exports.num)(y);
77
- exports.mul = mul;
78
- /** Divides two numbers, handling undefined values */
79
- const div = (x, y) => (0, exports.num)(x) / y;
80
- exports.div = div;
81
- /** Increments a number by 1, handling undefined values */
82
- const inc = (x) => (0, exports.add)(x, 1);
83
- exports.inc = inc;
84
- /** Decrements a number by 1, handling undefined values */
85
- const dec = (x) => (0, exports.sub)(x, 1);
86
- exports.dec = dec;
87
- /** Less than comparison, handling undefined values */
88
- const lt = (x, y) => (0, exports.num)(x) < (0, exports.num)(y);
89
- exports.lt = lt;
90
- /** Less than or equal comparison, handling undefined values */
91
- const lte = (x, y) => (0, exports.num)(x) <= (0, exports.num)(y);
92
- exports.lte = lte;
93
- /** Greater than comparison, handling undefined values */
94
- const gt = (x, y) => (0, exports.num)(x) > (0, exports.num)(y);
95
- exports.gt = gt;
96
- /** Greater than or equal comparison, handling undefined values */
97
- const gte = (x, y) => (0, exports.num)(x) >= (0, exports.num)(y);
98
- exports.gte = gte;
99
- /** Returns maximum value in array, handling undefined values */
100
- const max = (xs) => xs.reduce((a, b) => Math.max((0, exports.num)(a), (0, exports.num)(b)), 0);
101
- exports.max = max;
102
- /** Returns minimum value in array, handling undefined values */
103
- const min = (xs) => xs.reduce((a, b) => Math.min((0, exports.num)(a), (0, exports.num)(b)), 0);
104
- exports.min = min;
105
- /** Returns sum of array values, handling undefined values */
106
- const sum = (xs) => xs.reduce((a, b) => (0, exports.add)(a, b), 0);
107
- exports.sum = sum;
108
- /** Returns average of array values, handling undefined values */
109
- const avg = (xs) => (0, exports.sum)(xs) / xs.length;
110
- exports.avg = avg;
111
- /**
112
- * Returns array with first n elements removed
113
- * @param n - Number of elements to drop
114
- * @param xs - Input array
115
- * @returns Array with first n elements removed
116
- */
117
- const drop = (n, xs) => xs.slice(n);
118
- exports.drop = drop;
119
- /**
120
- * Returns first n elements of array
121
- * @param n - Number of elements to take
122
- * @param xs - Input array
123
- * @returns Array of first n elements
124
- */
125
- const take = (n, xs) => xs.slice(0, n);
126
- exports.take = take;
127
- /**
128
- * Creates new object with specified keys removed
129
- * @param ks - Keys to remove
130
- * @param x - Source object
131
- * @returns New object without specified keys
132
- */
133
- const omit = (ks, x) => {
134
- const r = { ...x };
135
- for (const k of ks) {
136
- delete r[k];
137
- }
138
- return r;
139
- };
140
- exports.omit = omit;
141
- /**
142
- * Creates new object excluding entries with specified values
143
- * @param xs - Values to exclude
144
- * @param x - Source object
145
- * @returns New object without entries containing specified values
146
- */
147
- const omitVals = (xs, x) => {
148
- const r = {};
149
- for (const [k, v] of Object.entries(x)) {
150
- if (!xs.includes(v)) {
151
- r[k] = v;
152
- }
153
- }
154
- return r;
155
- };
156
- exports.omitVals = omitVals;
157
- /**
158
- * Creates new object with only specified keys
159
- * @param ks - Keys to keep
160
- * @param x - Source object
161
- * @returns New object with only specified keys
162
- */
163
- const pick = (ks, x) => {
164
- const r = { ...x };
165
- for (const k of Object.keys(x)) {
166
- if (!ks.includes(k)) {
167
- delete r[k];
168
- }
169
- }
170
- return r;
171
- };
172
- exports.pick = pick;
173
- /**
174
- * Generates sequence of numbers from a to b
175
- * @param a - Start number (inclusive)
176
- * @param b - End number (exclusive)
177
- * @param step - Increment between numbers
178
- * @yields Numbers in sequence
179
- */
180
- function* range(a, b, step = 1) {
181
- for (let i = a; i < b; i += step) {
182
- yield i;
183
- }
184
- }
185
- exports.range = range;
186
- /**
187
- * Creates new object with transformed keys
188
- * @param f - Function to transform keys
189
- * @param x - Source object
190
- * @returns Object with transformed keys
191
- */
192
- const mapKeys = (f, x) => {
193
- const r = {};
194
- for (const [k, v] of Object.entries(x)) {
195
- r[f(k)] = v;
196
- }
197
- return r;
198
- };
199
- exports.mapKeys = mapKeys;
200
- /**
201
- * Creates new object with transformed values
202
- * @param f - Function to transform values
203
- * @param x - Source object
204
- * @returns Object with transformed values
205
- */
206
- const mapVals = (f, x) => {
207
- const r = {};
208
- for (const [k, v] of Object.entries(x)) {
209
- r[k] = f(v);
210
- }
211
- return r;
212
- };
213
- exports.mapVals = mapVals;
214
- /**
215
- * Merges two objects, with left object taking precedence
216
- * @param a - Left object
217
- * @param b - Right object
218
- * @returns Merged object with a's properties overriding b's
219
- */
220
- const mergeLeft = (a, b) => ({ ...b, ...a });
221
- exports.mergeLeft = mergeLeft;
222
- /**
223
- * Merges two objects, with right object taking precedence
224
- * @param a - Left object
225
- * @param b - Right object
226
- * @returns Merged object with b's properties overriding a's
227
- */
228
- const mergeRight = (a, b) => ({ ...a, ...b });
229
- exports.mergeRight = mergeRight;
230
- /**
231
- * Checks if a number is between two values (exclusive)
232
- * @param bounds - Lower and upper bounds
233
- * @param n - Number to check
234
- * @returns True if n is between low and high
235
- */
236
- const between = ([low, high], n) => n > low && n < high;
237
- exports.between = between;
238
- /**
239
- * Checks if a number is between two values (inclusive)
240
- * @param bounds - Lower and upper bounds
241
- * @param n - Number to check
242
- * @returns True if n is between low and high
243
- */
244
- const within = ([low, high], n) => n >= low && n <= high;
245
- exports.within = within;
246
- /**
247
- * Generates random integer between min and max (inclusive)
248
- * @param min - Minimum value
249
- * @param max - Maximum value
250
- * @returns Random integer
251
- */
252
- const randomInt = (min = 0, max = 9) => min + Math.round(Math.random() * (max - min));
253
- exports.randomInt = randomInt;
254
- /**
255
- * Generates random string ID
256
- * @returns Random string suitable for use as an ID
257
- */
258
- const randomId = () => Math.random().toString().slice(2);
259
- exports.randomId = randomId;
260
- /**
261
- * Removes protocol (http://, https://, etc) from URL
262
- * @param url - URL to process
263
- * @returns URL without protocol
264
- */
265
- const stripProtocol = (url) => url.replace(/.*:\/\//, "");
266
- exports.stripProtocol = stripProtocol;
267
- /**
268
- * Formats URL for display by removing protocol, www, and trailing slash
269
- * @param url - URL to format
270
- * @returns Formatted URL
271
- */
272
- const displayUrl = (url) => (0, exports.stripProtocol)(url).replace(/^(www\.)?/i, "").replace(/\/$/, "");
273
- exports.displayUrl = displayUrl;
274
- /**
275
- * Extracts and formats domain from URL
276
- * @param url - URL to process
277
- * @returns Formatted domain name
278
- */
279
- const displayDomain = (url) => (0, exports.displayUrl)((0, exports.first)(url.split(/[\/\?]/)));
280
- exports.displayDomain = displayDomain;
281
- /**
282
- * Creates a promise that resolves after specified time
283
- * @param t - Time in milliseconds
284
- * @returns Promise that resolves after t milliseconds
285
- */
286
- const sleep = (t) => new Promise(resolve => setTimeout(resolve, t));
287
- exports.sleep = sleep;
288
- /**
289
- * Concatenates multiple arrays, filtering out null/undefined
290
- * @param xs - Arrays to concatenate
291
- * @returns Combined array
292
- */
293
- const concat = (...xs) => xs.flatMap(x => (0, exports.isNil)(x) ? [] : x);
294
- exports.concat = concat;
295
- /**
296
- * Appends element to array
297
- * @param x - Element to append
298
- * @param xs - Array to append to
299
- * @returns New array with element appended
300
- */
301
- const append = (x, xs) => (0, exports.concat)(xs, [x]);
302
- exports.append = append;
303
- /**
304
- * Creates union of two arrays
305
- * @param a - First array
306
- * @param b - Second array
307
- * @returns Array containing unique elements from both arrays
308
- */
309
- const union = (a, b) => (0, exports.uniq)([...a, ...b]);
310
- exports.union = union;
311
- /**
312
- * Returns elements common to both arrays
313
- * @param a - First array
314
- * @param b - Second array
315
- * @returns Array of elements present in both inputs
316
- */
317
- const intersection = (a, b) => {
318
- const s = new Set(b);
319
- return a.filter(x => s.has(x));
320
- };
321
- exports.intersection = intersection;
322
- /**
323
- * Returns elements in first array not present in second
324
- * @param a - Source array
325
- * @param b - Array of elements to exclude
326
- * @returns Array containing elements unique to first array
327
- */
328
- const difference = (a, b) => {
329
- const s = new Set(b);
330
- return a.filter(x => !s.has(x));
331
- };
332
- exports.difference = difference;
333
- /**
334
- * Removes all instances of an element from array
335
- * @param a - Element to remove
336
- * @param xs - Source array
337
- * @returns New array with element removed
338
- */
339
- const remove = (a, xs) => xs.filter(x => x !== a);
340
- exports.remove = remove;
341
- /**
342
- * Returns elements from second array not present in first
343
- * @param a - Array of elements to exclude
344
- * @param b - Source array
345
- * @returns Filtered array
346
- */
347
- const without = (a, b) => b.filter(x => !a.includes(x));
348
- exports.without = without;
349
- /**
350
- * Toggles presence of element in array
351
- * @param x - Element to toggle
352
- * @param xs - Source array
353
- * @returns New array with element added or removed
354
- */
355
- const toggle = (x, xs) => xs.includes(x) ? (0, exports.remove)(x, xs) : (0, exports.append)(x, xs);
356
- exports.toggle = toggle;
357
- /**
358
- * Constrains number between min and max values
359
- * @param bounds - Minimum and maximum allowed values
360
- * @param n - Number to clamp
361
- * @returns Clamped value
362
- */
363
- const clamp = ([min, max], n) => Math.min(max, Math.max(min, n));
364
- exports.clamp = clamp;
365
- /**
366
- * Safely parses JSON string
367
- * @param json - JSON string to parse
368
- * @returns Parsed object or null if invalid
369
- */
370
- const parseJson = (json) => {
371
- if (!json)
372
- return undefined;
373
- try {
374
- return JSON.parse(json);
375
- }
376
- catch (e) {
377
- return undefined;
378
- }
379
- };
380
- exports.parseJson = parseJson;
381
- /**
382
- * Gets and parses JSON from localStorage
383
- * @param k - Storage key
384
- * @returns Parsed value or undefined if invalid/missing
385
- */
386
- const getJson = (k) => (0, exports.parseJson)(localStorage.getItem(k) || "");
387
- exports.getJson = getJson;
388
- /**
389
- * Stringifies and stores value in localStorage
390
- * @param k - Storage key
391
- * @param v - Value to store
392
- */
393
- const setJson = (k, v) => localStorage.setItem(k, JSON.stringify(v));
394
- exports.setJson = setJson;
395
- /**
396
- * Safely executes function and handles errors
397
- * @param f - Function to execute
398
- * @param onError - Optional error handler
399
- * @returns Function result or undefined if error
400
- */
401
- const tryCatch = (f, onError) => {
402
- try {
403
- const r = f();
404
- if (r instanceof Promise) {
405
- r.catch(e => onError === null || onError === void 0 ? void 0 : onError(e));
406
- }
407
- return r;
408
- }
409
- catch (e) {
410
- onError === null || onError === void 0 ? void 0 : onError(e);
411
- }
412
- return undefined;
413
- };
414
- exports.tryCatch = tryCatch;
415
- /**
416
- * Truncates string to length, breaking at word boundaries
417
- * @param s - String to truncate
418
- * @param l - Maximum length
419
- * @param suffix - String to append if truncated
420
- * @returns Truncated string
421
- */
422
- const ellipsize = (s, l, suffix = '...') => {
423
- if (s.length < l * 1.1) {
424
- return s;
425
- }
426
- while (s.length > l && s.includes(' ')) {
427
- s = s.split(' ').slice(0, -1).join(' ');
428
- }
429
- return s + suffix;
430
- };
431
- exports.ellipsize = ellipsize;
432
- /**
433
- * Checks if value is a plain object
434
- * @param obj - Value to check
435
- * @returns True if value is a plain object
436
- */
437
- const isPojo = (obj) => {
438
- if (obj === null || typeof obj !== "object") {
439
- return false;
440
- }
441
- return Object.getPrototypeOf(obj) === Object.prototype;
442
- };
443
- exports.isPojo = isPojo;
444
- /**
445
- * Deep equality comparison
446
- * @param a - First value
447
- * @param b - Second value
448
- * @returns True if values are deeply equal
449
- */
450
- const equals = (a, b) => {
451
- if (a === b)
452
- return true;
453
- if (a instanceof Set && b instanceof Set) {
454
- a = Array.from(a);
455
- b = Array.from(b);
456
- }
457
- if (a instanceof Set) {
458
- if (!(b instanceof Set) || a.size !== b.size) {
459
- return false;
460
- }
461
- return Array.from(a).every(x => b.has(x));
462
- }
463
- if (Array.isArray(a)) {
464
- if (!Array.isArray(b) || a.length !== b.length) {
465
- return false;
466
- }
467
- for (let i = 0; i < a.length; i++) {
468
- if (!(0, exports.equals)(a[i], b[i])) {
469
- return false;
470
- }
471
- }
472
- return true;
473
- }
474
- if ((0, exports.isPojo)(a)) {
475
- if (!(0, exports.isPojo)(b)) {
476
- return false;
477
- }
478
- const aKeys = Object.keys(a);
479
- const bKeys = Object.keys(b);
480
- if (aKeys.length !== bKeys.length) {
481
- return false;
482
- }
483
- for (const k of aKeys) {
484
- if (!(0, exports.equals)(a[k], b[k])) {
485
- return false;
486
- }
487
- }
488
- return true;
489
- }
490
- return false;
491
- };
492
- exports.equals = equals;
493
- // Curried utils
494
- /** Returns a function that gets the nth element of an array */
495
- const nth = (i) => (xs, ...args) => xs[i];
496
- exports.nth = nth;
497
- /** Returns a function that checks if nth element equals value */
498
- const nthEq = (i, v) => (xs, ...args) => xs[i] === v;
499
- exports.nthEq = nthEq;
500
- /** Returns a function that checks if nth element does not equal value */
501
- const nthNe = (i, v) => (xs, ...args) => xs[i] !== v;
502
- exports.nthNe = nthNe;
503
- /** Returns a function that checks if key/value pairs of x match all pairs in spec */
504
- const spec = (values) => (x) => {
505
- for (const [k, v] of Object.entries(values)) {
506
- if (x[k] !== v)
507
- return false;
508
- }
509
- return true;
510
- };
511
- exports.spec = spec;
512
- /** Returns a function that checks equality with value */
513
- const eq = (v) => (x) => x === v;
514
- exports.eq = eq;
515
- /** Returns a function that checks inequality with value */
516
- const ne = (v) => (x) => x !== v;
517
- exports.ne = ne;
518
- /** Returns a function that gets property value from object */
519
- const prop = (k) => (x) => x[k];
520
- exports.prop = prop;
521
- /** Returns a function that adds/updates property on object */
522
- const assoc = (k, v) => (o) => ({ ...o, [k]: v });
523
- exports.assoc = assoc;
524
- /** Generates a hash string from input string */
525
- const hash = (s) => Math.abs(s.split("").reduce((a, b) => ((a << 5) - a + b.charCodeAt(0)) | 0, 0)).toString();
526
- exports.hash = hash;
527
- // Collections
528
- /** Splits array into two parts at index */
529
- const splitAt = (n, xs) => [xs.slice(0, n), xs.slice(n)];
530
- exports.splitAt = splitAt;
531
- /** Inserts element into array at index */
532
- const insert = (n, x, xs) => [...xs.slice(0, n), x, ...xs.slice(n)];
533
- exports.insert = insert;
534
- /** Returns random element from array */
535
- const choice = (xs) => xs[Math.floor(xs.length * Math.random())];
536
- exports.choice = choice;
537
- /** Returns shuffled copy of iterable */
538
- const shuffle = (xs) => Array.from(xs).sort(() => Math.random() > 0.5 ? 1 : -1);
539
- exports.shuffle = shuffle;
540
- /** Returns n random elements from array */
541
- const sample = (n, xs) => (0, exports.shuffle)(xs).slice(0, n);
542
- exports.sample = sample;
543
- /** Checks if value is iterable */
544
- const isIterable = (x) => Symbol.iterator in Object(x);
545
- exports.isIterable = isIterable;
546
- /** Ensures value is iterable by wrapping in array if needed */
547
- const toIterable = (x) => (0, exports.isIterable)(x) ? x : [x];
548
- exports.toIterable = toIterable;
549
- /** Ensures value is array by wrapping if needed */
550
- const ensurePlural = (x) => (x instanceof Array ? x : [x]);
551
- exports.ensurePlural = ensurePlural;
552
- /** Converts string or number to number */
553
- const ensureNumber = (x) => parseFloat(x);
554
- exports.ensureNumber = ensureNumber;
555
- /** Returns a function that gets property value from object */
556
- const pluck = (k, xs) => xs.map(x => x[k]);
557
- exports.pluck = pluck;
558
- /**
559
- * Creates object from array of key-value pairs
560
- * @param pairs - Array of [key, value] tuples
561
- * @returns Object with keys and values from pairs
562
- */
563
- const fromPairs = (pairs) => {
564
- const r = {};
565
- for (const [k, v] of pairs) {
566
- if (k && v) {
567
- r[k] = v;
568
- }
569
- }
570
- return r;
571
- };
572
- exports.fromPairs = fromPairs;
573
- /**
574
- * Flattens array of arrays into single array
575
- * @param xs - Array of arrays to flatten
576
- * @returns Flattened array
577
- */
578
- const flatten = (xs) => xs.flatMap(exports.identity);
579
- exports.flatten = flatten;
580
- /**
581
- * Splits array into two arrays based on predicate
582
- * @param f - Function to test elements
583
- * @param xs - Array to partition
584
- * @returns Tuple of [matching, non-matching] arrays
585
- */
586
- const partition = (f, xs) => {
587
- const a = [];
588
- const b = [];
589
- for (const x of xs) {
590
- if (f(x)) {
591
- a.push(x);
592
- }
593
- else {
594
- b.push(x);
595
- }
596
- }
597
- return [a, b];
598
- };
599
- exports.partition = partition;
600
- /**
601
- * Returns array with duplicate elements removed
602
- * @param xs - Array with possible duplicates
603
- * @returns Array with unique elements
604
- */
605
- const uniq = (xs) => Array.from(new Set(xs));
606
- exports.uniq = uniq;
607
- /**
608
- * Returns array with elements unique by key function
609
- * @param f - Function to generate key for each element
610
- * @param xs - Input array
611
- * @returns Array with elements unique by key
612
- */
613
- const uniqBy = (f, xs) => {
614
- const s = new Set();
615
- const r = [];
616
- for (const x of xs) {
617
- const k = f(x);
618
- if (s.has(k)) {
619
- continue;
620
- }
621
- s.add(k);
622
- r.push(x);
623
- }
624
- return r;
625
- };
626
- exports.uniqBy = uniqBy;
627
- /**
628
- * Returns sorted copy of array
629
- * @param xs - Array to sort
630
- * @returns New sorted array
631
- */
632
- const sort = (xs) => [...xs].sort();
633
- exports.sort = sort;
634
- /**
635
- * Returns array sorted by key function
636
- * @param f - Function to generate sort key
637
- * @param xs - Array to sort
638
- * @returns Sorted array
639
- */
640
- const sortBy = (f, xs) => [...xs].sort((a, b) => {
641
- const x = f(a);
642
- const y = f(b);
643
- return x < y ? -1 : x > y ? 1 : 0;
644
- });
645
- exports.sortBy = sortBy;
646
- /**
647
- * Groups array elements by key function
648
- * @param f - Function to generate group key
649
- * @param xs - Array to group
650
- * @returns Map of groups
651
- */
652
- const groupBy = (f, xs) => {
653
- const r = new Map();
654
- for (const x of xs) {
655
- const k = f(x);
656
- let v = r.get(k);
657
- if (!v) {
658
- v = [];
659
- r.set(k, v);
660
- }
661
- v.push(x);
662
- }
663
- return r;
664
- };
665
- exports.groupBy = groupBy;
666
- /**
667
- * Creates map from array using key function
668
- * @param f - Function to generate key
669
- * @param xs - Array to index
670
- * @returns Map of values by key
671
- */
672
- const indexBy = (f, xs) => {
673
- const r = new Map();
674
- for (const x of xs) {
675
- r.set(f(x), x);
676
- }
677
- return r;
678
- };
679
- exports.indexBy = indexBy;
680
- /**
681
- * Creates array of specified length using generator function
682
- * @param n - Length of array
683
- * @param f - Function to generate each element
684
- * @returns Generated array
685
- */
686
- const initArray = (n, f) => {
687
- const result = [];
688
- for (let i = 0; i < n; i++) {
689
- result.push(f());
690
- }
691
- return result;
692
- };
693
- exports.initArray = initArray;
694
- /**
695
- * Splits array into chunks of specified length
696
- * @param chunkLength - Maximum length of each chunk
697
- * @param xs - Array to split
698
- * @returns Array of chunks
699
- */
700
- const chunk = (chunkLength, xs) => {
701
- const result = [];
702
- const current = [];
703
- for (const item of xs) {
704
- if (current.length < chunkLength) {
705
- current.push(item);
706
- }
707
- else {
708
- result.push(current.splice(0));
709
- }
710
- }
711
- if (current.length > 0) {
712
- result.push(current);
713
- }
714
- return result;
715
- };
716
- exports.chunk = chunk;
717
- /**
718
- * Splits array into specified number of chunks
719
- * @param n - Number of chunks
720
- * @param xs - Array to split
721
- * @returns Array of n chunks
722
- */
723
- const chunks = (n, xs) => {
724
- const result = (0, exports.initArray)(n, () => []);
725
- for (let i = 0; i < xs.length; i++) {
726
- result[i % n].push(xs[i]);
727
- }
728
- return result;
729
- };
730
- exports.chunks = chunks;
731
- /**
732
- * Creates function that only executes once
733
- * @param f - Function to wrap
734
- * @returns Function that executes f only on first call
735
- */
736
- const once = (f) => {
737
- let called = false;
738
- return (...args) => {
739
- if (!called) {
740
- called = true;
741
- f(...args);
742
- }
743
- };
744
- };
745
- exports.once = once;
746
- /**
747
- * Memoizes function results based on arguments
748
- * @param f - Function to memoize
749
- * @returns Memoized function
750
- */
751
- const memoize = (f) => {
752
- let prevArgs;
753
- let result;
754
- return (...args) => {
755
- if (!(0, exports.equals)(prevArgs, args)) {
756
- prevArgs = args;
757
- result = f(...args);
758
- }
759
- return result;
760
- };
761
- };
762
- exports.memoize = memoize;
763
- /**
764
- * Creates throttled version of function
765
- * @param ms - Minimum time between calls
766
- * @param f - Function to throttle
767
- * @returns Throttled function
768
- */
769
- const throttle = (ms, f) => {
770
- if (ms === 0) {
771
- return f;
772
- }
773
- let paused = false;
774
- let nextArgs;
775
- const unpause = () => {
776
- if (nextArgs) {
777
- f(...nextArgs);
778
- nextArgs = undefined;
779
- }
780
- paused = false;
781
- };
782
- return (...thisArgs) => {
783
- if (!paused) {
784
- f(...thisArgs);
785
- paused = true;
786
- setTimeout(unpause, ms);
787
- }
788
- else {
789
- nextArgs = thisArgs;
790
- }
791
- };
792
- };
793
- exports.throttle = throttle;
794
- /**
795
- * Creates throttled function that returns cached value
796
- * @param ms - Minimum time between updates
797
- * @param f - Function to throttle
798
- * @returns Function returning latest value
799
- */
800
- const throttleWithValue = (ms, f) => {
801
- let value;
802
- const update = (0, exports.throttle)(ms, () => {
803
- value = f();
804
- });
805
- return () => {
806
- update();
807
- return value;
808
- };
809
- };
810
- exports.throttleWithValue = throttleWithValue;
811
- /**
812
- * Creates batching function that collects items
813
- * @param t - Time window for batching
814
- * @param f - Function to process batch
815
- * @returns Function that adds items to batch
816
- */
817
- const batch = (t, f) => {
818
- const xs = [];
819
- const cb = (0, exports.throttle)(t, () => xs.length > 0 && f(xs.splice(0)));
820
- return (x) => {
821
- xs.push(x);
822
- cb();
823
- };
824
- };
825
- exports.batch = batch;
826
- /**
827
- * Creates batching function that returns results
828
- * @param t - Time window for batching
829
- * @param execute - Function to process batch
830
- * @returns Function that returns promise of result
831
- */
832
- const batcher = (t, execute) => {
833
- const queue = [];
834
- const _execute = async () => {
835
- const items = queue.splice(0);
836
- const results = await execute(items.map(item => item.request));
837
- if (results.length !== items.length) {
838
- throw new Error("Execute must return a result for each request");
839
- }
840
- results.forEach(async (r, i) => items[i].resolve(await r));
841
- };
842
- return (request) => new Promise(resolve => {
843
- if (queue.length === 0) {
844
- setTimeout(_execute, t);
845
- }
846
- queue.push({ request, resolve });
847
- });
848
- };
849
- exports.batcher = batcher;
850
- /**
851
- * Adds value to Set at key in object
852
- * @param m - Object mapping keys to Sets
853
- * @param k - Key to add to
854
- * @param v - Value to add
855
- */
856
- const addToKey = (m, k, v) => {
857
- const s = m[k] || new Set();
858
- s.add(v);
859
- m[k] = s;
860
- };
861
- exports.addToKey = addToKey;
862
- /**
863
- * Pushes value to array at key in object
864
- * @param m - Object mapping keys to arrays
865
- * @param k - Key to push to
866
- * @param v - Value to push
867
- */
868
- const pushToKey = (m, k, v) => {
869
- const a = m[k] || [];
870
- a.push(v);
871
- m[k] = a;
872
- };
873
- exports.pushToKey = pushToKey;
874
- /**
875
- * Adds value to Set at key in Map
876
- * @param m - Map of Sets
877
- * @param k - Key to add to
878
- * @param v - Value to add
879
- */
880
- const addToMapKey = (m, k, v) => {
881
- const s = m.get(k) || new Set();
882
- s.add(v);
883
- m.set(k, s);
884
- };
885
- exports.addToMapKey = addToMapKey;
886
- /**
887
- * Pushes value to array at key in Map
888
- * @param m - Map of arrays
889
- * @param k - Key to push to
890
- * @param v - Value to push
891
- */
892
- const pushToMapKey = (m, k, v) => {
893
- const a = m.get(k) || [];
894
- a.push(v);
895
- m.set(k, a);
896
- };
897
- exports.pushToMapKey = pushToMapKey;
898
- /**
899
- * Switches on key in object, with default fallback
900
- * @param k - Key to look up
901
- * @param m - Object with values and optional default
902
- * @returns Value at key or default value
903
- */
904
- const switcher = (k, m) => m[k] === undefined ? m.default : m[k];
905
- exports.switcher = switcher;
906
- /** One minute in seconds */
907
- exports.MINUTE = 60;
908
- /** One hour in seconds */
909
- exports.HOUR = 60 * exports.MINUTE;
910
- /** One day in seconds */
911
- exports.DAY = 24 * exports.HOUR;
912
- /** One week in seconds */
913
- exports.WEEK = 7 * exports.DAY;
914
- /** One month in seconds (approximate) */
915
- exports.MONTH = 30 * exports.DAY;
916
- /** One quarter in seconds (approximate) */
917
- exports.QUARTER = 90 * exports.DAY;
918
- /** One year in seconds (approximate) */
919
- exports.YEAR = 365 * exports.DAY;
920
- /**
921
- * Multiplies time unit by count
922
- * @param unit - Time unit in seconds
923
- * @param count - Number of units
924
- * @returns Total seconds
925
- */
926
- const int = (unit, count = 1) => unit * count;
927
- exports.int = int;
928
- /** Returns current Unix timestamp in seconds */
929
- const now = () => Math.round(Date.now() / 1000);
930
- exports.now = now;
931
- /**
932
- * Returns Unix timestamp from specified time ago
933
- * @param unit - Time unit in seconds
934
- * @param count - Number of units
935
- * @returns Timestamp in seconds
936
- */
937
- const ago = (unit, count = 1) => (0, exports.now)() - (0, exports.int)(unit, count);
938
- exports.ago = ago;
939
- /**
940
- * Converts seconds to milliseconds
941
- * @param seconds - Time in seconds
942
- * @returns Time in milliseconds
943
- */
944
- const ms = (seconds) => seconds * 1000;
945
- exports.ms = ms;
946
- /**
947
- * Fetches JSON from URL with options
948
- * @param url - URL to fetch from
949
- * @param opts - Fetch options
950
- * @returns Promise of parsed JSON response
951
- */
952
- const fetchJson = async (url, opts = {}) => {
953
- if (!opts.headers) {
954
- opts.headers = {};
955
- }
956
- opts.headers["Accept"] = "application/json";
957
- const res = await fetch(url, opts);
958
- const json = await res.json();
959
- return json;
960
- };
961
- exports.fetchJson = fetchJson;
962
- /**
963
- * Posts JSON data to URL
964
- * @param url - URL to post to
965
- * @param data - Data to send
966
- * @param opts - Additional fetch options
967
- * @returns Promise of parsed JSON response
968
- */
969
- const postJson = async (url, data, opts = {}) => {
970
- if (!opts.method) {
971
- opts.method = "POST";
972
- }
973
- if (!opts.headers) {
974
- opts.headers = {};
975
- }
976
- opts.headers["Content-Type"] = "application/json";
977
- opts.body = JSON.stringify(data);
978
- return (0, exports.fetchJson)(url, opts);
979
- };
980
- exports.postJson = postJson;
981
- /**
982
- * Uploads file to URL
983
- * @param url - Upload URL
984
- * @param file - File to upload
985
- * @returns Promise of parsed JSON response
986
- */
987
- const uploadFile = (url, file) => {
988
- const body = new FormData();
989
- body.append("file", file);
990
- return (0, exports.fetchJson)(url, { method: "POST", body });
991
- };
992
- exports.uploadFile = uploadFile;
993
- /**
994
- * Converts hex string to bech32 format
995
- * @param prefix - Bech32 prefix
996
- * @param hex - Hex string to convert
997
- * @returns Bech32 encoded string
998
- */
999
- const hexToBech32 = (prefix, hex) => base_1.bech32.encode(prefix, base_1.bech32.toWords(base_1.utf8.decode(hex)), false);
1000
- exports.hexToBech32 = hexToBech32;
1001
- /**
1002
- * Converts bech32 string to hex format
1003
- * @param b32 - Bech32 string to convert
1004
- * @returns Hex encoded string
1005
- */
1006
- const bech32ToHex = (b32) => base_1.utf8.encode(base_1.bech32.fromWords(base_1.bech32.decode(b32, false).words));
1007
- exports.bech32ToHex = bech32ToHex;
1008
- //# sourceMappingURL=Tools.cjs.map