@did-btcr2/api 0.3.0 → 0.4.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.
Files changed (54) hide show
  1. package/dist/.tsbuildinfo +1 -0
  2. package/dist/browser.js +137973 -182733
  3. package/dist/browser.mjs +138027 -182787
  4. package/dist/cjs/index.js +2239 -14
  5. package/dist/esm/api.js +1 -1
  6. package/dist/esm/bitcoin.js.map +1 -1
  7. package/dist/esm/cas.js +7 -8
  8. package/dist/esm/cas.js.map +1 -1
  9. package/dist/esm/crypto.js.map +1 -1
  10. package/dist/esm/did.js.map +1 -1
  11. package/dist/esm/kms.js.map +1 -1
  12. package/dist/esm/method.js +5 -5
  13. package/dist/esm/method.js.map +1 -1
  14. package/dist/types/api.d.ts +3 -3
  15. package/dist/types/api.d.ts.map +1 -1
  16. package/dist/types/bitcoin.d.ts +2 -1
  17. package/dist/types/bitcoin.d.ts.map +1 -1
  18. package/dist/types/cas.d.ts +5 -4
  19. package/dist/types/cas.d.ts.map +1 -1
  20. package/dist/types/crypto.d.ts +4 -3
  21. package/dist/types/crypto.d.ts.map +1 -1
  22. package/dist/types/did.d.ts +1 -2
  23. package/dist/types/did.d.ts.map +1 -1
  24. package/dist/types/kms.d.ts +3 -2
  25. package/dist/types/kms.d.ts.map +1 -1
  26. package/dist/types/method.d.ts +5 -5
  27. package/dist/types/method.d.ts.map +1 -1
  28. package/package.json +9 -8
  29. package/src/api.ts +3 -3
  30. package/src/bitcoin.ts +3 -2
  31. package/src/cas.ts +8 -8
  32. package/src/crypto.ts +10 -8
  33. package/src/did.ts +2 -2
  34. package/src/kms.ts +4 -3
  35. package/src/method.ts +9 -9
  36. package/dist/cjs/api.js +0 -240
  37. package/dist/cjs/api.js.map +0 -1
  38. package/dist/cjs/bitcoin.js +0 -110
  39. package/dist/cjs/bitcoin.js.map +0 -1
  40. package/dist/cjs/cas.js +0 -90
  41. package/dist/cjs/cas.js.map +0 -1
  42. package/dist/cjs/crypto.js +0 -425
  43. package/dist/cjs/crypto.js.map +0 -1
  44. package/dist/cjs/did.js +0 -70
  45. package/dist/cjs/did.js.map +0 -1
  46. package/dist/cjs/helpers.js +0 -28
  47. package/dist/cjs/helpers.js.map +0 -1
  48. package/dist/cjs/index.js.map +0 -1
  49. package/dist/cjs/kms.js +0 -73
  50. package/dist/cjs/kms.js.map +0 -1
  51. package/dist/cjs/method.js +0 -262
  52. package/dist/cjs/method.js.map +0 -1
  53. package/dist/cjs/types.js +0 -2
  54. package/dist/cjs/types.js.map +0 -1
