@dxos/util 0.6.13-main.ed424a1 → 0.6.13

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 (53) hide show
  1. package/dist/lib/browser/index.mjs +140 -105
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node/index.cjs +132 -96
  5. package/dist/lib/node/index.cjs.map +4 -4
  6. package/dist/lib/node/meta.json +1 -1
  7. package/dist/types/src/complex.d.ts +8 -8
  8. package/dist/types/src/complex.d.ts.map +1 -1
  9. package/dist/types/src/index.d.ts +3 -5
  10. package/dist/types/src/index.d.ts.map +1 -1
  11. package/dist/types/src/params.d.ts +22 -0
  12. package/dist/types/src/params.d.ts.map +1 -0
  13. package/dist/types/src/params.test.d.ts +2 -0
  14. package/dist/types/src/params.test.d.ts.map +1 -0
  15. package/dist/types/src/platform.test.d.ts +2 -0
  16. package/dist/types/src/platform.test.d.ts.map +1 -0
  17. package/dist/types/src/weak.d.ts +4 -4
  18. package/dist/types/src/weak.d.ts.map +1 -1
  19. package/package.json +9 -8
  20. package/src/array.test.ts +2 -1
  21. package/src/bitfield.test.ts +2 -1
  22. package/src/callback.test.ts +2 -1
  23. package/src/complex.test.ts +2 -1
  24. package/src/complex.ts +8 -8
  25. package/src/defer.test.ts +2 -1
  26. package/src/human-hash.test.ts +2 -1
  27. package/src/index.ts +3 -5
  28. package/src/join-tables.test.ts +2 -1
  29. package/src/order.test.ts +2 -1
  30. package/src/params.test.ts +38 -0
  31. package/src/params.ts +68 -0
  32. package/src/platform.test.ts +17 -0
  33. package/src/reducers.test.ts +2 -1
  34. package/src/safe-instanceof.test.ts +2 -1
  35. package/src/sort.test.ts +2 -1
  36. package/src/tracer.test.ts +2 -1
  37. package/src/types.test.ts +2 -1
  38. package/src/typings.d.ts +5 -0
  39. package/src/uint8array.test.ts +2 -1
  40. package/src/weak.test.ts +8 -4
  41. package/src/weak.ts +4 -4
  42. package/dist/lib/node-esm/index.mjs +0 -1943
  43. package/dist/lib/node-esm/index.mjs.map +0 -7
  44. package/dist/lib/node-esm/meta.json +0 -1
  45. package/dist/types/src/array-to-hex.d.ts +0 -2
  46. package/dist/types/src/array-to-hex.d.ts.map +0 -1
  47. package/dist/types/src/platform.browser.test.d.ts +0 -2
  48. package/dist/types/src/platform.browser.test.d.ts.map +0 -1
  49. package/dist/types/src/platform.node.test.d.ts +0 -2
  50. package/dist/types/src/platform.node.test.d.ts.map +0 -1
  51. package/src/array-to-hex.ts +0 -23
  52. package/src/platform.browser.test.ts +0 -11
  53. package/src/platform.node.test.ts +0 -11
