@dxos/util 0.8.4-main.84f28bd → 0.8.4-main.ae835ea

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 (54) hide show
  1. package/dist/lib/browser/index.mjs +162 -94
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +162 -94
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/array.d.ts.map +1 -1
  8. package/dist/types/src/assume.d.ts.map +1 -1
  9. package/dist/types/src/di-key.d.ts +3 -3
  10. package/dist/types/src/di-key.d.ts.map +1 -1
  11. package/dist/types/src/index.d.ts +1 -2
  12. package/dist/types/src/index.d.ts.map +1 -1
  13. package/dist/types/src/json.d.ts +1 -1
  14. package/dist/types/src/json.d.ts.map +1 -1
  15. package/dist/types/src/object.d.ts +3 -0
  16. package/dist/types/src/object.d.ts.map +1 -1
  17. package/dist/types/src/safe-parse.d.ts.map +1 -1
  18. package/dist/types/src/string.d.ts +8 -0
  19. package/dist/types/src/string.d.ts.map +1 -1
  20. package/dist/types/src/string.test.d.ts +2 -0
  21. package/dist/types/src/string.test.d.ts.map +1 -0
  22. package/dist/types/src/to-fallback.d.ts.map +1 -1
  23. package/dist/types/src/types.d.ts +1 -1
  24. package/dist/types/src/types.d.ts.map +1 -1
  25. package/dist/types/src/unit.d.ts +15 -0
  26. package/dist/types/src/unit.d.ts.map +1 -0
  27. package/dist/types/src/unit.test.d.ts +2 -0
  28. package/dist/types/src/unit.test.d.ts.map +1 -0
  29. package/dist/types/tsconfig.tsbuildinfo +1 -1
  30. package/package.json +8 -8
  31. package/src/array.test.ts +1 -1
  32. package/src/array.ts +0 -2
  33. package/src/assume.ts +0 -1
  34. package/src/circular-buffer.test.ts +1 -1
  35. package/src/complex.test.ts +1 -1
  36. package/src/human-hash.test.ts +1 -1
  37. package/src/index.ts +1 -2
  38. package/src/json.ts +2 -7
  39. package/src/object.ts +3 -0
  40. package/src/position.test.ts +2 -2
  41. package/src/safe-parse.ts +6 -3
  42. package/src/sort.test.ts +1 -1
  43. package/src/string.test.ts +19 -0
  44. package/src/string.ts +36 -0
  45. package/src/to-fallback.ts +5 -4
  46. package/src/tree.test.ts +1 -1
  47. package/src/types.ts +1 -1
  48. package/src/uint8array.test.ts +1 -1
  49. package/src/unit.test.ts +25 -0
  50. package/src/unit.ts +52 -0
  51. package/src/weak.test.ts +1 -1
  52. package/dist/types/src/first-two-chars.d.ts +0 -9
  53. package/dist/types/src/first-two-chars.d.ts.map +0 -1
  54. package/src/first-two-chars.ts +0 -44
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxos/util",
3
- "version": "0.8.4-main.84f28bd",
3
+ "version": "0.8.4-main.ae835ea",
4
4
  "description": "Temporary bucket for misc functions, which should graduate into separate packages.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
@@ -10,12 +10,12 @@
10
10
  "type": "module",
11
11
  "exports": {
12
12
  ".": {
13
+ "types": "./dist/types/src/index.d.ts",
13
14
  "browser": "./dist/lib/browser/index.mjs",
14
15
  "node": {
15
16
  "require": "./dist/lib/node/index.cjs",
16
17
  "default": "./dist/lib/node-esm/index.mjs"
17
- },
18
- "types": "./dist/types/src/index.d.ts"
18
+ }
19
19
  }
20
20
  },
21
21
  "types": "dist/types/src/index.d.ts",
@@ -29,15 +29,15 @@
29
29
  "dependencies": {
30
30
  "lodash.get": "^4.4.2",
31
31
  "lodash.set": "^4.3.2",
32
- "@dxos/debug": "0.8.4-main.84f28bd",
33
- "@dxos/invariant": "0.8.4-main.84f28bd",
34
- "@dxos/keys": "0.8.4-main.84f28bd",
35
- "@dxos/node-std": "0.8.4-main.84f28bd"
32
+ "@dxos/debug": "0.8.4-main.ae835ea",
33
+ "@dxos/invariant": "0.8.4-main.ae835ea",
34
+ "@dxos/keys": "0.8.4-main.ae835ea",
35
+ "@dxos/node-std": "0.8.4-main.ae835ea"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@types/lodash.get": "^4.4.9",
39
39
  "@types/lodash.set": "^4.3.9",
40
- "@dxos/crypto": "0.8.4-main.84f28bd"
40
+ "@dxos/crypto": "0.8.4-main.ae835ea"
41
41
  },
