@dxos/keys 0.5.8 → 0.5.9-main.079a532

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.
@@ -18,14 +18,25 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var node_exports = {};
20
20
  __export(node_exports, {
21
+ DXN: () => DXN,
22
+ LOCAL_SPACE_TAG: () => LOCAL_SPACE_TAG,
21
23
  PUBLIC_KEY_LENGTH: () => PUBLIC_KEY_LENGTH,
22
24
  PublicKey: () => PublicKey,
23
- SECRET_KEY_LENGTH: () => SECRET_KEY_LENGTH
25
+ SECRET_KEY_LENGTH: () => SECRET_KEY_LENGTH,
26
+ SpaceId: () => SpaceId
24
27
  });
25
28
  module.exports = __toCommonJS(node_exports);
26
29
  var import_node_util = require("node:util");
27
30
  var import_debug = require("@dxos/debug");
28
31
  var import_invariant = require("@dxos/invariant");
32
+ var import_invariant2 = require("@dxos/invariant");
33
+ var import_invariant3 = require("@dxos/invariant");
34
+ var __create = Object.create;
35
+ var __defProp2 = Object.defineProperty;
36
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
37
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
38
+ var __getProtoOf = Object.getPrototypeOf;
39
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
29
40
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
30
41
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
31
42
  }) : x)(function(x) {
@@ -33,6 +44,135 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
33
44
  return require.apply(this, arguments);
34
45
  throw Error('Dynamic require of "' + x + '" is not supported');
35
46
  });
47
+ var __commonJS = (cb, mod) => function __require2() {
48
+ return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
49
+ };
50
+ var __copyProps2 = (to, from, except, desc) => {
51
+ if (from && typeof from === "object" || typeof from === "function") {
52
+ for (let key of __getOwnPropNames2(from))
53
+ if (!__hasOwnProp2.call(to, key) && key !== except)
54
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
55
+ }
56
+ return to;
57
+ };
58
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps2(
59
+ // If the importer is in node compatibility mode or this is not an ESM
60
+ // file that has been converted to a CommonJS file using a Babel-
61
+ // compatible transform (i.e. "__esModule" has not been set), then set
62
+ // "default" to the CommonJS "module.exports" for node compatibility.
63
+ isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
64
+ mod
65
+ ));
66
+ var require_base32_decode = __commonJS({
67
+ "node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js"(exports, module2) {
68
+ var RFC46482 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
69
+ var RFC4648_HEX2 = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
70
+ var CROCKFORD2 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
71
+ function readChar(alphabet, char) {
72
+ var idx = alphabet.indexOf(char);
73
+ if (idx === -1) {
74
+ throw new Error("Invalid character found: " + char);
75
+ }
76
+ return idx;
77
+ }
78
+ module2.exports = function base32Decode3(input, variant) {
79
+ var alphabet;
80
+ switch (variant) {
81
+ case "RFC3548":
82
+ case "RFC4648":
83
+ alphabet = RFC46482;
84
+ input = input.replace(/=+$/, "");
85
+ break;
86
+ case "RFC4648-HEX":
87
+ alphabet = RFC4648_HEX2;
88
+ input = input.replace(/=+$/, "");
89
+ break;
90
+ case "Crockford":
91
+ alphabet = CROCKFORD2;
92
+ input = input.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1");
93
+ break;
94
+ default:
95
+ throw new Error("Unknown base32 variant: " + variant);
96
+ }
97
+ var length = input.length;
98
+ var bits = 0;
99
+ var value = 0;
100
+ var index = 0;
101
+ var output = new Uint8Array(length * 5 / 8 | 0);
102
+ for (var i = 0; i < length; i++) {
103
+ value = value << 5 | readChar(alphabet, input[i]);
104
+ bits += 5;
105
+ if (bits >= 8) {
106
+ output[index++] = value >>> bits - 8 & 255;
107
+ bits -= 8;
108
+ }
109
+ }
110
+ return output.buffer;
111
+ };
112
+ }
113
+ });
114
+ var import_base32_decode = __toESM(require_base32_decode());
115
+ function toDataView(data) {
116
+ if (data instanceof Int8Array || data instanceof Uint8Array || data instanceof Uint8ClampedArray) {
117
+ return new DataView(data.buffer, data.byteOffset, data.byteLength);
118
+ }
119
+ if (data instanceof ArrayBuffer) {
120
+ return new DataView(data);
121
+ }
122
+ throw new TypeError("Expected `data` to be an ArrayBuffer, Buffer, Int8Array, Uint8Array or Uint8ClampedArray");
123
+ }
124
+ var RFC4648 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
125
+ var RFC4648_HEX = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
126
+ var CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
127
+ function base32Encode(data, variant, options) {
128
+ options = options || {};
129
+ let alphabet, defaultPadding;
130
+ switch (variant) {
131
+ case "RFC3548":
132
+ case "RFC4648":
133
+ alphabet = RFC4648;
134
+ defaultPadding = true;
135
+ break;
136
+ case "RFC4648-HEX":
137
+ alphabet = RFC4648_HEX;
138
+ defaultPadding = true;
139
+ break;
140
+ case "Crockford":
141
+ alphabet = CROCKFORD;
142
+ defaultPadding = false;
143
+ break;
144
+ default:
145
+ throw new Error("Unknown base32 variant: " + variant);
146
+ }
147
+ const padding = options.padding !== void 0 ? options.padding : defaultPadding;
148
+ const view = toDataView(data);
149
+ let bits = 0;
150
+ let value = 0;
151
+ let output = "";
152
+ for (let i = 0; i < view.byteLength; i++) {
153
+ value = value << 8 | view.getUint8(i);
154
+ bits += 8;
155
+ while (bits >= 5) {
156
+ output += alphabet[value >>> bits - 5 & 31];
157
+ bits -= 5;
158
+ }
159
+ }
160
+ if (bits > 0) {
161
+ output += alphabet[value << 5 - bits & 31];
162
+ }
163
+ if (padding) {
164
+ while (output.length % 8 !== 0) {
165
+ output += "=";
166
+ }
167
+ }
168
+ return output;
169
+ }
170
+ var randomBytes = (length) => {
171
+ const webCrypto = globalThis.crypto ?? __require("node:crypto").webcrypto;
172
+ const bytes = new Uint8Array(length);
173
+ webCrypto.getRandomValues(bytes);
174
+ return bytes;
175
+ };
36
176
  var __dxlog_file = "/home/runner/work/dxos/dxos/packages/common/keys/src/public-key.ts";
37
177
  var PUBLIC_KEY_LENGTH = 32;
38
178
  var SECRET_KEY_LENGTH = 64;