@@ -1,1943 +0,0 @@
1
- import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
-
3
- // packages/common/util/src/array.ts
4
- var diff = (previous, next, comparator) => {
5
- const remaining = [
6
- ...previous
7
- ];
8
- const result = {
9
- added: [],
10
- updated: [],
11
- removed: remaining
12
- };
13
- for (const object of next) {
14
- const index = remaining.findIndex((item) => comparator(item, object));
15
- if (index === -1) {
16
- result.added.push(object);
17
- } else {
18
- result.updated.push(object);
19
- remaining.splice(index, 1);
20
- }
21
- }
22
- return result;
23
- };
24
- var intersection = (a, b, comparator) => a.filter((a2) => b.find((b2) => comparator(a2, b2)) !== void 0);
25
- var distinctBy = (array, selector) => {
26
- const seenKeys = /* @__PURE__ */ new Set();
27
- return array.filter((item) => {
28
- const key = selector(item);
29
- if (seenKeys.has(key)) {
30
- return false;
31
- }
32
- seenKeys.add(key);
33
- return true;
34
- });
35
- };
36
-
37
- // packages/common/util/src/assign.ts
38
- import { invariant } from "@dxos/invariant";
39
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/common/util/src/assign.ts";
40
- var setDeep = (obj, path, value) => {
41
- invariant(path.length > 0, void 0, {
42
- F: __dxlog_file,
43
- L: 12,
44
- S: void 0,
45
- A: [
46
- "path.length > 0",
47
- ""
48
- ]
49
- });
50
- let parent = obj;
51
- for (const key of path.slice(0, -1)) {
52
- parent[key] ??= {};
53
- parent = parent[key];
54
- }
55
- parent[path.at(-1)] = value;
56
- return parent[path.at(-1)];
57
- };
58
- var getDeep = (obj, path) => {
59
- let parent = obj;
60
- for (const key of path) {
61
- parent = parent?.[key];
62
- }
63
- return parent;
64
- };
65
-
66
- // packages/common/util/src/binder.ts
67
- import util from "node:util";
68
- var createBinder = (obj) => ({
69
- fn: (fn) => fn.bind(obj),
70
- async: (fn) => util.promisify(fn.bind(obj))
71
- });
72
-
73
- // packages/common/util/src/bitfield.ts
74
- import { invariant as invariant2 } from "@dxos/invariant";
75
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/common/util/src/bitfield.ts";
76
- var BitField = class _BitField {
77
- static get(data, idx) {
78
- const bit = data[idx >> 3] >> 7 - idx % 8 & 1;
79
- return !!bit;
80
- }
81
- static set(data, idx, value) {
82
- if (value) {
83
- data[idx >> 3] = data[idx >> 3] | 1 << 7 - idx % 8;
84
- } else {
85
- data[idx >> 3] = data[idx >> 3] & ~(1 << 7 - idx % 8);
86
- }
87
- }
88
- /**
89
- * [start; end)
90
- */
91
- static count(data, begin, end) {
92
- let count = 0;
93
- for (let i = begin; i < end; i++) {
94
- const bit = data[i >> 3] >> 7 - i % 8 & 1;
95
- count += bit;
96
- }
97
- return count;
98
- }
99
- static invert(data) {
100
- const result = new Uint8Array(data.length);
101
- for (let i = 0; i < data.length; i++) {
102
- result[i] = ~data[i];
103
- }
104
- return result;
105
- }
106
- static and(first, second) {
107
- invariant2(first.length === second.length, "Bitfields must be of the same length", {
108
- F: __dxlog_file2,
109
- L: 52,
110
- S: this,
111
- A: [
112
- "first.length === second.length",
113
- "'Bitfields must be of the same length'"
114
- ]
115
- });
116
- const result = new Uint8Array(first.length);
117
- for (let i = 0; i < first.length; i++) {
118
- result[i] = first[i] & second[i];
119
- }
120
- return result;
121
- }
122
- static findIndexes(data, opts = {}) {
123
- const { start = 0, end = data.length * 8, value = true } = opts;
124
- const result = [];
125
- for (let i = start; i < end; i++) {
126
- if (_BitField.get(data, i) === value) {
127
- result.push(i);
128
- }
129
- }
130
- return result;
131
- }
132
- static ones(count) {
133
- const res = new Uint8Array(Math.ceil(Math.ceil(count) / 8)).fill(255);
134
- const bitInLastByte = Math.ceil(count % 8);
135
- res[res.length - 1] = 255 << 8 - bitInLastByte;
136
- return res;
137
- }
138
- static zeros(count) {
139
- return new Uint8Array(Math.ceil(Math.ceil(count) / 8)).fill(0);
140
- }
141
- };
142
-
143
- // packages/common/util/src/callback.ts
144
- import { invariant as invariant3 } from "@dxos/invariant";
145
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/common/util/src/callback.ts";
146
- var Callback = class {
147
- call(...args) {
148
- invariant3(this._callback, "Callback not set", {
149
- F: __dxlog_file3,
150
- L: 20,
151
- S: this,
152
- A: [
153
- "this._callback",
154
- "'Callback not set'"
155
- ]
156
- });
157
- return this._callback(...args);
158
- }
159
- callIfSet(...args) {
160
- return this._callback?.(...args);
161
- }
162
- set(callback) {
163
- invariant3(!this._callback, "Callback already set", {
164
- F: __dxlog_file3,
165
- L: 29,
166
- S: this,
167
- A: [
168
- "!this._callback",
169
- "'Callback already set'"
170
- ]
171
- });
172
- this._callback = callback;
173
- }
174
- isSet() {
175
- return !!this._callback;
176
- }
177
- };
178
- var createSetDispatch = ({ handlers }) => {
179
- return new Proxy({
180
- handlers
181
- }, {
182
- get: (target, prop) => {
183
- return (...args) => {
184
- handlers.forEach((handler) => {
185
- const method = handler[prop];
186
- if (method) {
187
- method.apply(handler, args);
188
- }
189
- });
190
- };
191
- }
192
- });
193
- };
194
-
195
- // packages/common/util/src/callback-collection.ts
196
- var CallbackCollection = class {
197
- #callbacks = [];
198
- append(callback) {
199
- this.#callbacks.push(callback);
200
- }
201
- prepend(callback) {
202
- this.#callbacks.unshift(callback);
203
- }
204
- remove(callback) {
205
- this.#callbacks = this.#callbacks.filter((c) => c !== callback);
206
- }
207
- callParallel(...args) {
208
- return Promise.all(this.#callbacks.map((callback) => callback(...args)));
209
- }
210
- async callSerial(...args) {
211
- const results = [];
212
- for (const callback of this.#callbacks) {
213
- results.push(await callback(...args));
214
- }
215
- return results;
216
- }
217
- };
218
-
219
- // packages/common/util/src/chunk-array.ts
220
- var chunkArray = (array, size) => {
221
- const result = [];
222
- for (let i = 0; i < array.length; i += size) {
223
- result.push(array.slice(i, i + size));
224
- }
225
- return result;
226
- };
227
-
228
- // packages/common/util/src/circular-buffer.ts
229
- import { invariant as invariant4 } from "@dxos/invariant";
230
- var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/common/util/src/circular-buffer.ts";
231
- var CircularBuffer = class {
232
- constructor(size) {
233
- this._nextIndex = 0;
234
- this._elementCount = 0;
235
- invariant4(size >= 1, void 0, {
236
- F: __dxlog_file4,
237
- L: 13,
238
- S: this,
239
- A: [
240
- "size >= 1",
241
- ""
242
- ]
243
- });
244
- this._buffer = new Array(size);
245
- }
246
- push(element) {
247
- const evicted = this._elementCount === this._buffer.length ? this._buffer[this._nextIndex] : void 0;
248
- this._buffer[this._nextIndex] = element;
249
- this._nextIndex = (this._nextIndex + 1) % this._buffer.length;
250
- this._elementCount = Math.min(this._buffer.length, this._elementCount + 1);
251
- return evicted;
252
- }
253
- get elementCount() {
254
- return this._elementCount;
255
- }
256
- getLast() {
257
- if (this._elementCount === 0) {
258
- return void 0;
259
- }
260
- if (this._nextIndex === 0) {
261
- return this._buffer[this._buffer.length - 1];
262
- }
263
- return this._buffer[this._nextIndex - 1];
264
- }
265
- [Symbol.iterator]() {
266
- return this.values();
267
- }
268
- *values() {
269
- if (this._elementCount === 0) {
270
- return;
271
- }
272
- if (this._elementCount < this._buffer.length) {
273
- for (let i = 0; i < this._elementCount; i++) {
274
- yield this._buffer[i];
275
- }
276
- return;
277
- }
278
- for (let i = this._nextIndex; i < this._buffer.length; i++) {
279
- yield this._buffer[i];
280
- }
281
- for (let i = 0; i < this._nextIndex; i++) {
282
- yield this._buffer[i];
283
- }
284
- }
285
- };
286
-
287
- // packages/common/util/src/complex.ts
288
- import { inspect } from "node:util";
289
- import { inspectObject, raise } from "@dxos/debug";
290
- var MAX_SERIALIZATION_LENGTH = 10;
291
- var ComplexSet = class {
292
- // prettier-ignore
293
- constructor(_projection, values) {
294
- this._projection = _projection;
295
- this._values = /* @__PURE__ */ new Map();
296
- if (values) {
297
- for (const value of values) {
298
- this.add(value);
299
- }
300
- }
301
- }
302
- toString() {
303
- return inspectObject(this);
304
- }
305
- toJSON() {
306
- return this._values.size > MAX_SERIALIZATION_LENGTH ? {
307
- size: this._values.size
308
- } : Array.from(this._values.values());
309
- }
310
- [inspect.custom]() {
311
- return inspectObject(this);
312
- }
313
- add(value) {
314
- this._values.set(this._projection(value), value);
315
- return this;
316
- }
317
- clear() {
318
- this._values.clear();
319
- }
320
- delete(value) {
321
- return this._values.delete(this._projection(value));
322
- }
323
- forEach(callbackfn, thisArg) {
324
- if (thisArg) {
325
- callbackfn = callbackfn.bind(thisArg);
326
- }
327
- this._values.forEach((value) => callbackfn(value, value, this));
328
- }
329
- has(value) {
330
- return this._values.has(this._projection(value));
331
- }
332
- get size() {
333
- return this._values.size;
334
- }
335
- [Symbol.iterator]() {
336
- return this._values.values();
337
- }
338
- *entries() {
339
- for (const value of this._values.values()) {
340
- yield [
341
- value,
342
- value
343
- ];
344
- }
345
- }
346
- keys() {
347
- return this[Symbol.iterator]();
348
- }
349
- values() {
350
- return this[Symbol.iterator]();
351
- }
352
- get [Symbol.toStringTag]() {
353
- return "ComplexSet";
354
- }
355
- union(other) {
356
- throw new Error("Method not implemented.");
357
- }
358
- intersection(other) {
359
- throw new Error("Method not implemented.");
360
- }
361
- difference(other) {
362
- throw new Error("Method not implemented.");
363
- }
364
- symmetricDifference(other) {
365
- throw new Error("Method not implemented.");
366
- }
367
- isSubsetOf(other) {
368
- throw new Error("Method not implemented.");
369
- }
370
- isSupersetOf(other) {
371
- throw new Error("Method not implemented.");
372
- }
373
- isDisjointFrom(other) {
374
- throw new Error("Method not implemented.");
375
- }
376
- };
377
- var makeSet = (projection) => {
378
- return class BoundComplexSet extends ComplexSet {
379
- constructor(values) {
380
- super(projection, values);
381
- }
382
- };
383
- };
384
- var ComplexMap = class _ComplexMap {
385
- // prettier-ignore
386
- constructor(_keyProjection, entries) {
387
- this._keyProjection = _keyProjection;
388
- this._keys = /* @__PURE__ */ new Map();
389
- this._values = /* @__PURE__ */ new Map();
390
- if (entries) {
391
- for (const [key, value] of entries) {
392
- this.set(key, value);
393
- }
394
- }
395
- }
396
- toString() {
397
- return inspectObject(this);
398
- }
399
- toJSON() {
400
- return this._values.size > MAX_SERIALIZATION_LENGTH ? {
401
- size: this._values.size
402
- } : Array.from(this._values.values());
403
- }
404
- [inspect.custom]() {
405
- return inspectObject(this);
406
- }
407
- clear() {
408
- this._keys.clear();
409
- this._values.clear();
410
- }
411
- delete(key) {
412
- const keyDeleted = this._keys.delete(this._keyProjection(key));
413
- const valueDeleted = this._values.delete(this._keyProjection(key));
414
- return keyDeleted || valueDeleted;
415
- }
416
- forEach(callbackfn, thisArg) {
417
- if (thisArg) {
418
- callbackfn = callbackfn.bind(thisArg);
419
- }
420
- this._keys.forEach((key, primitive) => callbackfn(this._values.get(primitive) ?? raise(new Error("Map corrupted.")), key, this));
421
- }
422
- get(key) {
423
- return this._values.get(this._keyProjection(key));
424
- }
425
- has(key) {
426
- return this._keys.has(this._keyProjection(key));
427
- }
428
- set(key, value) {
429
- const primitive = this._keyProjection(key);
430
- this._keys.set(primitive, key);
431
- this._values.set(primitive, value);
432
- return this;
433
- }
434
- get size() {
435
- return this._keys.size;
436
- }
437
- *[Symbol.iterator]() {
438
- for (const [primitive, key] of this._keys) {
439
- const value = this._values.get(primitive) ?? raise(new Error("Map corrupted."));
440
- yield [
441
- key,
442
- value
443
- ];
444
- }
445
- }
446
- entries() {
447
- return this[Symbol.iterator]();
448
- }
449
- keys() {
450
- return this._keys.values();
451
- }
452
- values() {
453
- return this._values.values();
454
- }
455
- mapValues(mapper) {
456
- return new _ComplexMap(this._keyProjection, [
457
- ...this.entries()
458
- ].map(([key, value]) => [
459
- key,
460
- mapper(value, key)
461
- ]));
462
- }
463
- get [Symbol.toStringTag]() {
464
- return "ComplexMap";
465
- }
466
- };
467
- var makeMap = (keyProjection) => class BoundComplexMap extends ComplexMap {
468
- constructor(entries) {
469
- super(keyProjection, entries);
470
- }
471
- };
472
-
473
- // packages/common/util/src/explicit-resource-management-polyfill.ts
474
- Symbol.dispose ??= Symbol("Symbol.dispose");
475
- Symbol.asyncDispose ??= Symbol("Symbol.asyncDispose");
476
-
477
- // packages/common/util/src/defer.ts
478
- var defer = (fn) => new DeferGuard(fn);
479
- var DeferGuard = class {
480
- /**
481
- * @internal
482
- */
483
- constructor(_fn) {
484
- this._fn = _fn;
485
- }
486
- [Symbol.dispose]() {
487
- const result = this._fn();
488
- if (result instanceof Promise) {
489
- throw new Error("Async functions in defer are not supported. Use deferAsync instead.");
490
- }
491
- }
492
- };
493
- var deferAsync = (fn) => new DeferAsyncGuard(fn);
494
- var DeferAsyncGuard = class {
495
- /**
496
- * @internal
497
- */
498
- constructor(_fn) {
499
- this._fn = _fn;
500
- }
501
- async [Symbol.asyncDispose]() {
502
- await this._fn();
503
- }
504
- };
505
-
506
- // packages/common/util/src/defer-function.ts
507
- var deferFunction = (fnProvider) => (...args) => fnProvider()(...args);
508
-
509
- // packages/common/util/src/entry.ts
510
- var entry = (map, key) => new MapEntry(map, key);
511
- var MapEntry = class {
512
- /**
513
- * @internal
514
- */
515
- // prettier-ignore
516
- constructor(_map, _key) {
517
- this._map = _map;
518
- this._key = _key;
519
- }
520
- get key() {
521
- return this._key;
522
- }
523
- get value() {
524
- return this._map.get(this._key);
525
- }
526
- orInsert(value) {
527
- if (!this._map.has(this._key)) {
528
- this._map.set(this._key, value);
529
- }
530
- return this;
531
- }
532
- deep(key) {
533
- return entry(this.value, key);
534
- }
535
- };
536
-
537
- // packages/common/util/src/for-each-async.ts
538
- var forEachAsync = (items, fn) => Promise.all(items.map(fn));
539
-
540
- // packages/common/util/src/human-hash.ts
541
- import { PublicKey } from "@dxos/keys";
542
- var DEFAULT_WORDLIST = [
543
- "ack",
544
- "alabama",
545
- "alanine",
546
- "alaska",
547
- "alpha",
548
- "angel",
549
- "apart",
550
- "april",
551
- "arizona",
552
- "arkansas",
553
- "artist",
554
- "asparagus",
555
- "aspen",
556
- "august",
557
- "autumn",
558
- "avocado",
559
- "bacon",
560
- "bakerloo",
561
- "batman",
562
- "beer",
563
- "berlin",
564
- "beryllium",
565
- "black",
566
- "blossom",
567
- "blue",
568
- "bluebird",
569
- "bravo",
570
- "bulldog",
571
- "burger",
572
- "butter",
573
- "california",
574
- "carbon",
575
- "cardinal",
576
- "carolina",
577
- "carpet",
578
- "cat",
579
- "ceiling",
580
- "charlie",
581
- "chicken",
582
- "coffee",
583
- "cola",
584
- "cold",
585
- "colorado",
586
- "comet",
587
- "connecticut",
588
- "crazy",
589
- "cup",
590
- "dakota",
591
- "december",
592
- "delaware",
593
- "delta",
594
- "diet",
595
- "don",
596
- "double",
597
- "early",
598
- "earth",
599
- "east",
600
- "echo",
601
- "edward",
602
- "eight",
603
- "eighteen",
604
- "eleven",
605
- "emma",
606
- "enemy",
607
- "equal",
608
- "failed",
609
- "fanta",
610
- "fifteen",
611
- "fillet",
612
- "finch",
613
- "fish",
614
- "five",
615
- "fix",
616
- "floor",
617
- "florida",
618
- "football",
619
- "four",
620
- "fourteen",
621
- "foxtrot",
622
- "freddie",
623
- "friend",
624
- "fruit",
625
- "gee",
626
- "georgia",
627
- "glucose",
628
- "golf",
629
- "green",
630
- "grey",
631
- "hamper",
632
- "happy",
633
- "harry",
634
- "hawaii",
635
- "helium",
636
- "high",
637
- "hot",
638
- "hotel",
639
- "hydrogen",
640
- "idaho",
641
- "illinois",
642
- "india",
643
- "indigo",
644
- "ink",
645
- "iowa",
646
- "island",
647
- "item",
648
- "jersey",
649
- "jig",
650
- "johnny",
651
- "juliet",
652
- "july",
653
- "jupiter",
654
- "kansas",
655
- "kentucky",
656
- "kilo",
657
- "king",
658
- "kitten",
659
- "lactose",
660
- "lake",
661
- "lamp",
662
- "lemon",
663
- "leopard",
664
- "lima",
665
- "lion",
666
- "lithium",
667
- "london",
668
- "louisiana",
669
- "low",
670
- "magazine",
671
- "magnesium",
672
- "maine",
673
- "mango",
674
- "march",
675
- "mars",
676
- "maryland",
677
- "massachusetts",
678
- "may",
679
- "mexico",
680
- "michigan",
681
- "mike",
682
- "minnesota",
683
- "mirror",
684
- "mississippi",
685
- "missouri",
686
- "mobile",
687
- "mockingbird",
688
- "monkey",
689
- "montana",
690
- "moon",
691
- "mountain",
692
- "muppet",
693
- "music",
694
- "nebraska",
695
- "neptune",
696
- "network",
697
- "nevada",
698
- "nine",
699
- "nineteen",
700
- "nitrogen",
701
- "north",
702
- "november",
703
- "nuts",
704
- "october",
705
- "ohio",
706
- "oklahoma",
707
- "one",
708
- "orange",
709
- "oranges",
710
- "oregon",
711
- "oscar",
712
- "oven",
713
- "oxygen",
714
- "papa",
715
- "paris",
716
- "pasta",
717
- "pennsylvania",
718
- "pip",
719
- "pizza",
720
- "pluto",
721
- "potato",
722
- "princess",
723
- "purple",
724
- "quebec",
725
- "queen",
726
- "quiet",
727
- "red",
728
- "river",
729
- "robert",
730
- "robin",
731
- "romeo",
732
- "rugby",
733
- "sad",
734
- "salami",
735
- "saturn",
736
- "september",
737
- "seven",
738
- "seventeen",
739
- "shade",
740
- "sierra",
741
- "single",
742
- "sink",
743
- "six",
744
- "sixteen",
745
- "skylark",
746
- "snake",
747
- "social",
748
- "sodium",
749
- "solar",
750
- "south",
751
- "spaghetti",
752
- "speaker",
753
- "spring",
754
- "stairway",
755
- "steak",
756
- "stream",
757
- "summer",
758
- "sweet",
759
- "table",
760
- "tango",
761
- "ten",
762
- "tennessee",
763
- "tennis",
764
- "texas",
765
- "thirteen",
766
- "three",
767
- "timing",
768
- "triple",
769
- "twelve",
770
- "twenty",
771
- "two",
772
- "uncle",
773
- "undress",
774
- "uniform",
775
- "uranus",
776
- "utah",
777
- "vegan",
778
- "venus",
779
- "vermont",
780
- "victor",
781
- "video",
782
- "violet",
783
- "virginia",
784
- "washington",
785
- "west",
786
- "whiskey",
787
- "white",
788
- "william",
789
- "winner",
790
- "winter",
791
- "wisconsin",
792
- "wolfram",
793
- "wyoming",
794
- "xray",
795
- "yankee",
796
- "yellow",
797
- "zebra",
798
- "zulu"
799
- ];
800
- var HumanHasher = class {
801
- /**
802
- * Transforms hex digests to human-readable strings.
803
- *
804
- * The format of these strings will look something like:
805
- * `victor-bacon-zulu-lima`. The output is obtained by compressing the input
806
- * digest to a fixed number of bytes, then mapping those bytes to one of 256
807
- * words. A default wordlist is provided, but you can override this if you
808
- * prefer.
809
- * As long as you use the same wordlist, the output will be consistent (i.e.
810
- * the same digest will always render the same representation).
811
- *
812
- * @param wordlist A list of exactly 256 words to choose from
813
- */
814
- constructor(wordlist = DEFAULT_WORDLIST) {
815
- this.wordlist = wordlist;
816
- if (wordlist.length !== 256) {
817
- throw new Error("Wordlist must have exactly 256 items");
818
- }
819
- this.wordlist = wordlist;
820
- }
821
- /**
822
- * Humanize a given hexadecimal digest.
823
- *
824
- * Change the number of words output by specifying `words`. Change the
825
- * word separator with `separator`.
826
- *
827
- * @param hexdigest A string of hexadecimal characters to humanize
828
- * @param words How many words to output (more = safer)
829
- * @param separator The string used to seperate the words
830
- */
831
- humanize(hexdigest, words = 4, separator = "-") {
832
- const pairs = hexdigest.match(/(..?)/g);
833
- if (!pairs) {
834
- throw new Error("");
835
- }
836
- const bytes = pairs.map((x) => parseInt(x, 16));
837
- const compressed = this._compress(bytes, words);
838
- return compressed.map((x) => this.wordlist[x]).join(separator);
839
- }
840
- /**
841
- * Compress a list of byte values to a fixed target length.
842
- *
843
- * @param bytes A list of bytes (numbers from 0-254)
844
- * @param target The number of bytes to return / compress to
845
- */
846
- _compress(bytes, target) {
847
- const length = bytes.length;
848
- if (target > length) {
849
- throw new Error("Fewer input bytes than requested output");
850
- }
851
- const segSize = length / target >> 0;
852
- const segments = [];
853
- for (let i = 0; i < segSize * target; i += segSize) {
854
- segments.push(bytes.slice(i, i + segSize));
855
- }
856
- segments[segments.length - 1] = segments[segments.length - 1].concat(bytes.slice(target * segSize));
857
- const checksums = segments.map((x) => x.reduce((acc, curr) => acc ^ curr));
858
- return checksums;
859
- }
860
- };
861
- var hasher = new HumanHasher();
862
- var humanize = (value) => {
863
- if (value instanceof Buffer || value instanceof Uint8Array || value instanceof ArrayBuffer) {
864
- value = PublicKey.stringify(value);
865
- } else if (value instanceof PublicKey) {
866
- value = value.toHex();
867
- }
868
- return hasher.humanize(value);
869
- };
870
-
871
- // packages/common/util/src/interval.ts
872
- var exponentialBackoffInterval = (cb, initialInterval) => {
873
- let interval = initialInterval;
874
- const repeat = () => {
875
- cb();
876
- interval *= 2;
877
- timeoutId = setTimeout(repeat, interval);
878
- };
879
- let timeoutId = setTimeout(repeat, interval);
880
- return () => clearTimeout(timeoutId);
881
- };
882
-
883
- // packages/common/util/src/map.ts
884
- var defaultMap = (map, key, def) => {
885
- let value = map.get(key);
886
- if (value === void 0) {
887
- value = typeof def === "function" ? def() : def;
888
- map.set(key, value);
889
- }
890
- return value;
891
- };
892
-
893
- // packages/common/util/src/instance-id.ts
894
- var symbol = Symbol.for("dxos.instance-contexts");
895
- var instanceContexts = globalThis[symbol] ??= /* @__PURE__ */ new WeakMap();
896
- var getPrototypeSpecificInstanceId = (instance) => {
897
- const prototype = Object.getPrototypeOf(instance);
898
- const instanceCtx = defaultMap(instanceContexts, prototype, () => ({
899
- nextId: 0,
900
- instanceIds: /* @__PURE__ */ new WeakMap()
901
- }));
902
- let id = instanceCtx.instanceIds.get(instance);
903
- if (id === void 0) {
904
- id = instanceCtx.nextId++;
905
- instanceCtx.instanceIds.set(instance, id);
906
- }
907
- return id;
908
- };
909
- var getDebugName = (instance) => {
910
- if (instance == null) {
911
- return "null";
912
- }
913
- const prototype = Object.getPrototypeOf(instance);
914
- return `${prototype.constructor.name}#${getPrototypeSpecificInstanceId(instance)}`;
915
- };
916
-
917
- // packages/common/util/src/join-tables.ts
918
- var joinTables = (leftColumn, rightColumn, left, right) => {
919
- const map = /* @__PURE__ */ new Map();
920
- const used = /* @__PURE__ */ new Set();
921
- for (const row of right) {
922
- map.set(row[rightColumn], row);
923
- }
924
- const result = [];
925
- for (const row of left) {
926
- const right2 = map.get(row[leftColumn]);
927
- used.add(right2);
928
- result.push(Object.assign(right2 ?? {}, row));
929
- }
930
- for (const row of right) {
931
- if (!used.has(row)) {
932
- result.push(row);
933
- }
934
- }
935
- return result;
936
- };
937
-
938
- // packages/common/util/src/json.ts
939
- import { inspect as inspect2 } from "node:util";
940
- import { PublicKey as PublicKey2 } from "@dxos/keys";
941
-
942
- // packages/common/util/src/uint8array.ts
943
- var arraysEqual = (a, b) => {
944
- if (a.length !== b.length) {
945
- return false;
946
- }
947
- for (let i = 0; i < a.length; i++) {
948
- if (a[i] !== b[i]) {
949
- return false;
950
- }
951
- }
952
- return true;
953
- };
954
- var arrayToBuffer = (array) => {
955
- return Buffer.from(array.buffer, array.byteOffset, array.byteLength);
956
- };
957
- var bufferToArray = (buffer) => {
958
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
959
- };
960
- var stringToArray = (string) => bufferToArray(Buffer.from(string, "hex"));
961
- var arrayToString = (array) => arrayToBuffer(array).toString("hex");
962
-
963
- // packages/common/util/src/json.ts
964
- var MAX_DEPTH = 5;
965
- var LOG_MAX_DEPTH = 7;
966
- function jsonReplacer(key, value) {
967
- if (value !== null && typeof value === "object" && typeof value[inspect2.custom] === "function") {
968
- return value[inspect2.custom]();
969
- }
970
- if (value !== null && typeof value === "object" && value.type === "Buffer" && Array.isArray(value.data)) {
971
- if (value.data.length === 32) {
972
- const key2 = Buffer.from(value.data);
973
- return `[${humanize(key2)}]:[${PublicKey2.stringify(key2)}]`;
974
- } else {
975
- return Buffer.from(value.data).toString("hex");
976
- }
977
- }
978
- return value;
979
- }
980
- var jsonify = (value, depth = 0, visitedObjects = /* @__PURE__ */ new WeakSet()) => {
981
- if (depth > MAX_DEPTH) {
982
- return null;
983
- } else if (typeof value === "function") {
984
- return null;
985
- } else if (typeof value === "object" && value !== null) {
986
- if (visitedObjects.has(value)) {
987
- return null;
988
- }
989
- visitedObjects.add(value);
990
- try {
991
- if (value instanceof Uint8Array) {
992
- return arrayToBuffer(value).toString("hex");
993
- } else if (Array.isArray(value)) {
994
- return value.map((x) => jsonify(x, depth + 1, visitedObjects));
995
- } else if (typeof value.toJSON === "function") {
996
- return value.toJSON();
997
- } else {
998
- const res = {};
999
- for (const key of Object.keys(value)) {
1000
- res[key] = jsonify(value[key], depth + 1, visitedObjects);
1001
- }
1002
- return res;
1003
- }
1004
- } finally {
1005
- visitedObjects.delete(value);
1006
- }
1007
- } else {
1008
- return value;
1009
- }
1010
- };
1011
- var jsonlogify = (value, depth = 0, visitedObjects = /* @__PURE__ */ new WeakSet()) => {
1012
- if (depth > LOG_MAX_DEPTH) {
1013
- return null;
1014
- } else if (typeof value === "function") {
1015
- return null;
1016
- } else if (typeof value === "object" && value !== null) {
1017
- if (visitedObjects.has(value)) {
1018
- return null;
1019
- }
1020
- visitedObjects.add(value);
1021
- try {
1022
- if (value instanceof Uint8Array) {
1023
- return arrayToBuffer(value).toString("hex");
1024
- } else if (Array.isArray(value)) {
1025
- return value.map((x) => jsonlogify(x, depth + 1, visitedObjects));
1026
- } else if (typeof value.toJSONL === "function") {
1027
- return value.toJSONL();
1028
- } else if (typeof value.toJSON === "function") {
1029
- return value.toJSON();
1030
- } else {
1031
- const res = {};
1032
- for (const key of Object.keys(value)) {
1033
- res[key] = jsonlogify(value[key], depth + 1, visitedObjects);
1034
- }
1035
- return res;
1036
- }
1037
- } finally {
1038
- visitedObjects.delete(value);
1039
- }
1040
- } else {
1041
- return value;
1042
- }
1043
- };
1044
- var jsonKeyReplacer = (options = {}) => (key, value) => {
1045
- if (typeof value === "string") {
1046
- const key2 = PublicKey2.fromHex(value);
1047
- if (key2.toHex() === value) {
1048
- return options.humanize ? humanize(key2) : options.truncate ? key2.truncate() : key2.toHex();
1049
- }
1050
- }
1051
- return value;
1052
- };
1053
-
1054
- // packages/common/util/src/map-values.ts
1055
- var mapValues = (obj, fn) => {
1056
- const result = {};
1057
- Object.keys(obj).forEach((key) => {
1058
- result[key] = fn(obj[key], key);
1059
- });
1060
- return result;
1061
- };
1062
- var deepMapValues = (value, fn) => {
1063
- return new DeepMapper(fn).map(value);
1064
- };
1065
- var DeepMapper = class {
1066
- constructor(_fn) {
1067
- this._fn = _fn;
1068
- this._cyclic = /* @__PURE__ */ new Map();
1069
- this._recurse = (value) => {
1070
- if (this._cyclic.has(value)) {
1071
- return this._cyclic.get(value);
1072
- }
1073
- if (Array.isArray(value)) {
1074
- const res = new Array(value.length);
1075
- this._cyclic.set(value, res);
1076
- for (let i = 0; i < value.length; i++) {
1077
- res[i] = this.map(value[i]);
1078
- }
1079
- return res;
1080
- } else if (value !== null && typeof value === "object") {
1081
- const res = {};
1082
- this._cyclic.set(value, res);
1083
- for (const key in value) {
1084
- res[key] = this.map(value[key]);
1085
- }
1086
- return res;
1087
- } else {
1088
- return value;
1089
- }
1090
- };
1091
- }
1092
- map(value) {
1093
- if (this._cyclic.has(value)) {
1094
- return this._cyclic.get(value);
1095
- }
1096
- return this._fn(value, this._recurse);
1097
- }
1098
- };
1099
- var deepMapValuesAsync = (value, fn) => {
1100
- return new DeepMapperAsync(fn).map(value);
1101
- };
1102
- var DeepMapperAsync = class {
1103
- constructor(_fn) {
1104
- this._fn = _fn;
1105
- this._cyclic = /* @__PURE__ */ new Map();
1106
- this._recurse = async (value) => {
1107
- if (this._cyclic.has(value)) {
1108
- return this._cyclic.get(value);
1109
- }
1110
- if (Array.isArray(value)) {
1111
- const res = new Array(value.length);
1112
- this._cyclic.set(value, res);
1113
- for (let i = 0; i < value.length; i++) {
1114
- res[i] = await this.map(value[i]);
1115
- }
1116
- return res;
1117
- } else if (value !== null && typeof value === "object") {
1118
- const res = {};
1119
- this._cyclic.set(value, res);
1120
- for (const key in value) {
1121
- res[key] = await this.map(value[key]);
1122
- }
1123
- return res;
1124
- } else {
1125
- return value;
1126
- }
1127
- };
1128
- }
1129
- map(value) {
1130
- if (this._cyclic.has(value)) {
1131
- return this._cyclic.get(value);
1132
- }
1133
- return this._fn(value, this._recurse);
1134
- }
1135
- };
1136
-
1137
- // packages/common/util/src/order.ts
1138
- var inferObjectOrder = (objectMap, order = []) => {
1139
- const orderedObjects = order.reduce((acc, id) => {
1140
- if (id in objectMap) {
1141
- acc.objects.push(objectMap[id]);
1142
- acc.ids.add(id);
1143
- }
1144
- return acc;
1145
- }, {
1146
- objects: [],
1147
- ids: /* @__PURE__ */ new Set()
1148
- });
1149
- const { objects } = Object.keys(objectMap).reduce((acc, id) => {
1150
- if (!acc.ids.has(id)) {
1151
- acc.objects.push(objectMap[id]);
1152
- }
1153
- return acc;
1154
- }, orderedObjects);
1155
- return objects;
1156
- };
1157
- var inferRecordOrder = (objectMap, order = []) => {
1158
- return Object.assign(order.filter((id) => id in objectMap).reduce((acc, id) => {
1159
- acc[id] = null;
1160
- return acc;
1161
- }, {}), objectMap);
1162
- };
1163
-
1164
- // packages/common/util/src/pick.ts
1165
- var pick = (object, keys) => keys.reduce((obj, key) => {
1166
- if (object && key in object) {
1167
- obj[key] = object[key];
1168
- }
1169
- return obj;
1170
- }, {});
1171
- var pickBy = (object, predicate) => {
1172
- const obj = {};
1173
- for (const key in object) {
1174
- if (predicate(object[key])) {
1175
- obj[key] = object[key];
1176
- }
1177
- }
1178
- return obj;
1179
- };
1180
-
1181
- // packages/common/util/src/platform.ts
1182
- var isNode = () => typeof process !== "undefined" && process.versions != null && process.versions.node != null;
1183
- var mobileAndTabletCheck = () => {
1184
- let check = false;
1185
- ((a) => {
1186
- if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) {
1187
- check = true;
1188
- }
1189
- })(navigator.userAgent || navigator.vendor || window.opera);
1190
- return check;
1191
- };
1192
- var iosCheck = () => {
1193
- return [
1194
- "iPad Simulator",
1195
- "iPhone Simulator",
1196
- "iPod Simulator",
1197
- "iPad",
1198
- "iPhone",
1199
- "iPod"
1200
- ].includes(navigator.platform) || // iPad on iOS 13 detection
1201
- navigator.userAgent.includes("Mac") && "ontouchend" in document;
1202
- };
1203
- var safariCheck = () => typeof navigator !== "undefined" && /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
1204
- var getHostPlatform = () => {
1205
- if (!("navigator" in window)) {
1206
- return "unknown";
1207
- }
1208
- const platform = (navigator.userAgentData?.platform || navigator.platform)?.toLowerCase();
1209
- if (platform.startsWith("win")) {
1210
- return "windows";
1211
- } else if (platform.startsWith("mac")) {
1212
- return "macos";
1213
- } else if (platform.startsWith("ipad") || platform.startsWith("iphone") || platform.startsWith("ipod")) {
1214
- return "ios";
1215
- } else if (platform.startsWith("linux")) {
1216
- return "linux";
1217
- } else {
1218
- return "unknown";
1219
- }
1220
- };
1221
-
1222
- // packages/common/util/src/random.ts
1223
- var randomInt = (max, min) => {
1224
- min = Math.ceil(min);
1225
- max = Math.floor(max);
1226
- return Math.floor(Math.random() * (max - min + 1)) + min;
1227
- };
1228
-
1229
- // packages/common/util/src/range.ts
1230
- var range = (n, mapper) => {
1231
- const range2 = Array.from(Array(n).keys());
1232
- return mapper == null ? range2 : range2.map(mapper);
1233
- };
1234
- var rangeFromTo = (from, to, mapper) => {
1235
- return mapper == null ? range(to - from, (i) => i + from) : range(to - from, (i) => mapper(i + from));
1236
- };
1237
-
1238
- // packages/common/util/src/reducers.ts
1239
- var accessBy = (value, accessor) => typeof accessor === "function" ? accessor(value) : value[accessor];
1240
- var median = (values) => {
1241
- const mid = Math.floor(values.length / 2);
1242
- if (values.length % 2 === 1) {
1243
- return values[mid];
1244
- } else {
1245
- return (values[mid - 1] + values[mid]) / 2;
1246
- }
1247
- };
1248
- var numericalValues = (values, accessor) => {
1249
- const result = {
1250
- total: 0,
1251
- count: 0
1252
- };
1253
- const sorted = values.map((value) => {
1254
- const v = accessBy(value, accessor);
1255
- if (v === void 0 || isNaN(v)) {
1256
- return void 0;
1257
- }
1258
- result.total += v;
1259
- if (result.min === void 0 || v < result.min) {
1260
- result.min = v;
1261
- }
1262
- if (result.max === void 0 || v > result.max) {
1263
- result.max = v;
1264
- }
1265
- return v;
1266
- }).filter((value) => value !== void 0).sort((a, b) => a - b);
1267
- if (sorted.length) {
1268
- Object.assign(result, {
1269
- count: sorted.length,
1270
- mean: result.total / sorted.length,
1271
- median: median(sorted)
1272
- });
1273
- }
1274
- return result;
1275
- };
1276
- var reduceSet = (values, accessor) => {
1277
- return values.reduce((values2, value) => {
1278
- const v = accessBy(value, accessor);
1279
- values2.add(v);
1280
- return values2;
1281
- }, /* @__PURE__ */ new Set());
1282
- };
1283
- var reduceGroupBy = (values, accessor) => {
1284
- return values.reduce((values2, value) => {
1285
- const key = accessBy(value, accessor);
1286
- defaultMap(values2, key, []).push(value);
1287
- return values2;
1288
- }, /* @__PURE__ */ new Map());
1289
- };
1290
- var reduceSeries = (reducer, events) => {
1291
- const state = reducer.initialState();
1292
- for (const event of events) {
1293
- reducer.reduce(state, event);
1294
- }
1295
- return state;
1296
- };
1297
- var createGroupReducer = (groupBy, sub) => ({
1298
- initialState: () => ({}),
1299
- reduce: (state, event) => {
1300
- const key = groupBy(event);
1301
- state[key] = sub.reduce(state[key] ?? sub.initialState(), event);
1302
- return state;
1303
- }
1304
- });
1305
- var getDate = (value) => value instanceof Date ? value : new Date(value);
1306
- var createBucketReducer = (period) => ({
1307
- initialState: () => [],
1308
- reduce: (series, event) => {
1309
- const timestamp = getDate(event.timestamp);
1310
- let bucket = series[series.length - 1];
1311
- if (!bucket || bucket.start + period < timestamp.getTime()) {
1312
- bucket = {
1313
- start: timestamp.getTime(),
1314
- period,
1315
- count: 0
1316
- };
1317
- series.push(bucket);
1318
- }
1319
- bucket.count++;
1320
- return series;
1321
- }
1322
- });
1323
-
1324
- // packages/common/util/src/safe-await.ts
1325
- var safeAwaitAll = async (source, taskFactory, onError) => {
1326
- const failedItems = [];
1327
- await Promise.all([
1328
- ...source
1329
- ].map(async (item, idx) => {
1330
- try {
1331
- await taskFactory(item);
1332
- } catch (err) {
1333
- if (onError) {
1334
- onError(err, item, idx);
1335
- }
1336
- failedItems.push(item);
1337
- }
1338
- }));
1339
- return failedItems;
1340
- };
1341
-
1342
- // packages/common/util/src/safe-instanceof.ts
1343
- var instanceTag = Symbol("instanceTag");
1344
- var safeInstanceof = (tag) => (target) => {
1345
- target.prototype[instanceTag] = tag;
1346
- Object.defineProperty(target.prototype, Symbol.hasInstance, {
1347
- value: (instance) => instance?.[instanceTag] === tag
1348
- });
1349
- Object.defineProperty(target, Symbol.hasInstance, {
1350
- value: (instance) => instance?.[instanceTag] === tag
1351
- });
1352
- };
1353
-
1354
- // packages/common/util/src/safe-parse-json.ts
1355
- var safeParseJson = (data, defaultValue) => {
1356
- if (data) {
1357
- try {
1358
- return JSON.parse(data);
1359
- } catch (err) {
1360
- }
1361
- }
1362
- return defaultValue;
1363
- };
1364
-
1365
- // packages/common/util/src/sliding-window-summary.ts
1366
- import { invariant as invariant5 } from "@dxos/invariant";
1367
- var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/common/util/src/sliding-window-summary.ts";
1368
- var SlidingWindowSummary = class {
1369
- constructor(options) {
1370
- this._sum = 0;
1371
- this._buffer = new CircularBuffer(options.dataPoints);
1372
- if (options.precision != null) {
1373
- invariant5(options.precision >= 0, void 0, {
1374
- F: __dxlog_file5,
1375
- L: 26,
1376
- S: this,
1377
- A: [
1378
- "options.precision >= 0",
1379
- ""
1380
- ]
1381
- });
1382
- this._precision = Math.pow(10, options.precision);
1383
- }
1384
- }
1385
- record(value) {
1386
- const evicted = this._buffer.push(value);
1387
- this._sum += value - (evicted ?? 0);
1388
- }
1389
- average() {
1390
- return this._buffer.elementCount === 0 ? 0 : this._withPrecision(this._sum / this._buffer.elementCount);
1391
- }
1392
- computeWindowSummary() {
1393
- const mean = this.average();
1394
- const sortedElements = [
1395
- ...this._buffer
1396
- ].sort();
1397
- const median2 = this._withPrecision(sortedElements.length % 2 === 0 ? (sortedElements[sortedElements.length / 2] + sortedElements[sortedElements.length / 2 - 1]) / 2 : sortedElements[sortedElements.length / 2]);
1398
- const p90 = this._withPrecision(sortedElements[Math.round(sortedElements.length * 0.9)]);
1399
- const variance = sortedElements.reduce((acc, v) => acc + Math.pow(v - mean, 2)) / sortedElements.length;
1400
- const stdDev = this._withPrecision(Math.sqrt(variance));
1401
- const histogram = sortedElements.reduce((acc, v) => {
1402
- acc[v] += 1;
1403
- return acc;
1404
- }, {});
1405
- return {
1406
- mean,
1407
- median: median2,
1408
- p90,
1409
- stdDev,
1410
- histogram
1411
- };
1412
- }
1413
- _withPrecision(value) {
1414
- if (this._precision == null) {
1415
- return value;
1416
- }
1417
- return Math.round(value * this._precision) / this._precision;
1418
- }
1419
- };
1420
-
1421
- // packages/common/util/src/sort.ts
1422
- var compareScalar = (inc = true) => (a, b) => (inc ? 1 : -1) * (a < b ? -1 : a > b ? 1 : 0);
1423
- var compareString = (inc = true, caseInsensitive = true) => (a, b) => {
1424
- if (caseInsensitive) {
1425
- a = a?.toLowerCase();
1426
- b = b?.toLowerCase();
1427
- }
1428
- return (inc ? 1 : -1) * (a < b ? -1 : a > b ? 1 : 0);
1429
- };
1430
- var compareObject = (prop, sorter, inc = true) => (a, b) => (inc ? 1 : -1) * sorter(a[prop], b[prop]);
1431
- var compareMulti = (sorters) => (a, b) => {
1432
- const sort = (i = 0) => {
1433
- const s = sorters[i](a, b);
1434
- if (s === 0 && i < sorters.length - 1) {
1435
- return sort(i + 1);
1436
- } else {
1437
- return s;
1438
- }
1439
- };
1440
- return sort();
1441
- };
1442
-
1443
- // packages/common/util/src/sum.ts
1444
- var sum = (values) => values.reduce((a, b) => a + b, 0);
1445
-
1446
- // packages/common/util/src/throw-unhandled-error.ts
1447
- var throwUnhandledError = (error) => {
1448
- queueMicrotask(() => {
1449
- throw error;
1450
- });
1451
- };
1452
-
1453
- // packages/common/util/src/to-fallback.ts
1454
- var idEmoji = [
1455
- // When changing this set, please check the result in a console or e.g. RunKit (https://runkit.com/thure/642214441dd6ae000855a8de)
1456
- // Emoji sometimes use a combination of code points, and some code points aren't visible on their own, so by adding or deleting you may unintentionally create non-visible items.
1457
- // This set was chosen from the characters in Unicode Emoji v15.0 based on the following criteria:
1458
- // – not people or isolated anthropomorphic faces
1459
- // – not flags
1460
- // – more concrete than abstract
1461
- // – less culturally specific
1462
- // – less easily confused with another emoji in the set
1463
- // – requires less special knowledge to identify
1464
- // – less likely to evoke negative feelings (no meat, no drugs, no weapons, etc)
1465
- // – less common as a signifier in UX
1466
- // NOTE that this is intentionally an array of strings because of the way emoji graphemes work.
1467
- "\u{1F479}",
1468
- "\u{1F47B}",
1469
- "\u{1F47D}",
1470
- "\u{1F916}",
1471
- "\u{1F383}",
1472
- "\u{1F9BE}",
1473
- "\u{1F9BF}",
1474
- "\u{1F9B7}",
1475
- "\u{1F463}",
1476
- "\u{1F441}\uFE0F",
1477
- "\u{1F9F6}",
1478
- "\u{1F451}",
1479
- "\u{1F412}",
1480
- "\u{1F986}",
1481
- "\u{1F989}",
1482
- "\u{1F434}",
1483
- "\u{1F984}",
1484
- "\u{1F41D}",
1485
- "\u{1F98B}",
1486
- "\u{1F41E}",
1487
- "\u{1FAB2}",
1488
- "\u{1F422}",
1489
- "\u{1F98E}",
1490
- "\u{1F995}",
1491
- "\u{1F991}",
1492
- "\u{1F980}",
1493
- "\u{1F420}",
1494
- "\u{1F42C}",
1495
- "\u{1F40B}",
1496
- "\u{1F9AD}",
1497
- "\u{1F405}",
1498
- "\u{1F406}",
1499
- "\u{1F993}",
1500
- "\u{1F98D}",
1501
- "\u{1F9A7}",
1502
- "\u{1F418}",
1503
- "\u{1F42B}",
1504
- "\u{1F992}",
1505
- "\u{1F998}",
1506
- "\u{1F9AC}",
1507
- "\u{1F416}",
1508
- "\u{1F40F}",
1509
- "\u{1F98C}",
1510
- "\u{1F415}",
1511
- "\u{1F408}",
1512
- "\u{1F413}",
1513
- "\u{1F99A}",
1514
- "\u{1F99C}",
1515
- "\u{1F9A2}",
1516
- "\u{1F9A9}",
1517
- "\u{1F9A6}",
1518
- "\u{1F401}",
1519
- "\u{1F43F}\uFE0F",
1520
- "\u{1F335}",
1521
- "\u{1F332}",
1522
- "\u{1F333}",
1523
- "\u{1FAB5}",
1524
- "\u{1F331}",
1525
- "\u{1F341}",
1526
- "\u{1FABA}",
1527
- "\u{1F344}",
1528
- "\u{1F41A}",
1529
- "\u{1FAB8}",
1530
- "\u{1FAA8}",
1531
- "\u{1F33E}",
1532
- "\u{1F337}",
1533
- "\u{1F33B}",
1534
- "\u2600\uFE0F",
1535
- "\u{1F319}",
1536
- "\u{1FA90}",
1537
- "\u2B50\uFE0F",
1538
- "\u26A1\uFE0F",
1539
- "\u2604\uFE0F",
1540
- "\u{1F525}",
1541
- "\u{1F308}",
1542
- "\u2601\uFE0F",
1543
- "\u{1F4A7}",
1544
- "\u26F1\uFE0F",
1545
- "\u{1F30A}",
1546
- "\u{1F34E}",
1547
- "\u{1F34B}",
1548
- "\u{1F349}",
1549
- "\u{1F347}",
1550
- "\u{1FAD0}",
1551
- "\u{1F348}",
1552
- "\u{1F352}",
1553
- "\u{1F351}",
1554
- "\u{1F96D}",
1555
- "\u{1F34D}",
1556
- "\u{1F965}",
1557
- "\u{1F95D}",
1558
- "\u{1F951}",
1559
- "\u{1F336}\uFE0F",
1560
- "\u{1F33D}",
1561
- "\u{1F955}",
1562
- "\u{1F36C}",
1563
- "\u{1F95C}",
1564
- "\u{1FAD6}",
1565
- "\u2615\uFE0F",
1566
- "\u{1F375}",
1567
- "\u{1F9CA}",
1568
- "\u{1F9C2}",
1569
- "\u{1F3D4}\uFE0F",
1570
- "\u2693\uFE0F",
1571
- "\u{1F6DF}",
1572
- "\u{1F3DD}\uFE0F",
1573
- "\u{1F6F6}",
1574
- "\u{1F680}",
1575
- "\u{1F6F0}\uFE0F",
1576
- "\u26F2\uFE0F",
1577
- "\u{1F3F0}",
1578
- "\u{1F6B2}",
1579
- "\u26FA\uFE0F",
1580
- "\u{1F399}\uFE0F",
1581
- "\u{1F9F2}",
1582
- "\u2699\uFE0F",
1583
- "\u{1F529}",
1584
- "\u{1F52E}",
1585
- "\u{1F52D}",
1586
- "\u{1F52C}",
1587
- "\u{1F9EC}",
1588
- "\u{1F321}\uFE0F",
1589
- "\u{1F9FA}",
1590
- "\u{1F6CE}\uFE0F",
1591
- "\u{1F511}",
1592
- "\u{1FA91}",
1593
- "\u{1F9F8}",
1594
- "\u{1F388}",
1595
- "\u{1F380}",
1596
- "\u{1F38A}",
1597
- "\u267B\uFE0F",
1598
- "\u{1F3B5}"
1599
- ];
1600
- var idHue = [
1601
- "red",
1602
- // 'orange' as const, /* More shades in these palettes are considered “ugly” */
1603
- "amber",
1604
- // 'yellow' as const, /* More shades in these palettes are considered “ugly” */
1605
- "lime",
1606
- "green",
1607
- "emerald",
1608
- "teal",
1609
- "cyan",
1610
- // 'sky' as const, /* Omitted since it is quite similar to the primary accent palette */
1611
- // 'blue' as const, /* Omitted since it is quite similar to the primary accent palette */
1612
- // 'indigo' as const, /* Omitted since it is quite similar to the primary accent palette */
1613
- "violet",
1614
- "purple",
1615
- "fuchsia",
1616
- "pink",
1617
- "rose"
1618
- ];
1619
- var keyToEmoji = (key) => hexToEmoji(key.toHex());
1620
- var hexToEmoji = (hex) => toEmoji(parseInt(hex, 16));
1621
- var toEmoji = (hash) => idEmoji[hash % idEmoji.length];
1622
- var keyToHue = (key) => hexToHue(key.toHex());
1623
- var hexToHue = (hex) => toHue(parseInt(hex, 16));
1624
- var toHue = (hash) => idHue[hash % idHue.length];
1625
- var keyToFallback = (key) => hexToFallback(key.toHex());
1626
- var hexToFallback = (hex) => toFallback(parseInt(hex, 16));
1627
- var toFallback = (hash) => ({
1628
- emoji: toEmoji(hash),
1629
- hue: toHue(hash)
1630
- });
1631
-
1632
- // packages/common/util/src/tracer.ts
1633
- var Tracer = class {
1634
- constructor() {
1635
- this._events = /* @__PURE__ */ new Map();
1636
- this._recording = false;
1637
- }
1638
- // TODO(burdon): Start/stop methods for recording data? By id?
1639
- // Alternatively, enable subscriptions to track/compute series.
1640
- // TODO(burdon): Hierarchical traces?
1641
- get recording() {
1642
- return this._recording;
1643
- }
1644
- keys() {
1645
- return Array.from(this._events.keys());
1646
- }
1647
- get(id, filter) {
1648
- const events = this._events.get(id);
1649
- if (filter) {
1650
- return events?.filter((event) => Object.entries(filter).every(([key, value]) => event?.value[key] === value));
1651
- }
1652
- return events;
1653
- }
1654
- clear() {
1655
- this._events.clear();
1656
- }
1657
- start() {
1658
- this._recording = true;
1659
- return this;
1660
- }
1661
- stop() {
1662
- this._recording = false;
1663
- return this;
1664
- }
1665
- emit(id, value) {
1666
- this._post(this._createEvent(id, value));
1667
- }
1668
- mark(id, value) {
1669
- const event = this._createEvent(id, value);
1670
- const start = performance.now();
1671
- return {
1672
- start,
1673
- end: () => {
1674
- event.duration = performance.now() - start;
1675
- this._post(event);
1676
- }
1677
- };
1678
- }
1679
- _createEvent(id, value) {
1680
- const event = {
1681
- id,
1682
- timestamp: Date.now()
1683
- };
1684
- if (value !== void 0) {
1685
- event.value = value;
1686
- }
1687
- return event;
1688
- }
1689
- _post(event) {
1690
- if (this._recording) {
1691
- defaultMap(this._events, event.id, []).push(event);
1692
- }
1693
- }
1694
- };
1695
- var tracer = new Tracer();
1696
-
1697
- // packages/common/util/src/types.ts
1698
- var isNotFalsy = (value) => !!value;
1699
- var nonNullable = (value) => value !== null && value !== void 0;
1700
- var isNotNullOrUndefined = (value) => value != null;
1701
- var boolGuard = (value) => Boolean(value);
1702
- var doAsync = async (fn) => fn();
1703
- var getProviderValue = (provider, arg) => {
1704
- return typeof provider === "function" ? provider(arg) : provider;
1705
- };
1706
- var getAsyncProviderValue = (provider, arg) => {
1707
- return getProviderValue(provider, arg);
1708
- };
1709
- var stripUndefinedValues = (obj) => {
1710
- if (typeof obj === "object") {
1711
- Object.keys(obj).forEach((key) => {
1712
- const value = obj[key];
1713
- if (value === void 0) {
1714
- delete obj[key];
1715
- } else if (value !== null && typeof value === "object") {
1716
- stripUndefinedValues(value);
1717
- }
1718
- });
1719
- }
1720
- return obj;
1721
- };
1722
- var arrayMove = (array, from, to) => {
1723
- array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]);
1724
- return array;
1725
- };
1726
- var safeParseInt = (value, defaultValue) => {
1727
- try {
1728
- const n = parseInt(value ?? "");
1729
- return isNaN(n) ? defaultValue : n;
1730
- } catch (err) {
1731
- return defaultValue;
1732
- }
1733
- };
1734
-
1735
- // packages/common/util/src/weak.ts
1736
- var WeakDictionary = class {
1737
- constructor(entries) {
1738
- this._internal = /* @__PURE__ */ new Map();
1739
- this._finalization = new FinalizationRegistry((cleanUpCallback) => {
1740
- cleanUpCallback();
1741
- });
1742
- this._internal = new Map(entries?.map(([key, value]) => [
1743
- key,
1744
- new WeakRef(value)
1745
- ]));
1746
- entries?.forEach(([key, value]) => this._register(key, value));
1747
- }
1748
- *entries() {
1749
- for (const [key, value] of this._internal) {
1750
- yield [
1751
- key,
1752
- value.deref()
1753
- ];
1754
- }
1755
- }
1756
- keys() {
1757
- return this._internal.keys();
1758
- }
1759
- *values() {
1760
- for (const value of this._internal.values()) {
1761
- const deref = value.deref();
1762
- if (!deref) {
1763
- continue;
1764
- }
1765
- yield deref;
1766
- }
1767
- }
1768
- *[Symbol.iterator]() {
1769
- for (const [key, value] of this._internal) {
1770
- yield [
1771
- key,
1772
- value.deref()
1773
- ];
1774
- }
1775
- }
1776
- get [Symbol.toStringTag]() {
1777
- return "WeakDictionary";
1778
- }
1779
- get size() {
1780
- return this._internal.size;
1781
- }
1782
- get(key) {
1783
- return this._internal.get(key)?.deref();
1784
- }
1785
- set(key, value) {
1786
- this._internal.set(key, new WeakRef(value));
1787
- this._register(key, value);
1788
- return this;
1789
- }
1790
- has(key) {
1791
- return this._internal.has(key) && this._internal.get(key).deref() !== void 0;
1792
- }
1793
- delete(key) {
1794
- const value = this._internal.get(key)?.deref();
1795
- if (value) {
1796
- this._unregister(value);
1797
- }
1798
- return this._internal.delete(key);
1799
- }
1800
- clear() {
1801
- this._internal.forEach((value) => {
1802
- const v = value.deref();
1803
- if (v) {
1804
- this._unregister(v);
1805
- }
1806
- });
1807
- this._internal.clear();
1808
- }
1809
- forEach(callbackfn, thisArg) {
1810
- if (thisArg) {
1811
- callbackfn = callbackfn.bind(thisArg);
1812
- }
1813
- this._internal.forEach((value, key) => {
1814
- const v = value.deref();
1815
- if (v) {
1816
- callbackfn(v, key, this);
1817
- }
1818
- });
1819
- }
1820
- _register(key, value) {
1821
- this._finalization.register(value, () => {
1822
- this._internal.delete(key);
1823
- }, value);
1824
- }
1825
- _unregister(value) {
1826
- this._finalization.unregister(value);
1827
- }
1828
- };
1829
-
1830
- // packages/common/util/src/array-to-hex.ts
1831
- var byteToHex = [];
1832
- for (let n = 0; n <= 255; ++n) {
1833
- const hexOctet = n.toString(16).padStart(2, "0");
1834
- byteToHex.push(hexOctet);
1835
- }
1836
- var arrayToHex = (buf) => {
1837
- const buff = new Uint8Array(buf);
1838
- const hexOctets = [];
1839
- for (let i = 0; i < buff.length; ++i) {
1840
- hexOctets.push(byteToHex[buff[i]]);
1841
- }
1842
- return hexOctets.join("");
1843
- };
1844
- export {
1845
- BitField,
1846
- Callback,
1847
- CallbackCollection,
1848
- CircularBuffer,
1849
- ComplexMap,
1850
- ComplexSet,
1851
- HumanHasher,
1852
- MapEntry,
1853
- SlidingWindowSummary,
1854
- Tracer,
1855
- WeakDictionary,
1856
- accessBy,
1857
- arrayMove,
1858
- arrayToBuffer,
1859
- arrayToHex,
1860
- arrayToString,
1861
- arraysEqual,
1862
- boolGuard,
1863
- bufferToArray,
1864
- chunkArray,
1865
- compareMulti,
1866
- compareObject,
1867
- compareScalar,
1868
- compareString,
1869
- createBinder,
1870
- createBucketReducer,
1871
- createGroupReducer,
1872
- createSetDispatch,
1873
- deepMapValues,
1874
- deepMapValuesAsync,
1875
- defaultMap,
1876
- defer,
1877
- deferAsync,
1878
- deferFunction,
1879
- diff,
1880
- distinctBy,
1881
- doAsync,
1882
- entry,
1883
- exponentialBackoffInterval,
1884
- forEachAsync,
1885
- getAsyncProviderValue,
1886
- getDate,
1887
- getDebugName,
1888
- getDeep,
1889
- getHostPlatform,
1890
- getPrototypeSpecificInstanceId,
1891
- getProviderValue,
1892
- hexToEmoji,
1893
- hexToFallback,
1894
- hexToHue,
1895
- humanize,
1896
- idEmoji,
1897
- idHue,
1898
- inferObjectOrder,
1899
- inferRecordOrder,
1900
- intersection,
1901
- iosCheck,
1902
- isNode,
1903
- isNotFalsy,
1904
- isNotNullOrUndefined,
1905
- joinTables,
1906
- jsonKeyReplacer,
1907
- jsonReplacer,
1908
- jsonify,
1909
- jsonlogify,
1910
- keyToEmoji,
1911
- keyToFallback,
1912
- keyToHue,
1913
- makeMap,
1914
- makeSet,
1915
- mapValues,
1916
- median,
1917
- mobileAndTabletCheck,
1918
- nonNullable,
1919
- numericalValues,
1920
- pick,
1921
- pickBy,
1922
- randomInt,
1923
- range,
1924
- rangeFromTo,
1925
- reduceGroupBy,
1926
- reduceSeries,
1927
- reduceSet,
1928
- safariCheck,
1929
- safeAwaitAll,
1930
- safeInstanceof,
1931
- safeParseInt,
1932
- safeParseJson,
1933
- setDeep,
1934
- stringToArray,
1935
- stripUndefinedValues,
1936
- sum,
1937
- throwUnhandledError,
1938
- toEmoji,
1939
- toFallback,
1940
- toHue,
1941
- tracer
1942
- };
1943
- //# sourceMappingURL=index.mjs.map