42
42
  "publishConfig": {
43
43
  "access": "public"
package/src/array.test.ts CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { describe, expect, test } from 'vitest';
6
6
 
7
- import { diff, intersection, distinctBy, partition } from './array';
7
+ import { diff, distinctBy, intersection, partition } from './array';
8
8
 
9
9
  describe('diff', () => {
10
10
  test('returns the difference between two sets', () => {
package/src/array.ts CHANGED
@@ -16,7 +16,6 @@ export type DiffResult<A, B = A> = {
16
16
  * @param next
17
17
  * @param comparator
18
18
  */
19
- // TODO(burdon): Factor out.
20
19
  export const diff = <A, B = A>(
21
20
  previous: readonly A[],
22
21
  next: readonly B[],
@@ -43,7 +42,6 @@ export const diff = <A, B = A>(
43
42
  return result;
44
43
  };
45
44
 
46
- // TODO(burdon): Factor out.
47
45
  export const intersection = <A, B = A>(a: A[], b: B[], comparator: Comparator<A, B>): A[] =>
48
46
  a.filter((a) => b.find((b) => comparator(a, b)) !== undefined);
49
47
 
package/src/assume.ts CHANGED
@@ -16,7 +16,6 @@
16
16
  * ```
17
17
  */
18
18
  // NOTE: Keep as `function` to avoid type inference issues.
19
- // eslint-disable-next-line @stayradiated/prefer-arrow-functions/prefer-arrow-functions
20
19
  export function assumeType<T>(value: unknown): asserts value is T {
21
20
  // No-op.
22
21
  }
@@ -2,7 +2,7 @@
2
2
  // Copyright 2024 DXOS.org
3
3
  //
4
4
 
5
- import { describe, test, expect } from 'vitest';
5
+ import { describe, expect, test } from 'vitest';
6
6
 
7
7
  import { CircularBuffer } from './circular-buffer';
8
8
 
@@ -6,7 +6,7 @@ import { expect, test } from 'vitest';
6
6
 
7
7
  import { PublicKey } from '@dxos/keys';
8
8
 
9
- import { makeSet, makeMap } from './complex';
9
+ import { makeMap, makeSet } from './complex';
10
10
 
11
11
  const PulicKeySet = makeSet<PublicKey>(PublicKey.hash);
12
12
 
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { expect, test } from 'vitest';
6
6
 
7
- import { createKeyPair, createId } from '@dxos/crypto';
7
+ import { createId, createKeyPair } from '@dxos/crypto';
8
8
  import { PublicKey } from '@dxos/keys';
9
9
 
10
10
  import { humanize } from './human-hash';
package/src/index.ts CHANGED
@@ -18,7 +18,6 @@ export * from './deep';
18
18
  export * from './defer-function';
19
19
  export * from './defer';
20
20
  export * from './entry';
21
- export * from './first-two-chars';
22
21
  export * from './for-each-async';
23
22
  export * from './human-hash';
24
23
  export * from './instance-id';
@@ -42,7 +41,6 @@ export * from './safe-await';
42
41
  export * from './safe-instanceof';
43
42
  export * from './safe-parse';
44
43
  export * from './sliding-window-summary';
45
- export * from './sliding-window-summary';
46
44
  export * from './sort';
47
45
  export * from './string';
48
46
  export * from './sum';
@@ -52,5 +50,6 @@ export * from './tracer';
52
50
  export * from './tree';
53
51
  export * from './types';
54
52
  export * from './uint8array';
53
+ export * from './unit';
55
54
  export * from './url';
56
55
  export * from './weak';
package/src/json.ts CHANGED
@@ -17,7 +17,7 @@ const LOG_MAX_DEPTH = 7;
17
17
  /**
18
18
  * JSON.stringify replacer.
19
19
  */
20
- export function jsonReplacer(this: any, key: string, value: any): any {
20
+ export const jsonReplacer = (key: string, value: any): any => {
21
21
  // TODO(burdon): Why is this represented as `{ type: 'Buffer', data }`.
22
22
  if (value !== null && typeof value === 'object' && typeof value[inspect.custom] === 'function') {
23
23
  return value[inspect.custom]();
@@ -32,13 +32,8 @@ export function jsonReplacer(this: any, key: string, value: any): any {
32
32
  }
33
33
  }
34
34
 
35
- // TODO(burdon): Option.
36
- // code if (Array.isArray(value)) {
37
- // code return value.length;
38
- // code } else {
39
35
  return value;
40
- // code }
41
- }
36
+ };
42
37
 
43
38
  /**
44
39
  * Recursively converts an object into a JSON-compatible object.
package/src/object.ts CHANGED
@@ -2,6 +2,9 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
+ /**
6
+ * @deprecated Use `Struct.keys` from effect.
7
+ */
5
8
  export const keys = <R>(obj: R): (keyof R)[] => Object.keys(obj as any) as (keyof R)[];
6
9
 
7
10
  export const entries = <R>(obj: R): [keyof R, R[keyof R]][] => Object.entries(obj as any) as [keyof R, any][];
@@ -2,9 +2,9 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { describe, it, expect } from 'vitest';
5
+ import { describe, expect, it } from 'vitest';
6
6
 
7
- import { byPosition, type Position } from './position';
7
+ import { type Position, byPosition } from './position';
8
8
 
9
9
  type TestItem = {
10
10
  id: number;
package/src/safe-parse.ts CHANGED
@@ -6,7 +6,7 @@ export const safeParseInt = (value: string | undefined, defaultValue?: number) =
6
6
  try {
7
7
  const n = parseInt(value ?? '');
8
8
  return isNaN(n) ? defaultValue : n;
9
- } catch (err) {
9
+ } catch {
10
10
  return defaultValue;
11
11
  }
12
12
  };
@@ -22,11 +22,14 @@ export const safeParseFloat = (str: string, defaultValue?: number): number | und
22
22
  export const safeParseJson: {
23
23
  <T extends object>(data: string | undefined | null, defaultValue: T): T;
24
24
  <T extends object>(data: string | undefined | null): T | undefined;
25
- } = <T extends object>(data: string | undefined | null, defaultValue?: T) => {
25
+ } = <T extends object = any>(data: string | undefined | null, defaultValue?: T): T | undefined => {
26
26
  if (data && data.length > 0) {
27
27
  try {
28
28
  return JSON.parse(data);
29
- } catch (err) {}
29
+ } catch {
30
+ // no-op.
31
+ }
30
32
  }
33
+
31
34
  return defaultValue;
32
35
  };
package/src/sort.test.ts CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { describe, expect, test } from 'vitest';
6
6
 
7
- import { compareMulti, compareScalar, compareObject, compareString } from './sort';
7
+ import { compareMulti, compareObject, compareScalar, compareString } from './sort';
8
8
 
9
9
  const data = [
10
10
  { i: 0, idx: 1, label: 'apple' },
@@ -0,0 +1,19 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { describe, test } from 'vitest';
6
+
7
+ import { trim } from './string';
8
+
9
+ describe('string', () => {
10
+ test('dedent', async ({ expect }) => {
11
+ const text = trim`
12
+ - 1
13
+ - 2
14
+ - 3
15
+ `;
16
+
17
+ expect(text).to.eq('- 1\n- 2\n - 3');
18
+ });
19
+ });
package/src/string.ts CHANGED
@@ -12,3 +12,39 @@ export const capitalize = (str: string): string => {
12
12
 
13
13
  return str.charAt(0).toUpperCase() + str.slice(1);
14
14
  };
15
+
16
+ /**
17
+ * Remove leading space from multi-line strings.
18
+ */
19
+ export function trim(strings: TemplateStringsArray, ...values: any[]) {
20
+ // First, build the raw result with relative indentation.
21
+ const raw = strings.reduce((out, str, i) => {
22
+ out += str;
23
+ if (i < values.length) {
24
+ const match = str.match(/(^|\n)([ \t]*)$/);
25
+ const baseIndent = match ? match[2] : '';
26
+ const val = String(values[i]).replace(/\r?\n/g, '\n' + baseIndent);
27
+ out += val;
28
+ }
29
+ return out;
30
+ }, '');
31
+
32
+ // Split into lines and trim leading/trailing blank lines.
33
+ const lines = raw.split('\n');
34
+
35
+ while (lines.length && !lines[0].trim()) lines.shift();
36
+ while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
37
+
38
+ // Find smallest indent across all non-blank lines.
39
+ const minIndent = Math.min(...lines.filter((l) => l.trim()).map((l) => l.match(/^[ \t]*/)?.[0].length ?? 0));
40
+
41
+ // Remove that indent from all lines.
42
+ return lines.map((l) => l.slice(minIndent)).join('\n');
43
+ }
44
+
45
+ // From https://stackoverflow.com/a/67243723/2804332
46
+ /**
47
+ * Converts a string to kebab case.
48
+ */
49
+ export const kebabize = (str: string) =>
50
+ str.replace(/[A-Z]+(?![a-z])|[A-Z]/g, ($, ofs) => (ofs ? '-' : '') + $.toLowerCase());
@@ -194,17 +194,18 @@ export const keyToFallback = (key: PublicKey) => hexToFallback(key.toHex());
194
194
  // TODO(wittjosiah): Support non-hex strings (e.g. DIDs, UUIDs, etc.)
195
195
  export const hexToFallback = (hex: string) => toFallback(parseInt(hex, 16));
196
196
 
197
+ // TODO(burdon): Rename?
197
198
  export const toFallback = (hash: number): FallbackValue => {
198
- // Calculate total possible combinations of emoji and hue pairs
199
+ // Calculate total possible combinations of emoji and hue pairs.
199
200
  const totalCombinations = idEmoji.length * idHue.length;
200
201
 
201
- // Get a deterministic index within the range of all possible combinations
202
+ // Get a deterministic index within the range of all possible combinations.
202
203
  const combinationIndex = hash % totalCombinations;
203
204
 
204
- // Calculate which emoji to use based on the combination index
205
+ // Calculate which emoji to use based on the combination index.
205
206
  const emojiIndex = Math.floor(combinationIndex / idHue.length);
206
207
 
207
- // Calculate which hue to use based on the combination index
208
+ // Calculate which hue to use based on the combination index.
208
209
  const hueIndex = combinationIndex % idHue.length;
209
210
 
210
211
  return {
package/src/tree.test.ts CHANGED
@@ -6,7 +6,7 @@ import { describe, test } from 'vitest';
6
6
 
7
7
  import { PublicKey } from '@dxos/keys';
8
8
 
9
- import { stringifyTree, type TreeNode } from './tree';
9
+ import { type TreeNode, stringifyTree } from './tree';
10
10
 
11
11
  describe('Tree logging', () => {
12
12
  test('simple', () => {
package/src/types.ts CHANGED
@@ -48,7 +48,7 @@ export type Falsy = false | 0 | '' | null | undefined;
48
48
  * NOTE: To filter by type:
49
49
  * items.filter((item: any): item is RangeSet<Decoration> => item instanceof RangeSet)
50
50
  */
51
- export const isNotFalsy = <T>(value: T): value is Exclude<T, Falsy> => !!value;
51
+ export const isTruthy = <T>(value: T): value is Exclude<T, Falsy> => !!value;
52
52
  export const isNonNullable = <T>(value: T | null | undefined): value is T => value != null;
53
53
 
54
54
  // TODO(burdon): Replace use of setTimeout everywhere?
@@ -2,7 +2,7 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
- import { test, expect, describe } from 'vitest';
5
+ import { describe, expect, test } from 'vitest';
6
6
 
7
7
  import { arrayToBuffer, arrayToString, bufferToArray, stringToArray } from './uint8array';
8
8
 
@@ -0,0 +1,25 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { describe, it } from 'vitest';
6
+
7
+ import { Unit } from './unit';
8
+
9
+ describe('url', () => {
10
+ it('duration', ({ expect }) => {
11
+ const tests: [number, string][] = [
12
+ [0, '0ms'],
13
+ [1, '1ms'],
14
+ [1_000, '1.0s'],
15
+ [2_887, '2.9s'],
16
+ [1_000 * 60, '1m'],
17
+ [1_000 * 60 + 1_000 * 5, '1m 5s'],
18
+ [1_000 * 60 * 60 + 1_000 * 60 * 5, '1h 5m'],
19
+ ];
20
+
21
+ tests.forEach(([input, output]) => {
22
+ expect(Unit.Duration(input)).toBe(output);
23
+ });
24
+ });
25
+ });
package/src/unit.ts ADDED
@@ -0,0 +1,52 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ type Unit = {
6
+ symbol: string;
7
+ quotient: number;
8
+ };
9
+
10
+ type Format = (n: number, precision?: number) => string;
11
+
12
+ const Formatter = (unit: Unit): Format => {
13
+ return (n: number, precision = 2) => {
14
+ const value = n / unit.quotient;
15
+ return `${value.toFixed(precision)}${unit.symbol}`;
16
+ };
17
+ };
18
+
19
+ export const Unit = {
20
+ // ms.
21
+ Hour: Formatter({ symbol: 'h', quotient: 60 * 60 * 1_000 }),
22
+ Minute: Formatter({ symbol: 'm', quotient: 60 * 1_000 }),
23
+ Second: Formatter({ symbol: 's', quotient: 1_000 }),
24
+ Millisecond: Formatter({ symbol: 'ms', quotient: 1 }),
25
+ Duration: (n: number) => {
26
+ const hours = Math.floor(n / (60 * 60 * 1_000));
27
+ const minutes = Math.floor((n % (60 * 60 * 1_000)) / (60 * 1_000));
28
+ if (hours) {
29
+ return minutes ? `${hours}h ${minutes}m` : `${hours}h`;
30
+ }
31
+
32
+ const seconds = Math.floor((n % (60 * 1_000)) / 1_000);
33
+ if (minutes) {
34
+ return seconds ? `${minutes}m ${seconds}s` : `${minutes}m`;
35
+ }
36
+
37
+ if (seconds) {
38
+ return `${(n / 1_000).toFixed(1)}s`;
39
+ }
40
+
41
+ return `${n}ms`;
42
+ },
43
+
44
+ // bytes (note KB via KiB).
45
+ Gigabyte: Formatter({ symbol: 'GB', quotient: 1_000 * 1_000 * 1_000 }),
46
+ Megabyte: Formatter({ symbol: 'MB', quotient: 1_000 * 1_000 }),
47
+ Kilobyte: Formatter({ symbol: 'KB', quotient: 1_000 }),
48
+
49
+ // general.
50
+ Thousand: Formatter({ symbol: 'k', quotient: 1_000 }),
51
+ Percent: Formatter({ symbol: '%', quotient: 1 / 100 }),
52
+ };
package/src/weak.test.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
- import { test, expect, describe } from 'vitest';
5
+ import { describe, expect, test } from 'vitest';
6
6
 
7
7
  import { WeakDictionary } from './weak';
8
8
 
@@ -1,9 +0,0 @@
1
- /**
2
- * Returns the first two renderable characters from a string that are separated by non-word characters.
3
- * Handles Unicode characters correctly.
4
- *
5
- * @param {string} label - The input string to process
6
- * @returns {[string, string]} Array containing the two characters, or empty strings if not found
7
- */
8
- export declare const getFirstTwoRenderableChars: (label: string) => string[];
9
- //# sourceMappingURL=first-two-chars.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"first-two-chars.d.ts","sourceRoot":"","sources":["../../../src/first-two-chars.ts"],"names":[],"mappings":"AASA;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,GAAI,OAAO,MAAM,aA2BvD,CAAC"}
@@ -1,44 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- // Regular expression to match renderable characters
6
- // Excludes control characters, combining marks, and other non-renderable characters. Also excludes punctuation.
7
- const renderableCharRegex =
8
- /^(?![\p{Control}\p{Mark}\p{Separator}\p{Surrogate}\p{Unassigned}\p{P}])[\p{L}\p{N}\p{S}\p{Emoji}]$/u;
9
-
10
- /**
11
- * Returns the first two renderable characters from a string that are separated by non-word characters.
12
- * Handles Unicode characters correctly.
13
- *
14
- * @param {string} label - The input string to process
15
- * @returns {[string, string]} Array containing the two characters, or empty strings if not found
16
- */
17
- export const getFirstTwoRenderableChars = (label: string) => {
18
- // Convert string to array of Unicode characters
19
- const characters = Array.from(label);
20
-
21
- // Keep track of found renderable characters
22
- const result = ['', ''];
23
- let foundFirst = false;
24
-
25
- for (let i = 0; i < characters.length; i++) {
26
- const char = characters[i];
27
-
28
- if (renderableCharRegex.test(char)) {
29
- if (!foundFirst) {
30
- result[0] = char;
31
- foundFirst = true;
32
- } else {
33
- // Check if there's at least one non-word character between the first and current char
34
- const textBetween = characters.slice(result[0].length, i).join('');
35
- if (/[^\p{L}\p{N}_]/u.test(textBetween)) {
36
- result[1] = char;
37
- break;
38
- }
39
- }
40
- }
41
- }
42
-
43
- return result;
44
- };