@dxos/util 0.9.1-staging.ee54ba693a → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2696 +0,0 @@
1
- import "@dxos/node-std/globals";
2
- var __defProp = Object.defineProperty;
3
- var __export = (target, all) => {
4
- for (var name in all)
5
- __defProp(target, name, { get: all[name], enumerable: true });
6
- };
7
-
8
- // src/array-to-hex.ts
9
- var byteToHex = [];
10
- for (let n = 0; n <= 255; ++n) {
11
- const hexOctet = n.toString(16).padStart(2, "0");
12
- byteToHex.push(hexOctet);
13
- }
14
- var arrayToHex = (buf) => {
15
- const buff = new Uint8Array(buf);
16
- const hexOctets = [];
17
- for (let i = 0; i < buff.length; ++i) {
18
- hexOctets.push(byteToHex[buff[i]]);
19
- }
20
- return hexOctets.join("");
21
- };
22
-
23
- // src/array.ts
24
- var diff = (previous, next, comparator) => {
25
- const remaining = [
26
- ...previous
27
- ];
28
- const result = {
29
- added: [],
30
- updated: [],
31
- removed: remaining
32
- };
33
- for (const object of next) {
34
- const index = remaining.findIndex((item) => comparator(item, object));
35
- if (index === -1) {
36
- result.added.push(object);
37
- } else {
38
- result.updated.push(object);
39
- remaining.splice(index, 1);
40
- }
41
- }
42
- return result;
43
- };
44
- var intersection = (a, b, comparator) => a.filter((a2) => b.find((b2) => comparator(a2, b2)) !== void 0);
45
- var distinctBy = (array, selector) => {
46
- const seenKeys = /* @__PURE__ */ new Set();
47
- return array.filter((item) => {
48
- const key = selector(item);
49
- if (seenKeys.has(key)) {
50
- return false;
51
- }
52
- seenKeys.add(key);
53
- return true;
54
- });
55
- };
56
- var removeBy = (array, test) => {
57
- const removed = [];
58
- for (let i = array.length - 1; i >= 0; i--) {
59
- if (test(array[i], i)) {
60
- removed.push(...array.splice(i, 1));
61
- }
62
- }
63
- return removed;
64
- };
65
- var partition = (array, guard) => {
66
- return array.reduce(([accepted, rejected], item, index, array2) => guard(item, index, array2) ? [
67
- [
68
- ...accepted,
69
- item
70
- ],
71
- rejected
72
- ] : [
73
- accepted,
74
- [
75
- ...rejected,
76
- item
77
- ]
78
- ], [
79
- [],
80
- []
81
- ]);
82
- };
83
- var intersectBy = (arrays, selector) => {
84
- if (arrays.length === 0) {
85
- return [];
86
- }
87
- if (arrays.length === 1) {
88
- return [
89
- ...arrays[0]
90
- ];
91
- }
92
- const [first2, ...rest] = arrays;
93
- const lookups = rest.map((array) => {
94
- const map = /* @__PURE__ */ new Map();
95
- for (const item of array) {
96
- map.set(selector(item), item);
97
- }
98
- return map;
99
- });
100
- return first2.filter((item) => {
101
- const key = selector(item);
102
- return lookups.every((lookup) => lookup.has(key));
103
- });
104
- };
105
- var coerceArray = (arr) => {
106
- if (arr === void 0) {
107
- return [];
108
- }
109
- return Array.isArray(arr) ? arr : [
110
- arr
111
- ];
112
- };
113
-
114
- // src/assume.ts
115
- function assumeType(value) {
116
- }
117
-
118
- // src/binder.ts
119
- import { promisify } from "@dxos/node-std/util";
120
- var createBinder = (obj) => ({
121
- fn: (fn) => fn.bind(obj),
122
- async: (fn) => promisify(fn.bind(obj))
123
- });
124
-
125
- // src/bitfield.ts
126
- import { invariant } from "@dxos/invariant";
127
- var BitField = class _BitField {
128
- static get(data, idx) {
129
- const bit = data[idx >> 3] >> 7 - idx % 8 & 1;
130
- return !!bit;
131
- }
132
- static set(data, idx, value) {
133
- if (value) {
134
- data[idx >> 3] = data[idx >> 3] | 1 << 7 - idx % 8;
135
- } else {
136
- data[idx >> 3] = data[idx >> 3] & ~(1 << 7 - idx % 8);
137
- }
138
- }
139
- /**
140
- * [start; end)
141
- */
142
- static count(data, begin, end) {
143
- let count = 0;
144
- for (let i = begin; i < end; i++) {
145
- const bit = data[i >> 3] >> 7 - i % 8 & 1;
146
- count += bit;
147
- }
148
- return count;
149
- }
150
- static invert(data) {
151
- const result = new Uint8Array(data.length);
152
- for (let i = 0; i < data.length; i++) {
153
- result[i] = ~data[i];
154
- }
155
- return result;
156
- }
157
- static and(first2, second) {
158
- invariant(first2.length === second.length, "Bitfields must be of the same length");
159
- const result = new Uint8Array(first2.length);
160
- for (let i = 0; i < first2.length; i++) {
161
- result[i] = first2[i] & second[i];
162
- }
163
- return result;
164
- }
165
- static findIndexes(data, opts = {}) {
166
- const { start = 0, end = data.length * 8, value = true } = opts;
167
- const result = [];
168
- for (let i = start; i < end; i++) {
169
- if (_BitField.get(data, i) === value) {
170
- result.push(i);
171
- }
172
- }
173
- return result;
174
- }
175
- static ones(count) {
176
- const res = new Uint8Array(Math.ceil(Math.ceil(count) / 8)).fill(255);
177
- const bitInLastByte = Math.ceil(count % 8);
178
- res[res.length - 1] = 255 << 8 - bitInLastByte;
179
- return res;
180
- }
181
- static zeros(count) {
182
- return new Uint8Array(Math.ceil(Math.ceil(count) / 8)).fill(0);
183
- }
184
- };
185
-
186
- // src/browser-storage.ts
187
- var clearIndexedDB = async () => {
188
- const dbs = await indexedDB.databases();
189
- const results = await Promise.allSettled(dbs.filter((db) => db.name != null).map((db) => new Promise((resolve, reject) => {
190
- const request = indexedDB.deleteDatabase(db.name);
191
- request.onsuccess = () => resolve();
192
- request.onerror = () => reject(request.error);
193
- request.onblocked = () => reject(new Error(`IndexedDB deletion blocked: ${db.name}`));
194
- })));
195
- const failures = results.filter((r) => r.status === "rejected");
196
- if (failures.length > 0) {
197
- throw new AggregateError(failures.map((r) => r.reason), "Failed to delete some IndexedDB databases");
198
- }
199
- };
200
- var clearOPFS = async () => {
201
- const root = await navigator.storage.getDirectory();
202
- const errors = [];
203
- for await (const [name] of root.entries()) {
204
- try {
205
- await root.removeEntry(name, {
206
- recursive: true
207
- });
208
- } catch (err) {
209
- errors.push(err);
210
- }
211
- }
212
- if (errors.length > 0) {
213
- throw new AggregateError(errors, "Failed to remove some OPFS entries");
214
- }
215
- };
216
- var clearServiceWorkers = async () => {
217
- const regs = await navigator.serviceWorker.getRegistrations();
218
- for (const reg of regs) {
219
- await reg.unregister();
220
- }
221
- };
222
- var clearCaches = async () => {
223
- const keys2 = await caches.keys();
224
- for (const key of keys2) {
225
- await caches.delete(key);
226
- }
227
- };
228
-
229
- // src/callback-collection.ts
230
- var CallbackCollection = class {
231
- #callbacks = [];
232
- append(callback) {
233
- this.#callbacks.push(callback);
234
- }
235
- prepend(callback) {
236
- this.#callbacks.unshift(callback);
237
- }
238
- remove(callback) {
239
- this.#callbacks = this.#callbacks.filter((c) => c !== callback);
240
- }
241
- callParallel(...args) {
242
- return Promise.all(this.#callbacks.map((callback) => callback(...args)));
243
- }
244
- async callSerial(...args) {
245
- const results = [];
246
- for (const callback of this.#callbacks) {
247
- results.push(await callback(...args));
248
- }
249
- return results;
250
- }
251
- };
252
-
253
- // src/callback.ts
254
- import { invariant as invariant2 } from "@dxos/invariant";
255
- var Callback = class {
256
- _callback;
257
- call(...args) {
258
- invariant2(this._callback, "Callback not set");
259
- return this._callback(...args);
260
- }
261
- callIfSet(...args) {
262
- return this._callback?.(...args);
263
- }
264
- set(callback) {
265
- invariant2(!this._callback, "Callback already set");
266
- this._callback = callback;
267
- }
268
- isSet() {
269
- return !!this._callback;
270
- }
271
- };
272
- var createSetDispatch = ({ handlers }) => {
273
- return new Proxy({
274
- handlers
275
- }, {
276
- get: (target, prop) => {
277
- return (...args) => {
278
- handlers.forEach((handler) => {
279
- const method = handler[prop];
280
- if (method) {
281
- method.apply(handler, args);
282
- }
283
- });
284
- };
285
- }
286
- });
287
- };
288
-
289
- // src/case.ts
290
- var LOW_DASH = "_".codePointAt(0);
291
- var HI_DASH = "-".codePointAt(0);
292
- var SMALL_A = "a".codePointAt(0);
293
- var CAPITAL_A = "A".codePointAt(0);
294
- var SMALL_Z = "z".codePointAt(0);
295
- var CAPITAL_Z = "Z".codePointAt(0);
296
- var isLower = (char) => char >= SMALL_A && char <= SMALL_Z;
297
- var isUpper = (char) => char >= CAPITAL_A && char <= CAPITAL_Z;
298
- var toLower = (char) => char + 32;
299
- var changeCase = (str, delim) => {
300
- const firstChar = str.charCodeAt(0);
301
- if (!isLower(firstChar)) {
302
- return str;
303
- }
304
- const length = str.length;
305
- let changed = false;
306
- const out = [];
307
- for (let i = 0; i < length; ++i) {
308
- const c = str.charCodeAt(i);
309
- if (isUpper(c)) {
310
- out.push(delim);
311
- out.push(toLower(c));
312
- changed = true;
313
- } else {
314
- out.push(c);
315
- }
316
- }
317
- return changed ? String.fromCharCode.apply(void 0, out) : str;
318
- };
319
- var decamelize = (str) => changeCase(str, LOW_DASH);
320
- var hyphenize = (str) => changeCase(str, HI_DASH);
321
-
322
- // src/chunk-array.ts
323
- var chunkArray = (array, size) => {
324
- const result = [];
325
- for (let i = 0; i < array.length; i += size) {
326
- result.push(array.slice(i, i + size));
327
- }
328
- return result;
329
- };
330
-
331
- // src/circular-buffer.ts
332
- import { invariant as invariant3 } from "@dxos/invariant";
333
- var CircularBuffer = class {
334
- _buffer;
335
- _nextIndex = 0;
336
- _elementCount = 0;
337
- constructor(size) {
338
- invariant3(size >= 1);
339
- this._buffer = new Array(size);
340
- }
341
- push(element) {
342
- const evicted = this._elementCount === this._buffer.length ? this._buffer[this._nextIndex] : void 0;
343
- this._buffer[this._nextIndex] = element;
344
- this._nextIndex = (this._nextIndex + 1) % this._buffer.length;
345
- this._elementCount = Math.min(this._buffer.length, this._elementCount + 1);
346
- return evicted;
347
- }
348
- get elementCount() {
349
- return this._elementCount;
350
- }
351
- clear() {
352
- this._nextIndex = 0;
353
- this._elementCount = 0;
354
- }
355
- getLast() {
356
- if (this._elementCount === 0) {
357
- return void 0;
358
- }
359
- if (this._nextIndex === 0) {
360
- return this._buffer[this._buffer.length - 1];
361
- }
362
- return this._buffer[this._nextIndex - 1];
363
- }
364
- [Symbol.iterator]() {
365
- return this.values();
366
- }
367
- *values() {
368
- if (this._elementCount === 0) {
369
- return;
370
- }
371
- if (this._elementCount < this._buffer.length) {
372
- for (let i = 0; i < this._elementCount; i++) {
373
- yield this._buffer[i];
374
- }
375
- return;
376
- }
377
- for (let i = this._nextIndex; i < this._buffer.length; i++) {
378
- yield this._buffer[i];
379
- }
380
- for (let i = 0; i < this._nextIndex; i++) {
381
- yield this._buffer[i];
382
- }
383
- }
384
- };
385
-
386
- // src/clear-undefined.ts
387
- var clearUndefined = (obj) => {
388
- for (const key of [
389
- ...Object.getOwnPropertyNames(obj),
390
- ...Object.getOwnPropertySymbols(obj)
391
- ]) {
392
- if (obj[key] === void 0) {
393
- delete obj[key];
394
- }
395
- }
396
- return obj;
397
- };
398
-
399
- // src/complex.ts
400
- import { inspect } from "@dxos/node-std/util";
401
- import { inspectObject, raise } from "@dxos/debug";
402
- var MAX_SERIALIZATION_LENGTH = 10;
403
- var ComplexSet = class {
404
- _projection;
405
- _values = /* @__PURE__ */ new Map();
406
- // prettier-ignore
407
- constructor(_projection, values) {
408
- this._projection = _projection;
409
- if (values) {
410
- for (const value of values) {
411
- this.add(value);
412
- }
413
- }
414
- }
415
- toString() {
416
- return inspectObject(this);
417
- }
418
- toJSON() {
419
- return this._values.size > MAX_SERIALIZATION_LENGTH ? {
420
- size: this._values.size
421
- } : Array.from(this._values.values());
422
- }
423
- [inspect.custom]() {
424
- return inspectObject(this);
425
- }
426
- add(value) {
427
- this._values.set(this._projection(value), value);
428
- return this;
429
- }
430
- clear() {
431
- this._values.clear();
432
- }
433
- delete(value) {
434
- return this._values.delete(this._projection(value));
435
- }
436
- forEach(callbackfn, thisArg) {
437
- if (thisArg) {
438
- callbackfn = callbackfn.bind(thisArg);
439
- }
440
- this._values.forEach((value) => callbackfn(value, value, this));
441
- }
442
- has(value) {
443
- return this._values.has(this._projection(value));
444
- }
445
- get size() {
446
- return this._values.size;
447
- }
448
- [Symbol.iterator]() {
449
- return this._values.values();
450
- }
451
- *entries() {
452
- for (const value of this._values.values()) {
453
- yield [
454
- value,
455
- value
456
- ];
457
- }
458
- }
459
- keys() {
460
- return this[Symbol.iterator]();
461
- }
462
- values() {
463
- return this[Symbol.iterator]();
464
- }
465
- get [Symbol.toStringTag]() {
466
- return "ComplexSet";
467
- }
468
- union(other) {
469
- throw new Error("Method not implemented.");
470
- }
471
- intersection(other) {
472
- throw new Error("Method not implemented.");
473
- }
474
- difference(other) {
475
- throw new Error("Method not implemented.");
476
- }
477
- symmetricDifference(other) {
478
- throw new Error("Method not implemented.");
479
- }
480
- isSubsetOf(other) {
481
- throw new Error("Method not implemented.");
482
- }
483
- isSupersetOf(other) {
484
- throw new Error("Method not implemented.");
485
- }
486
- isDisjointFrom(other) {
487
- throw new Error("Method not implemented.");
488
- }
489
- };
490
- var makeSet = (projection) => {
491
- return class BoundComplexSet extends ComplexSet {
492
- constructor(values) {
493
- super(projection, values);
494
- }
495
- };
496
- };
497
- var ComplexMap = class _ComplexMap {
498
- _keyProjection;
499
- _keys = /* @__PURE__ */ new Map();
500
- _values = /* @__PURE__ */ new Map();
501
- // prettier-ignore
502
- constructor(_keyProjection, entries2) {
503
- this._keyProjection = _keyProjection;
504
- if (entries2) {
505
- for (const [key, value] of entries2) {
506
- this.set(key, value);
507
- }
508
- }
509
- }
510
- toString() {
511
- return inspectObject(this);
512
- }
513
- toJSON() {
514
- return this._values.size > MAX_SERIALIZATION_LENGTH ? {
515
- size: this._values.size
516
- } : Array.from(this._values.values());
517
- }
518
- [inspect.custom]() {
519
- return inspectObject(this);
520
- }
521
- clear() {
522
- this._keys.clear();
523
- this._values.clear();
524
- }
525
- delete(key) {
526
- const keyDeleted = this._keys.delete(this._keyProjection(key));
527
- const valueDeleted = this._values.delete(this._keyProjection(key));
528
- return keyDeleted || valueDeleted;
529
- }
530
- forEach(callbackfn, thisArg) {
531
- if (thisArg) {
532
- callbackfn = callbackfn.bind(thisArg);
533
- }
534
- this._keys.forEach((key, primitive) => callbackfn(this._values.get(primitive) ?? raise(new Error("Map corrupted.")), key, this));
535
- }
536
- get(key) {
537
- return this._values.get(this._keyProjection(key));
538
- }
539
- has(key) {
540
- return this._keys.has(this._keyProjection(key));
541
- }
542
- set(key, value) {
543
- const primitive = this._keyProjection(key);
544
- this._keys.set(primitive, key);
545
- this._values.set(primitive, value);
546
- return this;
547
- }
548
- /**
549
- * Returns the value for the given key if present, otherwise inserts and returns the default value.
550
- * @param key - The key to look up or insert.
551
- * @param defaultValue - The value to insert if the key is not present.
552
- * @returns The existing or newly inserted value.
553
- */
554
- getOrInsert(key, defaultValue) {
555
- const primitive = this._keyProjection(key);
556
- if (this._values.has(primitive)) {
557
- return this._values.get(primitive);
558
- }
559
- this.set(key, defaultValue);
560
- return defaultValue;
561
- }
562
- /**
563
- * Returns the value for the given key if present, otherwise computes, inserts, and returns a new value.
564
- * The callback is only invoked when the key is missing.
565
- * @param key - The key to look up or insert.
566
- * @param callbackfn - Function to compute the value if the key is not present.
567
- * @returns The existing or newly computed value.
568
- */
569
- getOrInsertComputed(key, callbackfn) {
570
- const primitive = this._keyProjection(key);
571
- if (this._values.has(primitive)) {
572
- return this._values.get(primitive);
573
- }
574
- const value = callbackfn(key);
575
- this.set(key, value);
576
- return value;
577
- }
578
- get size() {
579
- return this._keys.size;
580
- }
581
- *[Symbol.iterator]() {
582
- for (const [primitive, key] of this._keys) {
583
- const value = this._values.get(primitive) ?? raise(new Error("Map corrupted."));
584
- yield [
585
- key,
586
- value
587
- ];
588
- }
589
- }
590
- entries() {
591
- return this[Symbol.iterator]();
592
- }
593
- keys() {
594
- return this._keys.values();
595
- }
596
- values() {
597
- return this._values.values();
598
- }
599
- mapValues(mapper) {
600
- return new _ComplexMap(this._keyProjection, [
601
- ...this.entries()
602
- ].map(([key, value]) => [
603
- key,
604
- mapper(value, key)
605
- ]));
606
- }
607
- get [Symbol.toStringTag]() {
608
- return "ComplexMap";
609
- }
610
- };
611
- var makeMap = (keyProjection) => class BoundComplexMap extends ComplexMap {
612
- constructor(entries2) {
613
- super(keyProjection, entries2);
614
- }
615
- };
616
-
617
- // src/composite-key.ts
618
- var SEPARATOR = ":";
619
- var compositeKey = (...parts) => parts.join(SEPARATOR);
620
- var splitCompositeKey = (key) => key.split(SEPARATOR);
621
-
622
- // src/deep.ts
623
- import { invariant as invariant4 } from "@dxos/invariant";
624
- var setDeep = (obj, path, value) => {
625
- invariant4(path.length > 0);
626
- let parent = obj;
627
- for (const key of path.slice(0, -1)) {
628
- if (parent[key] === void 0) {
629
- const isArrayIndex = !isNaN(Number(key));
630
- parent[key] = isArrayIndex ? [] : {};
631
- }
632
- parent = parent[key];
633
- }
634
- parent[path.at(-1)] = value;
635
- return obj;
636
- };
637
- var getDeep = (obj, path) => {
638
- let parent = obj;
639
- for (const key of path) {
640
- parent = parent?.[key];
641
- }
642
- return parent;
643
- };
644
-
645
- // src/defer-function.ts
646
- var deferFunction = (fnProvider) => (...args) => fnProvider()(...args);
647
-
648
- // src/defer.ts
649
- import "@hazae41/symbol-dispose-polyfill";
650
- var defer = (fn) => new DeferGuard(fn);
651
- var DeferGuard = class {
652
- _fn;
653
- /**
654
- * @internal
655
- */
656
- constructor(_fn) {
657
- this._fn = _fn;
658
- }
659
- [Symbol.dispose]() {
660
- const result = this._fn();
661
- if (result instanceof Promise) {
662
- throw new Error("Async functions in defer are not supported. Use deferAsync instead.");
663
- }
664
- }
665
- };
666
- var deferAsync = (fn) => new DeferAsyncGuard(fn);
667
- var DeferAsyncGuard = class {
668
- _fn;
669
- /**
670
- * @internal
671
- */
672
- constructor(_fn) {
673
- this._fn = _fn;
674
- }
675
- async [Symbol.asyncDispose]() {
676
- await this._fn();
677
- }
678
- };
679
-
680
- // src/entry.ts
681
- var entry = (map, key) => new MapEntry(map, key);
682
- var MapEntry = class {
683
- _map;
684
- _key;
685
- /**
686
- * @internal
687
- */
688
- // prettier-ignore
689
- constructor(_map, _key) {
690
- this._map = _map;
691
- this._key = _key;
692
- }
693
- get key() {
694
- return this._key;
695
- }
696
- get value() {
697
- return this._map.get(this._key);
698
- }
699
- orInsert(value) {
700
- if (!this._map.has(this._key)) {
701
- this._map.set(this._key, value);
702
- }
703
- return this;
704
- }
705
- deep(key) {
706
- return entry(this.value, key);
707
- }
708
- };
709
-
710
- // src/error-format.ts
711
- var formatErrorWithCauses = (error) => {
712
- const lines = [];
713
- let current = error;
714
- let level = 0;
715
- while (current) {
716
- const prefix = level === 0 ? "" : `Caused by: `;
717
- lines.push(prefix + (current.stack ?? String(current)));
718
- if (!(current.cause instanceof Error)) {
719
- break;
720
- }
721
- current = current.cause;
722
- level += 1;
723
- }
724
- return lines.join("\n\n");
725
- };
726
-
727
- // src/filename.ts
728
- var createFilename = ({ parts = [], ext, date = /* @__PURE__ */ new Date() }) => [
729
- date.toISOString().replace(/[:.]/g, "-"),
730
- ...parts
731
- ].join("_") + (ext ? `.${ext}` : "");
732
-
733
- // src/for-each-async.ts
734
- var forEachAsync = (items, fn) => Promise.all(items.map(fn));
735
-
736
- // src/human-hash.ts
737
- import { PublicKey } from "@dxos/keys";
738
- var DEFAULT_WORDLIST = [
739
- "ack",
740
- "alabama",
741
- "alanine",
742
- "alaska",
743
- "alpha",
744
- "angel",
745
- "apart",
746
- "april",
747
- "arizona",
748
- "arkansas",
749
- "artist",
750
- "asparagus",
751
- "aspen",
752
- "august",
753
- "autumn",
754
- "avocado",
755
- "bacon",
756
- "bakerloo",
757
- "batman",
758
- "beer",
759
- "berlin",
760
- "beryllium",
761
- "black",
762
- "blossom",
763
- "blue",
764
- "bluebird",
765
- "bravo",
766
- "bulldog",
767
- "burger",
768
- "butter",
769
- "california",
770
- "carbon",
771
- "cardinal",
772
- "carolina",
773
- "carpet",
774
- "cat",
775
- "ceiling",
776
- "charlie",
777
- "chicken",
778
- "coffee",
779
- "cola",
780
- "cold",
781
- "colorado",
782
- "comet",
783
- "connecticut",
784
- "crazy",
785
- "cup",
786
- "dakota",
787
- "december",
788
- "delaware",
789
- "delta",
790
- "diet",
791
- "don",
792
- "double",
793
- "early",
794
- "earth",
795
- "east",
796
- "echo",
797
- "edward",
798
- "eight",
799
- "eighteen",
800
- "eleven",
801
- "emma",
802
- "enemy",
803
- "equal",
804
- "failed",
805
- "fanta",
806
- "fifteen",
807
- "fillet",
808
- "finch",
809
- "fish",
810
- "five",
811
- "fix",
812
- "floor",
813
- "florida",
814
- "football",
815
- "four",
816
- "fourteen",
817
- "foxtrot",
818
- "freddie",
819
- "friend",
820
- "fruit",
821
- "gee",
822
- "georgia",
823
- "glucose",
824
- "golf",
825
- "green",
826
- "grey",
827
- "hamper",
828
- "happy",
829
- "harry",
830
- "hawaii",
831
- "helium",
832
- "high",
833
- "hot",
834
- "hotel",
835
- "hydrogen",
836
- "idaho",
837
- "illinois",
838
- "india",
839
- "indigo",
840
- "ink",
841
- "iowa",
842
- "island",
843
- "item",
844
- "jersey",
845
- "jig",
846
- "johnny",
847
- "juliet",
848
- "july",
849
- "jupiter",
850
- "kansas",
851
- "kentucky",
852
- "kilo",
853
- "king",
854
- "kitten",
855
- "lactose",
856
- "lake",
857
- "lamp",
858
- "lemon",
859
- "leopard",
860
- "lima",
861
- "lion",
862
- "lithium",
863
- "london",
864
- "louisiana",
865
- "low",
866
- "magazine",
867
- "magnesium",
868
- "maine",
869
- "mango",
870
- "march",
871
- "mars",
872
- "maryland",
873
- "massachusetts",
874
- "may",
875
- "mexico",
876
- "michigan",
877
- "mike",
878
- "minnesota",
879
- "mirror",
880
- "mississippi",
881
- "missouri",
882
- "mobile",
883
- "mockingbird",
884
- "monkey",
885
- "montana",
886
- "moon",
887
- "mountain",
888
- "muppet",
889
- "music",
890
- "nebraska",
891
- "neptune",
892
- "network",
893
- "nevada",
894
- "nine",
895
- "nineteen",
896
- "nitrogen",
897
- "north",
898
- "november",
899
- "nuts",
900
- "october",
901
- "ohio",
902
- "oklahoma",
903
- "one",
904
- "orange",
905
- "oranges",
906
- "oregon",
907
- "oscar",
908
- "oven",
909
- "oxygen",
910
- "papa",
911
- "paris",
912
- "pasta",
913
- "pennsylvania",
914
- "pip",
915
- "pizza",
916
- "pluto",
917
- "potato",
918
- "princess",
919
- "purple",
920
- "quebec",
921
- "queen",
922
- "quiet",
923
- "red",
924
- "river",
925
- "robert",
926
- "robin",
927
- "romeo",
928
- "rugby",
929
- "sad",
930
- "salami",
931
- "saturn",
932
- "september",
933
- "seven",
934
- "seventeen",
935
- "shade",
936
- "sierra",
937
- "single",
938
- "sink",
939
- "six",
940
- "sixteen",
941
- "skylark",
942
- "snake",
943
- "social",
944
- "sodium",
945
- "solar",
946
- "south",
947
- "spaghetti",
948
- "speaker",
949
- "spring",
950
- "stairway",
951
- "steak",
952
- "stream",
953
- "summer",
954
- "sweet",
955
- "table",
956
- "tango",
957
- "ten",
958
- "tennessee",
959
- "tennis",
960
- "texas",
961
- "thirteen",
962
- "three",
963
- "timing",
964
- "triple",
965
- "twelve",
966
- "twenty",
967
- "two",
968
- "uncle",
969
- "undress",
970
- "uniform",
971
- "uranus",
972
- "utah",
973
- "vegan",
974
- "venus",
975
- "vermont",
976
- "victor",
977
- "video",
978
- "violet",
979
- "virginia",
980
- "washington",
981
- "west",
982
- "whiskey",
983
- "white",
984
- "william",
985
- "winner",
986
- "winter",
987
- "wisconsin",
988
- "wolfram",
989
- "wyoming",
990
- "xray",
991
- "yankee",
992
- "yellow",
993
- "zebra",
994
- "zulu"
995
- ];
996
- var HumanHasher = class {
997
- wordlist;
998
- /**
999
- * Transforms hex digests to human-readable strings.
1000
- *
1001
- * The format of these strings will look something like:
1002
- * `victor-bacon-zulu-lima`. The output is obtained by compressing the input
1003
- * digest to a fixed number of bytes, then mapping those bytes to one of 256
1004
- * words. A default wordlist is provided, but you can override this if you
1005
- * prefer.
1006
- * As long as you use the same wordlist, the output will be consistent (i.e.
1007
- * the same digest will always render the same representation).
1008
- *
1009
- * @param wordlist A list of exactly 256 words to choose from
1010
- */
1011
- constructor(wordlist = DEFAULT_WORDLIST) {
1012
- this.wordlist = wordlist;
1013
- if (wordlist.length !== 256) {
1014
- throw new Error("Wordlist must have exactly 256 items");
1015
- }
1016
- this.wordlist = wordlist;
1017
- }
1018
- /**
1019
- * Humanize a given hexadecimal digest.
1020
- *
1021
- * Change the number of words output by specifying `words`. Change the
1022
- * word separator with `separator`.
1023
- *
1024
- * @param hexdigest A string of hexadecimal characters to humanize
1025
- * @param words How many words to output (more = safer)
1026
- * @param separator The string used to seperate the words
1027
- */
1028
- humanize(hexdigest, words = 4, separator = "-") {
1029
- const pairs = hexdigest.match(/(..?)/g);
1030
- if (!pairs) {
1031
- throw new Error("");
1032
- }
1033
- const bytes = pairs.map((x) => parseInt(x, 16));
1034
- const compressed = this._compress(bytes, words);
1035
- return compressed.map((x) => this.wordlist[x]).join(separator);
1036
- }
1037
- /**
1038
- * Compress a list of byte values to a fixed target length.
1039
- *
1040
- * @param bytes A list of bytes (numbers from 0-254)
1041
- * @param target The number of bytes to return / compress to
1042
- */
1043
- _compress(bytes, target) {
1044
- const length = bytes.length;
1045
- if (target > length) {
1046
- throw new Error("Fewer input bytes than requested output");
1047
- }
1048
- const segSize = length / target >> 0;
1049
- const segments = [];
1050
- for (let i = 0; i < segSize * target; i += segSize) {
1051
- segments.push(bytes.slice(i, i + segSize));
1052
- }
1053
- segments[segments.length - 1] = segments[segments.length - 1].concat(bytes.slice(target * segSize));
1054
- const checksums = segments.map((x) => x.reduce((acc, curr) => acc ^ curr));
1055
- return checksums;
1056
- }
1057
- };
1058
- var hasher = new HumanHasher();
1059
- var humanize = (value) => {
1060
- if (value instanceof Buffer || value instanceof Uint8Array || value instanceof ArrayBuffer) {
1061
- value = PublicKey.stringify(value);
1062
- } else if (value instanceof PublicKey) {
1063
- value = value.toHex();
1064
- }
1065
- return hasher.humanize(value);
1066
- };
1067
-
1068
- // src/id.ts
1069
- var PART = /^[a-zA-Z][a-zA-Z0-9]{0,62}$/;
1070
- var ID = /^[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(\.[a-zA-Z]([a-zA-Z0-9]{0,62})?)$/;
1071
- function id(strings, ...values) {
1072
- const raw = strings.reduce((out, str, i) => out + str + (i < values.length ? String(values[i]) : ""), "");
1073
- if (!ID.test(raw)) {
1074
- throw new Error(`Invalid id (expected AT Protocol NSID): ${JSON.stringify(raw)}`);
1075
- }
1076
- return raw;
1077
- }
1078
- var isWellFormedId = (value) => ID.test(value);
1079
- var isWellFormedIdPart = (value) => PART.test(value);
1080
-
1081
- // src/map.ts
1082
- var defaultMap = (map, key, def) => {
1083
- let value = map.get(key);
1084
- if (value === void 0) {
1085
- value = typeof def === "function" ? def() : def;
1086
- map.set(key, value);
1087
- }
1088
- return value;
1089
- };
1090
-
1091
- // src/instance-id.ts
1092
- var symbol = /* @__PURE__ */ Symbol.for("dxos.instance-contexts");
1093
- var instanceContexts = globalThis[symbol] ??= /* @__PURE__ */ new WeakMap();
1094
- var getPrototypeSpecificInstanceId = (instance) => {
1095
- const prototype = Object.getPrototypeOf(instance);
1096
- const instanceCtx = defaultMap(instanceContexts, prototype, () => ({
1097
- nextId: 0,
1098
- instanceIds: /* @__PURE__ */ new WeakMap()
1099
- }));
1100
- let id2 = instanceCtx.instanceIds.get(instance);
1101
- if (id2 === void 0) {
1102
- id2 = instanceCtx.nextId++;
1103
- instanceCtx.instanceIds.set(instance, id2);
1104
- }
1105
- return id2;
1106
- };
1107
- var getDebugName = (instance) => {
1108
- if (instance == null) {
1109
- return "null";
1110
- }
1111
- const prototype = Object.getPrototypeOf(instance);
1112
- return `${prototype.constructor?.name ?? "Object"}#${getPrototypeSpecificInstanceId(instance)}`;
1113
- };
1114
-
1115
- // src/interval.ts
1116
- var exponentialBackoffInterval = (cb, initialInterval) => {
1117
- let interval = initialInterval;
1118
- const repeat = () => {
1119
- cb();
1120
- interval *= 2;
1121
- timeoutId = setTimeout(repeat, interval);
1122
- };
1123
- let timeoutId = setTimeout(repeat, interval);
1124
- return () => clearTimeout(timeoutId);
1125
- };
1126
-
1127
- // src/join-tables.ts
1128
- var joinTables = (leftColumn, rightColumn, left, right) => {
1129
- const map = /* @__PURE__ */ new Map();
1130
- const used = /* @__PURE__ */ new Set();
1131
- for (const row of right) {
1132
- map.set(row[rightColumn], row);
1133
- }
1134
- const result = [];
1135
- for (const row of left) {
1136
- const right2 = map.get(row[leftColumn]);
1137
- used.add(right2);
1138
- result.push(Object.assign(right2 ?? {}, row));
1139
- }
1140
- for (const row of right) {
1141
- if (!used.has(row)) {
1142
- result.push(row);
1143
- }
1144
- }
1145
- return result;
1146
- };
1147
-
1148
- // src/json.ts
1149
- import { inspect as inspect2 } from "@dxos/node-std/util";
1150
- import { PublicKey as PublicKey2 } from "@dxos/keys";
1151
-
1152
- // src/uint8array.ts
1153
- var arraysEqual = (a, b) => {
1154
- if (a.length !== b.length) {
1155
- return false;
1156
- }
1157
- for (let i = 0; i < a.length; i++) {
1158
- if (a[i] !== b[i]) {
1159
- return false;
1160
- }
1161
- }
1162
- return true;
1163
- };
1164
- var arrayToBuffer = (array) => {
1165
- return Buffer.from(array.buffer, array.byteOffset, array.byteLength);
1166
- };
1167
- var bufferToArray = (buffer) => {
1168
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
1169
- };
1170
- var stringToArray = (string) => bufferToArray(Buffer.from(string, "hex"));
1171
- var arrayToString = (array) => arrayToBuffer(array).toString("hex");
1172
- var toUnpaddedBase64 = (bytes) => arrayToBuffer(bytes).toString("base64").replace(/=+$/, "");
1173
- var encodeUint8ArrayToJson = (bytes) => ({
1174
- "/": {
1175
- bytes: toUnpaddedBase64(bytes)
1176
- }
1177
- });
1178
- var isEncodedUint8Array = (value) => {
1179
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
1180
- return false;
1181
- }
1182
- if (Object.keys(value).length !== 1) {
1183
- return false;
1184
- }
1185
- const inner = value["/"];
1186
- if (typeof inner !== "object" || inner === null || Array.isArray(inner)) {
1187
- return false;
1188
- }
1189
- return Object.keys(inner).length === 1 && typeof inner.bytes === "string";
1190
- };
1191
- var decodeUint8ArrayFromJson = (encoded) => bufferToArray(Buffer.from(encoded["/"].bytes, "base64"));
1192
-
1193
- // src/json.ts
1194
- var MAX_DEPTH = 5;
1195
- var LOG_MAX_DEPTH = 7;
1196
- var jsonReplacer = (key, value) => {
1197
- if (value !== null && typeof value === "object" && typeof value[inspect2.custom] === "function") {
1198
- return value[inspect2.custom]();
1199
- }
1200
- if (value !== null && typeof value === "object" && value.type === "Buffer" && Array.isArray(value.data)) {
1201
- if (value.data.length === 32) {
1202
- const key2 = Buffer.from(value.data);
1203
- return `[${humanize(key2)}]:[${PublicKey2.stringify(key2)}]`;
1204
- } else {
1205
- return Buffer.from(value.data).toString("hex");
1206
- }
1207
- }
1208
- return value;
1209
- };
1210
- var jsonify = (value, depth = 0, visitedObjects = /* @__PURE__ */ new WeakSet()) => {
1211
- if (depth > MAX_DEPTH) {
1212
- return null;
1213
- } else if (typeof value === "function") {
1214
- return null;
1215
- } else if (typeof value === "object" && value !== null) {
1216
- if (visitedObjects.has(value)) {
1217
- return null;
1218
- }
1219
- visitedObjects.add(value);
1220
- try {
1221
- if (value instanceof Uint8Array) {
1222
- return arrayToBuffer(value).toString("hex");
1223
- } else if (Array.isArray(value)) {
1224
- return value.map((x) => jsonify(x, depth + 1, visitedObjects));
1225
- } else if (typeof value.toJSON === "function") {
1226
- return value.toJSON();
1227
- } else {
1228
- const res = {};
1229
- for (const key of Object.keys(value)) {
1230
- res[key] = jsonify(value[key], depth + 1, visitedObjects);
1231
- }
1232
- return res;
1233
- }
1234
- } finally {
1235
- visitedObjects.delete(value);
1236
- }
1237
- } else {
1238
- return value;
1239
- }
1240
- };
1241
- var jsonlogify = (value, depth = 0, visitedObjects = /* @__PURE__ */ new WeakSet()) => {
1242
- if (depth > LOG_MAX_DEPTH) {
1243
- return null;
1244
- } else if (typeof value === "function") {
1245
- return null;
1246
- } else if (typeof value === "object" && value !== null) {
1247
- if (visitedObjects.has(value)) {
1248
- return null;
1249
- }
1250
- visitedObjects.add(value);
1251
- try {
1252
- if (value instanceof Uint8Array) {
1253
- return arrayToBuffer(value).toString("hex");
1254
- } else if (Array.isArray(value)) {
1255
- return value.map((x) => jsonlogify(x, depth + 1, visitedObjects));
1256
- } else if (typeof value.toJSONL === "function") {
1257
- return value.toJSONL();
1258
- } else if (typeof value.toJSON === "function") {
1259
- return value.toJSON();
1260
- } else {
1261
- const res = {};
1262
- for (const key of Object.keys(value)) {
1263
- res[key] = jsonlogify(value[key], depth + 1, visitedObjects);
1264
- }
1265
- return res;
1266
- }
1267
- } finally {
1268
- visitedObjects.delete(value);
1269
- }
1270
- } else {
1271
- return value;
1272
- }
1273
- };
1274
- var jsonKeyReplacer = (options = {}) => (key, value) => {
1275
- if (typeof value === "string") {
1276
- const key2 = PublicKey2.fromHex(value);
1277
- if (key2.toHex() === value) {
1278
- return options.humanize ? humanize(key2) : options.truncate ? key2.truncate() : key2.toHex();
1279
- }
1280
- }
1281
- return value;
1282
- };
1283
-
1284
- // src/map-values.ts
1285
- var mapValues = (obj, fn) => {
1286
- const result = {};
1287
- Object.keys(obj).forEach((key) => {
1288
- result[key] = fn(obj[key], key);
1289
- });
1290
- return result;
1291
- };
1292
- var deepMapValues = (value, fn) => {
1293
- return new DeepMapper(fn).map(value);
1294
- };
1295
- var DeepMapper = class {
1296
- _fn;
1297
- _cyclic = /* @__PURE__ */ new Map();
1298
- constructor(_fn) {
1299
- this._fn = _fn;
1300
- }
1301
- map(value) {
1302
- return this._map(value, void 0);
1303
- }
1304
- _map(value, key) {
1305
- if (this._cyclic.has(value)) {
1306
- return this._cyclic.get(value);
1307
- }
1308
- return this._fn(value, this._recurse, key);
1309
- }
1310
- _recurse = (value) => {
1311
- if (this._cyclic.has(value)) {
1312
- return this._cyclic.get(value);
1313
- }
1314
- if (Array.isArray(value)) {
1315
- const res = new Array(value.length);
1316
- this._cyclic.set(value, res);
1317
- for (let i = 0; i < value.length; i++) {
1318
- res[i] = this._map(value[i], i);
1319
- }
1320
- return res;
1321
- } else if (ArrayBuffer.isView(value)) {
1322
- return value;
1323
- } else if (value !== null && typeof value === "object") {
1324
- const res = {};
1325
- this._cyclic.set(value, res);
1326
- for (const key in value) {
1327
- res[key] = this._map(value[key], key);
1328
- }
1329
- return res;
1330
- } else {
1331
- return value;
1332
- }
1333
- };
1334
- };
1335
- var deepMapValuesAsync = (value, fn) => {
1336
- return new DeepMapperAsync(fn).map(value);
1337
- };
1338
- var DeepMapperAsync = class {
1339
- _fn;
1340
- _cyclic = /* @__PURE__ */ new Map();
1341
- constructor(_fn) {
1342
- this._fn = _fn;
1343
- }
1344
- map(value) {
1345
- return this._map(value, void 0);
1346
- }
1347
- _map(value, key) {
1348
- if (this._cyclic.has(value)) {
1349
- return this._cyclic.get(value);
1350
- }
1351
- return this._fn(value, this._recurse, key);
1352
- }
1353
- _recurse = async (value) => {
1354
- if (this._cyclic.has(value)) {
1355
- return this._cyclic.get(value);
1356
- }
1357
- if (Array.isArray(value)) {
1358
- const res = new Array(value.length);
1359
- this._cyclic.set(value, res);
1360
- for (let i = 0; i < value.length; i++) {
1361
- res[i] = await this._map(value[i], i);
1362
- }
1363
- return res;
1364
- } else if (ArrayBuffer.isView(value)) {
1365
- return value;
1366
- } else if (value !== null && typeof value === "object") {
1367
- const res = {};
1368
- this._cyclic.set(value, res);
1369
- for (const key in value) {
1370
- res[key] = await this._map(value[key], key);
1371
- }
1372
- return res;
1373
- } else {
1374
- return value;
1375
- }
1376
- };
1377
- };
1378
- var visitValues = (object, visitor) => {
1379
- if (Array.isArray(object)) {
1380
- object.forEach((item, index) => visitor(item, index));
1381
- } else if (typeof object === "object" && object !== null) {
1382
- for (const [key, value] of Object.entries(object)) {
1383
- visitor(value, key);
1384
- }
1385
- }
1386
- };
1387
-
1388
- // src/object.ts
1389
- var keys = (obj) => Object.keys(obj);
1390
- var entries = (obj) => Object.entries(obj);
1391
-
1392
- // src/order-keys.ts
1393
- var orderKeys = (obj, order) => {
1394
- const ordered = {};
1395
- for (const key of order) {
1396
- if (key in obj) {
1397
- ordered[key] = obj[key];
1398
- }
1399
- }
1400
- for (const key in obj) {
1401
- if (!(key in ordered)) {
1402
- ordered[key] = obj[key];
1403
- }
1404
- }
1405
- return ordered;
1406
- };
1407
-
1408
- // src/order.ts
1409
- var inferObjectOrder = (objectMap, order = []) => {
1410
- const orderedObjects = order.reduce((acc, id2) => {
1411
- if (id2 in objectMap) {
1412
- acc.objects.push(objectMap[id2]);
1413
- acc.ids.add(id2);
1414
- }
1415
- return acc;
1416
- }, {
1417
- objects: [],
1418
- ids: /* @__PURE__ */ new Set()
1419
- });
1420
- const { objects } = Object.keys(objectMap).reduce((acc, id2) => {
1421
- if (!acc.ids.has(id2)) {
1422
- acc.objects.push(objectMap[id2]);
1423
- }
1424
- return acc;
1425
- }, orderedObjects);
1426
- return objects;
1427
- };
1428
- var inferRecordOrder = (objectMap, order = []) => {
1429
- return Object.assign(order.filter((id2) => id2 in objectMap).reduce((acc, id2) => {
1430
- acc[id2] = null;
1431
- return acc;
1432
- }, {}), objectMap);
1433
- };
1434
-
1435
- // src/pick.ts
1436
- var pick = (obj, keys2) => {
1437
- return keys2.reduce((result, key) => {
1438
- if (obj && key in obj) {
1439
- result[key] = obj[key];
1440
- }
1441
- return result;
1442
- }, {});
1443
- };
1444
- var pickBy = (obj, predicate) => {
1445
- const result = {};
1446
- for (const key in obj) {
1447
- if (predicate(obj[key])) {
1448
- result[key] = obj[key];
1449
- }
1450
- }
1451
- return result;
1452
- };
1453
- var omit = (obj, keys2) => {
1454
- const result = {
1455
- ...obj
1456
- };
1457
- keys2.forEach((key) => {
1458
- delete result[key];
1459
- });
1460
- return result;
1461
- };
1462
-
1463
- // src/platform.ts
1464
- var isNode = () => typeof process !== "undefined" && process.versions != null && process.versions.node != null;
1465
- var isBun = () => globalThis.Bun !== void 0;
1466
- var isTauri = () => !!globalThis.__TAURI__;
1467
- var isMobile = () => {
1468
- let check = false;
1469
- (function(a) {
1470
- 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/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))) {
1471
- check = true;
1472
- }
1473
- })(navigator.userAgent || navigator.vendor || window.opera);
1474
- return check;
1475
- };
1476
- var isMobileOrTablet = () => {
1477
- let check = false;
1478
- ((a) => {
1479
- 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))) {
1480
- check = true;
1481
- }
1482
- })(navigator.userAgent || navigator.vendor || window.opera);
1483
- return check;
1484
- };
1485
- var iosCheck = () => {
1486
- return [
1487
- "iPad Simulator",
1488
- "iPhone Simulator",
1489
- "iPod Simulator",
1490
- "iPad",
1491
- "iPhone",
1492
- "iPod"
1493
- ].includes(navigator.platform) || // iPad on iOS 13 detection
1494
- navigator.userAgent.includes("Mac") && "ontouchend" in document;
1495
- };
1496
- var safariCheck = () => typeof navigator !== "undefined" && /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
1497
- var getHostPlatform = () => {
1498
- if (!("navigator" in globalThis)) {
1499
- return "unknown";
1500
- }
1501
- const platform = (navigator.userAgentData?.platform || navigator.platform)?.toLowerCase();
1502
- if (platform.startsWith("win")) {
1503
- return "windows";
1504
- } else if (platform.startsWith("mac")) {
1505
- return "macos";
1506
- } else if (platform.startsWith("ipad") || platform.startsWith("iphone") || platform.startsWith("ipod")) {
1507
- return "ios";
1508
- } else if (platform.startsWith("linux")) {
1509
- return "linux";
1510
- } else {
1511
- return "unknown";
1512
- }
1513
- };
1514
-
1515
- // src/Position.ts
1516
- var Position_exports = {};
1517
- __export(Position_exports, {
1518
- compare: () => compare,
1519
- first: () => first,
1520
- last: () => last
1521
- });
1522
- var first = -Infinity;
1523
- var last = Infinity;
1524
- var compare = ({ position: a }, { position: b }) => {
1525
- const aVal = a ?? 0;
1526
- const bVal = b ?? 0;
1527
- if (aVal === bVal) {
1528
- return 0;
1529
- }
1530
- return aVal < bVal ? -1 : 1;
1531
- };
1532
-
1533
- // src/random.ts
1534
- var randomInt = (max, min = 0) => {
1535
- min = Math.ceil(min);
1536
- max = Math.floor(max);
1537
- return Math.floor(Math.random() * (max - min + 1)) + min;
1538
- };
1539
-
1540
- // src/range.ts
1541
- var range = (n = 0, mapper) => {
1542
- const range2 = Array.from(Array(n).keys());
1543
- return mapper == null ? range2 : range2.map(mapper);
1544
- };
1545
- var rangeFromTo = (from, to, mapper) => {
1546
- return mapper == null ? range(to - from, (i) => i + from) : range(to - from, (i) => mapper(i + from));
1547
- };
1548
- var clamp = (value, min, max) => {
1549
- return Math.min(Math.max(value, min), max);
1550
- };
1551
-
1552
- // src/reducers.ts
1553
- var accessBy = (value, accessor) => typeof accessor === "function" ? accessor(value) : value[accessor];
1554
- var median = (values) => {
1555
- const mid = Math.floor(values.length / 2);
1556
- if (values.length % 2 === 1) {
1557
- return values[mid];
1558
- } else {
1559
- return (values[mid - 1] + values[mid]) / 2;
1560
- }
1561
- };
1562
- var numericalValues = (values, accessor) => {
1563
- const result = {
1564
- total: 0,
1565
- count: 0
1566
- };
1567
- const sorted = values.map((value) => {
1568
- const v = accessBy(value, accessor);
1569
- if (v === void 0 || isNaN(v)) {
1570
- return void 0;
1571
- }
1572
- result.total += v;
1573
- if (result.min === void 0 || v < result.min) {
1574
- result.min = v;
1575
- }
1576
- if (result.max === void 0 || v > result.max) {
1577
- result.max = v;
1578
- }
1579
- return v;
1580
- }).filter((value) => value !== void 0).sort((a, b) => a - b);
1581
- if (sorted.length) {
1582
- Object.assign(result, {
1583
- count: sorted.length,
1584
- mean: result.total / sorted.length,
1585
- median: median(sorted)
1586
- });
1587
- }
1588
- return result;
1589
- };
1590
- var reduceSet = (values, accessor) => {
1591
- return values.reduce((values2, value) => {
1592
- const v = accessBy(value, accessor);
1593
- values2.add(v);
1594
- return values2;
1595
- }, /* @__PURE__ */ new Set());
1596
- };
1597
- var reduceGroupBy = (values, accessor) => {
1598
- return values.reduce((values2, value) => {
1599
- const key = accessBy(value, accessor);
1600
- defaultMap(values2, key, []).push(value);
1601
- return values2;
1602
- }, /* @__PURE__ */ new Map());
1603
- };
1604
- var reduceSeries = (reducer, events) => {
1605
- const state = reducer.initialState();
1606
- for (const event of events) {
1607
- reducer.reduce(state, event);
1608
- }
1609
- return state;
1610
- };
1611
- var createGroupReducer = (groupBy, sub) => ({
1612
- initialState: () => ({}),
1613
- reduce: (state, event) => {
1614
- const key = groupBy(event);
1615
- state[key] = sub.reduce(state[key] ?? sub.initialState(), event);
1616
- return state;
1617
- }
1618
- });
1619
- var getDate = (value) => value instanceof Date ? value : new Date(value);
1620
- var createBucketReducer = (period) => ({
1621
- initialState: () => [],
1622
- reduce: (series, event) => {
1623
- const timestamp = getDate(event.timestamp);
1624
- let bucket = series[series.length - 1];
1625
- if (!bucket || bucket.start + period < timestamp.getTime()) {
1626
- bucket = {
1627
- start: timestamp.getTime(),
1628
- period,
1629
- count: 0
1630
- };
1631
- series.push(bucket);
1632
- }
1633
- bucket.count++;
1634
- return series;
1635
- }
1636
- });
1637
-
1638
- // src/remove-undefined-keys.ts
1639
- var removeUndefinedProperties = (object) => {
1640
- for (const prop of [
1641
- ...Object.getOwnPropertyNames(object),
1642
- ...Object.getOwnPropertySymbols(object)
1643
- ]) {
1644
- if (object[prop] === void 0) {
1645
- delete object[prop];
1646
- }
1647
- }
1648
- return object;
1649
- };
1650
- var removeProperties = (root, condition) => {
1651
- if (!root || typeof root !== "object") {
1652
- return root;
1653
- }
1654
- if (Array.isArray(root)) {
1655
- return root.map((item) => removeProperties(item, condition));
1656
- }
1657
- const result = {
1658
- ...root
1659
- };
1660
- if (typeof condition === "function") {
1661
- for (const [key, value] of Object.entries(result)) {
1662
- if (condition(key, value)) {
1663
- delete result[key];
1664
- }
1665
- }
1666
- } else {
1667
- for (const key of condition) {
1668
- delete result[key];
1669
- }
1670
- }
1671
- for (const [key, value] of Object.entries(result)) {
1672
- if (typeof value === "object") {
1673
- result[key] = removeProperties(value, condition);
1674
- }
1675
- }
1676
- return result;
1677
- };
1678
-
1679
- // src/retry.ts
1680
- var DEFAULT_RETRY_OPTIONS = {
1681
- count: 3,
1682
- delayMs: 100,
1683
- exponent: 2,
1684
- retryOnError: async () => true,
1685
- retryOnValue: async () => false
1686
- };
1687
- var retry = async (options, cb) => {
1688
- const fullOptions = {
1689
- ...DEFAULT_RETRY_OPTIONS,
1690
- ...options
1691
- };
1692
- let numRetries = 0, currentDelay = fullOptions.delayMs;
1693
- while (true) {
1694
- let result;
1695
- try {
1696
- result = await cb();
1697
- } catch (err) {
1698
- if (numRetries > fullOptions.count || !await fullOptions.retryOnError(err)) {
1699
- throw err;
1700
- }
1701
- await new Promise((resolve) => setTimeout(resolve, currentDelay));
1702
- currentDelay *= fullOptions.exponent;
1703
- numRetries++;
1704
- continue;
1705
- }
1706
- if (!await fullOptions.retryOnValue(result)) {
1707
- return result;
1708
- }
1709
- await new Promise((resolve) => setTimeout(resolve, currentDelay));
1710
- currentDelay *= fullOptions.exponent;
1711
- numRetries++;
1712
- continue;
1713
- }
1714
- };
1715
-
1716
- // src/safe-await.ts
1717
- var safeAwaitAll = async (source, taskFactory, onError) => {
1718
- const failedItems = [];
1719
- await Promise.all([
1720
- ...source
1721
- ].map(async (item, idx) => {
1722
- try {
1723
- await taskFactory(item);
1724
- } catch (err) {
1725
- if (onError) {
1726
- onError(err, item, idx);
1727
- }
1728
- failedItems.push(item);
1729
- }
1730
- }));
1731
- return failedItems;
1732
- };
1733
-
1734
- // src/safe-instanceof.ts
1735
- var instanceTag = /* @__PURE__ */ Symbol("instanceTag");
1736
- var safeInstanceof = (tag) => (target) => {
1737
- target.prototype[instanceTag] = tag;
1738
- Object.defineProperty(target.prototype, Symbol.hasInstance, {
1739
- value: (instance) => instance?.[instanceTag] === tag
1740
- });
1741
- Object.defineProperty(target, Symbol.hasInstance, {
1742
- value: (instance) => instance?.[instanceTag] === tag
1743
- });
1744
- };
1745
-
1746
- // src/safe-parse.ts
1747
- function safeParseInt(str, defaultValue) {
1748
- try {
1749
- const value = parseInt(str ?? "");
1750
- return isNaN(value) ? defaultValue : value;
1751
- } catch {
1752
- return defaultValue;
1753
- }
1754
- }
1755
- function safeParseFloat(str, defaultValue) {
1756
- try {
1757
- const value = parseFloat(str ?? "");
1758
- return isNaN(value) ? defaultValue : value;
1759
- } catch {
1760
- return defaultValue;
1761
- }
1762
- }
1763
- var safeParseJson = (str, defaultValue) => {
1764
- if (str && str.length > 0) {
1765
- try {
1766
- return JSON.parse(str);
1767
- } catch {
1768
- }
1769
- }
1770
- return defaultValue;
1771
- };
1772
- var safeUrl = (str) => {
1773
- try {
1774
- return new URL(str ?? "");
1775
- } catch {
1776
- return void 0;
1777
- }
1778
- };
1779
-
1780
- // src/safe-stringify.ts
1781
- var SKIP = Object.freeze({});
1782
- function safeStringify(obj, filter = defaultFilter, indent = 2) {
1783
- const seen = /* @__PURE__ */ new WeakMap();
1784
- function replacer(key, value) {
1785
- try {
1786
- let path = key;
1787
- if (!key) {
1788
- path = "$";
1789
- if (value != null && typeof value === "object") {
1790
- seen.set(value, path);
1791
- }
1792
- return value;
1793
- } else if (this) {
1794
- const parentPath = seen.get(this);
1795
- path = parentPath ? `${parentPath}.${key}` : key;
1796
- }
1797
- if (value == null) {
1798
- return value;
1799
- }
1800
- if (typeof value === "function") {
1801
- return void 0;
1802
- }
1803
- if (typeof value === "object" && Object.getPrototypeOf(value) !== Object.prototype && !Array.isArray(value)) {
1804
- return void 0;
1805
- }
1806
- if (typeof value === "object" && value !== null) {
1807
- const exists = seen.get(value);
1808
- if (exists) {
1809
- return `[${path} => ${exists}]`;
1810
- }
1811
- seen.set(value, path);
1812
- }
1813
- if (filter) {
1814
- const filteredValue = filter?.(key, value);
1815
- if (filteredValue !== void 0) {
1816
- return filteredValue === SKIP ? void 0 : filteredValue;
1817
- }
1818
- }
1819
- return value;
1820
- } catch (error) {
1821
- return `ERROR: ${error.message}`;
1822
- }
1823
- }
1824
- try {
1825
- return JSON.stringify(obj, replacer, indent);
1826
- } catch (error) {
1827
- return `ERROR: ${error.message}`;
1828
- }
1829
- }
1830
- var createReplacer = ({ omit: omit2, parse, maxDepth, maxArrayLen, maxStringLen } = {}) => {
1831
- let currentDepth = 0;
1832
- const depthMap = /* @__PURE__ */ new WeakMap();
1833
- return function(key, value) {
1834
- if (key === "") {
1835
- currentDepth = 0;
1836
- } else if (this && typeof this === "object") {
1837
- const parentDepth = depthMap.get(this) ?? 0;
1838
- currentDepth = parentDepth + 1;
1839
- }
1840
- if (typeof value === "function") {
1841
- return SKIP;
1842
- }
1843
- if (maxArrayLen != null && Array.isArray(value) && value.length > maxArrayLen) {
1844
- return `[length: ${value.length}]`;
1845
- }
1846
- if (value && typeof value === "object") {
1847
- depthMap.set(value, currentDepth);
1848
- if (maxDepth != null && currentDepth >= maxDepth) {
1849
- return Array.isArray(value) ? `[{ length: ${value.length} }]` : `{ keys: ${Object.keys(value).length} }`;
1850
- }
1851
- }
1852
- if (omit2?.includes(key)) {
1853
- return SKIP;
1854
- }
1855
- if (parse?.includes(key) && typeof value === "string") {
1856
- try {
1857
- return JSON.parse(value);
1858
- } catch {
1859
- return value;
1860
- }
1861
- }
1862
- if (maxStringLen != null && typeof value === "string" && value.length > maxStringLen) {
1863
- return value.slice(0, maxStringLen) + "...";
1864
- }
1865
- return value;
1866
- };
1867
- };
1868
- var defaultFilter = createReplacer();
1869
-
1870
- // src/sliding-window-summary.ts
1871
- import { invariant as invariant5 } from "@dxos/invariant";
1872
- var SlidingWindowSummary = class {
1873
- _buffer;
1874
- _sum = 0;
1875
- _precision;
1876
- constructor(options) {
1877
- this._buffer = new CircularBuffer(options.dataPoints);
1878
- if (options.precision != null) {
1879
- invariant5(options.precision >= 0);
1880
- this._precision = Math.pow(10, options.precision);
1881
- }
1882
- }
1883
- record(value) {
1884
- const evicted = this._buffer.push(value);
1885
- this._sum += value - (evicted ?? 0);
1886
- }
1887
- average() {
1888
- return this._buffer.elementCount === 0 ? 0 : this._withPrecision(this._sum / this._buffer.elementCount);
1889
- }
1890
- computeWindowSummary() {
1891
- const mean = this.average();
1892
- const sortedElements = [
1893
- ...this._buffer
1894
- ].sort();
1895
- const median2 = this._withPrecision(sortedElements.length % 2 === 0 ? (sortedElements[sortedElements.length / 2] + sortedElements[sortedElements.length / 2 - 1]) / 2 : sortedElements[sortedElements.length / 2]);
1896
- const p90 = this._withPrecision(sortedElements[Math.round(sortedElements.length * 0.9)]);
1897
- const variance = sortedElements.reduce((acc, v) => acc + Math.pow(v - mean, 2)) / sortedElements.length;
1898
- const stdDev = this._withPrecision(Math.sqrt(variance));
1899
- const histogram = sortedElements.reduce((acc, v) => {
1900
- acc[v] += 1;
1901
- return acc;
1902
- }, {});
1903
- return {
1904
- mean,
1905
- median: median2,
1906
- p90,
1907
- stdDev,
1908
- histogram
1909
- };
1910
- }
1911
- _withPrecision(value) {
1912
- if (this._precision == null) {
1913
- return value;
1914
- }
1915
- return Math.round(value * this._precision) / this._precision;
1916
- }
1917
- };
1918
-
1919
- // src/sort.ts
1920
- var compareScalar = (inc = true) => (a, b) => (inc ? 1 : -1) * (a < b ? -1 : a > b ? 1 : 0);
1921
- var compareString = (inc = true, caseInsensitive = true) => (a, b) => {
1922
- if (caseInsensitive) {
1923
- a = a?.toLowerCase();
1924
- b = b?.toLowerCase();
1925
- }
1926
- return (inc ? 1 : -1) * (a < b ? -1 : a > b ? 1 : 0);
1927
- };
1928
- var compareObject = (prop, sorter, inc = true) => (a, b) => (inc ? 1 : -1) * sorter(a[prop], b[prop]);
1929
- var compareMulti = (sorters) => (a, b) => {
1930
- const sort = (i = 0) => {
1931
- const s = sorters[i](a, b);
1932
- if (s === 0 && i < sorters.length - 1) {
1933
- return sort(i + 1);
1934
- } else {
1935
- return s;
1936
- }
1937
- };
1938
- return sort();
1939
- };
1940
-
1941
- // src/string.ts
1942
- var capitalize = (str) => {
1943
- if (str.length === 0) {
1944
- return "";
1945
- }
1946
- return str.charAt(0).toUpperCase() + str.slice(1);
1947
- };
1948
- function inline(strings, ...values) {
1949
- const raw = strings.reduce((out, str, i) => out + str + (i < values.length ? String(values[i]) : ""), "");
1950
- return raw.replace(/\s+/g, " ").trim();
1951
- }
1952
- function trim(strings, ...values) {
1953
- const raw = strings.reduce((out, str, i) => {
1954
- out += str;
1955
- if (i < values.length) {
1956
- const match = str.match(/(^|\n)([ \t]*)$/);
1957
- const baseIndent = match ? match[2] : "";
1958
- const val = String(values[i]).replace(/\r?\n/g, "\n" + baseIndent);
1959
- out += val;
1960
- }
1961
- return out;
1962
- }, "");
1963
- const lines = raw.split("\n");
1964
- while (lines.length && !lines[0].trim()) {
1965
- lines.shift();
1966
- }
1967
- while (lines.length && !lines[lines.length - 1].trim()) {
1968
- lines.pop();
1969
- }
1970
- const minIndent = Math.min(...lines.filter((l) => l.trim()).map((l) => l.match(/^[ \t]*/)?.[0].length ?? 0));
1971
- return lines.map((l) => l.slice(minIndent)).join("\n");
1972
- }
1973
- var kebabize = (str) => str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? "-" : "") + $.toLowerCase());
1974
-
1975
- // src/sum.ts
1976
- var sum = (values) => values.reduce((a, b) => a + b, 0);
1977
-
1978
- // src/throw-unhandled-error.ts
1979
- var throwUnhandledError = (error) => {
1980
- queueMicrotask(() => {
1981
- throw error;
1982
- });
1983
- };
1984
-
1985
- // src/to-fallback.ts
1986
- var idEmoji = [
1987
- "\u{1F47B}",
1988
- "\u{1F479}",
1989
- "\u{1F47D}",
1990
- "\u{1F916}",
1991
- "\u{1F383}",
1992
- "\u{1F9BE}",
1993
- "\u{1F9BF}",
1994
- "\u{1F9B7}",
1995
- "\u{1F463}",
1996
- "\u{1F441}\uFE0F",
1997
- "\u{1F9F6}",
1998
- "\u{1F451}",
1999
- "\u{1F412}",
2000
- "\u{1F986}",
2001
- "\u{1F989}",
2002
- "\u{1F434}",
2003
- "\u{1F984}",
2004
- "\u{1F41D}",
2005
- "\u{1F98B}",
2006
- "\u{1F41E}",
2007
- "\u{1FAB2}",
2008
- "\u{1F422}",
2009
- "\u{1F98E}",
2010
- "\u{1F995}",
2011
- "\u{1F991}",
2012
- "\u{1F980}",
2013
- "\u{1F420}",
2014
- "\u{1F42C}",
2015
- "\u{1F40B}",
2016
- "\u{1F9AD}",
2017
- "\u{1F405}",
2018
- "\u{1F406}",
2019
- "\u{1F993}",
2020
- "\u{1F98D}",
2021
- "\u{1F9A7}",
2022
- "\u{1F418}",
2023
- "\u{1F42B}",
2024
- "\u{1F992}",
2025
- "\u{1F998}",
2026
- "\u{1F9AC}",
2027
- "\u{1F416}",
2028
- "\u{1F40F}",
2029
- "\u{1F98C}",
2030
- "\u{1F415}",
2031
- "\u{1F408}",
2032
- "\u{1F413}",
2033
- "\u{1F99A}",
2034
- "\u{1F99C}",
2035
- "\u{1F9A2}",
2036
- "\u{1F9A9}",
2037
- "\u{1F9A6}",
2038
- "\u{1F401}",
2039
- "\u{1F43F}\uFE0F",
2040
- "\u{1F335}",
2041
- "\u{1F332}",
2042
- "\u{1F333}",
2043
- "\u{1FAB5}",
2044
- "\u{1F331}",
2045
- "\u{1F341}",
2046
- "\u{1FABA}",
2047
- "\u{1F344}",
2048
- "\u{1F41A}",
2049
- "\u{1FAB8}",
2050
- "\u{1FAA8}",
2051
- "\u{1F33E}",
2052
- "\u{1F337}",
2053
- "\u{1F33B}",
2054
- "\u2600\uFE0F",
2055
- "\u{1F319}",
2056
- "\u{1FA90}",
2057
- "\u2B50\uFE0F",
2058
- "\u26A1\uFE0F",
2059
- "\u2604\uFE0F",
2060
- "\u{1F525}",
2061
- "\u{1F308}",
2062
- "\u2601\uFE0F",
2063
- "\u{1F4A7}",
2064
- "\u26F1\uFE0F",
2065
- "\u{1F30A}",
2066
- "\u{1F34E}",
2067
- "\u{1F34B}",
2068
- "\u{1F349}",
2069
- "\u{1F347}",
2070
- "\u{1FAD0}",
2071
- "\u{1F348}",
2072
- "\u{1F352}",
2073
- "\u{1F351}",
2074
- "\u{1F96D}",
2075
- "\u{1F34D}",
2076
- "\u{1F965}",
2077
- "\u{1F95D}",
2078
- "\u{1F951}",
2079
- "\u{1F336}\uFE0F",
2080
- "\u{1F33D}",
2081
- "\u{1F955}",
2082
- "\u{1F36C}",
2083
- "\u{1F95C}",
2084
- "\u{1FAD6}",
2085
- "\u2615\uFE0F",
2086
- "\u{1F375}",
2087
- "\u{1F9CA}",
2088
- "\u{1F9C2}",
2089
- "\u{1F3D4}\uFE0F",
2090
- "\u2693\uFE0F",
2091
- "\u{1F6DF}",
2092
- "\u{1F3DD}\uFE0F",
2093
- "\u{1F6F6}",
2094
- "\u{1F680}",
2095
- "\u{1F6F0}\uFE0F",
2096
- "\u26F2\uFE0F",
2097
- "\u{1F3F0}",
2098
- "\u{1F6B2}",
2099
- "\u26FA\uFE0F",
2100
- "\u{1F399}\uFE0F",
2101
- "\u{1F9F2}",
2102
- "\u2699\uFE0F",
2103
- "\u{1F529}",
2104
- "\u{1F52E}",
2105
- "\u{1F52D}",
2106
- "\u{1F52C}",
2107
- "\u{1F9EC}",
2108
- "\u{1F321}\uFE0F",
2109
- "\u{1F9FA}",
2110
- "\u{1F6CE}\uFE0F",
2111
- "\u{1F511}",
2112
- "\u{1FA91}",
2113
- "\u{1F9F8}",
2114
- "\u{1F388}",
2115
- "\u{1F380}",
2116
- "\u{1F38A}",
2117
- "\u267B\uFE0F",
2118
- "\u{1F3B5}"
2119
- ];
2120
- var idHue = [
2121
- "red",
2122
- "orange",
2123
- "amber",
2124
- "yellow",
2125
- "lime",
2126
- "green",
2127
- "emerald",
2128
- "teal",
2129
- "cyan",
2130
- // Omit colors similar to primary accent.
2131
- // 'sky' as const,
2132
- // 'blue' as const,
2133
- // 'indigo' as const,
2134
- "violet",
2135
- "purple",
2136
- "fuchsia",
2137
- "pink",
2138
- "rose"
2139
- ];
2140
- var keyToEmoji = (key) => keyToFallback(key).emoji;
2141
- var hexToEmoji = (hex) => hexToFallback(hex).emoji;
2142
- var toEmoji = (hash) => toFallback(hash).emoji;
2143
- var keyToHue = (key) => keyToFallback(key).hue;
2144
- var hexToHue = (hex) => hexToFallback(hex).hue;
2145
- var toHue = (hash) => toFallback(hash).hue;
2146
- var keyToFallback = (key) => hexToFallback(key.toHex());
2147
- var hexToFallback = (hex) => toFallback(parseInt(hex, 16));
2148
- var toFallback = (hash) => {
2149
- const totalCombinations = idEmoji.length * idHue.length;
2150
- const combinationIndex = hash % totalCombinations;
2151
- const emojiIndex = Math.floor(combinationIndex / idHue.length);
2152
- const hueIndex = combinationIndex % idHue.length;
2153
- return {
2154
- emoji: idEmoji[emojiIndex],
2155
- hue: idHue[hueIndex]
2156
- };
2157
- };
2158
-
2159
- // src/tracer.ts
2160
- var Tracer = class {
2161
- _events = /* @__PURE__ */ new Map();
2162
- _recording = false;
2163
- // TODO(burdon): Start/stop methods for recording data? By id?
2164
- // Alternatively, enable subscriptions to track/compute series.
2165
- // TODO(burdon): Hierarchical traces?
2166
- get recording() {
2167
- return this._recording;
2168
- }
2169
- keys() {
2170
- return Array.from(this._events.keys());
2171
- }
2172
- get(id2, filter) {
2173
- const events = this._events.get(id2);
2174
- if (filter) {
2175
- return events?.filter((event) => Object.entries(filter).every(([key, value]) => event?.value[key] === value));
2176
- }
2177
- return events;
2178
- }
2179
- clear() {
2180
- this._events.clear();
2181
- }
2182
- start() {
2183
- this._recording = true;
2184
- return this;
2185
- }
2186
- stop() {
2187
- this._recording = false;
2188
- return this;
2189
- }
2190
- emit(id2, value) {
2191
- this._post(this._createEvent(id2, value));
2192
- }
2193
- mark(id2, value) {
2194
- const event = this._createEvent(id2, value);
2195
- const start = performance.now();
2196
- return {
2197
- start,
2198
- end: () => {
2199
- event.duration = performance.now() - start;
2200
- this._post(event);
2201
- }
2202
- };
2203
- }
2204
- _createEvent(id2, value) {
2205
- const event = {
2206
- id: id2,
2207
- timestamp: Date.now()
2208
- };
2209
- if (value !== void 0) {
2210
- event.value = value;
2211
- }
2212
- return event;
2213
- }
2214
- _post(event) {
2215
- if (this._recording) {
2216
- defaultMap(this._events, event.id, []).push(event);
2217
- }
2218
- }
2219
- };
2220
- var tracer = new Tracer();
2221
-
2222
- // src/tree.ts
2223
- import { truncateKey } from "@dxos/debug";
2224
- var stringifyTree = (node, ancestors = [], rows = []) => {
2225
- if (node.children?.length) {
2226
- node.children.forEach((child, i) => {
2227
- stringifyTree(child, [
2228
- ...ancestors,
2229
- [
2230
- node,
2231
- i
2232
- ]
2233
- ], rows);
2234
- });
2235
- } else {
2236
- const keyLen = 8;
2237
- const name = (node2) => truncateKey(node2.id, keyLen);
2238
- const parts = [];
2239
- ancestors.forEach(([node2, i], j) => {
2240
- const first2 = ancestors.slice(j).every(([_, i2]) => i2 === 0);
2241
- parts.push(j === 0 ? first2 ? "\u251C" : " " : "");
2242
- parts.push(first2 ? `\u2500(${name(node2)})\u2500` : "".padEnd(keyLen + 4));
2243
- if (node2.children) {
2244
- if (first2) {
2245
- parts.push(node2.children.length > 1 ? "\u252C" : "\u2500");
2246
- } else {
2247
- const childFirst = ancestors.slice(j + 1).every(([_, i2]) => i2 === 0);
2248
- if (node2.children.length - 1 === i) {
2249
- parts.push(childFirst ? "\u2570" : " ");
2250
- } else {
2251
- parts.push(childFirst ? "\u251C" : "\u2502");
2252
- }
2253
- }
2254
- }
2255
- });
2256
- parts.push(`\u2500(${name(node)})`);
2257
- rows.push(parts.join(""));
2258
- }
2259
- return rows;
2260
- };
2261
-
2262
- // src/types.ts
2263
- var isTruthy = (value) => !!value;
2264
- var isNonNullable = (value) => value != null;
2265
- var doAsync = async (fn) => fn();
2266
- var getProviderValue = (provider, arg) => {
2267
- return typeof provider === "function" ? provider(arg) : provider;
2268
- };
2269
- var getAsyncProviderValue = (provider, arg) => {
2270
- return getProviderValue(provider, arg);
2271
- };
2272
- var stripUndefined = (obj) => {
2273
- if (typeof obj === "object") {
2274
- Object.keys(obj).forEach((key) => {
2275
- const value = obj[key];
2276
- if (value === void 0) {
2277
- delete obj[key];
2278
- } else if (value !== null && typeof value === "object") {
2279
- stripUndefined(value);
2280
- }
2281
- });
2282
- }
2283
- return obj;
2284
- };
2285
- var sortKeys = (obj) => Object.keys(obj).sort().reduce((sorted, key) => {
2286
- sorted[key] = obj[key];
2287
- return sorted;
2288
- }, {});
2289
- var arrayMove = (array, from, to) => {
2290
- array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]);
2291
- return array;
2292
- };
2293
- function arraySwap(array, from, to) {
2294
- const current = array[from];
2295
- array[from] = array[to];
2296
- array[to] = current;
2297
- return array;
2298
- }
2299
-
2300
- // src/unit.ts
2301
- var createFormat = (unit) => {
2302
- return (n, precision = unit.precision ?? 0) => {
2303
- const value = n / unit.quotient;
2304
- const formattedValue = value.toLocaleString("en-US", {
2305
- minimumFractionDigits: precision,
2306
- maximumFractionDigits: precision
2307
- });
2308
- return {
2309
- unit,
2310
- value,
2311
- formattedValue,
2312
- toString: () => `${formattedValue}${unit.symbol}`
2313
- };
2314
- };
2315
- };
2316
- var MS_SECONDS = 1e3;
2317
- var MS_MINUTES = 60 * MS_SECONDS;
2318
- var MS_HOURS = 60 * MS_MINUTES;
2319
- var Unit = {
2320
- // General.
2321
- Percent: createFormat({
2322
- symbol: "%",
2323
- quotient: 1 / 100,
2324
- precision: 2
2325
- }),
2326
- Thousand: createFormat({
2327
- symbol: "k",
2328
- quotient: 1e3,
2329
- precision: 2
2330
- }),
2331
- // Bytes (note KB vs KiB).
2332
- Gigabyte: createFormat({
2333
- symbol: "GB",
2334
- quotient: 1e3 * 1e3 * 1e3,
2335
- precision: 2
2336
- }),
2337
- Megabyte: createFormat({
2338
- symbol: "MB",
2339
- quotient: 1e3 * 1e3,
2340
- precision: 2
2341
- }),
2342
- Kilobyte: createFormat({
2343
- symbol: "KB",
2344
- quotient: 1e3,
2345
- precision: 2
2346
- }),
2347
- Byte: createFormat({
2348
- symbol: "B",
2349
- quotient: 1
2350
- }),
2351
- // Time.
2352
- Hour: createFormat({
2353
- symbol: "h",
2354
- quotient: MS_HOURS
2355
- }),
2356
- Minute: createFormat({
2357
- symbol: "m",
2358
- quotient: MS_MINUTES
2359
- }),
2360
- Second: createFormat({
2361
- symbol: "s",
2362
- quotient: MS_SECONDS,
2363
- precision: 1
2364
- }),
2365
- Millisecond: createFormat({
2366
- symbol: "ms",
2367
- quotient: 1
2368
- }),
2369
- // TODO(burdon): Inconsistent formattedValue.
2370
- Duration: (n) => {
2371
- const hours = Math.floor(n / MS_HOURS);
2372
- const minutes = Math.floor(n % MS_HOURS / MS_MINUTES);
2373
- if (hours) {
2374
- const formattedValue = minutes ? `${hours}h ${minutes}m` : `${hours}h`;
2375
- return {
2376
- unit: {
2377
- symbol: "h",
2378
- quotient: MS_HOURS
2379
- },
2380
- value: hours,
2381
- formattedValue,
2382
- toString: () => formattedValue
2383
- };
2384
- }
2385
- if (minutes) {
2386
- const seconds2 = (n - MS_MINUTES * minutes) / MS_SECONDS;
2387
- const formattedValue = seconds2 ? `${minutes}m ${Math.round(seconds2)}s` : `${minutes}m`;
2388
- return {
2389
- unit: {
2390
- symbol: "m",
2391
- quotient: MS_MINUTES
2392
- },
2393
- value: minutes,
2394
- formattedValue,
2395
- toString: () => formattedValue
2396
- };
2397
- }
2398
- const seconds = n >= MS_SECONDS;
2399
- if (seconds) {
2400
- return Unit.Second(n);
2401
- }
2402
- return Unit.Millisecond(n);
2403
- }
2404
- };
2405
-
2406
- // src/url.ts
2407
- var createUrl = (url, search) => {
2408
- const base = typeof url === "string" ? new URL(url) : url;
2409
- if (search) {
2410
- base.search = new URLSearchParams(Object.entries(search).filter(([_, value]) => value != null)).toString();
2411
- }
2412
- return base;
2413
- };
2414
-
2415
- // src/weak.ts
2416
- var WeakDictionary = class {
2417
- _internal = /* @__PURE__ */ new Map();
2418
- _finalization = new FinalizationRegistry(({ key, ref }) => {
2419
- if (this._internal.get(key) === ref) {
2420
- this._internal.delete(key);
2421
- }
2422
- });
2423
- constructor(entries2) {
2424
- if (entries2) {
2425
- for (const [key, value] of entries2) {
2426
- const ref = new WeakRef(value);
2427
- this._internal.set(key, ref);
2428
- this._register(key, value, ref);
2429
- }
2430
- }
2431
- }
2432
- *entries() {
2433
- for (const [key, value] of this._internal) {
2434
- yield [
2435
- key,
2436
- value.deref()
2437
- ];
2438
- }
2439
- }
2440
- keys() {
2441
- return this._internal.keys();
2442
- }
2443
- *values() {
2444
- for (const value of this._internal.values()) {
2445
- const deref = value.deref();
2446
- if (!deref) {
2447
- continue;
2448
- }
2449
- yield deref;
2450
- }
2451
- }
2452
- *[Symbol.iterator]() {
2453
- for (const [key, value] of this._internal) {
2454
- yield [
2455
- key,
2456
- value.deref()
2457
- ];
2458
- }
2459
- }
2460
- get [Symbol.toStringTag]() {
2461
- return "WeakDictionary";
2462
- }
2463
- get size() {
2464
- return this._internal.size;
2465
- }
2466
- get(key) {
2467
- return this._internal.get(key)?.deref();
2468
- }
2469
- set(key, value) {
2470
- const previous = this._internal.get(key)?.deref();
2471
- if (previous) {
2472
- this._unregister(previous);
2473
- }
2474
- const ref = new WeakRef(value);
2475
- this._internal.set(key, ref);
2476
- this._register(key, value, ref);
2477
- return this;
2478
- }
2479
- /**
2480
- * Returns the value for the given key if present, otherwise inserts and returns the default value.
2481
- * @param key - The key to look up or insert.
2482
- * @param defaultValue - The value to insert if the key is not present.
2483
- * @returns The existing or newly inserted value.
2484
- */
2485
- getOrInsert(key, defaultValue) {
2486
- const existing = this.get(key);
2487
- if (existing !== void 0) {
2488
- return existing;
2489
- }
2490
- this.set(key, defaultValue);
2491
- return defaultValue;
2492
- }
2493
- /**
2494
- * Returns the value for the given key if present, otherwise computes, inserts, and returns a new value.
2495
- * The callback is only invoked when the key is missing.
2496
- * @param key - The key to look up or insert.
2497
- * @param callbackfn - Function to compute the value if the key is not present.
2498
- * @returns The existing or newly computed value.
2499
- */
2500
- getOrInsertComputed(key, callbackfn) {
2501
- const existing = this.get(key);
2502
- if (existing !== void 0) {
2503
- return existing;
2504
- }
2505
- const value = callbackfn(key);
2506
- this.set(key, value);
2507
- return value;
2508
- }
2509
- has(key) {
2510
- return this._internal.has(key) && this._internal.get(key).deref() !== void 0;
2511
- }
2512
- delete(key) {
2513
- const value = this._internal.get(key)?.deref();
2514
- if (value) {
2515
- this._unregister(value);
2516
- }
2517
- return this._internal.delete(key);
2518
- }
2519
- clear() {
2520
- this._internal.forEach((value) => {
2521
- const v = value.deref();
2522
- if (v) {
2523
- this._unregister(v);
2524
- }
2525
- });
2526
- this._internal.clear();
2527
- }
2528
- forEach(callbackfn, thisArg) {
2529
- if (thisArg) {
2530
- callbackfn = callbackfn.bind(thisArg);
2531
- }
2532
- this._internal.forEach((value, key) => {
2533
- const v = value.deref();
2534
- if (v) {
2535
- callbackfn(v, key, this);
2536
- }
2537
- });
2538
- }
2539
- _register(key, value, ref) {
2540
- this._finalization.register(value, {
2541
- key,
2542
- ref
2543
- }, value);
2544
- }
2545
- _unregister(value) {
2546
- this._finalization.unregister(value);
2547
- }
2548
- };
2549
- export {
2550
- BitField,
2551
- Callback,
2552
- CallbackCollection,
2553
- CircularBuffer,
2554
- ComplexMap,
2555
- ComplexSet,
2556
- HumanHasher,
2557
- MapEntry,
2558
- Position_exports as Position,
2559
- SKIP,
2560
- SlidingWindowSummary,
2561
- Tracer,
2562
- Unit,
2563
- WeakDictionary,
2564
- accessBy,
2565
- arrayMove,
2566
- arraySwap,
2567
- arrayToBuffer,
2568
- arrayToHex,
2569
- arrayToString,
2570
- arraysEqual,
2571
- assumeType,
2572
- bufferToArray,
2573
- capitalize,
2574
- chunkArray,
2575
- clamp,
2576
- clearCaches,
2577
- clearIndexedDB,
2578
- clearOPFS,
2579
- clearServiceWorkers,
2580
- clearUndefined,
2581
- coerceArray,
2582
- compareMulti,
2583
- compareObject,
2584
- compareScalar,
2585
- compareString,
2586
- compositeKey,
2587
- createBinder,
2588
- createBucketReducer,
2589
- createFilename,
2590
- createGroupReducer,
2591
- createReplacer,
2592
- createSetDispatch,
2593
- createUrl,
2594
- decamelize,
2595
- decodeUint8ArrayFromJson,
2596
- deepMapValues,
2597
- deepMapValuesAsync,
2598
- defaultFilter,
2599
- defaultMap,
2600
- defer,
2601
- deferAsync,
2602
- deferFunction,
2603
- diff,
2604
- distinctBy,
2605
- doAsync,
2606
- encodeUint8ArrayToJson,
2607
- entries,
2608
- entry,
2609
- exponentialBackoffInterval,
2610
- forEachAsync,
2611
- formatErrorWithCauses,
2612
- getAsyncProviderValue,
2613
- getDate,
2614
- getDebugName,
2615
- getDeep,
2616
- getHostPlatform,
2617
- getPrototypeSpecificInstanceId,
2618
- getProviderValue,
2619
- hexToEmoji,
2620
- hexToFallback,
2621
- hexToHue,
2622
- humanize,
2623
- hyphenize,
2624
- id,
2625
- idEmoji,
2626
- idHue,
2627
- inferObjectOrder,
2628
- inferRecordOrder,
2629
- inline,
2630
- intersectBy,
2631
- intersection,
2632
- iosCheck,
2633
- isBun,
2634
- isEncodedUint8Array,
2635
- isMobile,
2636
- isMobileOrTablet,
2637
- isNode,
2638
- isNonNullable,
2639
- isTauri,
2640
- isTruthy,
2641
- isWellFormedId,
2642
- isWellFormedIdPart,
2643
- joinTables,
2644
- jsonKeyReplacer,
2645
- jsonReplacer,
2646
- jsonify,
2647
- jsonlogify,
2648
- kebabize,
2649
- keyToEmoji,
2650
- keyToFallback,
2651
- keyToHue,
2652
- keys,
2653
- makeMap,
2654
- makeSet,
2655
- mapValues,
2656
- median,
2657
- numericalValues,
2658
- omit,
2659
- orderKeys,
2660
- partition,
2661
- pick,
2662
- pickBy,
2663
- randomInt,
2664
- range,
2665
- rangeFromTo,
2666
- reduceGroupBy,
2667
- reduceSeries,
2668
- reduceSet,
2669
- removeBy,
2670
- removeProperties,
2671
- removeUndefinedProperties,
2672
- retry,
2673
- safariCheck,
2674
- safeAwaitAll,
2675
- safeInstanceof,
2676
- safeParseFloat,
2677
- safeParseInt,
2678
- safeParseJson,
2679
- safeStringify,
2680
- safeUrl,
2681
- setDeep,
2682
- sortKeys,
2683
- splitCompositeKey,
2684
- stringToArray,
2685
- stringifyTree,
2686
- stripUndefined,
2687
- sum,
2688
- throwUnhandledError,
2689
- toEmoji,
2690
- toFallback,
2691
- toHue,
2692
- tracer,
2693
- trim,
2694
- visitValues
2695
- };
2696
- //# sourceMappingURL=index.mjs.map