package/dist/cjs/index.js CHANGED
@@ -1,14 +1,2239 @@
1
- // Upstream re-exports
2
- export { DidDocument, DidDocumentBuilder, Identifier } from '@did-btcr2/method';
3
- export { IdentifierTypes } from '@did-btcr2/common';
4
- // Local modules
5
- export * from './types.js';
6
- export * from './helpers.js';
7
- export * from './bitcoin.js';
8
- export * from './cas.js';
9
- export * from './kms.js';
10
- export * from './crypto.js';
11
- export * from './did.js';
12
- export * from './method.js';
13
- export * from './api.js';
14
- //# sourceMappingURL=index.js.map
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from3, except, desc) => {
13
+ if (from3 && typeof from3 === "object" || typeof from3 === "function") {
14
+ for (let key of __getOwnPropNames(from3))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from3[key], enumerable: !(desc = __getOwnPropDesc(from3, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ BitcoinApi: () => BitcoinApi,
34
+ CasApi: () => CasApi,
35
+ CryptoApi: () => CryptoApi,
36
+ CryptosuiteApi: () => CryptosuiteApi,
37
+ DataIntegrityProofApi: () => DataIntegrityProofApi,
38
+ DidApi: () => DidApi,
39
+ DidBtcr2Api: () => DidBtcr2Api,
40
+ DidDocument: () => import_method4.DidDocument,
41
+ DidDocumentBuilder: () => import_method4.DidDocumentBuilder,
42
+ DidMethodApi: () => DidMethodApi,
43
+ Identifier: () => import_method4.Identifier,
44
+ IdentifierTypes: () => import_common4.IdentifierTypes,
45
+ IpfsCasExecutor: () => IpfsCasExecutor,
46
+ KeyManagerApi: () => KeyManagerApi,
47
+ KeyPairApi: () => KeyPairApi,
48
+ MultikeyApi: () => MultikeyApi,
49
+ NOOP_LOGGER: () => NOOP_LOGGER,
50
+ UpdateBuilder: () => UpdateBuilder,
51
+ assertBytes: () => assertBytes,
52
+ assertCompressedPubkey: () => assertCompressedPubkey,
53
+ assertString: () => assertString,
54
+ createApi: () => createApi
55
+ });
56
+ module.exports = __toCommonJS(index_exports);
57
+ var import_method4 = require("@did-btcr2/method");
58
+ var import_common4 = require("@did-btcr2/common");
59
+
60
+ // src/helpers.ts
61
+ var noopFn = () => {
62
+ };
63
+ var NOOP_LOGGER = {
64
+ debug: noopFn,
65
+ info: noopFn,
66
+ warn: noopFn,
67
+ error: noopFn
68
+ };
69
+ function assertString(value, name) {
70
+ if (typeof value !== "string" || value.length === 0) {
71
+ throw new Error(`${name} must be a non-empty string.`);
72
+ }
73
+ }
74
+ function assertBytes(value, name) {
75
+ if (!(value instanceof Uint8Array) || value.length === 0) {
76
+ throw new Error(`${name} must be a non-empty Uint8Array.`);
77
+ }
78
+ }
79
+ function assertCompressedPubkey(value, name) {
80
+ assertBytes(value, name);
81
+ if (value.length !== 33) {
82
+ throw new Error(
83
+ `${name} must be a 33-byte compressed public key, got ${value.length} bytes.`
84
+ );
85
+ }
86
+ }
87
+
88
+ // src/bitcoin.ts
89
+ var import_bitcoin = require("@did-btcr2/bitcoin");
90
+ var BitcoinApi = class {
91
+ /** The underlying BitcoinConnection used for all operations. */
92
+ connection;
93
+ /** REST client for the active network. */
94
+ get rest() {
95
+ return this.connection.rest;
96
+ }
97
+ /**
98
+ * RPC client for the active network, or `undefined` if not configured.
99
+ * Use {@link requireRpc} when RPC is expected to be available.
100
+ */
101
+ get rpc() {
102
+ return this.connection.rpc;
103
+ }
104
+ /** Whether an RPC client is available for this network. */
105
+ get hasRpc() {
106
+ return this.connection.rpc !== void 0;
107
+ }
108
+ /**
109
+ * RPC client for the active network.
110
+ * @throws {Error} If RPC was not configured for this network.
111
+ */
112
+ requireRpc() {
113
+ const client = this.connection.rpc;
114
+ if (!client) {
115
+ throw new Error(
116
+ "RPC client not configured. Pass an rpc config when creating the BitcoinApi, e.g.: { network: 'regtest', rpc: { host: 'http://localhost:18443', username: 'u', password: 'p' } }"
117
+ );
118
+ }
119
+ return client;
120
+ }
121
+ /**
122
+ * Create a BitcoinApi for a specific network with optional endpoint overrides.
123
+ * Uses BitcoinConnection.forNetwork() — no env vars consulted.
124
+ * @param cfg The network and optional REST/RPC overrides.
125
+ */
126
+ constructor(cfg) {
127
+ let executor = cfg.executor;
128
+ if (!executor && cfg.timeoutMs !== void 0) {
129
+ const ms = cfg.timeoutMs;
130
+ executor = (req) => fetch(req.url, {
131
+ method: req.method,
132
+ headers: req.headers,
133
+ body: req.body,
134
+ signal: AbortSignal.timeout(ms)
135
+ });
136
+ }
137
+ this.connection = import_bitcoin.BitcoinConnection.forNetwork(cfg.network, {
138
+ rest: cfg.rest,
139
+ rpc: cfg.rpc,
140
+ executor
141
+ });
142
+ }
143
+ /**
144
+ * Fetch a transaction by txid via REST.
145
+ * @param txid The transaction ID (64-character hex string).
146
+ * @returns The fetched transaction.
147
+ */
148
+ async getTransaction(txid) {
149
+ assertString(txid, "txid");
150
+ return await this.rest.transaction.get(txid);
151
+ }
152
+ /**
153
+ * Broadcast a raw tx (hex) via REST.
154
+ * @param rawTxHex The raw transaction hex string.
155
+ */
156
+ async send(rawTxHex) {
157
+ assertString(rawTxHex, "rawTxHex");
158
+ return await this.rest.transaction.send(rawTxHex);
159
+ }
160
+ /**
161
+ * Get UTXOs for an address via REST.
162
+ * @param address The Bitcoin address.
163
+ */
164
+ async getUtxos(address) {
165
+ assertString(address, "address");
166
+ return await this.rest.address.getUtxos(address);
167
+ }
168
+ /**
169
+ * Get a block by hash or height via REST.
170
+ * @param params Block identifier — at least one of `hash` or `height` is required.
171
+ */
172
+ async getBlock(params) {
173
+ if (!params.hash && params.height === void 0) {
174
+ throw new Error("getBlock requires at least one of hash or height.");
175
+ }
176
+ return await this.rest.block.get({ blockhash: params.hash, height: params.height });
177
+ }
178
+ /** Convert BTC to satoshis (integer-safe string-split arithmetic). */
179
+ static btcToSats(btc) {
180
+ return import_bitcoin.BitcoinConnection.btcToSats(btc);
181
+ }
182
+ /** Convert satoshis to BTC (integer-safe string-split arithmetic). */
183
+ static satsToBtc(sats) {
184
+ return import_bitcoin.BitcoinConnection.satsToBtc(sats);
185
+ }
186
+ };
187
+
188
+ // src/cas.ts
189
+ var import_common = require("@did-btcr2/common");
190
+
191
+ // ../../node_modules/.pnpm/multiformats@13.4.1/node_modules/multiformats/dist/src/bytes.js
192
+ var empty = new Uint8Array(0);
193
+ function equals(aa, bb) {
194
+ if (aa === bb) {
195
+ return true;
196
+ }
197
+ if (aa.byteLength !== bb.byteLength) {
198
+ return false;
199
+ }
200
+ for (let ii = 0; ii < aa.byteLength; ii++) {
201
+ if (aa[ii] !== bb[ii]) {
202
+ return false;
203
+ }
204
+ }
205
+ return true;
206
+ }
207
+ function coerce(o) {
208
+ if (o instanceof Uint8Array && o.constructor.name === "Uint8Array") {
209
+ return o;
210
+ }
211
+ if (o instanceof ArrayBuffer) {
212
+ return new Uint8Array(o);
213
+ }
214
+ if (ArrayBuffer.isView(o)) {
215
+ return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
216
+ }
217
+ throw new Error("Unknown type, must be binary type");
218
+ }
219
+
220
+ // ../../node_modules/.pnpm/multiformats@13.4.1/node_modules/multiformats/dist/src/vendor/base-x.js
221
+ function base(ALPHABET, name) {
222
+ if (ALPHABET.length >= 255) {
223
+ throw new TypeError("Alphabet too long");
224
+ }
225
+ var BASE_MAP = new Uint8Array(256);
226
+ for (var j = 0; j < BASE_MAP.length; j++) {
227
+ BASE_MAP[j] = 255;
228
+ }
229
+ for (var i = 0; i < ALPHABET.length; i++) {
230
+ var x = ALPHABET.charAt(i);
231
+ var xc = x.charCodeAt(0);
232
+ if (BASE_MAP[xc] !== 255) {
233
+ throw new TypeError(x + " is ambiguous");
234
+ }
235
+ BASE_MAP[xc] = i;
236
+ }
237
+ var BASE = ALPHABET.length;
238
+ var LEADER = ALPHABET.charAt(0);
239
+ var FACTOR = Math.log(BASE) / Math.log(256);
240
+ var iFACTOR = Math.log(256) / Math.log(BASE);
241
+ function encode3(source) {
242
+ if (source instanceof Uint8Array)
243
+ ;
244
+ else if (ArrayBuffer.isView(source)) {
245
+ source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
246
+ } else if (Array.isArray(source)) {
247
+ source = Uint8Array.from(source);
248
+ }
249
+ if (!(source instanceof Uint8Array)) {
250
+ throw new TypeError("Expected Uint8Array");
251
+ }
252
+ if (source.length === 0) {
253
+ return "";
254
+ }
255
+ var zeroes = 0;
256
+ var length2 = 0;
257
+ var pbegin = 0;
258
+ var pend = source.length;
259
+ while (pbegin !== pend && source[pbegin] === 0) {
260
+ pbegin++;
261
+ zeroes++;
262
+ }
263
+ var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
264
+ var b58 = new Uint8Array(size);
265
+ while (pbegin !== pend) {
266
+ var carry = source[pbegin];
267
+ var i2 = 0;
268
+ for (var it1 = size - 1; (carry !== 0 || i2 < length2) && it1 !== -1; it1--, i2++) {
269
+ carry += 256 * b58[it1] >>> 0;
270
+ b58[it1] = carry % BASE >>> 0;
271
+ carry = carry / BASE >>> 0;
272
+ }
273
+ if (carry !== 0) {
274
+ throw new Error("Non-zero carry");
275
+ }
276
+ length2 = i2;
277
+ pbegin++;
278
+ }
279
+ var it2 = size - length2;
280
+ while (it2 !== size && b58[it2] === 0) {
281
+ it2++;
282
+ }
283
+ var str = LEADER.repeat(zeroes);
284
+ for (; it2 < size; ++it2) {
285
+ str += ALPHABET.charAt(b58[it2]);
286
+ }
287
+ return str;
288
+ }
289
+ function decodeUnsafe(source) {
290
+ if (typeof source !== "string") {
291
+ throw new TypeError("Expected String");
292
+ }
293
+ if (source.length === 0) {
294
+ return new Uint8Array();
295
+ }
296
+ var psz = 0;
297
+ if (source[psz] === " ") {
298
+ return;
299
+ }
300
+ var zeroes = 0;
301
+ var length2 = 0;
302
+ while (source[psz] === LEADER) {
303
+ zeroes++;
304
+ psz++;
305
+ }
306
+ var size = (source.length - psz) * FACTOR + 1 >>> 0;
307
+ var b256 = new Uint8Array(size);
308
+ while (source[psz]) {
309
+ var carry = BASE_MAP[source.charCodeAt(psz)];
310
+ if (carry === 255) {
311
+ return;
312
+ }
313
+ var i2 = 0;
314
+ for (var it3 = size - 1; (carry !== 0 || i2 < length2) && it3 !== -1; it3--, i2++) {
315
+ carry += BASE * b256[it3] >>> 0;
316
+ b256[it3] = carry % 256 >>> 0;
317
+ carry = carry / 256 >>> 0;
318
+ }
319
+ if (carry !== 0) {
320
+ throw new Error("Non-zero carry");
321
+ }
322
+ length2 = i2;
323
+ psz++;
324
+ }
325
+ if (source[psz] === " ") {
326
+ return;
327
+ }
328
+ var it4 = size - length2;
329
+ while (it4 !== size && b256[it4] === 0) {
330
+ it4++;
331
+ }
332
+ var vch = new Uint8Array(zeroes + (size - it4));
333
+ var j2 = zeroes;
334
+ while (it4 !== size) {
335
+ vch[j2++] = b256[it4++];
336
+ }
337
+ return vch;
338
+ }
339
+ function decode5(string) {
340
+ var buffer = decodeUnsafe(string);
341
+ if (buffer) {
342
+ return buffer;
343
+ }
344
+ throw new Error(`Non-${name} character`);
345
+ }
346
+ return {
347
+ encode: encode3,
348
+ decodeUnsafe,
349
+ decode: decode5
350
+ };
351
+ }
352
+ var src = base;
353
+ var _brrp__multiformats_scope_baseX = src;
354
+ var base_x_default = _brrp__multiformats_scope_baseX;
355
+
356
+ // ../../node_modules/.pnpm/multiformats@13.4.1/node_modules/multiformats/dist/src/bases/base.js
357
+ var Encoder = class {
358
+ name;
359
+ prefix;
360
+ baseEncode;
361
+ constructor(name, prefix, baseEncode) {
362
+ this.name = name;
363
+ this.prefix = prefix;
364
+ this.baseEncode = baseEncode;
365
+ }
366
+ encode(bytes) {
367
+ if (bytes instanceof Uint8Array) {
368
+ return `${this.prefix}${this.baseEncode(bytes)}`;
369
+ } else {
370
+ throw Error("Unknown type, must be binary type");
371
+ }
372
+ }
373
+ };
374
+ var Decoder = class {
375
+ name;
376
+ prefix;
377
+ baseDecode;
378
+ prefixCodePoint;
379
+ constructor(name, prefix, baseDecode) {
380
+ this.name = name;
381
+ this.prefix = prefix;
382
+ const prefixCodePoint = prefix.codePointAt(0);
383
+ if (prefixCodePoint === void 0) {
384
+ throw new Error("Invalid prefix character");
385
+ }
386
+ this.prefixCodePoint = prefixCodePoint;
387
+ this.baseDecode = baseDecode;
388
+ }
389
+ decode(text) {
390
+ if (typeof text === "string") {
391
+ if (text.codePointAt(0) !== this.prefixCodePoint) {
392
+ throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
393
+ }
394
+ return this.baseDecode(text.slice(this.prefix.length));
395
+ } else {
396
+ throw Error("Can only multibase decode strings");
397
+ }
398
+ }
399
+ or(decoder) {
400
+ return or(this, decoder);
401
+ }
402
+ };
403
+ var ComposedDecoder = class {
404
+ decoders;
405
+ constructor(decoders) {
406
+ this.decoders = decoders;
407
+ }
408
+ or(decoder) {
409
+ return or(this, decoder);
410
+ }
411
+ decode(input) {
412
+ const prefix = input[0];
413
+ const decoder = this.decoders[prefix];
414
+ if (decoder != null) {
415
+ return decoder.decode(input);
416
+ } else {
417
+ throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
418
+ }
419
+ }
420
+ };
421
+ function or(left, right) {
422
+ return new ComposedDecoder({
423
+ ...left.decoders ?? { [left.prefix]: left },
424
+ ...right.decoders ?? { [right.prefix]: right }
425
+ });
426
+ }
427
+ var Codec = class {
428
+ name;
429
+ prefix;
430
+ baseEncode;
431
+ baseDecode;
432
+ encoder;
433
+ decoder;
434
+ constructor(name, prefix, baseEncode, baseDecode) {
435
+ this.name = name;
436
+ this.prefix = prefix;
437
+ this.baseEncode = baseEncode;
438
+ this.baseDecode = baseDecode;
439
+ this.encoder = new Encoder(name, prefix, baseEncode);
440
+ this.decoder = new Decoder(name, prefix, baseDecode);
441
+ }
442
+ encode(input) {
443
+ return this.encoder.encode(input);
444
+ }
445
+ decode(input) {
446
+ return this.decoder.decode(input);
447
+ }
448
+ };
449
+ function from({ name, prefix, encode: encode3, decode: decode5 }) {
450
+ return new Codec(name, prefix, encode3, decode5);
451
+ }
452
+ function baseX({ name, prefix, alphabet }) {
453
+ const { encode: encode3, decode: decode5 } = base_x_default(alphabet, name);
454
+ return from({
455
+ prefix,
456
+ name,
457
+ encode: encode3,
458
+ decode: (text) => coerce(decode5(text))
459
+ });
460
+ }
461
+ function decode(string, alphabetIdx, bitsPerChar, name) {
462
+ let end = string.length;
463
+ while (string[end - 1] === "=") {
464
+ --end;
465
+ }
466
+ const out = new Uint8Array(end * bitsPerChar / 8 | 0);
467
+ let bits = 0;
468
+ let buffer = 0;
469
+ let written = 0;
470
+ for (let i = 0; i < end; ++i) {
471
+ const value = alphabetIdx[string[i]];
472
+ if (value === void 0) {
473
+ throw new SyntaxError(`Non-${name} character`);
474
+ }
475
+ buffer = buffer << bitsPerChar | value;
476
+ bits += bitsPerChar;
477
+ if (bits >= 8) {
478
+ bits -= 8;
479
+ out[written++] = 255 & buffer >> bits;
480
+ }
481
+ }
482
+ if (bits >= bitsPerChar || (255 & buffer << 8 - bits) !== 0) {
483
+ throw new SyntaxError("Unexpected end of data");
484
+ }
485
+ return out;
486
+ }
487
+ function encode(data, alphabet, bitsPerChar) {
488
+ const pad = alphabet[alphabet.length - 1] === "=";
489
+ const mask = (1 << bitsPerChar) - 1;
490
+ let out = "";
491
+ let bits = 0;
492
+ let buffer = 0;
493
+ for (let i = 0; i < data.length; ++i) {
494
+ buffer = buffer << 8 | data[i];
495
+ bits += 8;
496
+ while (bits > bitsPerChar) {
497
+ bits -= bitsPerChar;
498
+ out += alphabet[mask & buffer >> bits];
499
+ }
500
+ }
501
+ if (bits !== 0) {
502
+ out += alphabet[mask & buffer << bitsPerChar - bits];
503
+ }
504
+ if (pad) {
505
+ while ((out.length * bitsPerChar & 7) !== 0) {
506
+ out += "=";
507
+ }
508
+ }
509
+ return out;
510
+ }
511
+ function createAlphabetIdx(alphabet) {
512
+ const alphabetIdx = {};
513
+ for (let i = 0; i < alphabet.length; ++i) {
514
+ alphabetIdx[alphabet[i]] = i;
515
+ }
516
+ return alphabetIdx;
517
+ }
518
+ function rfc4648({ name, prefix, bitsPerChar, alphabet }) {
519
+ const alphabetIdx = createAlphabetIdx(alphabet);
520
+ return from({
521
+ prefix,
522
+ name,
523
+ encode(input) {
524
+ return encode(input, alphabet, bitsPerChar);
525
+ },
526
+ decode(input) {
527
+ return decode(input, alphabetIdx, bitsPerChar, name);
528
+ }
529
+ });
530
+ }
531
+
532
+ // ../../node_modules/.pnpm/multiformats@13.4.1/node_modules/multiformats/dist/src/bases/base32.js
533
+ var base32 = rfc4648({
534
+ prefix: "b",
535
+ name: "base32",
536
+ alphabet: "abcdefghijklmnopqrstuvwxyz234567",
537
+ bitsPerChar: 5
538
+ });
539
+ var base32upper = rfc4648({
540
+ prefix: "B",
541
+ name: "base32upper",
542
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
543
+ bitsPerChar: 5
544
+ });
545
+ var base32pad = rfc4648({
546
+ prefix: "c",
547
+ name: "base32pad",
548
+ alphabet: "abcdefghijklmnopqrstuvwxyz234567=",
549
+ bitsPerChar: 5
550
+ });
551
+ var base32padupper = rfc4648({
552
+ prefix: "C",
553
+ name: "base32padupper",
554
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",
555
+ bitsPerChar: 5
556
+ });
557
+ var base32hex = rfc4648({
558
+ prefix: "v",
559
+ name: "base32hex",
560
+ alphabet: "0123456789abcdefghijklmnopqrstuv",
561
+ bitsPerChar: 5
562
+ });
563
+ var base32hexupper = rfc4648({
564
+ prefix: "V",
565
+ name: "base32hexupper",
566
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV",
567
+ bitsPerChar: 5
568
+ });
569
+ var base32hexpad = rfc4648({
570
+ prefix: "t",
571
+ name: "base32hexpad",
572
+ alphabet: "0123456789abcdefghijklmnopqrstuv=",
573
+ bitsPerChar: 5
574
+ });
575
+ var base32hexpadupper = rfc4648({
576
+ prefix: "T",
577
+ name: "base32hexpadupper",
578
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=",
579
+ bitsPerChar: 5
580
+ });
581
+ var base32z = rfc4648({
582
+ prefix: "h",
583
+ name: "base32z",
584
+ alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769",
585
+ bitsPerChar: 5
586
+ });
587
+
588
+ // ../../node_modules/.pnpm/multiformats@13.4.1/node_modules/multiformats/dist/src/bases/base36.js
589
+ var base36 = baseX({
590
+ prefix: "k",
591
+ name: "base36",
592
+ alphabet: "0123456789abcdefghijklmnopqrstuvwxyz"
593
+ });
594
+ var base36upper = baseX({
595
+ prefix: "K",
596
+ name: "base36upper",
597
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
598
+ });
599
+
600
+ // ../../node_modules/.pnpm/multiformats@13.4.1/node_modules/multiformats/dist/src/bases/base58.js
601
+ var base58btc = baseX({
602
+ name: "base58btc",
603
+ prefix: "z",
604
+ alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
605
+ });
606
+ var base58flickr = baseX({
607
+ name: "base58flickr",
608
+ prefix: "Z",
609
+ alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
610
+ });
611
+
612
+ // ../../node_modules/.pnpm/multiformats@13.4.1/node_modules/multiformats/dist/src/vendor/varint.js
613
+ var encode_1 = encode2;
614
+ var MSB = 128;
615
+ var REST = 127;
616
+ var MSBALL = ~REST;
617
+ var INT = Math.pow(2, 31);
618
+ function encode2(num, out, offset) {
619
+ out = out || [];
620
+ offset = offset || 0;
621
+ var oldOffset = offset;
622
+ while (num >= INT) {
623
+ out[offset++] = num & 255 | MSB;
624
+ num /= 128;
625
+ }
626
+ while (num & MSBALL) {
627
+ out[offset++] = num & 255 | MSB;
628
+ num >>>= 7;
629
+ }
630
+ out[offset] = num | 0;
631
+ encode2.bytes = offset - oldOffset + 1;
632
+ return out;
633
+ }
634
+ var decode2 = read;
635
+ var MSB$1 = 128;
636
+ var REST$1 = 127;
637
+ function read(buf, offset) {
638
+ var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
639
+ do {
640
+ if (counter >= l) {
641
+ read.bytes = 0;
642
+ throw new RangeError("Could not decode varint");
643
+ }
644
+ b = buf[counter++];
645
+ res += shift < 28 ? (b & REST$1) << shift : (b & REST$1) * Math.pow(2, shift);
646
+ shift += 7;
647
+ } while (b >= MSB$1);
648
+ read.bytes = counter - offset;
649
+ return res;
650
+ }
651
+ var N1 = Math.pow(2, 7);
652
+ var N2 = Math.pow(2, 14);
653
+ var N3 = Math.pow(2, 21);
654
+ var N4 = Math.pow(2, 28);
655
+ var N5 = Math.pow(2, 35);
656
+ var N6 = Math.pow(2, 42);
657
+ var N7 = Math.pow(2, 49);
658
+ var N8 = Math.pow(2, 56);
659
+ var N9 = Math.pow(2, 63);
660
+ var length = function(value) {
661
+ return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10;
662
+ };
663
+ var varint = {
664
+ encode: encode_1,
665
+ decode: decode2,
666
+ encodingLength: length
667
+ };
668
+ var _brrp_varint = varint;
669
+ var varint_default = _brrp_varint;
670
+
671
+ // ../../node_modules/.pnpm/multiformats@13.4.1/node_modules/multiformats/dist/src/varint.js
672
+ function decode3(data, offset = 0) {
673
+ const code2 = varint_default.decode(data, offset);
674
+ return [code2, varint_default.decode.bytes];
675
+ }
676
+ function encodeTo(int, target, offset = 0) {
677
+ varint_default.encode(int, target, offset);
678
+ return target;
679
+ }
680
+ function encodingLength(int) {
681
+ return varint_default.encodingLength(int);
682
+ }
683
+
684
+ // ../../node_modules/.pnpm/multiformats@13.4.1/node_modules/multiformats/dist/src/hashes/digest.js
685
+ function create(code2, digest) {
686
+ const size = digest.byteLength;
687
+ const sizeOffset = encodingLength(code2);
688
+ const digestOffset = sizeOffset + encodingLength(size);
689
+ const bytes = new Uint8Array(digestOffset + size);
690
+ encodeTo(code2, bytes, 0);
691
+ encodeTo(size, bytes, sizeOffset);
692
+ bytes.set(digest, digestOffset);
693
+ return new Digest(code2, size, digest, bytes);
694
+ }
695
+ function decode4(multihash) {
696
+ const bytes = coerce(multihash);
697
+ const [code2, sizeOffset] = decode3(bytes);
698
+ const [size, digestOffset] = decode3(bytes.subarray(sizeOffset));
699
+ const digest = bytes.subarray(sizeOffset + digestOffset);
700
+ if (digest.byteLength !== size) {
701
+ throw new Error("Incorrect length");
702
+ }
703
+ return new Digest(code2, size, digest, bytes);
704
+ }
705
+ function equals2(a, b) {
706
+ if (a === b) {
707
+ return true;
708
+ } else {
709
+ const data = b;
710
+ return a.code === data.code && a.size === data.size && data.bytes instanceof Uint8Array && equals(a.bytes, data.bytes);
711
+ }
712
+ }
713
+ var Digest = class {
714
+ code;
715
+ size;
716
+ digest;
717
+ bytes;
718
+ /**
719
+ * Creates a multihash digest.
720
+ */
721
+ constructor(code2, size, digest, bytes) {
722
+ this.code = code2;
723
+ this.size = size;
724
+ this.digest = digest;
725
+ this.bytes = bytes;
726
+ }
727
+ };
728
+
729
+ // ../../node_modules/.pnpm/multiformats@13.4.1/node_modules/multiformats/dist/src/cid.js
730
+ function format(link, base2) {
731
+ const { bytes, version } = link;
732
+ switch (version) {
733
+ case 0:
734
+ return toStringV0(bytes, baseCache(link), base2 ?? base58btc.encoder);
735
+ default:
736
+ return toStringV1(bytes, baseCache(link), base2 ?? base32.encoder);
737
+ }
738
+ }
739
+ var cache = /* @__PURE__ */ new WeakMap();
740
+ function baseCache(cid) {
741
+ const baseCache2 = cache.get(cid);
742
+ if (baseCache2 == null) {
743
+ const baseCache3 = /* @__PURE__ */ new Map();
744
+ cache.set(cid, baseCache3);
745
+ return baseCache3;
746
+ }
747
+ return baseCache2;
748
+ }
749
+ var CID = class _CID {
750
+ code;
751
+ version;
752
+ multihash;
753
+ bytes;
754
+ "/";
755
+ /**
756
+ * @param version - Version of the CID
757
+ * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
758
+ * @param multihash - (Multi)hash of the of the content.
759
+ */
760
+ constructor(version, code2, multihash, bytes) {
761
+ this.code = code2;
762
+ this.version = version;
763
+ this.multihash = multihash;
764
+ this.bytes = bytes;
765
+ this["/"] = bytes;
766
+ }
767
+ /**
768
+ * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
769
+ * please either use `CID.asCID(cid)` or switch to new signalling mechanism
770
+ *
771
+ * @deprecated
772
+ */
773
+ get asCID() {
774
+ return this;
775
+ }
776
+ // ArrayBufferView
777
+ get byteOffset() {
778
+ return this.bytes.byteOffset;
779
+ }
780
+ // ArrayBufferView
781
+ get byteLength() {
782
+ return this.bytes.byteLength;
783
+ }
784
+ toV0() {
785
+ switch (this.version) {
786
+ case 0: {
787
+ return this;
788
+ }
789
+ case 1: {
790
+ const { code: code2, multihash } = this;
791
+ if (code2 !== DAG_PB_CODE) {
792
+ throw new Error("Cannot convert a non dag-pb CID to CIDv0");
793
+ }
794
+ if (multihash.code !== SHA_256_CODE) {
795
+ throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");
796
+ }
797
+ return _CID.createV0(multihash);
798
+ }
799
+ default: {
800
+ throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
801
+ }
802
+ }
803
+ }
804
+ toV1() {
805
+ switch (this.version) {
806
+ case 0: {
807
+ const { code: code2, digest } = this.multihash;
808
+ const multihash = create(code2, digest);
809
+ return _CID.createV1(this.code, multihash);
810
+ }
811
+ case 1: {
812
+ return this;
813
+ }
814
+ default: {
815
+ throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
816
+ }
817
+ }
818
+ }
819
+ equals(other) {
820
+ return _CID.equals(this, other);
821
+ }
822
+ static equals(self, other) {
823
+ const unknown = other;
824
+ return unknown != null && self.code === unknown.code && self.version === unknown.version && equals2(self.multihash, unknown.multihash);
825
+ }
826
+ toString(base2) {
827
+ return format(this, base2);
828
+ }
829
+ toJSON() {
830
+ return { "/": format(this) };
831
+ }
832
+ link() {
833
+ return this;
834
+ }
835
+ [Symbol.toStringTag] = "CID";
836
+ // Legacy
837
+ [Symbol.for("nodejs.util.inspect.custom")]() {
838
+ return `CID(${this.toString()})`;
839
+ }
840
+ /**
841
+ * Takes any input `value` and returns a `CID` instance if it was
842
+ * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
843
+ * it will return value back. If `value` is not instance of this CID
844
+ * class, but is compatible CID it will return new instance of this
845
+ * `CID` class. Otherwise returns null.
846
+ *
847
+ * This allows two different incompatible versions of CID library to
848
+ * co-exist and interop as long as binary interface is compatible.
849
+ */
850
+ static asCID(input) {
851
+ if (input == null) {
852
+ return null;
853
+ }
854
+ const value = input;
855
+ if (value instanceof _CID) {
856
+ return value;
857
+ } else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) {
858
+ const { version, code: code2, multihash, bytes } = value;
859
+ return new _CID(version, code2, multihash, bytes ?? encodeCID(version, code2, multihash.bytes));
860
+ } else if (value[cidSymbol] === true) {
861
+ const { version, multihash, code: code2 } = value;
862
+ const digest = decode4(multihash);
863
+ return _CID.create(version, code2, digest);
864
+ } else {
865
+ return null;
866
+ }
867
+ }
868
+ /**
869
+ * @param version - Version of the CID
870
+ * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
871
+ * @param digest - (Multi)hash of the of the content.
872
+ */
873
+ static create(version, code2, digest) {
874
+ if (typeof code2 !== "number") {
875
+ throw new Error("String codecs are no longer supported");
876
+ }
877
+ if (!(digest.bytes instanceof Uint8Array)) {
878
+ throw new Error("Invalid digest");
879
+ }
880
+ switch (version) {
881
+ case 0: {
882
+ if (code2 !== DAG_PB_CODE) {
883
+ throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
884
+ } else {
885
+ return new _CID(version, code2, digest, digest.bytes);
886
+ }
887
+ }
888
+ case 1: {
889
+ const bytes = encodeCID(version, code2, digest.bytes);
890
+ return new _CID(version, code2, digest, bytes);
891
+ }
892
+ default: {
893
+ throw new Error("Invalid version");
894
+ }
895
+ }
896
+ }
897
+ /**
898
+ * Simplified version of `create` for CIDv0.
899
+ */
900
+ static createV0(digest) {
901
+ return _CID.create(0, DAG_PB_CODE, digest);
902
+ }
903
+ /**
904
+ * Simplified version of `create` for CIDv1.
905
+ *
906
+ * @param code - Content encoding format code.
907
+ * @param digest - Multihash of the content.
908
+ */
909
+ static createV1(code2, digest) {
910
+ return _CID.create(1, code2, digest);
911
+ }
912
+ /**
913
+ * Decoded a CID from its binary representation. The byte array must contain
914
+ * only the CID with no additional bytes.
915
+ *
916
+ * An error will be thrown if the bytes provided do not contain a valid
917
+ * binary representation of a CID.
918
+ */
919
+ static decode(bytes) {
920
+ const [cid, remainder] = _CID.decodeFirst(bytes);
921
+ if (remainder.length !== 0) {
922
+ throw new Error("Incorrect length");
923
+ }
924
+ return cid;
925
+ }
926
+ /**
927
+ * Decoded a CID from its binary representation at the beginning of a byte
928
+ * array.
929
+ *
930
+ * Returns an array with the first element containing the CID and the second
931
+ * element containing the remainder of the original byte array. The remainder
932
+ * will be a zero-length byte array if the provided bytes only contained a
933
+ * binary CID representation.
934
+ */
935
+ static decodeFirst(bytes) {
936
+ const specs = _CID.inspectBytes(bytes);
937
+ const prefixSize = specs.size - specs.multihashSize;
938
+ const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
939
+ if (multihashBytes.byteLength !== specs.multihashSize) {
940
+ throw new Error("Incorrect length");
941
+ }
942
+ const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
943
+ const digest = new Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
944
+ const cid = specs.version === 0 ? _CID.createV0(digest) : _CID.createV1(specs.codec, digest);
945
+ return [cid, bytes.subarray(specs.size)];
946
+ }
947
+ /**
948
+ * Inspect the initial bytes of a CID to determine its properties.
949
+ *
950
+ * Involves decoding up to 4 varints. Typically this will require only 4 to 6
951
+ * bytes but for larger multicodec code values and larger multihash digest
952
+ * lengths these varints can be quite large. It is recommended that at least
953
+ * 10 bytes be made available in the `initialBytes` argument for a complete
954
+ * inspection.
955
+ */
956
+ static inspectBytes(initialBytes) {
957
+ let offset = 0;
958
+ const next = () => {
959
+ const [i, length2] = decode3(initialBytes.subarray(offset));
960
+ offset += length2;
961
+ return i;
962
+ };
963
+ let version = next();
964
+ let codec = DAG_PB_CODE;
965
+ if (version === 18) {
966
+ version = 0;
967
+ offset = 0;
968
+ } else {
969
+ codec = next();
970
+ }
971
+ if (version !== 0 && version !== 1) {
972
+ throw new RangeError(`Invalid CID version ${version}`);
973
+ }
974
+ const prefixSize = offset;
975
+ const multihashCode = next();
976
+ const digestSize = next();
977
+ const size = offset + digestSize;
978
+ const multihashSize = size - prefixSize;
979
+ return { version, codec, multihashCode, digestSize, multihashSize, size };
980
+ }
981
+ /**
982
+ * Takes cid in a string representation and creates an instance. If `base`
983
+ * decoder is not provided will use a default from the configuration. It will
984
+ * throw an error if encoding of the CID is not compatible with supplied (or
985
+ * a default decoder).
986
+ */
987
+ static parse(source, base2) {
988
+ const [prefix, bytes] = parseCIDtoBytes(source, base2);
989
+ const cid = _CID.decode(bytes);
990
+ if (cid.version === 0 && source[0] !== "Q") {
991
+ throw Error("Version 0 CID string must not include multibase prefix");
992
+ }
993
+ baseCache(cid).set(prefix, source);
994
+ return cid;
995
+ }
996
+ };
997
+ function parseCIDtoBytes(source, base2) {
998
+ switch (source[0]) {
999
+ // CIDv0 is parsed differently
1000
+ case "Q": {
1001
+ const decoder = base2 ?? base58btc;
1002
+ return [
1003
+ base58btc.prefix,
1004
+ decoder.decode(`${base58btc.prefix}${source}`)
1005
+ ];
1006
+ }
1007
+ case base58btc.prefix: {
1008
+ const decoder = base2 ?? base58btc;
1009
+ return [base58btc.prefix, decoder.decode(source)];
1010
+ }
1011
+ case base32.prefix: {
1012
+ const decoder = base2 ?? base32;
1013
+ return [base32.prefix, decoder.decode(source)];
1014
+ }
1015
+ case base36.prefix: {
1016
+ const decoder = base2 ?? base36;
1017
+ return [base36.prefix, decoder.decode(source)];
1018
+ }
1019
+ default: {
1020
+ if (base2 == null) {
1021
+ throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");
1022
+ }
1023
+ return [source[0], base2.decode(source)];
1024
+ }
1025
+ }
1026
+ }
1027
+ function toStringV0(bytes, cache2, base2) {
1028
+ const { prefix } = base2;
1029
+ if (prefix !== base58btc.prefix) {
1030
+ throw Error(`Cannot string encode V0 in ${base2.name} encoding`);
1031
+ }
1032
+ const cid = cache2.get(prefix);
1033
+ if (cid == null) {
1034
+ const cid2 = base2.encode(bytes).slice(1);
1035
+ cache2.set(prefix, cid2);
1036
+ return cid2;
1037
+ } else {
1038
+ return cid;
1039
+ }
1040
+ }
1041
+ function toStringV1(bytes, cache2, base2) {
1042
+ const { prefix } = base2;
1043
+ const cid = cache2.get(prefix);
1044
+ if (cid == null) {
1045
+ const cid2 = base2.encode(bytes);
1046
+ cache2.set(prefix, cid2);
1047
+ return cid2;
1048
+ } else {
1049
+ return cid;
1050
+ }
1051
+ }
1052
+ var DAG_PB_CODE = 112;
1053
+ var SHA_256_CODE = 18;
1054
+ function encodeCID(version, code2, multihash) {
1055
+ const codeOffset = encodingLength(version);
1056
+ const hashOffset = codeOffset + encodingLength(code2);
1057
+ const bytes = new Uint8Array(hashOffset + multihash.byteLength);
1058
+ encodeTo(version, bytes, 0);
1059
+ encodeTo(code2, bytes, codeOffset);
1060
+ bytes.set(multihash, hashOffset);
1061
+ return bytes;
1062
+ }
1063
+ var cidSymbol = Symbol.for("@ipld/js-cid/CID");
1064
+
1065
+ // ../../node_modules/.pnpm/multiformats@13.4.1/node_modules/multiformats/dist/src/codecs/raw.js
1066
+ var code = 85;
1067
+
1068
+ // ../../node_modules/.pnpm/multiformats@13.4.1/node_modules/multiformats/dist/src/hashes/sha2.js
1069
+ var import_crypto = __toESM(require("crypto"), 1);
1070
+
1071
+ // ../../node_modules/.pnpm/multiformats@13.4.1/node_modules/multiformats/dist/src/hashes/hasher.js
1072
+ var DEFAULT_MIN_DIGEST_LENGTH = 20;
1073
+ function from2({ name, code: code2, encode: encode3, minDigestLength, maxDigestLength }) {
1074
+ return new Hasher(name, code2, encode3, minDigestLength, maxDigestLength);
1075
+ }
1076
+ var Hasher = class {
1077
+ name;
1078
+ code;
1079
+ encode;
1080
+ minDigestLength;
1081
+ maxDigestLength;
1082
+ constructor(name, code2, encode3, minDigestLength, maxDigestLength) {
1083
+ this.name = name;
1084
+ this.code = code2;
1085
+ this.encode = encode3;
1086
+ this.minDigestLength = minDigestLength ?? DEFAULT_MIN_DIGEST_LENGTH;
1087
+ this.maxDigestLength = maxDigestLength;
1088
+ }
1089
+ digest(input, options) {
1090
+ if (options?.truncate != null) {
1091
+ if (options.truncate < this.minDigestLength) {
1092
+ throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);
1093
+ }
1094
+ if (this.maxDigestLength != null && options.truncate > this.maxDigestLength) {
1095
+ throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`);
1096
+ }
1097
+ }
1098
+ if (input instanceof Uint8Array) {
1099
+ const result = this.encode(input);
1100
+ if (result instanceof Uint8Array) {
1101
+ return createDigest(result, this.code, options?.truncate);
1102
+ }
1103
+ return result.then((digest) => createDigest(digest, this.code, options?.truncate));
1104
+ } else {
1105
+ throw Error("Unknown type, must be binary type");
1106
+ }
1107
+ }
1108
+ };
1109
+ function createDigest(digest, code2, truncate) {
1110
+ if (truncate != null && truncate !== digest.byteLength) {
1111
+ if (truncate > digest.byteLength) {
1112
+ throw new Error(`Invalid truncate option, must be less than or equal to ${digest.byteLength}`);
1113
+ }
1114
+ digest = digest.subarray(0, truncate);
1115
+ }
1116
+ return create(code2, digest);
1117
+ }
1118
+
1119
+ // ../../node_modules/.pnpm/multiformats@13.4.1/node_modules/multiformats/dist/src/hashes/sha2.js
1120
+ var sha256 = from2({
1121
+ name: "sha2-256",
1122
+ code: 18,
1123
+ encode: (input) => coerce(import_crypto.default.createHash("sha256").update(input).digest())
1124
+ });
1125
+ var sha512 = from2({
1126
+ name: "sha2-512",
1127
+ code: 19,
1128
+ encode: (input) => coerce(import_crypto.default.createHash("sha512").update(input).digest())
1129
+ });
1130
+
1131
+ // src/cas.ts
1132
+ var IpfsCasExecutor = class {
1133
+ #helia;
1134
+ constructor(helia) {
1135
+ this.#helia = helia;
1136
+ }
1137
+ async retrieve(hash) {
1138
+ const hashBytes = (0, import_common.decode)(hash, "base64urlnopad");
1139
+ const cid = CID.create(1, code, create(sha256.code, hashBytes));
1140
+ try {
1141
+ return await this.#helia.blockstore.get(cid);
1142
+ } catch {
1143
+ return null;
1144
+ }
1145
+ }
1146
+ async publish(data) {
1147
+ const digest = await sha256.digest(data);
1148
+ const cid = CID.createV1(code, digest);
1149
+ await this.#helia.blockstore.put(cid, data);
1150
+ return btoa(String.fromCharCode(...digest.bytes.slice(2))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1151
+ }
1152
+ };
1153
+ var CasApi = class {
1154
+ #executor;
1155
+ constructor(config) {
1156
+ if (config.executor) {
1157
+ this.#executor = config.executor;
1158
+ } else if (config.helia) {
1159
+ this.#executor = new IpfsCasExecutor(config.helia);
1160
+ } else {
1161
+ throw new Error(
1162
+ "CAS configuration requires either an executor or a Helia instance. Example: createApi({ cas: { helia: await createHelia() } })"
1163
+ );
1164
+ }
1165
+ }
1166
+ /**
1167
+ * Retrieve a JSON object from the CAS by its SHA-256 hash bytes.
1168
+ * @param hashBytes Raw SHA-256 hash bytes of the JCS-canonicalized object.
1169
+ * @returns The parsed JSON object, or `null` if not found.
1170
+ */
1171
+ async retrieve(hashBytes) {
1172
+ const hash = (0, import_common.encode)(hashBytes, "base64urlnopad");
1173
+ const bytes = await this.#executor.retrieve(hash);
1174
+ if (!bytes) return null;
1175
+ return JSON.parse(new TextDecoder().decode(bytes));
1176
+ }
1177
+ /**
1178
+ * Publish a JSON object to the CAS.
1179
+ * The object is JCS-canonicalized before storage; the returned hash
1180
+ * matches what `canonicalHash` (from @did-btcr2/common) would produce.
1181
+ * @param object The JSON object to publish.
1182
+ * @returns The base64url-encoded SHA-256 hash (content address).
1183
+ */
1184
+ async publish(object) {
1185
+ const bytes = new TextEncoder().encode((0, import_common.canonicalize)(object));
1186
+ return await this.#executor.publish(bytes);
1187
+ }
1188
+ };
1189
+
1190
+ // src/kms.ts
1191
+ var import_kms = require("@did-btcr2/kms");
1192
+ var KeyManagerApi = class {
1193
+ /** The backing KeyManager instance. */
1194
+ kms;
1195
+ /** Create a new KeyManagerApi, optionally backed by a custom KeyManager. */
1196
+ constructor(kms) {
1197
+ this.kms = kms ?? new import_kms.Kms();
1198
+ }
1199
+ /** Generate a new key directly in the KMS. */
1200
+ generateKey(options) {
1201
+ return this.kms.generateKey(options);
1202
+ }
1203
+ /** Set the active key by its identifier. */
1204
+ setActive(id) {
1205
+ this.kms.setActiveKey(id);
1206
+ }
1207
+ /** Get the public key bytes for a key identifier. */
1208
+ getPublicKey(id) {
1209
+ return this.kms.getPublicKey(id);
1210
+ }
1211
+ /** Import a Schnorr keypair into the KMS. */
1212
+ import(kp, options) {
1213
+ return this.kms.importKey(kp, options);
1214
+ }
1215
+ /**
1216
+ * Export a Schnorr keypair from the KMS.
1217
+ * Only supported when the backing KMS is the built-in {@link Kms} class.
1218
+ * @throws {Error} If the backing KMS does not support key export.
1219
+ */
1220
+ export(id) {
1221
+ if (!(this.kms instanceof import_kms.Kms)) {
1222
+ throw new Error(
1223
+ "Key export is not supported by the current KeyManager implementation. Export is only available with the built-in Kms class."
1224
+ );
1225
+ }
1226
+ return this.kms.exportKey(id);
1227
+ }
1228
+ /** List all managed key identifiers. */
1229
+ listKeys() {
1230
+ return this.kms.listKeys();
1231
+ }
1232
+ /** Remove a key from the KMS. */
1233
+ removeKey(id, options = {}) {
1234
+ return this.kms.removeKey(id, options);
1235
+ }
1236
+ /**
1237
+ * Sign data via the KMS.
1238
+ * @param data The data to sign (must be non-empty).
1239
+ * @param id Optional key identifier; uses the active key if omitted.
1240
+ * @param options Signing options (scheme defaults to 'schnorr').
1241
+ */
1242
+ sign(data, id, options) {
1243
+ assertBytes(data, "data");
1244
+ return this.kms.sign(data, id, options);
1245
+ }
1246
+ /** Verify a signature via the KMS. */
1247
+ verify(signature, data, id, options) {
1248
+ return this.kms.verify(signature, data, id, options);
1249
+ }
1250
+ /** Compute a SHA-256 digest. */
1251
+ digest(data) {
1252
+ return this.kms.digest(data);
1253
+ }
1254
+ };
1255
+
1256
+ // src/crypto.ts
1257
+ var import_cryptosuite = require("@did-btcr2/cryptosuite");
1258
+ var import_keypair = require("@did-btcr2/keypair");
1259
+ var KeyPairApi = class {
1260
+ /**
1261
+ * Generate a new Schnorr keypair.
1262
+ * @returns The generated Schnorr keypair.
1263
+ */
1264
+ generate() {
1265
+ return import_keypair.SchnorrKeyPair.generate();
1266
+ }
1267
+ /**
1268
+ * Create a Schnorr keypair from secret key bytes or hex string.
1269
+ * @param data The secret key bytes or hex string.
1270
+ * @returns The created Schnorr keypair.
1271
+ */
1272
+ fromSecret(data) {
1273
+ return import_keypair.SchnorrKeyPair.fromSecret(data);
1274
+ }
1275
+ /** Create a secret key from entropy (bytes or bigint). */
1276
+ secretKeyFrom(ent) {
1277
+ return new import_keypair.Secp256k1SecretKey(ent);
1278
+ }
1279
+ /** Create a compressed public key from bytes. */
1280
+ publicKeyFrom(byt) {
1281
+ return new import_keypair.CompressedSecp256k1PublicKey(byt);
1282
+ }
1283
+ /** Deserialize a keypair from a JSON object. */
1284
+ fromJSON(obj) {
1285
+ return import_keypair.SchnorrKeyPair.fromJSON(obj);
1286
+ }
1287
+ /** Serialize a keypair to a JSON object. */
1288
+ toJSON(kp) {
1289
+ return kp.exportJSON();
1290
+ }
1291
+ /** Compare two keypairs for equality. */
1292
+ equals(kp1, kp2) {
1293
+ return import_keypair.SchnorrKeyPair.equals(kp1, kp2);
1294
+ }
1295
+ };
1296
+ var CryptosuiteApi = class {
1297
+ #current;
1298
+ /** The currently active cryptosuite, or `undefined` if none is set. */
1299
+ get current() {
1300
+ return this.#current;
1301
+ }
1302
+ /**
1303
+ * Set the current cryptosuite for subsequent operations.
1304
+ * @param cs The cryptosuite to activate.
1305
+ * @returns `this` for chaining.
1306
+ */
1307
+ use(cs) {
1308
+ this.#current = cs;
1309
+ return this;
1310
+ }
1311
+ /** Clear the current cryptosuite. */
1312
+ clear() {
1313
+ this.#current = void 0;
1314
+ }
1315
+ /**
1316
+ * Create a new Schnorr cryptosuite from a multikey.
1317
+ * @param multikey The Schnorr multikey to use.
1318
+ * @returns The created Schnorr cryptosuite.
1319
+ */
1320
+ create(multikey) {
1321
+ return new import_cryptosuite.BIP340Cryptosuite(multikey);
1322
+ }
1323
+ /**
1324
+ * Convenience: resolve a key from the KMS and create a cryptosuite in one step.
1325
+ * @param id The multikey ID (e.g. '#initialKey').
1326
+ * @param controller The DID that controls this key.
1327
+ * @param keyId The KMS key identifier to resolve.
1328
+ * @param kms The KeyManagerApi instance holding the key.
1329
+ * @returns The created Schnorr cryptosuite.
1330
+ */
1331
+ createFromKms(id, controller, keyId, kms) {
1332
+ const pubBytes = kms.getPublicKey(keyId);
1333
+ const mk = import_cryptosuite.SchnorrMultikey.fromPublicKey({ id, controller, publicKeyBytes: pubBytes });
1334
+ return new import_cryptosuite.BIP340Cryptosuite(mk);
1335
+ }
1336
+ /**
1337
+ * Convert a cryptosuite to a Data Integrity Proof instance.
1338
+ * Uses the current cryptosuite when `cryptosuite` is omitted.
1339
+ * @param cryptosuite Optional explicit cryptosuite to convert.
1340
+ * @returns The Data Integrity Proof instance.
1341
+ */
1342
+ toDataIntegrityProof(cryptosuite) {
1343
+ const cs = cryptosuite ?? this.#requireCurrent();
1344
+ return cs.toDataIntegrityProof();
1345
+ }
1346
+ /**
1347
+ * Create a proof for a document.
1348
+ * Uses the current cryptosuite when `cryptosuite` is omitted.
1349
+ * @param document The document to create the proof for.
1350
+ * @param config Configuration for the proof creation.
1351
+ * @param cryptosuite Optional explicit cryptosuite; defaults to current.
1352
+ * @returns The created proof.
1353
+ */
1354
+ createProof(document, config, cryptosuite) {
1355
+ const cs = cryptosuite ?? this.#requireCurrent();
1356
+ return cs.createProof(document, config);
1357
+ }
1358
+ /**
1359
+ * Verify a proof for a document.
1360
+ * Uses the current cryptosuite when `cryptosuite` is omitted.
1361
+ * @param document The document to verify the proof for.
1362
+ * @param cryptosuite Optional explicit cryptosuite; defaults to current.
1363
+ * @returns The full verification result.
1364
+ */
1365
+ verifyProof(document, cryptosuite) {
1366
+ const cs = cryptosuite ?? this.#requireCurrent();
1367
+ return cs.verifyProof(document);
1368
+ }
1369
+ #requireCurrent() {
1370
+ if (!this.#current) {
1371
+ throw new Error(
1372
+ "No current cryptosuite set. Call cryptosuite.use(cs) first, or pass an explicit instance."
1373
+ );
1374
+ }
1375
+ return this.#current;
1376
+ }
1377
+ };
1378
+ var DataIntegrityProofApi = class {
1379
+ #current;
1380
+ /** The currently active proof instance, or `undefined` if none is set. */
1381
+ get current() {
1382
+ return this.#current;
1383
+ }
1384
+ /**
1385
+ * Set the current proof instance for subsequent operations.
1386
+ * @param p The proof instance to activate.
1387
+ * @returns `this` for chaining.
1388
+ */
1389
+ use(p) {
1390
+ this.#current = p;
1391
+ return this;
1392
+ }
1393
+ /** Clear the current proof instance. */
1394
+ clear() {
1395
+ this.#current = void 0;
1396
+ }
1397
+ /**
1398
+ * Create a BIP340DataIntegrityProof instance with the given cryptosuite.
1399
+ * @param cryptosuite The cryptosuite to use for proof operations.
1400
+ * @returns The created BIP340DataIntegrityProof instance.
1401
+ */
1402
+ create(cryptosuite) {
1403
+ return new import_cryptosuite.BIP340DataIntegrityProof(cryptosuite);
1404
+ }
1405
+ /**
1406
+ * Add a proof to a document.
1407
+ * Uses the current proof instance when `proof` is omitted.
1408
+ * @param document The document to add the proof to.
1409
+ * @param config Configuration for adding the proof.
1410
+ * @param proof Optional explicit proof instance; defaults to current.
1411
+ * @returns A document with a proof added.
1412
+ */
1413
+ addProof(document, config, proof) {
1414
+ const p = proof ?? this.#requireCurrent();
1415
+ return p.addProof(document, config);
1416
+ }
1417
+ /**
1418
+ * Convenience: create a cryptosuite, proof instance, and sign a document
1419
+ * in one call. Requires a multikey with signing capability.
1420
+ * @param multikey The Schnorr multikey (must include secret key).
1421
+ * @param document The unsigned document to sign.
1422
+ * @param config The Data Integrity proof configuration.
1423
+ * @returns The signed document with proof attached.
1424
+ */
1425
+ signDocument(multikey, document, config) {
1426
+ const cs = new import_cryptosuite.BIP340Cryptosuite(multikey);
1427
+ const proofInst = new import_cryptosuite.BIP340DataIntegrityProof(cs);
1428
+ return proofInst.addProof(document, config);
1429
+ }
1430
+ /**
1431
+ * Verify a proof using a BIP340DataIntegrityProof instance.
1432
+ * Uses the current proof instance when `proof` is omitted.
1433
+ * @param document The document to verify the proof for.
1434
+ * @param expectedPurpose The expected proof purpose.
1435
+ * @param mediaType The media type of the document.
1436
+ * @param expectedDomain The expected domain for the proof.
1437
+ * @param expectedChallenge The expected challenge for the proof.
1438
+ * @param proof Optional explicit proof instance; defaults to current.
1439
+ * @returns The result of verifying the proof.
1440
+ */
1441
+ verifyProof(document, expectedPurpose, mediaType, expectedDomain, expectedChallenge, proof) {
1442
+ const p = proof ?? this.#requireCurrent();
1443
+ return p.verifyProof(
1444
+ document,
1445
+ expectedPurpose,
1446
+ mediaType,
1447
+ expectedDomain,
1448
+ expectedChallenge
1449
+ );
1450
+ }
1451
+ #requireCurrent() {
1452
+ if (!this.#current) {
1453
+ throw new Error(
1454
+ "No current proof instance set. Call proof.use(p) first, or pass an explicit instance."
1455
+ );
1456
+ }
1457
+ return this.#current;
1458
+ }
1459
+ };
1460
+ var MultikeyApi = class {
1461
+ #current;
1462
+ /** The currently active multikey, or `undefined` if none is set. */
1463
+ get current() {
1464
+ return this.#current;
1465
+ }
1466
+ /**
1467
+ * Set the current multikey for subsequent operations.
1468
+ * @param mk The multikey to activate.
1469
+ * @returns `this` for chaining.
1470
+ */
1471
+ use(mk) {
1472
+ this.#current = mk;
1473
+ return this;
1474
+ }
1475
+ /** Clear the current multikey. */
1476
+ clear() {
1477
+ this.#current = void 0;
1478
+ }
1479
+ /**
1480
+ * Create a new Schnorr multikey from a keypair.
1481
+ * @param id The multikey ID.
1482
+ * @param controller The multikey controller.
1483
+ * @param keyPair The Schnorr keypair to use.
1484
+ * @returns The created Schnorr multikey.
1485
+ */
1486
+ create(id, controller, keyPair) {
1487
+ return new import_cryptosuite.SchnorrMultikey({ id, controller, keyPair });
1488
+ }
1489
+ /**
1490
+ * Create a Schnorr multikey from raw secret key bytes.
1491
+ * @param id The multikey ID.
1492
+ * @param controller The multikey controller.
1493
+ * @param secretKeyBytes The secret key bytes.
1494
+ * @returns The created Schnorr multikey.
1495
+ */
1496
+ fromSecretKey(id, controller, secretKeyBytes) {
1497
+ return import_cryptosuite.SchnorrMultikey.fromSecretKey(id, controller, secretKeyBytes);
1498
+ }
1499
+ /**
1500
+ * Create a verification-only multikey from public key bytes.
1501
+ * @param params The id, controller, and publicKeyBytes.
1502
+ * @returns The created Multikey.
1503
+ */
1504
+ fromPublicKey(params) {
1505
+ return import_cryptosuite.SchnorrMultikey.fromPublicKey(params);
1506
+ }
1507
+ /**
1508
+ * Convenience: resolve a key from the KMS and create a multikey in one step.
1509
+ * @param id The multikey ID.
1510
+ * @param controller The multikey controller DID.
1511
+ * @param keyId The KMS key identifier to resolve.
1512
+ * @param kms The KeyManagerApi instance holding the key.
1513
+ * @returns The created Multikey (verification-only; public key from KMS).
1514
+ */
1515
+ fromKms(id, controller, keyId, kms) {
1516
+ const pubBytes = kms.getPublicKey(keyId);
1517
+ return import_cryptosuite.SchnorrMultikey.fromPublicKey({ id, controller, publicKeyBytes: pubBytes });
1518
+ }
1519
+ /**
1520
+ * Reconstruct a multikey from a DID document's verification method.
1521
+ * @param verificationMethod The verification method to convert.
1522
+ * @returns The reconstructed multikey.
1523
+ */
1524
+ fromVerificationMethod(verificationMethod) {
1525
+ return import_cryptosuite.SchnorrMultikey.fromVerificationMethod(verificationMethod);
1526
+ }
1527
+ /**
1528
+ * Produce a DID Verification Method JSON from a multikey.
1529
+ * Uses the current multikey when `mk` is omitted.
1530
+ * @param mk Optional explicit multikey; defaults to current.
1531
+ */
1532
+ toVerificationMethod(mk) {
1533
+ const m = mk ?? this.#requireCurrent();
1534
+ return m.toVerificationMethod();
1535
+ }
1536
+ /**
1537
+ * Sign bytes via the multikey (requires secret).
1538
+ * Uses the current multikey when `mk` is omitted.
1539
+ * @param data The data to sign.
1540
+ * @param mk Optional explicit multikey; defaults to current.
1541
+ */
1542
+ sign(data, mk) {
1543
+ const m = mk ?? this.#requireCurrent();
1544
+ return m.sign(data);
1545
+ }
1546
+ /**
1547
+ * Verify signature via multikey.
1548
+ * Uses the current multikey when `mk` is omitted.
1549
+ * @param data The data that was signed.
1550
+ * @param signature The signature to verify.
1551
+ * @param mk Optional explicit multikey; defaults to current.
1552
+ */
1553
+ verify(data, signature, mk) {
1554
+ const m = mk ?? this.#requireCurrent();
1555
+ return m.verify(signature, data);
1556
+ }
1557
+ #requireCurrent() {
1558
+ if (!this.#current) {
1559
+ throw new Error(
1560
+ "No current multikey set. Call multikey.use(mk) first, or pass an explicit instance."
1561
+ );
1562
+ }
1563
+ return this.#current;
1564
+ }
1565
+ };
1566
+ var CryptoApi = class {
1567
+ /** Schnorr keypair operations. */
1568
+ keypair = new KeyPairApi();
1569
+ /** Schnorr Multikey operations (optionally stateful). */
1570
+ multikey = new MultikeyApi();
1571
+ /** Schnorr Cryptosuite operations (optionally stateful). */
1572
+ cryptosuite = new CryptosuiteApi();
1573
+ /** Data Integrity Proof operations (optionally stateful). */
1574
+ proof = new DataIntegrityProofApi();
1575
+ /**
1576
+ * Activate a multikey and propagate through the full pipeline.
1577
+ * Sets the current multikey, creates a cryptosuite from it, and creates
1578
+ * a proof instance from the cryptosuite — all three sub-facades become
1579
+ * ready for stateful operations.
1580
+ * @param mk The multikey to activate (must include a secret key for signing).
1581
+ * @returns `this` for chaining.
1582
+ */
1583
+ activate(mk) {
1584
+ this.multikey.use(mk);
1585
+ const cs = this.cryptosuite.create(mk);
1586
+ this.cryptosuite.use(cs);
1587
+ const p = this.proof.create(cs);
1588
+ this.proof.use(p);
1589
+ return this;
1590
+ }
1591
+ /**
1592
+ * Clear stateful defaults from all sub-facades.
1593
+ */
1594
+ deactivate() {
1595
+ this.multikey.clear();
1596
+ this.cryptosuite.clear();
1597
+ this.proof.clear();
1598
+ }
1599
+ /**
1600
+ * Sign data using the current multikey.
1601
+ * Shorthand for `crypto.multikey.sign(data)`.
1602
+ * @param data The data to sign.
1603
+ * @returns The signature bytes.
1604
+ */
1605
+ sign(data) {
1606
+ return this.multikey.sign(data);
1607
+ }
1608
+ /**
1609
+ * Verify a signature using the current multikey.
1610
+ * Shorthand for `crypto.multikey.verify(data, signature)`.
1611
+ * @param data The data that was signed.
1612
+ * @param signature The signature to verify.
1613
+ * @returns `true` if the signature is valid.
1614
+ */
1615
+ verify(data, signature) {
1616
+ return this.multikey.verify(data, signature);
1617
+ }
1618
+ /**
1619
+ * Sign a BTCR2 update document using the current proof instance.
1620
+ * Shorthand for `crypto.proof.addProof(document, config)`.
1621
+ *
1622
+ * Requires {@link activate} to have been called first, or the three
1623
+ * sub-facades to have been configured individually.
1624
+ * @param document The unsigned BTCR2 update document.
1625
+ * @param config The Data Integrity proof configuration.
1626
+ * @returns The signed document with proof attached.
1627
+ */
1628
+ signDocument(document, config) {
1629
+ return this.proof.addProof(document, config);
1630
+ }
1631
+ /**
1632
+ * Verify a signed BTCR2 update document using the current cryptosuite.
1633
+ * Shorthand for `crypto.cryptosuite.verifyProof(document)`.
1634
+ * @param document The signed document to verify.
1635
+ * @returns The full verification result.
1636
+ */
1637
+ verifyDocument(document) {
1638
+ return this.cryptosuite.verifyProof(document);
1639
+ }
1640
+ };
1641
+
1642
+ // src/did.ts
1643
+ var import_common2 = require("@did-btcr2/common");
1644
+ var import_keypair2 = require("@did-btcr2/keypair");
1645
+ var import_method = require("@did-btcr2/method");
1646
+ var import_dids = require("@web5/dids");
1647
+ var DidApi = class {
1648
+ /**
1649
+ * Encode a DID from genesis bytes and options.
1650
+ * @param genesisBytes The genesis document bytes.
1651
+ * @param options The creation options.
1652
+ * @returns The encoded DID string.
1653
+ */
1654
+ encode(genesisBytes, options) {
1655
+ assertBytes(genesisBytes, "genesisBytes");
1656
+ return import_method.Identifier.encode(genesisBytes, options);
1657
+ }
1658
+ /**
1659
+ * Decode a DID into its components.
1660
+ * @param did The DID string to decode.
1661
+ * @returns The decoded identifier components.
1662
+ */
1663
+ decode(did) {
1664
+ assertString(did, "did");
1665
+ return import_method.Identifier.decode(did);
1666
+ }
1667
+ /**
1668
+ * Generate a new DID along with its keypair.
1669
+ *
1670
+ * When no `network` is given, defaults to `'regtest'` (upstream default).
1671
+ * Pass an explicit network to generate DIDs for other networks.
1672
+ *
1673
+ * @param network Optional network to generate the DID for.
1674
+ * @returns The generated keypair and DID string.
1675
+ */
1676
+ generate(network) {
1677
+ if (!network) return import_method.Identifier.generate();
1678
+ const kp = import_keypair2.SchnorrKeyPair.generate();
1679
+ const did = import_method.Identifier.encode(kp.publicKey.compressed, {
1680
+ idType: import_common2.IdentifierTypes.KEY,
1681
+ network
1682
+ });
1683
+ return { keyPair: kp.exportJSON(), did };
1684
+ }
1685
+ /**
1686
+ * Check if a DID string is valid.
1687
+ * @param did The DID string to validate.
1688
+ * @returns `true` if valid, `false` otherwise.
1689
+ */
1690
+ isValid(did) {
1691
+ if (typeof did !== "string" || did.length === 0) return false;
1692
+ return import_method.Identifier.isValid(did);
1693
+ }
1694
+ /**
1695
+ * Parse a DID string into a Did instance.
1696
+ * @param did The DID string to parse.
1697
+ * @returns The parsed Did instance, or `null` if parsing failed.
1698
+ */
1699
+ parse(did) {
1700
+ if (typeof did !== "string" || did.length === 0) return null;
1701
+ return import_dids.Did.parse(did);
1702
+ }
1703
+ };
1704
+
1705
+ // src/method.ts
1706
+ var import_common3 = require("@did-btcr2/common");
1707
+ var import_method2 = require("@did-btcr2/method");
1708
+ var DidMethodApi = class {
1709
+ #btc;
1710
+ #cas;
1711
+ #log;
1712
+ constructor(btc, cas, logger) {
1713
+ this.#btc = btc;
1714
+ this.#cas = cas;
1715
+ this.#log = logger ?? NOOP_LOGGER;
1716
+ }
1717
+ /**
1718
+ * Create a deterministic (k1) DID from a public key.
1719
+ * Sets idType to KEY automatically.
1720
+ * @param genesisBytes The compressed public key bytes (33 bytes).
1721
+ * @param options Creation options (idType is set for you).
1722
+ * @returns The created DID identifier string.
1723
+ */
1724
+ createDeterministic(genesisBytes, options = {}) {
1725
+ assertCompressedPubkey(genesisBytes, "genesisBytes");
1726
+ return import_method2.DidBtcr2.create(genesisBytes, { ...options, idType: import_common3.IdentifierTypes.KEY });
1727
+ }
1728
+ /**
1729
+ * Create a non-deterministic (x1) DID from external genesis document bytes.
1730
+ * Sets idType to EXTERNAL automatically.
1731
+ * @param genesisBytes The genesis document bytes.
1732
+ * @param options Creation options (idType is set for you).
1733
+ * @returns The created DID identifier string.
1734
+ */
1735
+ createExternal(genesisBytes, options = {}) {
1736
+ assertBytes(genesisBytes, "genesisBytes");
1737
+ return import_method2.DidBtcr2.create(genesisBytes, { ...options, idType: import_common3.IdentifierTypes.EXTERNAL });
1738
+ }
1739
+ /**
1740
+ * Resolve a DID by driving the sans-I/O `Resolver` state machine (from @did-btcr2/method).
1741
+ * If a Bitcoin connection is configured on the API, it is used automatically
1742
+ * to fetch beacon signals. Sidecar data flows through `options.sidecar`.
1743
+ * @param did The DID to resolve.
1744
+ * @param options Resolution options.
1745
+ * @returns The resolution result.
1746
+ */
1747
+ async resolve(did, options) {
1748
+ assertString(did, "did");
1749
+ this.#log.debug("Resolving DID", did);
1750
+ try {
1751
+ const resolver = import_method2.DidBtcr2.resolve(did, options);
1752
+ let state = resolver.resolve();
1753
+ while (state.status === "action-required") {
1754
+ for (const need of state.needs) {
1755
+ switch (need.kind) {
1756
+ case "NeedBeaconSignals": {
1757
+ if (!this.#btc) {
1758
+ throw new Error(
1759
+ "Bitcoin connection required to fetch beacon signals. Configure a BitcoinApi on the DidBtcr2Api instance."
1760
+ );
1761
+ }
1762
+ this.#log.debug(
1763
+ "Fetching beacon signals for %d service(s)",
1764
+ need.beaconServices.length
1765
+ );
1766
+ const signals = await import_method2.BeaconSignalDiscovery.indexer(
1767
+ [...need.beaconServices],
1768
+ this.#btc.connection
1769
+ );
1770
+ resolver.provide(need, signals);
1771
+ break;
1772
+ }
1773
+ case "NeedGenesisDocument": {
1774
+ if (!this.#cas) {
1775
+ throw new Error(
1776
+ `Genesis document required but not in sidecar (hash: ${need.genesisHash}), and no CAS driver configured. Either provide the genesis document via options.sidecar.genesisDocument or configure a CAS driver.`
1777
+ );
1778
+ }
1779
+ this.#log.debug("Fetching genesis document from CAS: %s", need.genesisHash);
1780
+ const doc = await this.#cas.retrieve((0, import_common3.decode)(need.genesisHash, "hex"));
1781
+ if (!doc) {
1782
+ throw new Error(
1783
+ `Genesis document not found in CAS (hash: ${need.genesisHash}).`
1784
+ );
1785
+ }
1786
+ resolver.provide(need, doc);
1787
+ break;
1788
+ }
1789
+ case "NeedCASAnnouncement": {
1790
+ if (!this.#cas) {
1791
+ throw new Error(
1792
+ `CAS announcement required but not in sidecar (hash: ${need.announcementHash}), and no CAS driver configured. Either provide it via options.sidecar.casUpdates or configure a CAS driver.`
1793
+ );
1794
+ }
1795
+ this.#log.debug("Fetching CAS announcement from CAS: %s", need.announcementHash);
1796
+ const announcement = await this.#cas.retrieve((0, import_common3.decode)(need.announcementHash, "hex"));
1797
+ if (!announcement) {
1798
+ throw new Error(
1799
+ `CAS announcement not found in CAS (hash: ${need.announcementHash}).`
1800
+ );
1801
+ }
1802
+ resolver.provide(need, announcement);
1803
+ break;
1804
+ }
1805
+ case "NeedSignedUpdate": {
1806
+ if (!this.#cas) {
1807
+ throw new Error(
1808
+ `Signed update required but not in sidecar (hash: ${need.updateHash}), and no CAS driver configured. Either provide it via options.sidecar.updates or configure a CAS driver.`
1809
+ );
1810
+ }
1811
+ this.#log.debug("Fetching signed update from CAS: %s", need.updateHash);
1812
+ const update = await this.#cas.retrieve((0, import_common3.decode)(need.updateHash, "hex"));
1813
+ if (!update) {
1814
+ throw new Error(
1815
+ `Signed update not found in CAS (hash: ${need.updateHash}).`
1816
+ );
1817
+ }
1818
+ resolver.provide(need, update);
1819
+ break;
1820
+ }
1821
+ }
1822
+ }
1823
+ state = resolver.resolve();
1824
+ }
1825
+ this.#log.debug("DID resolved successfully", did, state.result.metadata);
1826
+ return {
1827
+ didResolutionMetadata: {},
1828
+ didDocument: state.result.didDocument,
1829
+ didDocumentMetadata: state.result.metadata
1830
+ };
1831
+ } catch (err) {
1832
+ this.#log.error("DID resolution failed", did, err);
1833
+ throw new Error(
1834
+ `Failed to resolve DID: ${did}`,
1835
+ { cause: err }
1836
+ );
1837
+ }
1838
+ }
1839
+ /**
1840
+ * Update an existing DID document. If a Bitcoin connection is configured on
1841
+ * the API, it is injected automatically.
1842
+ * @param params The update parameters.
1843
+ * @returns The signed update.
1844
+ */
1845
+ async update({
1846
+ sourceDocument,
1847
+ patches,
1848
+ sourceVersionId,
1849
+ verificationMethodId,
1850
+ beaconId,
1851
+ signingMaterial,
1852
+ bitcoin
1853
+ }) {
1854
+ const btcConnection = bitcoin ?? this.#btc?.connection ?? void 0;
1855
+ return await import_method2.DidBtcr2.update({
1856
+ sourceDocument,
1857
+ patches,
1858
+ sourceVersionId,
1859
+ verificationMethodId,
1860
+ beaconId,
1861
+ signingMaterial,
1862
+ bitcoin: btcConnection
1863
+ });
1864
+ }
1865
+ /**
1866
+ * Get the signing method from a DID document by method ID.
1867
+ * @param didDocument The DID document.
1868
+ * @param methodId The method ID (if omitted, the first signing method is returned).
1869
+ * @returns The found signing method.
1870
+ */
1871
+ getSigningMethod(didDocument, methodId) {
1872
+ return import_method2.DidBtcr2.getSigningMethod(didDocument, methodId);
1873
+ }
1874
+ /**
1875
+ * Create a fluent builder for a DID update operation.
1876
+ * @param sourceDocument The current DID document to update.
1877
+ * @returns An {@link UpdateBuilder} for chaining update parameters.
1878
+ *
1879
+ * @example
1880
+ * ```ts
1881
+ * const signed = await api.btcr2
1882
+ * .buildUpdate(currentDoc)
1883
+ * .patch({ op: 'add', path: '/service/1', value: newService })
1884
+ * .version(2)
1885
+ * .signer('#initialKey')
1886
+ * .beacon('#beacon-0')
1887
+ * .execute();
1888
+ * ```
1889
+ */
1890
+ buildUpdate(sourceDocument) {
1891
+ return new UpdateBuilder(this, sourceDocument);
1892
+ }
1893
+ /** Deactivate a DID (not yet implemented in the core method). */
1894
+ async deactivate() {
1895
+ throw new import_common3.NotImplementedError(
1896
+ "DidMethodApi.deactivate is not implemented yet.",
1897
+ {
1898
+ type: "DID_API_METHOD_NOT_IMPLEMENTED",
1899
+ name: "NOT_IMPLEMENTED_ERROR"
1900
+ }
1901
+ );
1902
+ }
1903
+ };
1904
+ var UpdateBuilder = class {
1905
+ #methodApi;
1906
+ #sourceDocument;
1907
+ #patches = [];
1908
+ #sourceVersionId;
1909
+ #verificationMethodId;
1910
+ #beaconId;
1911
+ #signingMaterial;
1912
+ #bitcoin;
1913
+ /** @internal */
1914
+ constructor(methodApi, sourceDocument) {
1915
+ this.#methodApi = methodApi;
1916
+ this.#sourceDocument = sourceDocument;
1917
+ }
1918
+ /** Add a single JSON Patch operation. Can be called multiple times. */
1919
+ patch(op) {
1920
+ this.#patches.push(op);
1921
+ return this;
1922
+ }
1923
+ /** Set all patches at once (replaces any previously added). */
1924
+ patches(ops) {
1925
+ this.#patches = [...ops];
1926
+ return this;
1927
+ }
1928
+ /** Set the source version ID. */
1929
+ version(id) {
1930
+ this.#sourceVersionId = id;
1931
+ return this;
1932
+ }
1933
+ /** Set the verification method ID used for signing. */
1934
+ signer(methodId) {
1935
+ this.#verificationMethodId = methodId;
1936
+ return this;
1937
+ }
1938
+ /** Set the beacon ID for the update announcement. */
1939
+ beacon(beaconId) {
1940
+ this.#beaconId = beaconId;
1941
+ return this;
1942
+ }
1943
+ /** Set the signing material (secret key bytes or hex). */
1944
+ signingMaterial(material) {
1945
+ this.#signingMaterial = material;
1946
+ return this;
1947
+ }
1948
+ /** Override the Bitcoin connection for this update. */
1949
+ withBitcoin(connection) {
1950
+ this.#bitcoin = connection;
1951
+ return this;
1952
+ }
1953
+ /**
1954
+ * Execute the update.
1955
+ * @throws {Error} If required fields (version, signer, beacon) are missing.
1956
+ */
1957
+ async execute() {
1958
+ if (this.#sourceVersionId === void 0) {
1959
+ throw new Error("UpdateBuilder: sourceVersionId is required. Call .version(id) before .execute().");
1960
+ }
1961
+ if (!this.#verificationMethodId) {
1962
+ throw new Error("UpdateBuilder: verificationMethodId is required. Call .signer(id) before .execute().");
1963
+ }
1964
+ if (!this.#beaconId) {
1965
+ throw new Error("UpdateBuilder: beaconId is required. Call .beacon(id) before .execute().");
1966
+ }
1967
+ return this.#methodApi.update({
1968
+ sourceDocument: this.#sourceDocument,
1969
+ patches: this.#patches,
1970
+ sourceVersionId: this.#sourceVersionId,
1971
+ verificationMethodId: this.#verificationMethodId,
1972
+ beaconId: this.#beaconId,
1973
+ signingMaterial: this.#signingMaterial,
1974
+ bitcoin: this.#bitcoin
1975
+ });
1976
+ }
1977
+ };
1978
+
1979
+ // src/api.ts
1980
+ var import_keypair3 = require("@did-btcr2/keypair");
1981
+ var DidBtcr2Api = class {
1982
+ /** Cryptographic operations (keypair, multikey, cryptosuite, proof). */
1983
+ crypto;
1984
+ /** DID identifier operations (encode, decode, generate, parse). */
1985
+ did;
1986
+ /** Key management operations. */
1987
+ kms;
1988
+ #btcConfig;
1989
+ #btc;
1990
+ #casConfig;
1991
+ #cas;
1992
+ #btcr2;
1993
+ #log;
1994
+ #disposed = false;
1995
+ constructor(config) {
1996
+ this.#btcConfig = config?.btc;
1997
+ this.#casConfig = config?.cas;
1998
+ this.#log = config?.logger ?? NOOP_LOGGER;
1999
+ this.kms = new KeyManagerApi(config?.kms);
2000
+ this.did = new DidApi();
2001
+ this.crypto = new CryptoApi();
2002
+ }
2003
+ /**
2004
+ * Bitcoin API sub-facade (lazily initialized).
2005
+ * Only available when `btc` config was provided to the constructor.
2006
+ * @throws {Error} If the instance has been disposed or no Bitcoin config was provided.
2007
+ */
2008
+ get btc() {
2009
+ this.#assertNotDisposed();
2010
+ if (!this.#btc) {
2011
+ if (!this.#btcConfig) {
2012
+ throw new Error(
2013
+ "Bitcoin not configured. Pass a btc config to createApi(), e.g.: createApi({ btc: { network: 'regtest' } })"
2014
+ );
2015
+ }
2016
+ this.#btc = new BitcoinApi(this.#btcConfig);
2017
+ }
2018
+ return this.#btc;
2019
+ }
2020
+ /**
2021
+ * CAS API sub-facade (lazily initialized).
2022
+ * Only available when `cas` config was provided to the constructor.
2023
+ * @throws {Error} If the instance has been disposed or no CAS config was provided.
2024
+ */
2025
+ get cas() {
2026
+ this.#assertNotDisposed();
2027
+ if (!this.#cas) {
2028
+ if (!this.#casConfig) {
2029
+ throw new Error(
2030
+ "CAS not configured. Pass a cas config to createApi(), e.g.: createApi({ cas: { helia: await createHelia() } })"
2031
+ );
2032
+ }
2033
+ this.#cas = new CasApi(this.#casConfig);
2034
+ }
2035
+ return this.#cas;
2036
+ }
2037
+ /**
2038
+ * DID Method API sub-facade (lazily initialized with bitcoin + CAS wiring).
2039
+ * @throws {Error} If the instance has been disposed.
2040
+ */
2041
+ get btcr2() {
2042
+ this.#assertNotDisposed();
2043
+ if (!this.#btcr2) {
2044
+ this.#btcr2 = new DidMethodApi(
2045
+ this.#btcConfig ? this.btc : void 0,
2046
+ this.#casConfig ? this.cas : void 0,
2047
+ this.#log
2048
+ );
2049
+ }
2050
+ return this.#btcr2;
2051
+ }
2052
+ /**
2053
+ * Whether this API instance has been disposed.
2054
+ */
2055
+ get disposed() {
2056
+ return this.#disposed;
2057
+ }
2058
+ /**
2059
+ * Create a DID using either deterministic (KEY) or external (EXTERNAL) mode.
2060
+ * @param type The creation mode.
2061
+ * @param genesisBytes Public key bytes (deterministic) or document bytes (external).
2062
+ * @param options Creation options (idType is set for you).
2063
+ * @returns The created DID identifier string.
2064
+ */
2065
+ createDid(type, genesisBytes, options) {
2066
+ this.#assertNotDisposed();
2067
+ return type === "deterministic" ? this.btcr2.createDeterministic(genesisBytes, options) : this.btcr2.createExternal(genesisBytes, options);
2068
+ }
2069
+ /**
2070
+ * Generate a new DID, create the keypair, and import it into the KMS.
2071
+ * @param options Optional settings.
2072
+ * @param options.setActive Whether to set the imported key as active in the KMS (default `true`).
2073
+ * @param options.network Network for the generated DID (default `'regtest'`).
2074
+ * @returns The generated DID string and KMS key identifier.
2075
+ */
2076
+ generateDid(options) {
2077
+ this.#assertNotDisposed();
2078
+ const { keyPair, did } = this.did.generate(options?.network);
2079
+ const kp = import_keypair3.SchnorrKeyPair.fromJSON(keyPair);
2080
+ const keyId = this.kms.import(kp, { setActive: options?.setActive ?? true });
2081
+ return { did, keyId };
2082
+ }
2083
+ /**
2084
+ * Resolve a DID, automatically injecting the configured Bitcoin connection.
2085
+ * @param did The DID to resolve.
2086
+ * @param options Optional resolution options.
2087
+ * @returns The resolution result.
2088
+ */
2089
+ async resolveDid(did, options) {
2090
+ this.#assertNotDisposed();
2091
+ return await this.btcr2.resolve(did, options);
2092
+ }
2093
+ /**
2094
+ * Resolve a DID and return a discriminated result instead of throwing.
2095
+ * Useful when resolution failure is an expected outcome (e.g. checking
2096
+ * whether a DID exists before creating it).
2097
+ * @param did The DID to resolve.
2098
+ * @param options Optional resolution options.
2099
+ * @returns A {@link ResolutionResult} with `ok: true` on success or
2100
+ * `ok: false` with error details on failure.
2101
+ */
2102
+ async tryResolveDid(did, options) {
2103
+ this.#assertNotDisposed();
2104
+ assertString(did, "did");
2105
+ try {
2106
+ const raw = await this.btcr2.resolve(did, options);
2107
+ if (raw.didDocument) {
2108
+ return {
2109
+ ok: true,
2110
+ document: raw.didDocument,
2111
+ metadata: raw.didDocumentMetadata,
2112
+ raw
2113
+ };
2114
+ }
2115
+ return {
2116
+ ok: false,
2117
+ error: raw.didResolutionMetadata?.error ?? "unknown",
2118
+ errorMessage: raw.didResolutionMetadata?.errorMessage,
2119
+ raw
2120
+ };
2121
+ } catch (err) {
2122
+ return {
2123
+ ok: false,
2124
+ error: "internalError",
2125
+ errorMessage: err.message,
2126
+ raw: {
2127
+ didDocument: null,
2128
+ didDocumentMetadata: {},
2129
+ didResolutionMetadata: { error: "internalError", errorMessage: err.message }
2130
+ }
2131
+ };
2132
+ }
2133
+ }
2134
+ /**
2135
+ * Update a DID document: resolve the current state, apply patches, sign, and announce.
2136
+ * Automatically injects the configured Bitcoin connection.
2137
+ *
2138
+ * If `sourceDocument` and `sourceVersionId` are both provided, resolution
2139
+ * is skipped. Otherwise the DID is resolved first to obtain them.
2140
+ * @param params The update parameters.
2141
+ * @returns The signed update.
2142
+ */
2143
+ async updateDid({
2144
+ did,
2145
+ patches,
2146
+ verificationMethodId,
2147
+ beaconId,
2148
+ sourceDocument,
2149
+ sourceVersionId
2150
+ }) {
2151
+ this.#assertNotDisposed();
2152
+ assertString(did, "did");
2153
+ let doc = sourceDocument;
2154
+ let versionId = sourceVersionId;
2155
+ if (!doc || versionId === void 0) {
2156
+ const resolution = await this.resolveDid(did);
2157
+ if (!resolution.didDocument) {
2158
+ const meta = resolution.didResolutionMetadata;
2159
+ const detail = meta?.error ? `: ${meta.error}` : ".";
2160
+ const extra = meta?.errorMessage ? ` ${meta.errorMessage}` : "";
2161
+ throw new Error(
2162
+ `Failed to resolve DID ${did} for update${detail}${extra}`,
2163
+ { cause: meta }
2164
+ );
2165
+ }
2166
+ doc = doc ?? resolution.didDocument;
2167
+ if (versionId === void 0) {
2168
+ const rawVersionId = resolution.didDocumentMetadata?.versionId;
2169
+ if (rawVersionId === void 0 || rawVersionId === null) {
2170
+ throw new Error(
2171
+ `Resolution of DID ${did} succeeded but returned no versionId in metadata. Provide sourceVersionId explicitly.`
2172
+ );
2173
+ }
2174
+ const parsed = Number(rawVersionId);
2175
+ if (!Number.isFinite(parsed)) {
2176
+ throw new Error(
2177
+ `Resolution of DID ${did} returned a non-numeric versionId: ${String(rawVersionId)}.`
2178
+ );
2179
+ }
2180
+ versionId = parsed;
2181
+ }
2182
+ }
2183
+ return await this.btcr2.update({
2184
+ sourceDocument: doc,
2185
+ patches,
2186
+ sourceVersionId: versionId,
2187
+ verificationMethodId,
2188
+ beaconId
2189
+ });
2190
+ }
2191
+ /**
2192
+ * Release internal references. After disposal, accessing `btc`, `btcr2`,
2193
+ * or calling top-level methods will throw.
2194
+ *
2195
+ * Note: the underlying `BitcoinConnection` does not hold persistent
2196
+ * connections, so this is primarily a guard against accidental reuse.
2197
+ */
2198
+ dispose() {
2199
+ this.#btc = void 0;
2200
+ this.#cas = void 0;
2201
+ this.#btcr2 = void 0;
2202
+ this.#btcConfig = void 0;
2203
+ this.#casConfig = void 0;
2204
+ this.#disposed = true;
2205
+ }
2206
+ #assertNotDisposed() {
2207
+ if (this.#disposed) {
2208
+ throw new Error("This DidBtcr2Api instance has been disposed and can no longer be used.");
2209
+ }
2210
+ }
2211
+ };
2212
+ function createApi(config) {
2213
+ return new DidBtcr2Api(config);
2214
+ }
2215
+ // Annotate the CommonJS export names for ESM import in node:
2216
+ 0 && (module.exports = {
2217
+ BitcoinApi,
2218
+ CasApi,
2219
+ CryptoApi,
2220
+ CryptosuiteApi,
2221
+ DataIntegrityProofApi,
2222
+ DidApi,
2223
+ DidBtcr2Api,
2224
+ DidDocument,
2225
+ DidDocumentBuilder,
2226
+ DidMethodApi,
2227
+ Identifier,
2228
+ IdentifierTypes,
2229
+ IpfsCasExecutor,
2230
+ KeyManagerApi,
2231
+ KeyPairApi,
2232
+ MultikeyApi,
2233
+ NOOP_LOGGER,
2234
+ UpdateBuilder,
2235
+ assertBytes,
2236
+ assertCompressedPubkey,
2237
+ assertString,
2238
+ createApi
2239
+ });