@@ -45,7 +185,7 @@ var PublicKey = class _PublicKey {
45
185
  static from(source) {
46
186
  (0, import_invariant.invariant)(source, void 0, {
47
187
  F: __dxlog_file,
48
- L: 30,
188
+ L: 34,
49
189
  S: this,
50
190
  A: [
51
191
  "source",
@@ -100,6 +240,9 @@ var PublicKey = class _PublicKey {
100
240
  static random() {
101
241
  return _PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));
102
242
  }
243
+ static randomOfLength(length) {
244
+ return _PublicKey.from(randomBytes(length));
245
+ }
103
246
  static *randomSequence() {
104
247
  for (let i = 0; i < 1e4; i++) {
105
248
  yield _PublicKey.random();
@@ -134,7 +277,7 @@ var PublicKey = class _PublicKey {
134
277
  static bufferize(str) {
135
278
  (0, import_invariant.invariant)(typeof str === "string", "Invalid type", {
136
279
  F: __dxlog_file,
137
- L: 129,
280
+ L: 137,
138
281
  S: this,
139
282
  A: [
140
283
  "typeof str === 'string'",
@@ -157,7 +300,7 @@ var PublicKey = class _PublicKey {
157
300
  }
158
301
  (0, import_invariant.invariant)(key instanceof Buffer, "Invalid type", {
159
302
  F: __dxlog_file,
160
- L: 148,
303
+ L: 156,
161
304
  S: this,
162
305
  A: [
163
306
  "key instanceof Buffer",
@@ -173,6 +316,18 @@ var PublicKey = class _PublicKey {
173
316
  static hash(key) {
174
317
  return key.toHex();
175
318
  }
319
+ static fromMultibase32(encoded) {
320
+ (0, import_invariant.invariant)(encoded.startsWith("B"), "Invalid multibase32 encoding", {
321
+ F: __dxlog_file,
322
+ L: 169,
323
+ S: this,
324
+ A: [
325
+ "encoded.startsWith('B')",
326
+ "'Invalid multibase32 encoding'"
327
+ ]
328
+ });
329
+ return new _PublicKey(new Uint8Array((0, import_base32_decode.default)(encoded.slice(1), "RFC4648")));
330
+ }
176
331
  constructor(_value) {
177
332
  this._value = _value;
178
333
  if (!(_value instanceof Uint8Array)) {
@@ -194,6 +349,9 @@ var PublicKey = class _PublicKey {
194
349
  toHex() {
195
350
  return this.asBuffer().toString("hex");
196
351
  }
352
+ toMultibase32() {
353
+ return "B" + base32Encode(this._value, "RFC4648");
354
+ }
197
355
  truncate(length = void 0) {
198
356
  return (0, import_debug.truncateKey)(this, length);
199
357
  }
@@ -298,16 +456,142 @@ var PublicKey = class _PublicKey {
298
456
  return this.equals(other);
299
457
  }
300
458
  };
301
- var randomBytes = (length) => {
302
- const webCrypto = globalThis.crypto ?? __require("node:crypto").webcrypto;
303
- const bytes = new Uint8Array(length);
304
- webCrypto.getRandomValues(bytes);
305
- return bytes;
459
+ var import_base32_decode2 = __toESM(require_base32_decode());
460
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/common/keys/src/space-id.ts";
461
+ var SpaceId = Object.freeze({
462
+ byteLength: 20,
463
+ encode: (value) => {
464
+ (0, import_invariant2.invariant)(value instanceof Uint8Array, "Invalid type", {
465
+ F: __dxlog_file2,
466
+ L: 22,
467
+ S: void 0,
468
+ A: [
469
+ "value instanceof Uint8Array",
470
+ "'Invalid type'"
471
+ ]
472
+ });
473
+ (0, import_invariant2.invariant)(value.length === SpaceId.byteLength, "Invalid length", {
474
+ F: __dxlog_file2,
475
+ L: 23,
476
+ S: void 0,
477
+ A: [
478
+ "value.length === SpaceId.byteLength",
479
+ "'Invalid length'"
480
+ ]
481
+ });
482
+ return MULTIBASE_PREFIX + base32Encode(value, "RFC4648");
483
+ },
484
+ decode: (value) => {
485
+ (0, import_invariant2.invariant)(value.startsWith(MULTIBASE_PREFIX), "Invalid multibase32 encoding", {
486
+ F: __dxlog_file2,
487
+ L: 28,
488
+ S: void 0,
489
+ A: [
490
+ "value.startsWith(MULTIBASE_PREFIX)",
491
+ "'Invalid multibase32 encoding'"
492
+ ]
493
+ });
494
+ return new Uint8Array((0, import_base32_decode2.default)(value.slice(1), "RFC4648"));
495
+ },
496
+ isValid: (value) => {
497
+ return typeof value === "string" && value.startsWith(MULTIBASE_PREFIX) && value.length === ENCODED_LENGTH;
498
+ },
499
+ random: () => {
500
+ return SpaceId.encode(randomBytes(SpaceId.byteLength));
501
+ }
502
+ });
503
+ var MULTIBASE_PREFIX = "B";
504
+ var ENCODED_LENGTH = 33;
505
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/common/keys/src/dxn.ts";
506
+ var DXN = class _DXN {
507
+ static {
508
+ this.kind = Object.freeze({
509
+ ECHO: "echo",
510
+ TYPE: "type"
511
+ });
512
+ }
513
+ static parse(dxn) {
514
+ const [prefix, kind, ...parts] = dxn.split(":");
515
+ if (!(prefix === "dxn")) {
516
+ throw new Error("Invalid DXN");
517
+ }
518
+ if (!(typeof kind === "string" && kind.length > 0)) {
519
+ throw new Error("Invalid DXN");
520
+ }
521
+ if (!(parts.length > 0)) {
522
+ throw new Error("Invalid DXN");
523
+ }
524
+ return new _DXN(kind, parts);
525
+ }
526
+ #kind;
527
+ #parts;
528
+ constructor(kind, parts) {
529
+ (0, import_invariant3.invariant)(parts.length > 0, void 0, {
530
+ F: __dxlog_file3,
531
+ L: 51,
532
+ S: this,
533
+ A: [
534
+ "parts.length > 0",
535
+ ""
536
+ ]
537
+ });
538
+ (0, import_invariant3.invariant)(parts.every((part) => typeof part === "string" && part.length > 0 && part.indexOf(":") === -1), void 0, {
539
+ F: __dxlog_file3,
540
+ L: 52,
541
+ S: this,
542
+ A: [
543
+ "parts.every((part) => typeof part === 'string' && part.length > 0 && part.indexOf(':') === -1)",
544
+ ""
545
+ ]
546
+ });
547
+ switch (kind) {
548
+ case _DXN.kind.ECHO:
549
+ (0, import_invariant3.invariant)(parts.length === 2, void 0, {
550
+ F: __dxlog_file3,
551
+ L: 57,
552
+ S: this,
553
+ A: [
554
+ "parts.length === 2",
555
+ ""
556
+ ]
557
+ });
558
+ break;
559
+ case _DXN.kind.TYPE:
560
+ (0, import_invariant3.invariant)(parts.length === 1, void 0, {
561
+ F: __dxlog_file3,
562
+ L: 60,
563
+ S: this,
564
+ A: [
565
+ "parts.length === 1",
566
+ ""
567
+ ]
568
+ });
569
+ break;
570
+ }
571
+ this.#kind = kind;
572
+ this.#parts = parts;
573
+ }
574
+ get kind() {
575
+ return this.#kind;
576
+ }
577
+ get parts() {
578
+ return this.#parts;
579
+ }
580
+ isTypeDXNOf(typename) {
581
+ return this.#kind === _DXN.kind.TYPE && this.#parts.length === 1 && this.#parts[0] === typename;
582
+ }
583
+ toString() {
584
+ return `dxn:${this.#kind}:${this.#parts.join(":")}`;
585
+ }
306
586
  };
587
+ var LOCAL_SPACE_TAG = "@";
307
588
  // Annotate the CommonJS export names for ESM import in node:
308
589
  0 && (module.exports = {
590
+ DXN,
591
+ LOCAL_SPACE_TAG,
309
592
  PUBLIC_KEY_LENGTH,
310
593
  PublicKey,
311
- SECRET_KEY_LENGTH
594
+ SECRET_KEY_LENGTH,
595
+ SpaceId
312
596
  });
313
597
  //# sourceMappingURL=index.cjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../src/public-key.ts"],
4
- "sourcesContent": ["//\n// Copyright 2020 DXOS.org\n//\n\nimport { inspect, type InspectOptionsStylized } from 'node:util';\n\nimport { truncateKey, devtoolsFormatter, type DevtoolsFormatter, equalsSymbol, type Equatable } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 64;\n\n/**\n * All representations that can be converted to a PublicKey.\n */\nexport type PublicKeyLike = PublicKey | Buffer | Uint8Array | ArrayBuffer | string;\n\n/**\n * The purpose of this class is to assure consistent use of keys throughout the project.\n * Keys should be maintained as buffers in objects and proto definitions, and converted to hex\n * strings as late as possible (eg, to log/display).\n */\nexport class PublicKey implements Equatable {\n /**\n * Creates new instance of PublicKey automatically determining the input format.\n * @param source A Buffer, or Uint8Array, or hex encoded string, or something with an `asUint8Array` method on it\n * @returns PublicKey\n */\n static from(source: PublicKeyLike): PublicKey {\n invariant(source);\n if (source instanceof PublicKey) {\n return source;\n } else if (source instanceof Buffer) {\n return new PublicKey(new Uint8Array(source.buffer, source.byteOffset, source.byteLength));\n } else if (source instanceof Uint8Array) {\n return new PublicKey(source);\n } else if (source instanceof ArrayBuffer) {\n return new PublicKey(new Uint8Array(source));\n } else if (typeof source === 'string') {\n // TODO(burdon): Check length.\n return PublicKey.fromHex(source);\n } else if ((<any>source).asUint8Array) {\n return new PublicKey((<any>source).asUint8Array());\n } else {\n throw new TypeError(`Unable to create PublicKey from ${source}`);\n }\n }\n\n /**\n * Same as `PublicKey.from` but does not throw and instead returns a `{ key: PublicKey }` or `{ error: Error }`\n * @param source Same PublicKeyLike argument as for `PublicKey.from`\n * @returns PublicKey\n */\n static safeFrom(source?: PublicKeyLike): PublicKey | undefined {\n if (!source) {\n return undefined;\n }\n\n try {\n const key = PublicKey.from(source);\n // TODO(wittjosiah): Space keys don't pass this check.\n // if (key.length !== PUBLIC_KEY_LENGTH && key.length !== SECRET_KEY_LENGTH) {\n // return undefined;\n // }\n return key;\n } catch (err: any) {\n return undefined;\n }\n }\n\n /**\n * Creates new instance of PublicKey from hex string.\n */\n static fromHex(hex: string) {\n if (hex.startsWith('0x')) {\n hex = hex.slice(2);\n }\n\n const buf = Buffer.from(hex, 'hex');\n // TODO(burdon): Test if key.\n return new PublicKey(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));\n }\n\n /**\n * Creates a new key.\n */\n static random(): PublicKey {\n // TODO(burdon): Enable seed for debugging.\n return PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));\n }\n\n static *randomSequence(): Generator<PublicKey> {\n for (let i = 0; i < 1_0000; i++) {\n // Counter just to protect against infinite loops.\n yield PublicKey.random();\n }\n throw new Error('Too many keys requested');\n }\n\n /**\n * Tests if provided values is an instance of PublicKey.\n */\n static isPublicKey(value: any): value is PublicKey {\n return value instanceof PublicKey;\n }\n\n /**\n * Asserts that provided values is an instance of PublicKey.\n */\n static assertValidPublicKey(value: any): asserts value is PublicKey {\n if (!this.isPublicKey(value)) {\n throw new TypeError('Invalid PublicKey');\n }\n }\n\n /**\n * Tests two keys for equality.\n */\n static equals(left: PublicKeyLike, right: PublicKeyLike) {\n return PublicKey.from(left).equals(right);\n }\n\n /**\n * @param str string representation of key.\n * @return Key buffer.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static bufferize(str: string): Buffer {\n invariant(typeof str === 'string', 'Invalid type');\n const buffer = Buffer.from(str, 'hex');\n // invariant(buffer.length === PUBLIC_KEY_LENGTH || buffer.length === SECRET_KEY_LENGTH,\n // `Invalid key length: ${buffer.length}`);\n return buffer;\n }\n\n /**\n * @param key key like data structure (but not PublicKey which should use toString).\n * @return Hex string representation of key.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static stringify(key: Buffer | Uint8Array | ArrayBuffer): string {\n if (key instanceof PublicKey) {\n key = key.asBuffer();\n } else if (key instanceof Uint8Array) {\n key = Buffer.from(key.buffer, key.byteOffset, key.byteLength);\n }\n\n invariant(key instanceof Buffer, 'Invalid type');\n return key.toString('hex');\n }\n\n /**\n * To be used with ComplexMap and ComplexSet.\n * Returns a scalar representation for this key.\n */\n static hash(key: PublicKey): string {\n return key.toHex();\n }\n\n constructor(private readonly _value: Uint8Array) {\n if (!(_value instanceof Uint8Array)) {\n throw new TypeError(`Expected Uint8Array, got: ${_value}`);\n }\n }\n\n toString(): string {\n return this.toHex();\n }\n\n toJSON() {\n return this.toHex();\n }\n\n toJSONL(): string {\n return this.truncate();\n }\n\n get length() {\n return this._value.length;\n }\n\n toHex(): string {\n return this.asBuffer().toString('hex');\n }\n\n truncate(length = undefined) {\n return truncateKey(this, length);\n }\n\n asBuffer(): Buffer {\n return Buffer.from(this._value.buffer, this._value.byteOffset, this._value.byteLength);\n }\n\n asUint8Array(): Uint8Array {\n return this._value;\n }\n\n getInsecureHash(modulo: number) {\n return Math.abs(this._value.reduce((acc, val) => (acc ^ val) | 0, 0)) % modulo;\n }\n\n /**\n * Used by Node.js to get textual representation of this object when it's printed with a `console.log` statement.\n */\n [inspect.custom](depth: number, options: InspectOptionsStylized) {\n if (!options.colors || typeof process.stdout.hasColors !== 'function' || !process.stdout.hasColors()) {\n return `<PublicKey ${this.truncate()}>`;\n }\n\n const printControlCode = (code: number) => {\n return `\\x1b[${code}m`;\n };\n\n // NOTE: Keep in sync with formatter colors.\n const colors = [\n 'red',\n 'green',\n 'yellow',\n 'blue',\n 'magenta',\n 'cyan',\n 'redBright',\n 'greenBright',\n 'yellowBright',\n 'blueBright',\n 'magentaBright',\n 'cyanBright',\n 'whiteBright',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return `PublicKey(${printControlCode(inspect.colors[color]![0])}${this.truncate()}${printControlCode(\n inspect.colors.reset![0],\n )})`;\n }\n\n get [devtoolsFormatter](): DevtoolsFormatter {\n return {\n header: () => {\n // NOTE: Keep in sync with inspect colors.\n const colors = [\n 'darkred',\n 'green',\n 'orange',\n 'blue',\n 'darkmagenta',\n 'darkcyan',\n 'red',\n 'green',\n 'orange',\n 'blue',\n 'magenta',\n 'darkcyan',\n 'black',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return [\n 'span',\n {},\n ['span', {}, 'PublicKey('],\n ['span', { style: `color: ${color};` }, this.truncate()],\n ['span', {}, ')'],\n ];\n },\n };\n }\n\n /**\n * Test this key for equality with some other key.\n */\n equals(other: PublicKeyLike) {\n const otherConverted = PublicKey.from(other);\n if (this._value.length !== otherConverted._value.length) {\n return false;\n }\n\n let equal = true;\n for (let i = 0; i < this._value.length; i++) {\n equal &&= this._value[i] === otherConverted._value[i];\n }\n\n return equal;\n }\n\n [equalsSymbol](other: any) {\n if (!PublicKey.isPublicKey(other)) {\n return false;\n }\n\n return this.equals(other);\n }\n}\n\nconst randomBytes = (length: number) => {\n // globalThis.crypto is not available in Node.js when running in vitest even though the documentation says it should be.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const webCrypto = globalThis.crypto ?? require('node:crypto').webcrypto;\n\n const bytes = new Uint8Array(length);\n webCrypto.getRandomValues(bytes);\n return bytes;\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAIA,uBAAqD;AAErD,mBAAqG;AACrG,uBAA0B;;;;;;;;;AAEnB,IAAMA,oBAAoB;AAC1B,IAAMC,oBAAoB;AAY1B,IAAMC,YAAN,MAAMA,WAAAA;;;;;;EAMX,OAAOC,KAAKC,QAAkC;AAC5CC,oCAAUD,QAAAA,QAAAA;;;;;;;;;AACV,QAAIA,kBAAkBF,YAAW;AAC/B,aAAOE;IACT,WAAWA,kBAAkBE,QAAQ;AACnC,aAAO,IAAIJ,WAAU,IAAIK,WAAWH,OAAOI,QAAQJ,OAAOK,YAAYL,OAAOM,UAAU,CAAA;IACzF,WAAWN,kBAAkBG,YAAY;AACvC,aAAO,IAAIL,WAAUE,MAAAA;IACvB,WAAWA,kBAAkBO,aAAa;AACxC,aAAO,IAAIT,WAAU,IAAIK,WAAWH,MAAAA,CAAAA;IACtC,WAAW,OAAOA,WAAW,UAAU;AAErC,aAAOF,WAAUU,QAAQR,MAAAA;IAC3B,WAAiBA,OAAQS,cAAc;AACrC,aAAO,IAAIX,WAAgBE,OAAQS,aAAY,CAAA;IACjD,OAAO;AACL,YAAM,IAAIC,UAAU,mCAAmCV,MAAAA,EAAQ;IACjE;EACF;;;;;;EAOA,OAAOW,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AAA;AAGnB,QAAM4B,YAAYC,WAAWC,UAAUC,UAAQ,aAAA,EAAeC;AAE9D,QAAMC,QAAQ,IAAIxE,WAAWuC,MAAAA;AAC7B4B,YAAUM,gBAAgBD,KAAAA;AAC1B,SAAOA;AACT;",
6
- "names": ["PUBLIC_KEY_LENGTH", "SECRET_KEY_LENGTH", "PublicKey", "from", "source", "invariant", "Buffer", "Uint8Array", "buffer", "byteOffset", "byteLength", "ArrayBuffer", "fromHex", "asUint8Array", "TypeError", "safeFrom", "undefined", "key", "err", "hex", "startsWith", "slice", "buf", "random", "randomBytes", "randomSequence", "i", "Error", "isPublicKey", "value", "assertValidPublicKey", "equals", "left", "right", "bufferize", "str", "stringify", "asBuffer", "toString", "hash", "toHex", "constructor", "_value", "toJSON", "toJSONL", "truncate", "length", "truncateKey", "getInsecureHash", "modulo", "Math", "abs", "reduce", "acc", "val", "inspect", "custom", "depth", "options", "colors", "process", "stdout", "hasColors", "printControlCode", "code", "color", "reset", "devtoolsFormatter", "header", "style", "other", "otherConverted", "equal", "equalsSymbol", "webCrypto", "globalThis", "crypto", "require", "webcrypto", "bytes", "getRandomValues"]
3
+ "sources": ["../../../../../../node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js", "../../../src/public-key.ts", "../../../../../../node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js", "../../../../../../node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js", "../../../src/random-bytes.ts", "../../../src/space-id.ts", "../../../src/dxn.ts"],
4
+ "sourcesContent": ["var RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\nvar RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'\nvar CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\nfunction readChar (alphabet, char) {\n var idx = alphabet.indexOf(char)\n\n if (idx === -1) {\n throw new Error('Invalid character found: ' + char)\n }\n\n return idx\n}\n\nmodule.exports = function base32Decode (input, variant) {\n var alphabet\n\n switch (variant) {\n case 'RFC3548':\n case 'RFC4648':\n alphabet = RFC4648\n input = input.replace(/=+$/, '')\n break\n case 'RFC4648-HEX':\n alphabet = RFC4648_HEX\n input = input.replace(/=+$/, '')\n break\n case 'Crockford':\n alphabet = CROCKFORD\n input = input.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')\n break\n default:\n throw new Error('Unknown base32 variant: ' + variant)\n }\n\n var length = input.length\n\n var bits = 0\n var value = 0\n\n var index = 0\n var output = new Uint8Array((length * 5 / 8) | 0)\n\n for (var i = 0; i < length; i++) {\n value = (value << 5) | readChar(alphabet, input[i])\n bits += 5\n\n if (bits >= 8) {\n output[index++] = (value >>> (bits - 8)) & 255\n bits -= 8\n }\n }\n\n return output.buffer\n}\n", "//\n// Copyright 2020 DXOS.org\n//\n\nimport base32Decode from 'base32-decode';\nimport base32Encode from 'base32-encode';\nimport { inspect, type InspectOptionsStylized } from 'node:util';\n\nimport { truncateKey, devtoolsFormatter, type DevtoolsFormatter, equalsSymbol, type Equatable } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\n\nimport { randomBytes } from './random-bytes';\n\nexport const PUBLIC_KEY_LENGTH = 32;\nexport const SECRET_KEY_LENGTH = 64;\n\n/**\n * All representations that can be converted to a PublicKey.\n */\nexport type PublicKeyLike = PublicKey | Buffer | Uint8Array | ArrayBuffer | string;\n\n/**\n * The purpose of this class is to assure consistent use of keys throughout the project.\n * Keys should be maintained as buffers in objects and proto definitions, and converted to hex\n * strings as late as possible (eg, to log/display).\n */\nexport class PublicKey implements Equatable {\n /**\n * Creates new instance of PublicKey automatically determining the input format.\n * @param source A Buffer, or Uint8Array, or hex encoded string, or something with an `asUint8Array` method on it\n * @returns PublicKey\n */\n static from(source: PublicKeyLike): PublicKey {\n invariant(source);\n if (source instanceof PublicKey) {\n return source;\n } else if (source instanceof Buffer) {\n return new PublicKey(new Uint8Array(source.buffer, source.byteOffset, source.byteLength));\n } else if (source instanceof Uint8Array) {\n return new PublicKey(source);\n } else if (source instanceof ArrayBuffer) {\n return new PublicKey(new Uint8Array(source));\n } else if (typeof source === 'string') {\n // TODO(burdon): Check length.\n return PublicKey.fromHex(source);\n } else if ((<any>source).asUint8Array) {\n return new PublicKey((<any>source).asUint8Array());\n } else {\n throw new TypeError(`Unable to create PublicKey from ${source}`);\n }\n }\n\n /**\n * Same as `PublicKey.from` but does not throw and instead returns a `{ key: PublicKey }` or `{ error: Error }`\n * @param source Same PublicKeyLike argument as for `PublicKey.from`\n * @returns PublicKey\n */\n static safeFrom(source?: PublicKeyLike): PublicKey | undefined {\n if (!source) {\n return undefined;\n }\n\n try {\n const key = PublicKey.from(source);\n // TODO(wittjosiah): Space keys don't pass this check.\n // if (key.length !== PUBLIC_KEY_LENGTH && key.length !== SECRET_KEY_LENGTH) {\n // return undefined;\n // }\n return key;\n } catch (err: any) {\n return undefined;\n }\n }\n\n /**\n * Creates new instance of PublicKey from hex string.\n */\n static fromHex(hex: string) {\n if (hex.startsWith('0x')) {\n hex = hex.slice(2);\n }\n\n const buf = Buffer.from(hex, 'hex');\n // TODO(burdon): Test if key.\n return new PublicKey(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));\n }\n\n /**\n * Creates a new key.\n */\n static random(): PublicKey {\n // TODO(burdon): Enable seed for debugging.\n return PublicKey.from(randomBytes(PUBLIC_KEY_LENGTH));\n }\n\n static randomOfLength(length: number): PublicKey {\n return PublicKey.from(randomBytes(length));\n }\n\n static *randomSequence(): Generator<PublicKey> {\n for (let i = 0; i < 1_0000; i++) {\n // Counter just to protect against infinite loops.\n yield PublicKey.random();\n }\n throw new Error('Too many keys requested');\n }\n\n /**\n * Tests if provided values is an instance of PublicKey.\n */\n static isPublicKey(value: any): value is PublicKey {\n return value instanceof PublicKey;\n }\n\n /**\n * Asserts that provided values is an instance of PublicKey.\n */\n static assertValidPublicKey(value: any): asserts value is PublicKey {\n if (!this.isPublicKey(value)) {\n throw new TypeError('Invalid PublicKey');\n }\n }\n\n /**\n * Tests two keys for equality.\n */\n static equals(left: PublicKeyLike, right: PublicKeyLike) {\n return PublicKey.from(left).equals(right);\n }\n\n /**\n * @param str string representation of key.\n * @return Key buffer.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static bufferize(str: string): Buffer {\n invariant(typeof str === 'string', 'Invalid type');\n const buffer = Buffer.from(str, 'hex');\n // invariant(buffer.length === PUBLIC_KEY_LENGTH || buffer.length === SECRET_KEY_LENGTH,\n // `Invalid key length: ${buffer.length}`);\n return buffer;\n }\n\n /**\n * @param key key like data structure (but not PublicKey which should use toString).\n * @return Hex string representation of key.\n * @deprecated All keys should be represented as instances of PublicKey.\n */\n static stringify(key: Buffer | Uint8Array | ArrayBuffer): string {\n if (key instanceof PublicKey) {\n key = key.asBuffer();\n } else if (key instanceof Uint8Array) {\n key = Buffer.from(key.buffer, key.byteOffset, key.byteLength);\n }\n\n invariant(key instanceof Buffer, 'Invalid type');\n return key.toString('hex');\n }\n\n /**\n * To be used with ComplexMap and ComplexSet.\n * Returns a scalar representation for this key.\n */\n static hash(key: PublicKey): string {\n return key.toHex();\n }\n\n static fromMultibase32(encoded: string): PublicKey {\n invariant(encoded.startsWith('B'), 'Invalid multibase32 encoding');\n\n return new PublicKey(new Uint8Array(base32Decode(encoded.slice(1), 'RFC4648')));\n }\n\n constructor(private readonly _value: Uint8Array) {\n if (!(_value instanceof Uint8Array)) {\n throw new TypeError(`Expected Uint8Array, got: ${_value}`);\n }\n }\n\n toString(): string {\n return this.toHex();\n }\n\n toJSON() {\n return this.toHex();\n }\n\n toJSONL(): string {\n return this.truncate();\n }\n\n get length() {\n return this._value.length;\n }\n\n toHex(): string {\n return this.asBuffer().toString('hex');\n }\n\n toMultibase32(): string {\n return 'B' + base32Encode(this._value, 'RFC4648');\n }\n\n truncate(length = undefined) {\n return truncateKey(this, length);\n }\n\n asBuffer(): Buffer {\n return Buffer.from(this._value.buffer, this._value.byteOffset, this._value.byteLength);\n }\n\n asUint8Array(): Uint8Array {\n return this._value;\n }\n\n getInsecureHash(modulo: number) {\n return Math.abs(this._value.reduce((acc, val) => (acc ^ val) | 0, 0)) % modulo;\n }\n\n /**\n * Used by Node.js to get textual representation of this object when it's printed with a `console.log` statement.\n */\n [inspect.custom](depth: number, options: InspectOptionsStylized) {\n if (!options.colors || typeof process.stdout.hasColors !== 'function' || !process.stdout.hasColors()) {\n return `<PublicKey ${this.truncate()}>`;\n }\n\n const printControlCode = (code: number) => {\n return `\\x1b[${code}m`;\n };\n\n // NOTE: Keep in sync with formatter colors.\n const colors = [\n 'red',\n 'green',\n 'yellow',\n 'blue',\n 'magenta',\n 'cyan',\n 'redBright',\n 'greenBright',\n 'yellowBright',\n 'blueBright',\n 'magentaBright',\n 'cyanBright',\n 'whiteBright',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return `PublicKey(${printControlCode(inspect.colors[color]![0])}${this.truncate()}${printControlCode(\n inspect.colors.reset![0],\n )})`;\n }\n\n get [devtoolsFormatter](): DevtoolsFormatter {\n return {\n header: () => {\n // NOTE: Keep in sync with inspect colors.\n const colors = [\n 'darkred',\n 'green',\n 'orange',\n 'blue',\n 'darkmagenta',\n 'darkcyan',\n 'red',\n 'green',\n 'orange',\n 'blue',\n 'magenta',\n 'darkcyan',\n 'black',\n ];\n const color = colors[this.getInsecureHash(colors.length)];\n\n return [\n 'span',\n {},\n ['span', {}, 'PublicKey('],\n ['span', { style: `color: ${color};` }, this.truncate()],\n ['span', {}, ')'],\n ];\n },\n };\n }\n\n /**\n * Test this key for equality with some other key.\n */\n equals(other: PublicKeyLike) {\n const otherConverted = PublicKey.from(other);\n if (this._value.length !== otherConverted._value.length) {\n return false;\n }\n\n let equal = true;\n for (let i = 0; i < this._value.length; i++) {\n equal &&= this._value[i] === otherConverted._value[i];\n }\n\n return equal;\n }\n\n [equalsSymbol](other: any) {\n if (!PublicKey.isPublicKey(other)) {\n return false;\n }\n\n return this.equals(other);\n }\n}\n", "export default function toDataView (data) {\n if (data instanceof Int8Array || data instanceof Uint8Array || data instanceof Uint8ClampedArray) {\n return new DataView(data.buffer, data.byteOffset, data.byteLength)\n }\n\n if (data instanceof ArrayBuffer) {\n return new DataView(data)\n }\n\n throw new TypeError('Expected `data` to be an ArrayBuffer, Buffer, Int8Array, Uint8Array or Uint8ClampedArray')\n}\n", "import toDataView from 'to-data-view'\n\nconst RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'\nconst RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'\nconst CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\nexport default function base32Encode (data, variant, options) {\n options = options || {}\n let alphabet, defaultPadding\n\n switch (variant) {\n case 'RFC3548':\n case 'RFC4648':\n alphabet = RFC4648\n defaultPadding = true\n break\n case 'RFC4648-HEX':\n alphabet = RFC4648_HEX\n defaultPadding = true\n break\n case 'Crockford':\n alphabet = CROCKFORD\n defaultPadding = false\n break\n default:\n throw new Error('Unknown base32 variant: ' + variant)\n }\n\n const padding = (options.padding !== undefined ? options.padding : defaultPadding)\n const view = toDataView(data)\n\n let bits = 0\n let value = 0\n let output = ''\n\n for (let i = 0; i < view.byteLength; i++) {\n value = (value << 8) | view.getUint8(i)\n bits += 8\n\n while (bits >= 5) {\n output += alphabet[(value >>> (bits - 5)) & 31]\n bits -= 5\n }\n }\n\n if (bits > 0) {\n output += alphabet[(value << (5 - bits)) & 31]\n }\n\n if (padding) {\n while ((output.length % 8) !== 0) {\n output += '='\n }\n }\n\n return output\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nexport const randomBytes = (length: number) => {\n // globalThis.crypto is not available in Node.js when running in vitest even though the documentation says it should be.\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const webCrypto = globalThis.crypto ?? require('node:crypto').webcrypto;\n\n const bytes = new Uint8Array(length);\n webCrypto.getRandomValues(bytes);\n return bytes;\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport base32Decode from 'base32-decode';\nimport base32Encode from 'base32-encode';\n\nimport { invariant } from '@dxos/invariant';\n\nimport { randomBytes } from './random-bytes';\n\n/**\n * A unique identifier for a space.\n * Space keys are generated by creating a keypair, and then taking the first 20 bytes of the SHA-256 hash of the public key and encoding them to multibase RFC4648 base-32 format (prefixed with B, see Multibase Table).\n * @example BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE\n */\nexport type SpaceId = string & { __SpaceId: true };\n\nexport const SpaceId = Object.freeze({\n byteLength: 20,\n encode: (value: Uint8Array): SpaceId => {\n invariant(value instanceof Uint8Array, 'Invalid type');\n invariant(value.length === SpaceId.byteLength, 'Invalid length');\n\n return (MULTIBASE_PREFIX + base32Encode(value, 'RFC4648')) as SpaceId;\n },\n decode: (value: SpaceId): Uint8Array => {\n invariant(value.startsWith(MULTIBASE_PREFIX), 'Invalid multibase32 encoding');\n\n return new Uint8Array(base32Decode(value.slice(1), 'RFC4648'));\n },\n isValid: (value: string): value is SpaceId => {\n return typeof value === 'string' && value.startsWith(MULTIBASE_PREFIX) && value.length === ENCODED_LENGTH;\n },\n random: (): SpaceId => {\n return SpaceId.encode(randomBytes(SpaceId.byteLength));\n },\n});\n\n/**\n * Denotes RFC4648 base-32 format.\n */\nconst MULTIBASE_PREFIX = 'B';\n\nconst ENCODED_LENGTH = 33;\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { invariant } from '@dxos/invariant';\n\n/**\n * DXN unambiguously names a resource like an ECHO object, schema definition, plugin, etc.\n * Each DXN starts with a dx prefix, followed by a resource kind.\n * Colon Symbol : is used a delimiter between parts.\n * DXNs may contain slashes.\n * '@' in the place of the space id is used to denote that the DXN should be resolved in the local space.\n *\n * @example\n *\n * ```\n * dx:echo:<space key>:<echo id>\n * dx:echo:BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE:01J00J9B45YHYSGZQTQMSKMGJ6\n * dx:echo:@:01J00J9B45YHYSGZQTQMSKMGJ6\n * dx:type:dxos.org/type/Calendar\n * dx:plugin:dxos.org/agent/plugin/functions\n * ```\n */\nexport class DXN {\n /**\n * Kind constants.\n */\n static kind = Object.freeze({\n ECHO: 'echo',\n TYPE: 'type',\n });\n\n static parse(dxn: string): DXN {\n const [prefix, kind, ...parts] = dxn.split(':');\n if (!(prefix === 'dxn')) {\n throw new Error('Invalid DXN');\n }\n if (!(typeof kind === 'string' && kind.length > 0)) {\n throw new Error('Invalid DXN');\n }\n if (!(parts.length > 0)) {\n throw new Error('Invalid DXN');\n }\n return new DXN(kind, parts);\n }\n\n #kind: string;\n #parts: string[];\n\n constructor(kind: string, parts: string[]) {\n invariant(parts.length > 0);\n invariant(parts.every((part) => typeof part === 'string' && part.length > 0 && part.indexOf(':') === -1));\n\n // Per-type validation.\n switch (kind) {\n case DXN.kind.ECHO:\n invariant(parts.length === 2);\n break;\n case DXN.kind.TYPE:\n invariant(parts.length === 1);\n break;\n }\n\n this.#kind = kind;\n this.#parts = parts;\n }\n\n get kind() {\n return this.#kind;\n }\n\n get parts() {\n return this.#parts;\n }\n\n isTypeDXNOf(typename: string) {\n return this.#kind === DXN.kind.TYPE && this.#parts.length === 1 && this.#parts[0] === typename;\n }\n\n toString() {\n return `dxn:${this.#kind}:${this.#parts.join(':')}`;\n }\n}\n\n/**\n * Tags for ECHO DXNs that should resolve the object ID in the local space.\n */\nexport const LOCAL_SPACE_TAG = '@';\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;ACMA,uBAAqD;AAErD,mBAAqG;AACrG,uBAA0B;AIF1B,IAAAA,oBAA0B;ACH1B,IAAAA,oBAA0B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ANJ1B,IAAA,wBAAA,WAAA;EAAA,6EAAA,SAAAC,SAAA;AAAA,QAAIC,WAAU;AACd,QAAIC,eAAc;AAClB,QAAIC,aAAY;AAEhB,aAAS,SAAU,UAAU,MAAM;AACjC,UAAI,MAAM,SAAS,QAAQ,IAAI;AAE/B,UAAI,QAAQ,IAAI;AACd,cAAM,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F;AACb,SAAK,SAASM;EAChB;EAEA,IAAIN,OAAO;AACT,WAAO,KAAK;EACd;EAEA,IAAIM,QAAQ;AACV,WAAO,KAAK;EACd;EAEAK,YAAYC,UAAkB;AAC5B,WAAO,KAAK,UAAUb,KAAIC,KAAKE,QAAQ,KAAK,OAAOjG,WAAW,KAAK,KAAK,OAAO,CAAA,MAAO2G;EACxF;EAEA7D,WAAW;AACT,WAAO,OAAO,KAAK,KAAK,IAAI,KAAK,OAAO8D,KAAK,GAAA,CAAA;EAC/C;AACF;AAKO,IAAMC,kBAAkB;",
6
+ "names": ["import_invariant", "module", "RFC4648", "RFC4648_HEX", "CROCKFORD", "base32Decode", "randomBytes", "length", "webCrypto", "globalThis", "crypto", "require", "webcrypto", "bytes", "Uint8Array", "getRandomValues", "PUBLIC_KEY_LENGTH", "SECRET_KEY_LENGTH", "PublicKey", "from", "source", "invariant", "Buffer", "buffer", "byteOffset", "byteLength", "ArrayBuffer", "fromHex", "asUint8Array", "TypeError", "safeFrom", "undefined", "key", "err", "hex", "startsWith", "slice", "buf", "random", "randomOfLength", "randomSequence", "i", "Error", "isPublicKey", "value", "assertValidPublicKey", "equals", "left", "right", "bufferize", "str", "stringify", "asBuffer", "toString", "hash", "toHex", "fromMultibase32", "encoded", "constructor", "_value", "toJSON", "toJSONL", "truncate", "toMultibase32", "base32Encode", "truncateKey", "getInsecureHash", "modulo", "Math", "abs", "reduce", "acc", "val", "inspect", "custom", "depth", "options", "colors", "process", "stdout", "hasColors", "printControlCode", "code", "color", "reset", "devtoolsFormatter", "header", "style", "other", "otherConverted", "equal", "equalsSymbol", "import_base32_decode", "SpaceId", "Object", "freeze", "encode", "MULTIBASE_PREFIX", "decode", "isValid", "ENCODED_LENGTH", "DXN", "kind", "ECHO", "TYPE", "parse", "dxn", "prefix", "parts", "split", "every", "part", "indexOf", "isTypeDXNOf", "typename", "join", "LOCAL_SPACE_TAG"]
7
7
  }
@@ -1 +1 @@
1
- {"inputs":{"packages/common/keys/src/public-key.ts":{"bytes":29335,"imports":[{"path":"node:util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"node:crypto","kind":"require-call","external":true}],"format":"esm"},"packages/common/keys/src/types.ts":{"bytes":673,"imports":[],"format":"esm"},"packages/common/keys/src/index.ts":{"bytes":579,"imports":[{"path":"packages/common/keys/src/public-key.ts","kind":"import-statement","original":"./public-key"},{"path":"packages/common/keys/src/types.ts","kind":"import-statement","original":"./types"}],"format":"esm"}},"outputs":{"packages/common/keys/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":13772},"packages/common/keys/dist/lib/node/index.cjs":{"imports":[{"path":"node:util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"node:crypto","kind":"require-call","external":true}],"exports":["PUBLIC_KEY_LENGTH","PublicKey","SECRET_KEY_LENGTH"],"entryPoint":"packages/common/keys/src/index.ts","inputs":{"packages/common/keys/src/public-key.ts":{"bytesInOutput":7245},"packages/common/keys/src/index.ts":{"bytesInOutput":0}},"bytes":7758}}}
1
+ {"inputs":{"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js":{"bytes":1217,"imports":[],"format":"cjs"},"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js":{"bytes":410,"imports":[],"format":"esm"},"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js":{"bytes":1266,"imports":[{"path":"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js","kind":"import-statement","original":"to-data-view"}],"format":"esm"},"packages/common/keys/src/random-bytes.ts":{"bytes":1792,"imports":[{"path":"node:crypto","kind":"require-call","external":true}],"format":"esm"},"packages/common/keys/src/public-key.ts":{"bytes":30143,"imports":[{"path":"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js","kind":"import-statement","original":"base32-decode"},{"path":"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js","kind":"import-statement","original":"base32-encode"},{"path":"node:util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/common/keys/src/random-bytes.ts","kind":"import-statement","original":"./random-bytes"}],"format":"esm"},"packages/common/keys/src/types.ts":{"bytes":528,"imports":[],"format":"esm"},"packages/common/keys/src/space-id.ts":{"bytes":5162,"imports":[{"path":"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js","kind":"import-statement","original":"base32-decode"},{"path":"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js","kind":"import-statement","original":"base32-encode"},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"packages/common/keys/src/random-bytes.ts","kind":"import-statement","original":"./random-bytes"}],"format":"esm"},"packages/common/keys/src/dxn.ts":{"bytes":8722,"imports":[{"path":"@dxos/invariant","kind":"import-statement","external":true}],"format":"esm"},"packages/common/keys/src/index.ts":{"bytes":746,"imports":[{"path":"packages/common/keys/src/public-key.ts","kind":"import-statement","original":"./public-key"},{"path":"packages/common/keys/src/types.ts","kind":"import-statement","original":"./types"},{"path":"packages/common/keys/src/space-id.ts","kind":"import-statement","original":"./space-id"},{"path":"packages/common/keys/src/dxn.ts","kind":"import-statement","original":"./dxn"}],"format":"esm"}},"outputs":{"packages/common/keys/dist/lib/node/index.cjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":26254},"packages/common/keys/dist/lib/node/index.cjs":{"imports":[{"path":"node:util","kind":"import-statement","external":true},{"path":"@dxos/debug","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"node:crypto","kind":"require-call","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true}],"exports":["DXN","LOCAL_SPACE_TAG","PUBLIC_KEY_LENGTH","PublicKey","SECRET_KEY_LENGTH","SpaceId"],"entryPoint":"packages/common/keys/src/index.ts","inputs":{"node_modules/.pnpm/base32-decode@1.0.0/node_modules/base32-decode/index.js":{"bytesInOutput":1554},"packages/common/keys/src/public-key.ts":{"bytesInOutput":7643},"node_modules/.pnpm/to-data-view@2.0.0/node_modules/to-data-view/index.js":{"bytesInOutput":395},"node_modules/.pnpm/base32-encode@2.0.0/node_modules/base32-encode/index.js":{"bytesInOutput":1206},"packages/common/keys/src/random-bytes.ts":{"bytesInOutput":204},"packages/common/keys/src/index.ts":{"bytesInOutput":0},"packages/common/keys/src/space-id.ts":{"bytesInOutput":1431},"packages/common/keys/src/dxn.ts":{"bytesInOutput":2074}},"bytes":16821}}}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * DXN unambiguously names a resource like an ECHO object, schema definition, plugin, etc.
3
+ * Each DXN starts with a dx prefix, followed by a resource kind.
4
+ * Colon Symbol : is used a delimiter between parts.
5
+ * DXNs may contain slashes.
6
+ * '@' in the place of the space id is used to denote that the DXN should be resolved in the local space.
7
+ *
8
+ * @example
9
+ *
10
+ * ```
11
+ * dx:echo:<space key>:<echo id>
12
+ * dx:echo:BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE:01J00J9B45YHYSGZQTQMSKMGJ6
13
+ * dx:echo:@:01J00J9B45YHYSGZQTQMSKMGJ6
14
+ * dx:type:dxos.org/type/Calendar
15
+ * dx:plugin:dxos.org/agent/plugin/functions
16
+ * ```
17
+ */
18
+ export declare class DXN {
19
+ #private;
20
+ /**
21
+ * Kind constants.
22
+ */
23
+ static kind: Readonly<{
24
+ ECHO: "echo";
25
+ TYPE: "type";
26
+ }>;
27
+ static parse(dxn: string): DXN;
28
+ constructor(kind: string, parts: string[]);
29
+ get kind(): string;
30
+ get parts(): string[];
31
+ isTypeDXNOf(typename: string): boolean;
32
+ toString(): string;
33
+ }
34
+ /**
35
+ * Tags for ECHO DXNs that should resolve the object ID in the local space.
36
+ */
37
+ export declare const LOCAL_SPACE_TAG = "@";
38
+ //# sourceMappingURL=dxn.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dxn.d.ts","sourceRoot":"","sources":["../../../src/dxn.ts"],"names":[],"mappings":"AAMA;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,GAAG;;IACd;;OAEG;IACH,MAAM,CAAC,IAAI;;;OAGR;IAEH,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG;gBAiBlB,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE;IAkBzC,IAAI,IAAI,WAEP;IAED,IAAI,KAAK,aAER;IAED,WAAW,CAAC,QAAQ,EAAE,MAAM;IAI5B,QAAQ;CAGT;AAED;;GAEG;AACH,eAAO,MAAM,eAAe,MAAM,CAAC"}
@@ -1,3 +1,5 @@
1
1
  export * from './public-key';
2
2
  export * from './types';
3
+ export * from './space-id';
4
+ export * from './dxn';
3
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,OAAO,CAAC"}
@@ -35,6 +35,7 @@ export declare class PublicKey implements Equatable {
35
35
  * Creates a new key.
36
36
  */
37
37
  static random(): PublicKey;
38
+ static randomOfLength(length: number): PublicKey;
38
39
  static randomSequence(): Generator<PublicKey>;
39
40
  /**
40
41
  * Tests if provided values is an instance of PublicKey.
@@ -65,12 +66,14 @@ export declare class PublicKey implements Equatable {
65
66
  * Returns a scalar representation for this key.
66
67
  */
67
68
  static hash(key: PublicKey): string;
69
+ static fromMultibase32(encoded: string): PublicKey;
68
70
  constructor(_value: Uint8Array);
69
71
  toString(): string;
70
72
  toJSON(): string;
71
73
  toJSONL(): string;
72
74
  get length(): number;
73
75
  toHex(): string;
76
+ toMultibase32(): string;
74
77
  truncate(length?: undefined): string;
75
78
  asBuffer(): Buffer;
76
79
  asUint8Array(): Uint8Array;
@@ -1 +1 @@
1
- {"version":3,"file":"public-key.d.ts","sourceRoot":"","sources":["../../../src/public-key.ts"],"names":[],"mappings":";;AAIA,OAAO,EAAE,OAAO,EAAE,KAAK,sBAAsB,EAAE,MAAM,WAAW,CAAC;AAEjE,OAAO,EAAe,iBAAiB,EAAE,KAAK,iBAAiB,EAAE,YAAY,EAAE,KAAK,SAAS,EAAE,MAAM,aAAa,CAAC;AAGnH,eAAO,MAAM,iBAAiB,KAAK,CAAC;AACpC,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAEpC;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,SAAS,GAAG,MAAM,GAAG,UAAU,GAAG,WAAW,GAAG,MAAM,CAAC;AAEnF;;;;GAIG;AACH,qBAAa,SAAU,YAAW,SAAS;IAyI7B,OAAO,CAAC,QAAQ,CAAC,MAAM;IAxInC;;;;OAIG;IACH,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,aAAa,GAAG,SAAS;IAoB7C;;;;OAIG;IACH,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,aAAa,GAAG,SAAS,GAAG,SAAS;IAiB9D;;OAEG;IACH,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,MAAM;IAU1B;;OAEG;IACH,MAAM,CAAC,MAAM,IAAI,SAAS;IAK1B,MAAM,CAAE,cAAc,IAAI,SAAS,CAAC,SAAS,CAAC;IAQ9C;;OAEG;IACH,MAAM,CAAC,WAAW,CAAC,KAAK,EAAE,GAAG,GAAG,KAAK,IAAI,SAAS;IAIlD;;OAEG;IACH,MAAM,CAAC,oBAAoB,CAAC,KAAK,EAAE,GAAG,GAAG,OAAO,CAAC,KAAK,IAAI,SAAS;IAMnE;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,KAAK,IAAI,MAAM;IAIf,aAAa,IAAI,MAAM;IAIvB,QAAQ,CAAC,MAAM,YAAY;IAI3B,QAAQ,IAAI,MAAM;IAIlB,YAAY,IAAI,UAAU;IAI1B,eAAe,CAAC,MAAM,EAAE,MAAM;IAI9B;;OAEG;IACH,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,sBAAsB;IAgC/D,IAAI,CAAC,iBAAiB,CAAC,IAAI,iBAAiB,CA8B3C;IAED;;OAEG;IACH,MAAM,CAAC,KAAK,EAAE,aAAa;IAc3B,CAAC,YAAY,CAAC,CAAC,KAAK,EAAE,GAAG;CAO1B"}
@@ -0,0 +1,2 @@
1
+ export declare const randomBytes: (length: number) => Uint8Array;
2
+ //# sourceMappingURL=random-bytes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"random-bytes.d.ts","sourceRoot":"","sources":["../../../src/random-bytes.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,WAAW,WAAY,MAAM,eAQzC,CAAC"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * A unique identifier for a space.
3
+ * Space keys are generated by creating a keypair, and then taking the first 20 bytes of the SHA-256 hash of the public key and encoding them to multibase RFC4648 base-32 format (prefixed with B, see Multibase Table).
4
+ * @example BA25QRC2FEWCSAMRP4RZL65LWJ7352CKE
5
+ */
6
+ export type SpaceId = string & {
7
+ __SpaceId: true;
8
+ };
9
+ export declare const SpaceId: Readonly<{
10
+ byteLength: 20;
11
+ encode: (value: Uint8Array) => SpaceId;
12
+ decode: (value: SpaceId) => Uint8Array;
13
+ isValid: (value: string) => value is SpaceId;
14
+ random: () => SpaceId;
15
+ }>;
16
+ //# sourceMappingURL=space-id.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"space-id.d.ts","sourceRoot":"","sources":["../../../src/space-id.ts"],"names":[],"mappings":"AAWA;;;;GAIG;AACH,MAAM,MAAM,OAAO,GAAG,MAAM,GAAG;IAAE,SAAS,EAAE,IAAI,CAAA;CAAE,CAAC;AAEnD,eAAO,MAAM,OAAO;;oBAEF,UAAU,KAAG,OAAO;oBAMpB,OAAO,KAAG,UAAU;qBAKnB,MAAM;kBAGX,OAAO;EAGnB,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=space-id.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"space-id.test.d.ts","sourceRoot":"","sources":["../../../src/space-id.test.ts"],"names":[],"mappings":""}
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/types.ts"],"names":[],"mappings":";AAKA,MAAM,MAAM,OAAO,GAAG;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/types.ts"],"names":[],"mappings":";AAIA,MAAM,MAAM,OAAO,GAAG;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC"}