@tinycloud/sdk-core 2.7.0-beta.2 → 2.7.0-beta.4

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.
package/dist/index.js CHANGED
@@ -1,3 +1,18 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __typeError = (msg) => {
3
+ throw TypeError(msg);
4
+ };
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __export = (target, all) => {
7
+ for (var name2 in all)
8
+ __defProp(target, name2, { get: all[name2], enumerable: true });
9
+ };
10
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
11
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
12
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
13
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
14
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
15
+
1
16
  // src/client-types.ts
2
17
  import { z } from "zod";
3
18
  import { SiweMessage } from "siwe";
@@ -110,40 +125,945 @@ function canonicalizeDidUrl(didUrl) {
110
125
  function principalDid(didUrl) {
111
126
  return canonicalizeDid(splitDidUrl(didUrl).did);
112
127
  }
113
- function didEquals(a, b, options = {}) {
114
- const canonicalize = options.ignoreFragment ? principalDid : canonicalizeDidUrl;
128
+ function didEquals(a, b, options2 = {}) {
129
+ const canonicalize = options2.ignoreFragment ? principalDid : canonicalizeDidUrl;
115
130
  return canonicalize(a) === canonicalize(b);
116
131
  }
117
132
  function principalDidEquals(a, b) {
118
133
  return didEquals(a, b, { ignoreFragment: true });
119
134
  }
120
- function didCacheKey(input, options = {}) {
135
+ function didCacheKey(input, options2 = {}) {
121
136
  const { did, fragment } = splitDidUrl(input);
122
137
  const pkh = parsePkhDid(did);
123
- const base = pkh ? `did:pkh:eip155:${pkh.chainId}:${addressStorageKey(pkh.address)}` : canonicalizeDid(did);
124
- return options.preserveFragment ? `${base}${fragment}` : base;
138
+ const base3 = pkh ? `did:pkh:eip155:${pkh.chainId}:${addressStorageKey(pkh.address)}` : canonicalizeDid(did);
139
+ return options2.preserveFragment ? `${base3}${fragment}` : base3;
125
140
  }
126
- function makePkhSpaceId(address, chainId, name) {
141
+ function makePkhSpaceId(address, chainId, name2) {
127
142
  assertValidChainId(chainId);
128
- if (!name) {
143
+ if (!name2) {
129
144
  throw new IdentityParseError("Space name cannot be empty");
130
145
  }
131
- return `tinycloud:pkh:eip155:${chainId}:${canonicalizeAddress(address)}:${name}`;
146
+ return `tinycloud:pkh:eip155:${chainId}:${canonicalizeAddress(address)}:${name2}`;
132
147
  }
133
148
 
134
149
  // src/requester/index.ts
135
- import { bytesToHex as bytesToHex3, sha256 as sha2563 } from "viem";
150
+ import { bytesToHex as bytesToHex3, sha256 as sha2564 } from "viem";
136
151
  import { blake3 } from "@noble/hashes/blake3";
137
- import { CID } from "multiformats/cid";
138
- import { create as createDigest } from "multiformats/hashes/digest";
152
+
153
+ // ../../node_modules/multiformats/dist/src/bases/base32.js
154
+ var base32_exports = {};
155
+ __export(base32_exports, {
156
+ base32: () => base32,
157
+ base32hex: () => base32hex,
158
+ base32hexpad: () => base32hexpad,
159
+ base32hexpadupper: () => base32hexpadupper,
160
+ base32hexupper: () => base32hexupper,
161
+ base32pad: () => base32pad,
162
+ base32padupper: () => base32padupper,
163
+ base32upper: () => base32upper,
164
+ base32z: () => base32z
165
+ });
166
+
167
+ // ../../node_modules/multiformats/dist/src/bytes.js
168
+ var empty = new Uint8Array(0);
169
+ function equals(aa, bb) {
170
+ if (aa === bb) {
171
+ return true;
172
+ }
173
+ if (aa.byteLength !== bb.byteLength) {
174
+ return false;
175
+ }
176
+ for (let ii = 0; ii < aa.byteLength; ii++) {
177
+ if (aa[ii] !== bb[ii]) {
178
+ return false;
179
+ }
180
+ }
181
+ return true;
182
+ }
183
+ function coerce(o) {
184
+ if (o instanceof Uint8Array && o.constructor.name === "Uint8Array") {
185
+ return o;
186
+ }
187
+ if (o instanceof ArrayBuffer) {
188
+ return new Uint8Array(o);
189
+ }
190
+ if (ArrayBuffer.isView(o)) {
191
+ return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
192
+ }
193
+ throw new Error("Unknown type, must be binary type");
194
+ }
195
+ function fromString(str) {
196
+ return new TextEncoder().encode(str);
197
+ }
198
+ function toString(b) {
199
+ return new TextDecoder().decode(b);
200
+ }
201
+
202
+ // ../../node_modules/multiformats/dist/src/vendor/base-x.js
203
+ function base(ALPHABET, name2) {
204
+ if (ALPHABET.length >= 255) {
205
+ throw new TypeError("Alphabet too long");
206
+ }
207
+ var BASE_MAP = new Uint8Array(256);
208
+ for (var j = 0; j < BASE_MAP.length; j++) {
209
+ BASE_MAP[j] = 255;
210
+ }
211
+ for (var i = 0; i < ALPHABET.length; i++) {
212
+ var x = ALPHABET.charAt(i);
213
+ var xc = x.charCodeAt(0);
214
+ if (BASE_MAP[xc] !== 255) {
215
+ throw new TypeError(x + " is ambiguous");
216
+ }
217
+ BASE_MAP[xc] = i;
218
+ }
219
+ var BASE = ALPHABET.length;
220
+ var LEADER = ALPHABET.charAt(0);
221
+ var FACTOR = Math.log(BASE) / Math.log(256);
222
+ var iFACTOR = Math.log(256) / Math.log(BASE);
223
+ function encode5(source) {
224
+ if (source instanceof Uint8Array)
225
+ ;
226
+ else if (ArrayBuffer.isView(source)) {
227
+ source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
228
+ } else if (Array.isArray(source)) {
229
+ source = Uint8Array.from(source);
230
+ }
231
+ if (!(source instanceof Uint8Array)) {
232
+ throw new TypeError("Expected Uint8Array");
233
+ }
234
+ if (source.length === 0) {
235
+ return "";
236
+ }
237
+ var zeroes = 0;
238
+ var length2 = 0;
239
+ var pbegin = 0;
240
+ var pend = source.length;
241
+ while (pbegin !== pend && source[pbegin] === 0) {
242
+ pbegin++;
243
+ zeroes++;
244
+ }
245
+ var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
246
+ var b58 = new Uint8Array(size);
247
+ while (pbegin !== pend) {
248
+ var carry = source[pbegin];
249
+ var i2 = 0;
250
+ for (var it1 = size - 1; (carry !== 0 || i2 < length2) && it1 !== -1; it1--, i2++) {
251
+ carry += 256 * b58[it1] >>> 0;
252
+ b58[it1] = carry % BASE >>> 0;
253
+ carry = carry / BASE >>> 0;
254
+ }
255
+ if (carry !== 0) {
256
+ throw new Error("Non-zero carry");
257
+ }
258
+ length2 = i2;
259
+ pbegin++;
260
+ }
261
+ var it2 = size - length2;
262
+ while (it2 !== size && b58[it2] === 0) {
263
+ it2++;
264
+ }
265
+ var str = LEADER.repeat(zeroes);
266
+ for (; it2 < size; ++it2) {
267
+ str += ALPHABET.charAt(b58[it2]);
268
+ }
269
+ return str;
270
+ }
271
+ function decodeUnsafe(source) {
272
+ if (typeof source !== "string") {
273
+ throw new TypeError("Expected String");
274
+ }
275
+ if (source.length === 0) {
276
+ return new Uint8Array();
277
+ }
278
+ var psz = 0;
279
+ if (source[psz] === " ") {
280
+ return;
281
+ }
282
+ var zeroes = 0;
283
+ var length2 = 0;
284
+ while (source[psz] === LEADER) {
285
+ zeroes++;
286
+ psz++;
287
+ }
288
+ var size = (source.length - psz) * FACTOR + 1 >>> 0;
289
+ var b256 = new Uint8Array(size);
290
+ while (source[psz]) {
291
+ var carry = BASE_MAP[source.charCodeAt(psz)];
292
+ if (carry === 255) {
293
+ return;
294
+ }
295
+ var i2 = 0;
296
+ for (var it3 = size - 1; (carry !== 0 || i2 < length2) && it3 !== -1; it3--, i2++) {
297
+ carry += BASE * b256[it3] >>> 0;
298
+ b256[it3] = carry % 256 >>> 0;
299
+ carry = carry / 256 >>> 0;
300
+ }
301
+ if (carry !== 0) {
302
+ throw new Error("Non-zero carry");
303
+ }
304
+ length2 = i2;
305
+ psz++;
306
+ }
307
+ if (source[psz] === " ") {
308
+ return;
309
+ }
310
+ var it4 = size - length2;
311
+ while (it4 !== size && b256[it4] === 0) {
312
+ it4++;
313
+ }
314
+ var vch = new Uint8Array(zeroes + (size - it4));
315
+ var j2 = zeroes;
316
+ while (it4 !== size) {
317
+ vch[j2++] = b256[it4++];
318
+ }
319
+ return vch;
320
+ }
321
+ function decode7(string2) {
322
+ var buffer = decodeUnsafe(string2);
323
+ if (buffer) {
324
+ return buffer;
325
+ }
326
+ throw new Error(`Non-${name2} character`);
327
+ }
328
+ return {
329
+ encode: encode5,
330
+ decodeUnsafe,
331
+ decode: decode7
332
+ };
333
+ }
334
+ var src = base;
335
+ var _brrp__multiformats_scope_baseX = src;
336
+ var base_x_default = _brrp__multiformats_scope_baseX;
337
+
338
+ // ../../node_modules/multiformats/dist/src/bases/base.js
339
+ var Encoder = class {
340
+ constructor(name2, prefix, baseEncode) {
341
+ __publicField(this, "name");
342
+ __publicField(this, "prefix");
343
+ __publicField(this, "baseEncode");
344
+ this.name = name2;
345
+ this.prefix = prefix;
346
+ this.baseEncode = baseEncode;
347
+ }
348
+ encode(bytes) {
349
+ if (bytes instanceof Uint8Array) {
350
+ return `${this.prefix}${this.baseEncode(bytes)}`;
351
+ } else {
352
+ throw Error("Unknown type, must be binary type");
353
+ }
354
+ }
355
+ };
356
+ var Decoder = class {
357
+ constructor(name2, prefix, baseDecode) {
358
+ __publicField(this, "name");
359
+ __publicField(this, "prefix");
360
+ __publicField(this, "baseDecode");
361
+ __publicField(this, "prefixCodePoint");
362
+ this.name = name2;
363
+ this.prefix = prefix;
364
+ const prefixCodePoint = prefix.codePointAt(0);
365
+ if (prefixCodePoint === void 0) {
366
+ throw new Error("Invalid prefix character");
367
+ }
368
+ this.prefixCodePoint = prefixCodePoint;
369
+ this.baseDecode = baseDecode;
370
+ }
371
+ decode(text) {
372
+ if (typeof text === "string") {
373
+ if (text.codePointAt(0) !== this.prefixCodePoint) {
374
+ throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
375
+ }
376
+ return this.baseDecode(text.slice(this.prefix.length));
377
+ } else {
378
+ throw Error("Can only multibase decode strings");
379
+ }
380
+ }
381
+ or(decoder) {
382
+ return or(this, decoder);
383
+ }
384
+ };
385
+ var ComposedDecoder = class {
386
+ constructor(decoders2) {
387
+ __publicField(this, "decoders");
388
+ this.decoders = decoders2;
389
+ }
390
+ or(decoder) {
391
+ return or(this, decoder);
392
+ }
393
+ decode(input) {
394
+ const prefix = input[0];
395
+ const decoder = this.decoders[prefix];
396
+ if (decoder != null) {
397
+ return decoder.decode(input);
398
+ } else {
399
+ throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
400
+ }
401
+ }
402
+ };
403
+ function or(left, right) {
404
+ return new ComposedDecoder({
405
+ ...left.decoders ?? { [left.prefix]: left },
406
+ ...right.decoders ?? { [right.prefix]: right }
407
+ });
408
+ }
409
+ var Codec = class {
410
+ constructor(name2, prefix, baseEncode, baseDecode) {
411
+ __publicField(this, "name");
412
+ __publicField(this, "prefix");
413
+ __publicField(this, "baseEncode");
414
+ __publicField(this, "baseDecode");
415
+ __publicField(this, "encoder");
416
+ __publicField(this, "decoder");
417
+ this.name = name2;
418
+ this.prefix = prefix;
419
+ this.baseEncode = baseEncode;
420
+ this.baseDecode = baseDecode;
421
+ this.encoder = new Encoder(name2, prefix, baseEncode);
422
+ this.decoder = new Decoder(name2, prefix, baseDecode);
423
+ }
424
+ encode(input) {
425
+ return this.encoder.encode(input);
426
+ }
427
+ decode(input) {
428
+ return this.decoder.decode(input);
429
+ }
430
+ };
431
+ function from({ name: name2, prefix, encode: encode5, decode: decode7 }) {
432
+ return new Codec(name2, prefix, encode5, decode7);
433
+ }
434
+ function baseX({ name: name2, prefix, alphabet: alphabet2 }) {
435
+ const { encode: encode5, decode: decode7 } = base_x_default(alphabet2, name2);
436
+ return from({
437
+ prefix,
438
+ name: name2,
439
+ encode: encode5,
440
+ decode: (text) => coerce(decode7(text))
441
+ });
442
+ }
443
+ function decode(string2, alphabetIdx, bitsPerChar, name2) {
444
+ let end = string2.length;
445
+ while (string2[end - 1] === "=") {
446
+ --end;
447
+ }
448
+ const out = new Uint8Array(end * bitsPerChar / 8 | 0);
449
+ let bits = 0;
450
+ let buffer = 0;
451
+ let written = 0;
452
+ for (let i = 0; i < end; ++i) {
453
+ const value = alphabetIdx[string2[i]];
454
+ if (value === void 0) {
455
+ throw new SyntaxError(`Non-${name2} character`);
456
+ }
457
+ buffer = buffer << bitsPerChar | value;
458
+ bits += bitsPerChar;
459
+ if (bits >= 8) {
460
+ bits -= 8;
461
+ out[written++] = 255 & buffer >> bits;
462
+ }
463
+ }
464
+ if (bits >= bitsPerChar || (255 & buffer << 8 - bits) !== 0) {
465
+ throw new SyntaxError("Unexpected end of data");
466
+ }
467
+ return out;
468
+ }
469
+ function encode(data, alphabet2, bitsPerChar) {
470
+ const pad = alphabet2[alphabet2.length - 1] === "=";
471
+ const mask = (1 << bitsPerChar) - 1;
472
+ let out = "";
473
+ let bits = 0;
474
+ let buffer = 0;
475
+ for (let i = 0; i < data.length; ++i) {
476
+ buffer = buffer << 8 | data[i];
477
+ bits += 8;
478
+ while (bits > bitsPerChar) {
479
+ bits -= bitsPerChar;
480
+ out += alphabet2[mask & buffer >> bits];
481
+ }
482
+ }
483
+ if (bits !== 0) {
484
+ out += alphabet2[mask & buffer << bitsPerChar - bits];
485
+ }
486
+ if (pad) {
487
+ while ((out.length * bitsPerChar & 7) !== 0) {
488
+ out += "=";
489
+ }
490
+ }
491
+ return out;
492
+ }
493
+ function createAlphabetIdx(alphabet2) {
494
+ const alphabetIdx = {};
495
+ for (let i = 0; i < alphabet2.length; ++i) {
496
+ alphabetIdx[alphabet2[i]] = i;
497
+ }
498
+ return alphabetIdx;
499
+ }
500
+ function rfc4648({ name: name2, prefix, bitsPerChar, alphabet: alphabet2 }) {
501
+ const alphabetIdx = createAlphabetIdx(alphabet2);
502
+ return from({
503
+ prefix,
504
+ name: name2,
505
+ encode(input) {
506
+ return encode(input, alphabet2, bitsPerChar);
507
+ },
508
+ decode(input) {
509
+ return decode(input, alphabetIdx, bitsPerChar, name2);
510
+ }
511
+ });
512
+ }
513
+
514
+ // ../../node_modules/multiformats/dist/src/bases/base32.js
515
+ var base32 = rfc4648({
516
+ prefix: "b",
517
+ name: "base32",
518
+ alphabet: "abcdefghijklmnopqrstuvwxyz234567",
519
+ bitsPerChar: 5
520
+ });
521
+ var base32upper = rfc4648({
522
+ prefix: "B",
523
+ name: "base32upper",
524
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
525
+ bitsPerChar: 5
526
+ });
527
+ var base32pad = rfc4648({
528
+ prefix: "c",
529
+ name: "base32pad",
530
+ alphabet: "abcdefghijklmnopqrstuvwxyz234567=",
531
+ bitsPerChar: 5
532
+ });
533
+ var base32padupper = rfc4648({
534
+ prefix: "C",
535
+ name: "base32padupper",
536
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",
537
+ bitsPerChar: 5
538
+ });
539
+ var base32hex = rfc4648({
540
+ prefix: "v",
541
+ name: "base32hex",
542
+ alphabet: "0123456789abcdefghijklmnopqrstuv",
543
+ bitsPerChar: 5
544
+ });
545
+ var base32hexupper = rfc4648({
546
+ prefix: "V",
547
+ name: "base32hexupper",
548
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV",
549
+ bitsPerChar: 5
550
+ });
551
+ var base32hexpad = rfc4648({
552
+ prefix: "t",
553
+ name: "base32hexpad",
554
+ alphabet: "0123456789abcdefghijklmnopqrstuv=",
555
+ bitsPerChar: 5
556
+ });
557
+ var base32hexpadupper = rfc4648({
558
+ prefix: "T",
559
+ name: "base32hexpadupper",
560
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=",
561
+ bitsPerChar: 5
562
+ });
563
+ var base32z = rfc4648({
564
+ prefix: "h",
565
+ name: "base32z",
566
+ alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769",
567
+ bitsPerChar: 5
568
+ });
569
+
570
+ // ../../node_modules/multiformats/dist/src/bases/base36.js
571
+ var base36_exports = {};
572
+ __export(base36_exports, {
573
+ base36: () => base36,
574
+ base36upper: () => base36upper
575
+ });
576
+ var base36 = baseX({
577
+ prefix: "k",
578
+ name: "base36",
579
+ alphabet: "0123456789abcdefghijklmnopqrstuvwxyz"
580
+ });
581
+ var base36upper = baseX({
582
+ prefix: "K",
583
+ name: "base36upper",
584
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
585
+ });
586
+
587
+ // ../../node_modules/multiformats/dist/src/bases/base58.js
588
+ var base58_exports = {};
589
+ __export(base58_exports, {
590
+ base58btc: () => base58btc,
591
+ base58flickr: () => base58flickr
592
+ });
593
+ var base58btc = baseX({
594
+ name: "base58btc",
595
+ prefix: "z",
596
+ alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
597
+ });
598
+ var base58flickr = baseX({
599
+ name: "base58flickr",
600
+ prefix: "Z",
601
+ alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
602
+ });
603
+
604
+ // ../../node_modules/multiformats/dist/src/vendor/varint.js
605
+ var encode_1 = encode2;
606
+ var MSB = 128;
607
+ var REST = 127;
608
+ var MSBALL = ~REST;
609
+ var INT = Math.pow(2, 31);
610
+ function encode2(num, out, offset) {
611
+ out = out || [];
612
+ offset = offset || 0;
613
+ var oldOffset = offset;
614
+ while (num >= INT) {
615
+ out[offset++] = num & 255 | MSB;
616
+ num /= 128;
617
+ }
618
+ while (num & MSBALL) {
619
+ out[offset++] = num & 255 | MSB;
620
+ num >>>= 7;
621
+ }
622
+ out[offset] = num | 0;
623
+ encode2.bytes = offset - oldOffset + 1;
624
+ return out;
625
+ }
626
+ var decode2 = read;
627
+ var MSB$1 = 128;
628
+ var REST$1 = 127;
629
+ function read(buf, offset) {
630
+ var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
631
+ do {
632
+ if (counter >= l) {
633
+ read.bytes = 0;
634
+ throw new RangeError("Could not decode varint");
635
+ }
636
+ b = buf[counter++];
637
+ res += shift < 28 ? (b & REST$1) << shift : (b & REST$1) * Math.pow(2, shift);
638
+ shift += 7;
639
+ } while (b >= MSB$1);
640
+ read.bytes = counter - offset;
641
+ return res;
642
+ }
643
+ var N1 = Math.pow(2, 7);
644
+ var N2 = Math.pow(2, 14);
645
+ var N3 = Math.pow(2, 21);
646
+ var N4 = Math.pow(2, 28);
647
+ var N5 = Math.pow(2, 35);
648
+ var N6 = Math.pow(2, 42);
649
+ var N7 = Math.pow(2, 49);
650
+ var N8 = Math.pow(2, 56);
651
+ var N9 = Math.pow(2, 63);
652
+ var length = function(value) {
653
+ 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;
654
+ };
655
+ var varint = {
656
+ encode: encode_1,
657
+ decode: decode2,
658
+ encodingLength: length
659
+ };
660
+ var _brrp_varint = varint;
661
+ var varint_default = _brrp_varint;
662
+
663
+ // ../../node_modules/multiformats/dist/src/varint.js
664
+ function decode3(data, offset = 0) {
665
+ const code2 = varint_default.decode(data, offset);
666
+ return [code2, varint_default.decode.bytes];
667
+ }
668
+ function encodeTo(int, target, offset = 0) {
669
+ varint_default.encode(int, target, offset);
670
+ return target;
671
+ }
672
+ function encodingLength(int) {
673
+ return varint_default.encodingLength(int);
674
+ }
675
+
676
+ // ../../node_modules/multiformats/dist/src/hashes/digest.js
677
+ function create(code2, digest2) {
678
+ const size = digest2.byteLength;
679
+ const sizeOffset = encodingLength(code2);
680
+ const digestOffset = sizeOffset + encodingLength(size);
681
+ const bytes = new Uint8Array(digestOffset + size);
682
+ encodeTo(code2, bytes, 0);
683
+ encodeTo(size, bytes, sizeOffset);
684
+ bytes.set(digest2, digestOffset);
685
+ return new Digest(code2, size, digest2, bytes);
686
+ }
687
+ function decode4(multihash) {
688
+ const bytes = coerce(multihash);
689
+ const [code2, sizeOffset] = decode3(bytes);
690
+ const [size, digestOffset] = decode3(bytes.subarray(sizeOffset));
691
+ const digest2 = bytes.subarray(sizeOffset + digestOffset);
692
+ if (digest2.byteLength !== size) {
693
+ throw new Error("Incorrect length");
694
+ }
695
+ return new Digest(code2, size, digest2, bytes);
696
+ }
697
+ function equals2(a, b) {
698
+ if (a === b) {
699
+ return true;
700
+ } else {
701
+ const data = b;
702
+ return a.code === data.code && a.size === data.size && data.bytes instanceof Uint8Array && equals(a.bytes, data.bytes);
703
+ }
704
+ }
705
+ var Digest = class {
706
+ /**
707
+ * Creates a multihash digest.
708
+ */
709
+ constructor(code2, size, digest2, bytes) {
710
+ __publicField(this, "code");
711
+ __publicField(this, "size");
712
+ __publicField(this, "digest");
713
+ __publicField(this, "bytes");
714
+ this.code = code2;
715
+ this.size = size;
716
+ this.digest = digest2;
717
+ this.bytes = bytes;
718
+ }
719
+ };
720
+
721
+ // ../../node_modules/multiformats/dist/src/cid.js
722
+ function format(link, base3) {
723
+ const { bytes, version } = link;
724
+ switch (version) {
725
+ case 0:
726
+ return toStringV0(bytes, baseCache(link), base3 ?? base58btc.encoder);
727
+ default:
728
+ return toStringV1(bytes, baseCache(link), base3 ?? base32.encoder);
729
+ }
730
+ }
731
+ var cache = /* @__PURE__ */ new WeakMap();
732
+ function baseCache(cid) {
733
+ const baseCache2 = cache.get(cid);
734
+ if (baseCache2 == null) {
735
+ const baseCache3 = /* @__PURE__ */ new Map();
736
+ cache.set(cid, baseCache3);
737
+ return baseCache3;
738
+ }
739
+ return baseCache2;
740
+ }
741
+ var _a;
742
+ var CID = class _CID {
743
+ /**
744
+ * @param version - Version of the CID
745
+ * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
746
+ * @param multihash - (Multi)hash of the of the content.
747
+ */
748
+ constructor(version, code2, multihash, bytes) {
749
+ __publicField(this, "code");
750
+ __publicField(this, "version");
751
+ __publicField(this, "multihash");
752
+ __publicField(this, "bytes");
753
+ __publicField(this, "/");
754
+ __publicField(this, _a, "CID");
755
+ this.code = code2;
756
+ this.version = version;
757
+ this.multihash = multihash;
758
+ this.bytes = bytes;
759
+ this["/"] = bytes;
760
+ }
761
+ /**
762
+ * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`
763
+ * please either use `CID.asCID(cid)` or switch to new signalling mechanism
764
+ *
765
+ * @deprecated
766
+ */
767
+ get asCID() {
768
+ return this;
769
+ }
770
+ // ArrayBufferView
771
+ get byteOffset() {
772
+ return this.bytes.byteOffset;
773
+ }
774
+ // ArrayBufferView
775
+ get byteLength() {
776
+ return this.bytes.byteLength;
777
+ }
778
+ toV0() {
779
+ switch (this.version) {
780
+ case 0: {
781
+ return this;
782
+ }
783
+ case 1: {
784
+ const { code: code2, multihash } = this;
785
+ if (code2 !== DAG_PB_CODE) {
786
+ throw new Error("Cannot convert a non dag-pb CID to CIDv0");
787
+ }
788
+ if (multihash.code !== SHA_256_CODE) {
789
+ throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");
790
+ }
791
+ return _CID.createV0(multihash);
792
+ }
793
+ default: {
794
+ throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
795
+ }
796
+ }
797
+ }
798
+ toV1() {
799
+ switch (this.version) {
800
+ case 0: {
801
+ const { code: code2, digest: digest2 } = this.multihash;
802
+ const multihash = create(code2, digest2);
803
+ return _CID.createV1(this.code, multihash);
804
+ }
805
+ case 1: {
806
+ return this;
807
+ }
808
+ default: {
809
+ throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);
810
+ }
811
+ }
812
+ }
813
+ equals(other) {
814
+ return _CID.equals(this, other);
815
+ }
816
+ static equals(self, other) {
817
+ const unknown = other;
818
+ return unknown != null && self.code === unknown.code && self.version === unknown.version && equals2(self.multihash, unknown.multihash);
819
+ }
820
+ toString(base3) {
821
+ return format(this, base3);
822
+ }
823
+ toJSON() {
824
+ return { "/": format(this) };
825
+ }
826
+ link() {
827
+ return this;
828
+ }
829
+ // Legacy
830
+ [(_a = Symbol.toStringTag, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"))]() {
831
+ return `CID(${this.toString()})`;
832
+ }
833
+ /**
834
+ * Takes any input `value` and returns a `CID` instance if it was
835
+ * a `CID` otherwise returns `null`. If `value` is instanceof `CID`
836
+ * it will return value back. If `value` is not instance of this CID
837
+ * class, but is compatible CID it will return new instance of this
838
+ * `CID` class. Otherwise returns null.
839
+ *
840
+ * This allows two different incompatible versions of CID library to
841
+ * co-exist and interop as long as binary interface is compatible.
842
+ */
843
+ static asCID(input) {
844
+ if (input == null) {
845
+ return null;
846
+ }
847
+ const value = input;
848
+ if (value instanceof _CID) {
849
+ return value;
850
+ } else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) {
851
+ const { version, code: code2, multihash, bytes } = value;
852
+ return new _CID(version, code2, multihash, bytes ?? encodeCID(version, code2, multihash.bytes));
853
+ } else if (value[cidSymbol] === true) {
854
+ const { version, multihash, code: code2 } = value;
855
+ const digest2 = decode4(multihash);
856
+ return _CID.create(version, code2, digest2);
857
+ } else {
858
+ return null;
859
+ }
860
+ }
861
+ /**
862
+ * @param version - Version of the CID
863
+ * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv
864
+ * @param digest - (Multi)hash of the of the content.
865
+ */
866
+ static create(version, code2, digest2) {
867
+ if (typeof code2 !== "number") {
868
+ throw new Error("String codecs are no longer supported");
869
+ }
870
+ if (!(digest2.bytes instanceof Uint8Array)) {
871
+ throw new Error("Invalid digest");
872
+ }
873
+ switch (version) {
874
+ case 0: {
875
+ if (code2 !== DAG_PB_CODE) {
876
+ throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
877
+ } else {
878
+ return new _CID(version, code2, digest2, digest2.bytes);
879
+ }
880
+ }
881
+ case 1: {
882
+ const bytes = encodeCID(version, code2, digest2.bytes);
883
+ return new _CID(version, code2, digest2, bytes);
884
+ }
885
+ default: {
886
+ throw new Error("Invalid version");
887
+ }
888
+ }
889
+ }
890
+ /**
891
+ * Simplified version of `create` for CIDv0.
892
+ */
893
+ static createV0(digest2) {
894
+ return _CID.create(0, DAG_PB_CODE, digest2);
895
+ }
896
+ /**
897
+ * Simplified version of `create` for CIDv1.
898
+ *
899
+ * @param code - Content encoding format code.
900
+ * @param digest - Multihash of the content.
901
+ */
902
+ static createV1(code2, digest2) {
903
+ return _CID.create(1, code2, digest2);
904
+ }
905
+ /**
906
+ * Decoded a CID from its binary representation. The byte array must contain
907
+ * only the CID with no additional bytes.
908
+ *
909
+ * An error will be thrown if the bytes provided do not contain a valid
910
+ * binary representation of a CID.
911
+ */
912
+ static decode(bytes) {
913
+ const [cid, remainder] = _CID.decodeFirst(bytes);
914
+ if (remainder.length !== 0) {
915
+ throw new Error("Incorrect length");
916
+ }
917
+ return cid;
918
+ }
919
+ /**
920
+ * Decoded a CID from its binary representation at the beginning of a byte
921
+ * array.
922
+ *
923
+ * Returns an array with the first element containing the CID and the second
924
+ * element containing the remainder of the original byte array. The remainder
925
+ * will be a zero-length byte array if the provided bytes only contained a
926
+ * binary CID representation.
927
+ */
928
+ static decodeFirst(bytes) {
929
+ const specs = _CID.inspectBytes(bytes);
930
+ const prefixSize = specs.size - specs.multihashSize;
931
+ const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
932
+ if (multihashBytes.byteLength !== specs.multihashSize) {
933
+ throw new Error("Incorrect length");
934
+ }
935
+ const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
936
+ const digest2 = new Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
937
+ const cid = specs.version === 0 ? _CID.createV0(digest2) : _CID.createV1(specs.codec, digest2);
938
+ return [cid, bytes.subarray(specs.size)];
939
+ }
940
+ /**
941
+ * Inspect the initial bytes of a CID to determine its properties.
942
+ *
943
+ * Involves decoding up to 4 varints. Typically this will require only 4 to 6
944
+ * bytes but for larger multicodec code values and larger multihash digest
945
+ * lengths these varints can be quite large. It is recommended that at least
946
+ * 10 bytes be made available in the `initialBytes` argument for a complete
947
+ * inspection.
948
+ */
949
+ static inspectBytes(initialBytes) {
950
+ let offset = 0;
951
+ const next = () => {
952
+ const [i, length2] = decode3(initialBytes.subarray(offset));
953
+ offset += length2;
954
+ return i;
955
+ };
956
+ let version = next();
957
+ let codec = DAG_PB_CODE;
958
+ if (version === 18) {
959
+ version = 0;
960
+ offset = 0;
961
+ } else {
962
+ codec = next();
963
+ }
964
+ if (version !== 0 && version !== 1) {
965
+ throw new RangeError(`Invalid CID version ${version}`);
966
+ }
967
+ const prefixSize = offset;
968
+ const multihashCode = next();
969
+ const digestSize = next();
970
+ const size = offset + digestSize;
971
+ const multihashSize = size - prefixSize;
972
+ return { version, codec, multihashCode, digestSize, multihashSize, size };
973
+ }
974
+ /**
975
+ * Takes cid in a string representation and creates an instance. If `base`
976
+ * decoder is not provided will use a default from the configuration. It will
977
+ * throw an error if encoding of the CID is not compatible with supplied (or
978
+ * a default decoder).
979
+ */
980
+ static parse(source, base3) {
981
+ const [prefix, bytes] = parseCIDtoBytes(source, base3);
982
+ const cid = _CID.decode(bytes);
983
+ if (cid.version === 0 && source[0] !== "Q") {
984
+ throw Error("Version 0 CID string must not include multibase prefix");
985
+ }
986
+ baseCache(cid).set(prefix, source);
987
+ return cid;
988
+ }
989
+ };
990
+ function parseCIDtoBytes(source, base3) {
991
+ switch (source[0]) {
992
+ // CIDv0 is parsed differently
993
+ case "Q": {
994
+ const decoder = base3 ?? base58btc;
995
+ return [
996
+ base58btc.prefix,
997
+ decoder.decode(`${base58btc.prefix}${source}`)
998
+ ];
999
+ }
1000
+ case base58btc.prefix: {
1001
+ const decoder = base3 ?? base58btc;
1002
+ return [base58btc.prefix, decoder.decode(source)];
1003
+ }
1004
+ case base32.prefix: {
1005
+ const decoder = base3 ?? base32;
1006
+ return [base32.prefix, decoder.decode(source)];
1007
+ }
1008
+ case base36.prefix: {
1009
+ const decoder = base3 ?? base36;
1010
+ return [base36.prefix, decoder.decode(source)];
1011
+ }
1012
+ default: {
1013
+ if (base3 == null) {
1014
+ throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");
1015
+ }
1016
+ return [source[0], base3.decode(source)];
1017
+ }
1018
+ }
1019
+ }
1020
+ function toStringV0(bytes, cache2, base3) {
1021
+ const { prefix } = base3;
1022
+ if (prefix !== base58btc.prefix) {
1023
+ throw Error(`Cannot string encode V0 in ${base3.name} encoding`);
1024
+ }
1025
+ const cid = cache2.get(prefix);
1026
+ if (cid == null) {
1027
+ const cid2 = base3.encode(bytes).slice(1);
1028
+ cache2.set(prefix, cid2);
1029
+ return cid2;
1030
+ } else {
1031
+ return cid;
1032
+ }
1033
+ }
1034
+ function toStringV1(bytes, cache2, base3) {
1035
+ const { prefix } = base3;
1036
+ const cid = cache2.get(prefix);
1037
+ if (cid == null) {
1038
+ const cid2 = base3.encode(bytes);
1039
+ cache2.set(prefix, cid2);
1040
+ return cid2;
1041
+ } else {
1042
+ return cid;
1043
+ }
1044
+ }
1045
+ var DAG_PB_CODE = 112;
1046
+ var SHA_256_CODE = 18;
1047
+ function encodeCID(version, code2, multihash) {
1048
+ const codeOffset = encodingLength(version);
1049
+ const hashOffset = codeOffset + encodingLength(code2);
1050
+ const bytes = new Uint8Array(hashOffset + multihash.byteLength);
1051
+ encodeTo(version, bytes, 0);
1052
+ encodeTo(code2, bytes, codeOffset);
1053
+ bytes.set(multihash, hashOffset);
1054
+ return bytes;
1055
+ }
1056
+ var cidSymbol = /* @__PURE__ */ Symbol.for("@ipld/js-cid/CID");
1057
+
1058
+ // src/requester/index.ts
139
1059
  import { z as z2 } from "zod";
140
1060
 
141
1061
  // src/policy/errors.ts
142
1062
  var SignedObjectProfileError = class extends Error {
143
- constructor(code, message) {
1063
+ constructor(code2, message) {
144
1064
  super(message);
145
1065
  this.name = "SignedObjectProfileError";
146
- this.code = code;
1066
+ this.code = code2;
147
1067
  }
148
1068
  };
149
1069
  var SignedObjectSchemaError = class extends SignedObjectProfileError {
@@ -341,35 +1261,33 @@ function assertNoSymbolKeys(input, path) {
341
1261
  );
342
1262
  }
343
1263
  }
344
- function isArrayIndexKey(key, length) {
1264
+ function isArrayIndexKey(key, length2) {
345
1265
  if (!/^(0|[1-9]\d*)$/.test(key)) {
346
1266
  return false;
347
1267
  }
348
1268
  const index = Number(key);
349
- return Number.isSafeInteger(index) && index >= 0 && index < length;
1269
+ return Number.isSafeInteger(index) && index >= 0 && index < length2;
350
1270
  }
351
1271
  function serializeObject(value) {
352
- const keys = Object.keys(value).sort(compareCodePoints);
1272
+ const keys = Object.keys(value).sort(compareUtf16CodeUnits);
353
1273
  const parts = keys.map((key) => `${JSON.stringify(key)}:${serialize(value[key])}`);
354
1274
  return `{${parts.join(",")}}`;
355
1275
  }
356
- function compareCodePoints(a, b) {
357
- const left = Array.from(a);
358
- const right = Array.from(b);
359
- const max = Math.min(left.length, right.length);
1276
+ function compareUtf16CodeUnits(a, b) {
1277
+ const max = Math.min(a.length, b.length);
360
1278
  for (let index = 0; index < max; index++) {
361
- const leftPoint = left[index].codePointAt(0) ?? 0;
362
- const rightPoint = right[index].codePointAt(0) ?? 0;
363
- if (leftPoint !== rightPoint) {
364
- return leftPoint - rightPoint;
1279
+ const leftCodeUnit = a.charCodeAt(index);
1280
+ const rightCodeUnit = b.charCodeAt(index);
1281
+ if (leftCodeUnit !== rightCodeUnit) {
1282
+ return leftCodeUnit - rightCodeUnit;
365
1283
  }
366
1284
  }
367
- return left.length - right.length;
1285
+ return a.length - b.length;
368
1286
  }
369
1287
  function assertUnicodeScalarString(value, path) {
370
1288
  for (let index = 0; index < value.length; index++) {
371
- const code = value.charCodeAt(index);
372
- if (code >= 55296 && code <= 56319) {
1289
+ const code2 = value.charCodeAt(index);
1290
+ if (code2 >= 55296 && code2 <= 56319) {
373
1291
  const next = value.charCodeAt(index + 1);
374
1292
  if (Number.isNaN(next) || next < 56320 || next > 57343) {
375
1293
  throw new SignedObjectCanonicalizationError(
@@ -379,7 +1297,7 @@ function assertUnicodeScalarString(value, path) {
379
1297
  index++;
380
1298
  continue;
381
1299
  }
382
- if (code >= 56320 && code <= 57343) {
1300
+ if (code2 >= 56320 && code2 <= 57343) {
383
1301
  throw new SignedObjectCanonicalizationError(
384
1302
  `${path} contains a lone low surrogate`
385
1303
  );
@@ -392,10 +1310,10 @@ import { CAPABILITY_REGISTRY } from "@tinycloud/bootstrap";
392
1310
  import { bytesToHex, sha256 } from "viem";
393
1311
  var textEncoder = new TextEncoder();
394
1312
  var PolicyCapabilityError = class extends Error {
395
- constructor(code, message) {
1313
+ constructor(code2, message) {
396
1314
  super(message);
397
1315
  this.name = "PolicyCapabilityError";
398
- this.code = code;
1316
+ this.code = code2;
399
1317
  }
400
1318
  };
401
1319
  var objectHasOwn2 = Object.hasOwn ?? Object.prototype.hasOwnProperty.call.bind(
@@ -446,7 +1364,7 @@ function policyCapabilityContains(authority, request) {
446
1364
  }
447
1365
  return caveatsContain(auth.caveats, req.caveats);
448
1366
  }
449
- function normalizePolicyCapabilityWithOptions(input, options) {
1367
+ function normalizePolicyCapabilityWithOptions(input, options2) {
450
1368
  const object = expectObject(input, "$");
451
1369
  assertExactKeys(object, ["service", "space", "path", "actions", "caveats"], "$");
452
1370
  const service = requiredString(object, "service", "$", "policy-capability-malformed-service");
@@ -459,26 +1377,26 @@ function normalizePolicyCapabilityWithOptions(input, options) {
459
1377
  const space = requiredString(object, "space", "$", "policy-capability-malformed-space");
460
1378
  validateConcreteSpace(space);
461
1379
  const canonicalSpace = space.normalize("NFC");
462
- if (options.requireCanonical && canonicalSpace !== space) {
1380
+ if (options2.requireCanonical && canonicalSpace !== space) {
463
1381
  throw new PolicyCapabilityError(
464
1382
  "policy-capability-malformed-space",
465
1383
  "$.space must already be canonical NFC"
466
1384
  );
467
1385
  }
468
1386
  const rawPath = requiredString(object, "path", "$", "policy-capability-malformed-path");
469
- validateRawPath(rawPath, options);
1387
+ validateRawPath(rawPath, options2);
470
1388
  const path = normalizePath(rawPath);
471
- if (options.requireCanonical && path !== rawPath) {
1389
+ if (options2.requireCanonical && path !== rawPath) {
472
1390
  throw new PolicyCapabilityError(
473
1391
  "policy-capability-malformed-path",
474
1392
  "$.path must already be canonical"
475
1393
  );
476
1394
  }
477
- validateRawPath(path, options);
1395
+ validateRawPath(path, options2);
478
1396
  const actions = normalizeActions(
479
1397
  requiredArray(object, "actions", "$", "policy-capability-malformed-action"),
480
1398
  service,
481
- options
1399
+ options2
482
1400
  );
483
1401
  const output = /* @__PURE__ */ Object.create(null);
484
1402
  output.service = service;
@@ -521,23 +1439,23 @@ function assertExactKeys(object, allowed, path) {
521
1439
  }
522
1440
  }
523
1441
  }
524
- function requiredValue(object, key, path, code) {
1442
+ function requiredValue(object, key, path, code2) {
525
1443
  if (!hasOwn(object, key)) {
526
- throw new PolicyCapabilityError(code, `${path}.${key} is required`);
1444
+ throw new PolicyCapabilityError(code2, `${path}.${key} is required`);
527
1445
  }
528
1446
  return object[key];
529
1447
  }
530
- function requiredString(object, key, path, code) {
531
- const value = requiredValue(object, key, path, code);
1448
+ function requiredString(object, key, path, code2) {
1449
+ const value = requiredValue(object, key, path, code2);
532
1450
  if (typeof value !== "string" || value.length === 0) {
533
- throw new PolicyCapabilityError(code, `${path}.${key} must be a non-empty string`);
1451
+ throw new PolicyCapabilityError(code2, `${path}.${key} must be a non-empty string`);
534
1452
  }
535
1453
  return value;
536
1454
  }
537
- function requiredArray(object, key, path, code) {
538
- const value = requiredValue(object, key, path, code);
1455
+ function requiredArray(object, key, path, code2) {
1456
+ const value = requiredValue(object, key, path, code2);
539
1457
  if (!Array.isArray(value)) {
540
- throw new PolicyCapabilityError(code, `${path}.${key} must be an array`);
1458
+ throw new PolicyCapabilityError(code2, `${path}.${key} must be an array`);
541
1459
  }
542
1460
  return value;
543
1461
  }
@@ -549,11 +1467,11 @@ function validateConcreteSpace(space) {
549
1467
  );
550
1468
  }
551
1469
  }
552
- function validateRawPath(path, options) {
1470
+ function validateRawPath(path, options2) {
553
1471
  if (path.length === 0) {
554
1472
  throw new PolicyCapabilityError("policy-capability-malformed-path", "$.path is empty");
555
1473
  }
556
- if (!options.allowPrefixPaths && path.endsWith("/")) {
1474
+ if (!options2.allowPrefixPaths && path.endsWith("/")) {
557
1475
  throw new PolicyCapabilityError(
558
1476
  "policy-capability-malformed-path",
559
1477
  "$.path must be an exact concrete path, not a prefix"
@@ -565,7 +1483,7 @@ function validateRawPath(path, options) {
565
1483
  const segments = path.split("/");
566
1484
  for (let index = 0; index < segments.length; index++) {
567
1485
  const segment = segments[index];
568
- const isTrailingPrefixSegment = options.allowPrefixPaths && index === segments.length - 1 && segment.length === 0;
1486
+ const isTrailingPrefixSegment = options2.allowPrefixPaths && index === segments.length - 1 && segment.length === 0;
569
1487
  if (segment.length === 0 && !isTrailingPrefixSegment) {
570
1488
  throw new PolicyCapabilityError("policy-capability-malformed-path", "$.path has an empty segment");
571
1489
  }
@@ -592,7 +1510,7 @@ function decodeUnreserved(path) {
592
1510
  return /^[A-Za-z0-9._~-]$/.test(char) ? char : encoded.toUpperCase();
593
1511
  });
594
1512
  }
595
- function normalizeActions(actions, service, options) {
1513
+ function normalizeActions(actions, service, options2) {
596
1514
  const accepted = GRANTABLE_ACTIONS.get(service);
597
1515
  if (accepted === void 0) {
598
1516
  throw new PolicyCapabilityError(
@@ -626,7 +1544,7 @@ function normalizeActions(actions, service, options) {
626
1544
  );
627
1545
  }
628
1546
  const normalizedActions = [...unique].sort();
629
- if (options.requireCanonical && (rawActions.length !== normalizedActions.length || rawActions.some((action, index) => action !== normalizedActions[index]))) {
1547
+ if (options2.requireCanonical && (rawActions.length !== normalizedActions.length || rawActions.some((action, index) => action !== normalizedActions[index]))) {
630
1548
  throw new PolicyCapabilityError(
631
1549
  "policy-capability-malformed-action",
632
1550
  "$.actions must already be sorted, deduplicated canonical action URNs"
@@ -768,49 +1686,290 @@ function hasOwn(object, key) {
768
1686
 
769
1687
  // src/policy/signed-object.ts
770
1688
  import { ed25519 } from "@noble/curves/ed25519";
771
- import { bases } from "multiformats/basics";
772
- import { bytesToHex as bytesToHex2, sha256 as sha2562, verifyMessage } from "viem";
773
- var POLICY_SCHEMA = "xyz.tinycloud.policy/policy/v0";
774
- var POLICY_STATUS_SCHEMA = "xyz.tinycloud.policy/status/v0";
775
- var POLICY_ENGINE_RECORD_SCHEMA = "xyz.tinycloud.policy/engine-record/v0";
776
- var ED25519_JCS_SIGNATURE_SUITE = "eddsa-ed25519-sha256-jcs-v1";
777
- var EIP191_JCS_SIGNATURE_SUITE = "eip191-secp256k1-sha256-jcs-v1";
778
- var DESCRIPTORS = {
779
- Policy: {
780
- kind: "Policy",
781
- schema: POLICY_SCHEMA,
782
- idField: "policyId",
783
- idPrefix: "pol_",
784
- domain: POLICY_SCHEMA
785
- },
786
- PolicyStatus: {
787
- kind: "PolicyStatus",
788
- schema: POLICY_STATUS_SCHEMA,
789
- idField: "statusId",
790
- idPrefix: "polst_",
791
- domain: POLICY_STATUS_SCHEMA
792
- },
793
- PolicyEngineRecord: {
794
- kind: "PolicyEngineRecord",
795
- schema: POLICY_ENGINE_RECORD_SCHEMA,
796
- idField: "engineRecordId",
797
- idPrefix: "peng_",
798
- domain: POLICY_ENGINE_RECORD_SCHEMA
799
- }
800
- };
801
- var textEncoder2 = new TextEncoder();
802
- var BASE32_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
803
- var BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
804
- var objectHasOwn3 = Object.hasOwn ?? Object.prototype.hasOwnProperty.call.bind(
805
- Object.prototype.hasOwnProperty
806
- );
807
- function canonicalizeSignedObjectUnsigned(input) {
808
- return jcsCanonicalize(input);
809
- }
810
- function deriveSignedObjectMaterial(input) {
811
- const descriptor = descriptorForUnsigned(input);
812
- const unsigned = validateUnsignedForDescriptor(input, descriptor);
813
- return materialForUnsigned(unsigned, descriptor);
1689
+
1690
+ // ../../node_modules/multiformats/dist/src/bases/base10.js
1691
+ var base10_exports = {};
1692
+ __export(base10_exports, {
1693
+ base10: () => base10
1694
+ });
1695
+ var base10 = baseX({
1696
+ prefix: "9",
1697
+ name: "base10",
1698
+ alphabet: "0123456789"
1699
+ });
1700
+
1701
+ // ../../node_modules/multiformats/dist/src/bases/base16.js
1702
+ var base16_exports = {};
1703
+ __export(base16_exports, {
1704
+ base16: () => base16,
1705
+ base16upper: () => base16upper
1706
+ });
1707
+ var base16 = rfc4648({
1708
+ prefix: "f",
1709
+ name: "base16",
1710
+ alphabet: "0123456789abcdef",
1711
+ bitsPerChar: 4
1712
+ });
1713
+ var base16upper = rfc4648({
1714
+ prefix: "F",
1715
+ name: "base16upper",
1716
+ alphabet: "0123456789ABCDEF",
1717
+ bitsPerChar: 4
1718
+ });
1719
+
1720
+ // ../../node_modules/multiformats/dist/src/bases/base2.js
1721
+ var base2_exports = {};
1722
+ __export(base2_exports, {
1723
+ base2: () => base2
1724
+ });
1725
+ var base2 = rfc4648({
1726
+ prefix: "0",
1727
+ name: "base2",
1728
+ alphabet: "01",
1729
+ bitsPerChar: 1
1730
+ });
1731
+
1732
+ // ../../node_modules/multiformats/dist/src/bases/base256emoji.js
1733
+ var base256emoji_exports = {};
1734
+ __export(base256emoji_exports, {
1735
+ base256emoji: () => base256emoji
1736
+ });
1737
+ var alphabet = Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}");
1738
+ var alphabetBytesToChars = alphabet.reduce((p, c, i) => {
1739
+ p[i] = c;
1740
+ return p;
1741
+ }, []);
1742
+ var alphabetCharsToBytes = alphabet.reduce((p, c, i) => {
1743
+ const codePoint = c.codePointAt(0);
1744
+ if (codePoint == null) {
1745
+ throw new Error(`Invalid character: ${c}`);
1746
+ }
1747
+ p[codePoint] = i;
1748
+ return p;
1749
+ }, []);
1750
+ function encode3(data) {
1751
+ return data.reduce((p, c) => {
1752
+ p += alphabetBytesToChars[c];
1753
+ return p;
1754
+ }, "");
1755
+ }
1756
+ function decode5(str) {
1757
+ const byts = [];
1758
+ for (const char of str) {
1759
+ const codePoint = char.codePointAt(0);
1760
+ if (codePoint == null) {
1761
+ throw new Error(`Invalid character: ${char}`);
1762
+ }
1763
+ const byt = alphabetCharsToBytes[codePoint];
1764
+ if (byt == null) {
1765
+ throw new Error(`Non-base256emoji character: ${char}`);
1766
+ }
1767
+ byts.push(byt);
1768
+ }
1769
+ return new Uint8Array(byts);
1770
+ }
1771
+ var base256emoji = from({
1772
+ prefix: "\u{1F680}",
1773
+ name: "base256emoji",
1774
+ encode: encode3,
1775
+ decode: decode5
1776
+ });
1777
+
1778
+ // ../../node_modules/multiformats/dist/src/bases/base64.js
1779
+ var base64_exports = {};
1780
+ __export(base64_exports, {
1781
+ base64: () => base64,
1782
+ base64pad: () => base64pad,
1783
+ base64url: () => base64url,
1784
+ base64urlpad: () => base64urlpad
1785
+ });
1786
+ var base64 = rfc4648({
1787
+ prefix: "m",
1788
+ name: "base64",
1789
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
1790
+ bitsPerChar: 6
1791
+ });
1792
+ var base64pad = rfc4648({
1793
+ prefix: "M",
1794
+ name: "base64pad",
1795
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
1796
+ bitsPerChar: 6
1797
+ });
1798
+ var base64url = rfc4648({
1799
+ prefix: "u",
1800
+ name: "base64url",
1801
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
1802
+ bitsPerChar: 6
1803
+ });
1804
+ var base64urlpad = rfc4648({
1805
+ prefix: "U",
1806
+ name: "base64urlpad",
1807
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",
1808
+ bitsPerChar: 6
1809
+ });
1810
+
1811
+ // ../../node_modules/multiformats/dist/src/bases/base8.js
1812
+ var base8_exports = {};
1813
+ __export(base8_exports, {
1814
+ base8: () => base8
1815
+ });
1816
+ var base8 = rfc4648({
1817
+ prefix: "7",
1818
+ name: "base8",
1819
+ alphabet: "01234567",
1820
+ bitsPerChar: 3
1821
+ });
1822
+
1823
+ // ../../node_modules/multiformats/dist/src/bases/identity.js
1824
+ var identity_exports = {};
1825
+ __export(identity_exports, {
1826
+ identity: () => identity
1827
+ });
1828
+ var identity = from({
1829
+ prefix: "\0",
1830
+ name: "identity",
1831
+ encode: (buf) => toString(buf),
1832
+ decode: (str) => fromString(str)
1833
+ });
1834
+
1835
+ // ../../node_modules/multiformats/dist/src/codecs/json.js
1836
+ var textEncoder2 = new TextEncoder();
1837
+ var textDecoder = new TextDecoder();
1838
+
1839
+ // ../../node_modules/multiformats/dist/src/hashes/identity.js
1840
+ var identity_exports2 = {};
1841
+ __export(identity_exports2, {
1842
+ identity: () => identity2
1843
+ });
1844
+ var code = 0;
1845
+ var name = "identity";
1846
+ var encode4 = coerce;
1847
+ function digest(input, options2) {
1848
+ if (options2?.truncate != null && options2.truncate !== input.byteLength) {
1849
+ if (options2.truncate < 0 || options2.truncate > input.byteLength) {
1850
+ throw new Error(`Invalid truncate option, must be less than or equal to ${input.byteLength}`);
1851
+ }
1852
+ input = input.subarray(0, options2.truncate);
1853
+ }
1854
+ return create(code, encode4(input));
1855
+ }
1856
+ var identity2 = { code, name, encode: encode4, digest };
1857
+
1858
+ // ../../node_modules/multiformats/dist/src/hashes/sha2.js
1859
+ var sha2_exports = {};
1860
+ __export(sha2_exports, {
1861
+ sha256: () => sha2562,
1862
+ sha512: () => sha512
1863
+ });
1864
+ import crypto from "crypto";
1865
+
1866
+ // ../../node_modules/multiformats/dist/src/hashes/hasher.js
1867
+ var DEFAULT_MIN_DIGEST_LENGTH = 20;
1868
+ function from2({ name: name2, code: code2, encode: encode5, minDigestLength, maxDigestLength }) {
1869
+ return new Hasher(name2, code2, encode5, minDigestLength, maxDigestLength);
1870
+ }
1871
+ var Hasher = class {
1872
+ constructor(name2, code2, encode5, minDigestLength, maxDigestLength) {
1873
+ __publicField(this, "name");
1874
+ __publicField(this, "code");
1875
+ __publicField(this, "encode");
1876
+ __publicField(this, "minDigestLength");
1877
+ __publicField(this, "maxDigestLength");
1878
+ this.name = name2;
1879
+ this.code = code2;
1880
+ this.encode = encode5;
1881
+ this.minDigestLength = minDigestLength ?? DEFAULT_MIN_DIGEST_LENGTH;
1882
+ this.maxDigestLength = maxDigestLength;
1883
+ }
1884
+ digest(input, options2) {
1885
+ if (options2?.truncate != null) {
1886
+ if (options2.truncate < this.minDigestLength) {
1887
+ throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);
1888
+ }
1889
+ if (this.maxDigestLength != null && options2.truncate > this.maxDigestLength) {
1890
+ throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`);
1891
+ }
1892
+ }
1893
+ if (input instanceof Uint8Array) {
1894
+ const result = this.encode(input);
1895
+ if (result instanceof Uint8Array) {
1896
+ return createDigest(result, this.code, options2?.truncate);
1897
+ }
1898
+ return result.then((digest2) => createDigest(digest2, this.code, options2?.truncate));
1899
+ } else {
1900
+ throw Error("Unknown type, must be binary type");
1901
+ }
1902
+ }
1903
+ };
1904
+ function createDigest(digest2, code2, truncate) {
1905
+ if (truncate != null && truncate !== digest2.byteLength) {
1906
+ if (truncate > digest2.byteLength) {
1907
+ throw new Error(`Invalid truncate option, must be less than or equal to ${digest2.byteLength}`);
1908
+ }
1909
+ digest2 = digest2.subarray(0, truncate);
1910
+ }
1911
+ return create(code2, digest2);
1912
+ }
1913
+
1914
+ // ../../node_modules/multiformats/dist/src/hashes/sha2.js
1915
+ var sha2562 = from2({
1916
+ name: "sha2-256",
1917
+ code: 18,
1918
+ encode: (input) => coerce(crypto.createHash("sha256").update(input).digest())
1919
+ });
1920
+ var sha512 = from2({
1921
+ name: "sha2-512",
1922
+ code: 19,
1923
+ encode: (input) => coerce(crypto.createHash("sha512").update(input).digest())
1924
+ });
1925
+
1926
+ // ../../node_modules/multiformats/dist/src/basics.js
1927
+ var bases = { ...identity_exports, ...base2_exports, ...base8_exports, ...base10_exports, ...base16_exports, ...base32_exports, ...base36_exports, ...base58_exports, ...base64_exports, ...base256emoji_exports };
1928
+ var hashes = { ...sha2_exports, ...identity_exports2 };
1929
+
1930
+ // src/policy/signed-object.ts
1931
+ import { bytesToHex as bytesToHex2, sha256 as sha2563, verifyMessage } from "viem";
1932
+ var POLICY_SCHEMA = "xyz.tinycloud.policy/policy/v0";
1933
+ var POLICY_STATUS_SCHEMA = "xyz.tinycloud.policy/status/v0";
1934
+ var POLICY_ENGINE_RECORD_SCHEMA = "xyz.tinycloud.policy/engine-record/v0";
1935
+ var ED25519_JCS_SIGNATURE_SUITE = "eddsa-ed25519-sha256-jcs-v1";
1936
+ var EIP191_JCS_SIGNATURE_SUITE = "eip191-secp256k1-sha256-jcs-v1";
1937
+ var DESCRIPTORS = {
1938
+ Policy: {
1939
+ kind: "Policy",
1940
+ schema: POLICY_SCHEMA,
1941
+ idField: "policyId",
1942
+ idPrefix: "pol_",
1943
+ domain: POLICY_SCHEMA
1944
+ },
1945
+ PolicyStatus: {
1946
+ kind: "PolicyStatus",
1947
+ schema: POLICY_STATUS_SCHEMA,
1948
+ idField: "statusId",
1949
+ idPrefix: "polst_",
1950
+ domain: POLICY_STATUS_SCHEMA
1951
+ },
1952
+ PolicyEngineRecord: {
1953
+ kind: "PolicyEngineRecord",
1954
+ schema: POLICY_ENGINE_RECORD_SCHEMA,
1955
+ idField: "engineRecordId",
1956
+ idPrefix: "peng_",
1957
+ domain: POLICY_ENGINE_RECORD_SCHEMA
1958
+ }
1959
+ };
1960
+ var textEncoder3 = new TextEncoder();
1961
+ var BASE32_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
1962
+ var BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
1963
+ var objectHasOwn3 = Object.hasOwn ?? Object.prototype.hasOwnProperty.call.bind(
1964
+ Object.prototype.hasOwnProperty
1965
+ );
1966
+ function canonicalizeSignedObjectUnsigned(input) {
1967
+ return jcsCanonicalize(input);
1968
+ }
1969
+ function deriveSignedObjectMaterial(input) {
1970
+ const descriptor = descriptorForUnsigned(input);
1971
+ const unsigned = validateUnsignedForDescriptor(input, descriptor);
1972
+ return materialForUnsigned(unsigned, descriptor);
814
1973
  }
815
1974
  function signedObjectIdFor(input) {
816
1975
  return deriveSignedObjectMaterial(input).id;
@@ -1247,9 +2406,9 @@ function validateAudit(input, path) {
1247
2406
  }
1248
2407
  function materialForUnsigned(unsigned, descriptor) {
1249
2408
  const jcs = jcsCanonicalize(unsigned);
1250
- const jcsBytes = textEncoder2.encode(jcs);
1251
- const digest = sha256Bytes(concatBytes(textEncoder2.encode(`${descriptor.domain}\0`), jcsBytes));
1252
- const id = `${descriptor.idPrefix}${base32LowerNoPad(digest)}`;
2409
+ const jcsBytes = textEncoder3.encode(jcs);
2410
+ const digest2 = sha256Bytes(concatBytes(textEncoder3.encode(`${descriptor.domain}\0`), jcsBytes));
2411
+ const id = `${descriptor.idPrefix}${base32LowerNoPad(digest2)}`;
1253
2412
  return {
1254
2413
  kind: descriptor.kind,
1255
2414
  idField: descriptor.idField,
@@ -1258,8 +2417,8 @@ function materialForUnsigned(unsigned, descriptor) {
1258
2417
  unsigned,
1259
2418
  jcs,
1260
2419
  jcsBytes,
1261
- digest,
1262
- digestHex: bytesToHex2(digest).slice(2)
2420
+ digest: digest2,
2421
+ digestHex: bytesToHex2(digest2).slice(2)
1263
2422
  };
1264
2423
  }
1265
2424
  function assertIdMatches(signed, material, descriptor) {
@@ -1307,12 +2466,12 @@ function assertSignerDidMatchesSuite(signerDid, suite) {
1307
2466
  }
1308
2467
  throw new UnsupportedSignatureSuiteError(`unsupported signature suite: ${suite}`);
1309
2468
  }
1310
- async function verifySignature(signature, digest) {
2469
+ async function verifySignature(signature, digest2) {
1311
2470
  if (signature.suite === ED25519_JCS_SIGNATURE_SUITE) {
1312
2471
  const publicKey = ed25519PublicKeyFromDidKey(signature.signerDid);
1313
2472
  const signatureBytes = decodeSignatureValue(signature.value, signature.suite);
1314
2473
  try {
1315
- return ed25519.verify(signatureBytes, digest, publicKey);
2474
+ return ed25519.verify(signatureBytes, digest2, publicKey);
1316
2475
  } catch {
1317
2476
  throw new SignatureVerificationError("Ed25519 signature verification failed");
1318
2477
  }
@@ -1323,7 +2482,7 @@ async function verifySignature(signature, digest) {
1323
2482
  try {
1324
2483
  return verifyMessage({
1325
2484
  address: pkh.address,
1326
- message: { raw: digest },
2485
+ message: { raw: digest2 },
1327
2486
  signature: bytesToHex2(signatureBytes)
1328
2487
  });
1329
2488
  } catch {
@@ -1529,7 +2688,7 @@ function assertSupportedSignatureSuite(suite) {
1529
2688
  }
1530
2689
  }
1531
2690
  function sha256Bytes(bytes) {
1532
- return sha2562(bytes, "bytes");
2691
+ return sha2563(bytes, "bytes");
1533
2692
  }
1534
2693
  function concatBytes(left, right) {
1535
2694
  const output = new Uint8Array(left.length + right.length);
@@ -1555,20 +2714,20 @@ function base32LowerNoPad(bytes) {
1555
2714
  return output;
1556
2715
  }
1557
2716
  function base64UrlEncode(bytes) {
1558
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
2717
+ const alphabet2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1559
2718
  let output = "";
1560
2719
  for (let index = 0; index < bytes.length; index += 3) {
1561
2720
  const a = bytes[index];
1562
2721
  const b = bytes[index + 1];
1563
2722
  const c = bytes[index + 2];
1564
2723
  const triplet = a << 16 | (b ?? 0) << 8 | (c ?? 0);
1565
- output += alphabet[triplet >> 18 & 63];
1566
- output += alphabet[triplet >> 12 & 63];
2724
+ output += alphabet2[triplet >> 18 & 63];
2725
+ output += alphabet2[triplet >> 12 & 63];
1567
2726
  if (index + 1 < bytes.length) {
1568
- output += alphabet[triplet >> 6 & 63];
2727
+ output += alphabet2[triplet >> 6 & 63];
1569
2728
  }
1570
2729
  if (index + 2 < bytes.length) {
1571
- output += alphabet[triplet & 63];
2730
+ output += alphabet2[triplet & 63];
1572
2731
  }
1573
2732
  }
1574
2733
  return output;
@@ -1577,12 +2736,12 @@ function base64UrlDecode(value) {
1577
2736
  if (value.length % 4 === 1) {
1578
2737
  throw new SignatureMaterialError("signature value is not canonical base64url");
1579
2738
  }
1580
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
2739
+ const alphabet2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1581
2740
  const bytes = [];
1582
2741
  let buffer = 0;
1583
2742
  let bits = 0;
1584
2743
  for (const char of value) {
1585
- const index = alphabet.indexOf(char);
2744
+ const index = alphabet2.indexOf(char);
1586
2745
  if (index < 0) {
1587
2746
  throw new SignatureMaterialError("signature value is not base64url");
1588
2747
  }
@@ -1617,14 +2776,14 @@ var OWNER_NODE_ENDPOINT_SCHEMA = "xyz.tinycloud.exchange/owner-node-endpoint/v1"
1617
2776
  var POLICY_VERSION_V0 = "v0";
1618
2777
  var W3C_VC_CREDENTIAL_VERIFIER = "w3c.vc/credential/v1";
1619
2778
  var PolicyAuthoringError = class extends Error {
1620
- constructor(code, message) {
2779
+ constructor(code2, message) {
1621
2780
  super(message);
1622
2781
  this.name = "PolicyAuthoringError";
1623
- this.code = code;
2782
+ this.code = code2;
1624
2783
  }
1625
2784
  };
1626
- async function verifyPolicyEngineRecordForRequester(options) {
1627
- const normalized = expectObject2(options, "$", "policy-authoring-malformed");
2785
+ async function verifyPolicyEngineRecordForRequester(options2) {
2786
+ const normalized = expectObject2(options2, "$", "policy-authoring-malformed");
1628
2787
  assertExactKeys3(
1629
2788
  normalized,
1630
2789
  [
@@ -1731,11 +2890,11 @@ async function verifyPolicyEngineRecordForRequester(options) {
1731
2890
  }
1732
2891
  return verified;
1733
2892
  }
1734
- function expectObject2(input, path, code) {
2893
+ function expectObject2(input, path, code2) {
1735
2894
  try {
1736
2895
  const normalized = normalizeJson(input);
1737
2896
  if (normalized === null || typeof normalized !== "object" || Array.isArray(normalized)) {
1738
- throw new PolicyAuthoringError(code, `${path} must be an object`);
2897
+ throw new PolicyAuthoringError(code2, `${path} must be an object`);
1739
2898
  }
1740
2899
  return normalized;
1741
2900
  } catch (error) {
@@ -1743,7 +2902,7 @@ function expectObject2(input, path, code) {
1743
2902
  throw error;
1744
2903
  }
1745
2904
  throw new PolicyAuthoringError(
1746
- code,
2905
+ code2,
1747
2906
  error instanceof Error ? error.message : String(error)
1748
2907
  );
1749
2908
  }
@@ -1778,14 +2937,14 @@ function requiredString3(object, key, path) {
1778
2937
  }
1779
2938
  return value;
1780
2939
  }
1781
- function fieldString(object, key, path, code) {
2940
+ function fieldString(object, key, path, code2) {
1782
2941
  if (!hasOwn3(object, key)) {
1783
- throw new PolicyAuthoringError(code, `${path}.${key} is required`);
2942
+ throw new PolicyAuthoringError(code2, `${path}.${key} is required`);
1784
2943
  }
1785
2944
  const value = object[key];
1786
2945
  if (typeof value !== "string" || value.length === 0) {
1787
2946
  throw new PolicyAuthoringError(
1788
- code,
2947
+ code2,
1789
2948
  `${path}.${key} must be a non-empty string`
1790
2949
  );
1791
2950
  }
@@ -1891,10 +3050,10 @@ var POLICY_ENGINE_GRANT_PRESENTATION_DENIAL_CODES = [
1891
3050
  "rate-limited"
1892
3051
  ];
1893
3052
  var TranscriptRequesterError = class extends Error {
1894
- constructor(code, message, state = "invalid", denialCode, status) {
3053
+ constructor(code2, message, state = "invalid", denialCode, status) {
1895
3054
  super(message);
1896
3055
  this.name = "TranscriptRequesterError";
1897
- this.code = code;
3056
+ this.code = code2;
1898
3057
  this.state = state;
1899
3058
  this.denialCode = denialCode;
1900
3059
  this.status = status;
@@ -2032,50 +3191,50 @@ var LISTEN_SQL_STATEMENT_BY_NAME = new Map(
2032
3191
  ])
2033
3192
  );
2034
3193
  var TranscriptRequester = class _TranscriptRequester {
2035
- constructor(bootstrap, requestedCapabilities, nativeAuthorityCeiling, requestedCapabilitiesHash2, policyEngineRecordExpiresAtMs, policyEngineAddresses, ownerNodeAddresses, options) {
3194
+ constructor(bootstrap, requestedCapabilities, nativeAuthorityCeiling, requestedCapabilitiesHash2, policyEngineRecordExpiresAtMs, policyEngineAddresses, ownerNodeAddresses, options2) {
2036
3195
  this.usedChallengeNonces = /* @__PURE__ */ new Set();
2037
3196
  this.accessEnded = false;
2038
3197
  this.bootstrap = bootstrap;
2039
3198
  this.requestedCapabilities = requestedCapabilities;
2040
3199
  this.nativeAuthorityCeiling = nativeAuthorityCeiling;
2041
3200
  this.requestedCapabilitiesHash = requestedCapabilitiesHash2;
2042
- this.requesterDid = options.requesterDid;
2043
- this.ownerDid = options.ownerDid;
2044
- this.audience = options.audience;
2045
- this.grantIssuerDid = options.grantIssuerDid;
2046
- this.transport = options.transport;
2047
- this.signingCapability = options.signingCapability;
2048
- this.invocationCapability = options.invocationCapability;
3201
+ this.requesterDid = options2.requesterDid;
3202
+ this.ownerDid = options2.ownerDid;
3203
+ this.audience = options2.audience;
3204
+ this.grantIssuerDid = options2.grantIssuerDid;
3205
+ this.transport = options2.transport;
3206
+ this.signingCapability = options2.signingCapability;
3207
+ this.invocationCapability = options2.invocationCapability;
2049
3208
  this.policyEngineRecordExpiresAtMs = policyEngineRecordExpiresAtMs;
2050
3209
  this.policyEngineAddresses = policyEngineAddresses;
2051
3210
  this.ownerNodeAddresses = ownerNodeAddresses;
2052
- this.eligibleSubjectDid = options.eligibleSubjectDid ?? options.signingCapability?.eligibleSubjectDid ?? options.requesterDid;
2053
- this.holderBinding = options.holderBinding ?? options.signingCapability?.holderBinding ?? {
3211
+ this.eligibleSubjectDid = options2.eligibleSubjectDid ?? options2.signingCapability?.eligibleSubjectDid ?? options2.requesterDid;
3212
+ this.holderBinding = options2.holderBinding ?? options2.signingCapability?.holderBinding ?? {
2054
3213
  type: "enrolled-agent",
2055
3214
  enrollment: {
2056
3215
  schema: "xyz.tinycloud.policy/holder-enrollment/v0",
2057
- holderDid: options.requesterDid
3216
+ holderDid: options2.requesterDid
2058
3217
  }
2059
3218
  };
2060
- this.evidence = options.evidence ?? options.signingCapability?.evidence;
3219
+ this.evidence = options2.evidence ?? options2.signingCapability?.evidence;
2061
3220
  this.presentationTtlSeconds = Math.min(
2062
- Math.max(options.presentationTtlSeconds ?? 60, 1),
3221
+ Math.max(options2.presentationTtlSeconds ?? 60, 1),
2063
3222
  300
2064
3223
  );
2065
- this.now = options.now ?? (() => /* @__PURE__ */ new Date());
2066
- this.sleep = options.sleep ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
2067
- this.random = options.random ?? Math.random;
2068
- this.engineRetryAttempts = options.engineRetryAttempts ?? REQUESTER_ENGINE_RETRY_ATTEMPTS;
2069
- }
2070
- static async create(options) {
2071
- const bootstrap = parseBootstrap(options.bootstrap);
2072
- if (bootstrap.ownerNode.endpoint !== options.trustedOwnerNode.endpoint || bootstrap.ownerNode.spaceId !== options.trustedOwnerNode.spaceId) {
3224
+ this.now = options2.now ?? (() => /* @__PURE__ */ new Date());
3225
+ this.sleep = options2.sleep ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)));
3226
+ this.random = options2.random ?? Math.random;
3227
+ this.engineRetryAttempts = options2.engineRetryAttempts ?? REQUESTER_ENGINE_RETRY_ATTEMPTS;
3228
+ }
3229
+ static async create(options2) {
3230
+ const bootstrap = parseBootstrap(options2.bootstrap);
3231
+ if (bootstrap.ownerNode.endpoint !== options2.trustedOwnerNode.endpoint || bootstrap.ownerNode.spaceId !== options2.trustedOwnerNode.spaceId) {
2073
3232
  throw endpointError(
2074
3233
  "owner-node",
2075
3234
  "bootstrap owner-node binding does not match trusted discovery/config"
2076
3235
  );
2077
3236
  }
2078
- const record = await verifyRecordBeforeEgress(bootstrap, options);
3237
+ const record = await verifyRecordBeforeEgress(bootstrap, options2);
2079
3238
  if (record.endpoint !== bootstrap.policyEngine.endpoint) {
2080
3239
  throw new TranscriptRequesterError(
2081
3240
  "requester-engine-record-endpoint-mismatch",
@@ -2092,12 +3251,12 @@ var TranscriptRequester = class _TranscriptRequester {
2092
3251
  }
2093
3252
  const policyEngineAddresses = await validateAndResolvePublicEndpoint(
2094
3253
  bootstrap.policyEngine.endpoint,
2095
- options.transport,
3254
+ options2.transport,
2096
3255
  "policy-engine"
2097
3256
  );
2098
3257
  const ownerNodeAddresses = await validateAndResolveOwnerNode(
2099
3258
  bootstrap.ownerNode.endpoint,
2100
- options.transport
3259
+ options2.transport
2101
3260
  );
2102
3261
  const requestedCapabilities = bootstrap.resourceHint.requestedCapabilities.map(
2103
3262
  (capability, index) => parsePolicyCapability(
@@ -2117,7 +3276,7 @@ var TranscriptRequester = class _TranscriptRequester {
2117
3276
  parseStrictRfc33392(record.expiresAt),
2118
3277
  policyEngineAddresses,
2119
3278
  ownerNodeAddresses,
2120
- options
3279
+ options2
2121
3280
  );
2122
3281
  }
2123
3282
  get accessState() {
@@ -2641,8 +3800,8 @@ var TranscriptRequester = class _TranscriptRequester {
2641
3800
  }
2642
3801
  }
2643
3802
  };
2644
- async function createTranscriptRequester(options) {
2645
- return TranscriptRequester.create(options);
3803
+ async function createTranscriptRequester(options2) {
3804
+ return TranscriptRequester.create(options2);
2646
3805
  }
2647
3806
  function parseBootstrap(input) {
2648
3807
  const normalized = normalizeExternal(input, "requester-bootstrap-malformed");
@@ -2656,35 +3815,35 @@ function parseBootstrap(input) {
2656
3815
  }
2657
3816
  return parsed.data;
2658
3817
  }
2659
- async function verifyRecordBeforeEgress(bootstrap, options) {
3818
+ async function verifyRecordBeforeEgress(bootstrap, options2) {
2660
3819
  try {
2661
3820
  return await verifyPolicyEngineRecordForRequester({
2662
3821
  signedRecord: bootstrap.policyEngine.signedRecord,
2663
- ownerDid: options.ownerDid,
2664
- audience: options.audience,
2665
- grantIssuerDid: options.grantIssuerDid,
2666
- now: (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString().replace(".000Z", "Z"),
3822
+ ownerDid: options2.ownerDid,
3823
+ audience: options2.audience,
3824
+ grantIssuerDid: options2.grantIssuerDid,
3825
+ now: (options2.now ?? (() => /* @__PURE__ */ new Date()))().toISOString().replace(".000Z", "Z"),
2667
3826
  requiredPolicyVersion: POLICY_VERSION_V0,
2668
3827
  requiredEvidenceVerifier: W3C_VC_CREDENTIAL_VERIFIER
2669
3828
  });
2670
3829
  } catch (error) {
2671
- const code = errorCodeForRecordFailure(error);
3830
+ const code2 = errorCodeForRecordFailure(error);
2672
3831
  throw new TranscriptRequesterError(
2673
- code,
3832
+ code2,
2674
3833
  error instanceof Error ? error.message : String(error),
2675
3834
  "bootstrap-invalid"
2676
3835
  );
2677
3836
  }
2678
3837
  }
2679
3838
  function errorCodeForRecordFailure(error) {
2680
- const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
2681
- if (code === "policy-engine-record-signature-invalid") {
3839
+ const code2 = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
3840
+ if (code2 === "policy-engine-record-signature-invalid") {
2682
3841
  return "requester-engine-record-signature-invalid";
2683
3842
  }
2684
- if (code === "policy-engine-record-owner-mismatch") {
3843
+ if (code2 === "policy-engine-record-owner-mismatch") {
2685
3844
  return "requester-engine-record-owner-mismatch";
2686
3845
  }
2687
- if (code === "policy-engine-record-audience-mismatch") {
3846
+ if (code2 === "policy-engine-record-audience-mismatch") {
2688
3847
  return "requester-engine-record-audience-mismatch";
2689
3848
  }
2690
3849
  return "requester-engine-record-invalid";
@@ -2737,7 +3896,7 @@ function requestedCapabilitiesHash(capabilities) {
2737
3896
  const bytes = new Uint8Array(domain.length + body.length);
2738
3897
  bytes.set(domain, 0);
2739
3898
  bytes.set(body, domain.length);
2740
- return bytesToHex3(sha2563(bytes, "bytes")).slice(2);
3899
+ return bytesToHex3(sha2564(bytes, "bytes")).slice(2);
2741
3900
  }
2742
3901
  function normalizeWireDelegation(delegation) {
2743
3902
  const signed = delegationAuthorityFromCompactJws(delegation.encoded);
@@ -2984,16 +4143,16 @@ function nodeErrorMessage(body) {
2984
4143
  if (typeof body === "string") return body;
2985
4144
  if (body !== null && typeof body === "object") {
2986
4145
  const record = body;
2987
- const code = typeof record.code === "string" ? record.code : void 0;
4146
+ const code2 = typeof record.code === "string" ? record.code : void 0;
2988
4147
  const message = typeof record.message === "string" ? record.message : void 0;
2989
- if (code !== void 0)
2990
- return message === void 0 ? code : `${code}: ${message}`;
4148
+ if (code2 !== void 0)
4149
+ return message === void 0 ? code2 : `${code2}: ${message}`;
2991
4150
  }
2992
4151
  return "native node refusal";
2993
4152
  }
2994
4153
  function deriveDelegationCid(encoded) {
2995
- const digest = createDigest(30, blake3(new TextEncoder().encode(encoded)));
2996
- return CID.createV1(85, digest).toString();
4154
+ const digest2 = create(30, blake3(new TextEncoder().encode(encoded)));
4155
+ return CID.createV1(85, digest2).toString();
2997
4156
  }
2998
4157
  function headersRecord(headers) {
2999
4158
  return Array.isArray(headers) ? Object.fromEntries(headers) : headers;
@@ -3104,21 +4263,21 @@ function errorForDenial(denial, status) {
3104
4263
  );
3105
4264
  }
3106
4265
  function retryDelay(attempt, random) {
3107
- const base = Math.min(REQUESTER_ENGINE_RETRY_MAX_DELAY_MS, 50 * 2 ** attempt);
4266
+ const base3 = Math.min(REQUESTER_ENGINE_RETRY_MAX_DELAY_MS, 50 * 2 ** attempt);
3108
4267
  return Math.min(
3109
4268
  REQUESTER_ENGINE_RETRY_MAX_DELAY_MS,
3110
- Math.floor(base * (0.5 + random))
4269
+ Math.floor(base3 * (0.5 + random))
3111
4270
  );
3112
4271
  }
3113
4272
  function trimTrailingSlash(value) {
3114
4273
  return value.endsWith("/") ? value.slice(0, -1) : value;
3115
4274
  }
3116
- function normalizeExternal(input, code) {
4275
+ function normalizeExternal(input, code2) {
3117
4276
  try {
3118
4277
  return normalizeJson(input);
3119
4278
  } catch (error) {
3120
4279
  throw new TranscriptRequesterError(
3121
- code,
4280
+ code2,
3122
4281
  error instanceof Error ? error.message : String(error)
3123
4282
  );
3124
4283
  }
@@ -3424,6 +4583,8 @@ var DelegationSchema = z4.object({
3424
4583
  path: z4.string(),
3425
4584
  /** Actions this delegation authorizes */
3426
4585
  actions: z4.array(z4.string()),
4586
+ /** Exact ReCap caveats that constrain every action in this scope. */
4587
+ caveats: z4.array(z4.record(z4.string(), z4.unknown())).optional(),
3427
4588
  /** When this delegation expires (accepts Date or ISO string from JSON) */
3428
4589
  expiry: z4.coerce.date(),
3429
4590
  /** Whether this delegation has been revoked */
@@ -3455,6 +4616,43 @@ var DelegationStatusSchema = z4.object({
3455
4616
  });
3456
4617
  }
3457
4618
  });
4619
+ var DelegationRevocationReceiptSchema = z4.object({
4620
+ revoked: z4.literal(true),
4621
+ cid: z4.string().min(1)
4622
+ }).strict();
4623
+ var AccountDelegationResourceSchema = z4.object({
4624
+ resource: z4.string().min(1),
4625
+ actions: z4.array(z4.string()),
4626
+ caveats: z4.array(z4.record(z4.string(), z4.unknown()))
4627
+ }).strict();
4628
+ var AccountDelegationDateSchema = z4.string().datetime({ offset: true }).transform((value) => new Date(value));
4629
+ var AccountDelegationRecordSchema = z4.object({
4630
+ cid: z4.string().min(1),
4631
+ direction: z4.enum(["granted", "received"]),
4632
+ delegatorDid: z4.string().min(1),
4633
+ delegateDid: z4.string().min(1),
4634
+ resources: z4.array(AccountDelegationResourceSchema),
4635
+ parents: z4.array(z4.string()),
4636
+ issuedAt: AccountDelegationDateSchema.nullable(),
4637
+ notBefore: AccountDelegationDateSchema.nullable(),
4638
+ expiresAt: AccountDelegationDateSchema.nullable(),
4639
+ status: z4.enum(["active", "pending", "expired", "revoked", "ancestor_revoked"]),
4640
+ revokedAt: AccountDelegationDateSchema.nullable().optional(),
4641
+ revokedBy: z4.string().optional(),
4642
+ revokedAncestorCid: z4.string().optional()
4643
+ }).strict();
4644
+ var AccountDelegationPageSchema = z4.object({
4645
+ schemaVersion: z4.literal(2),
4646
+ items: z4.array(AccountDelegationRecordSchema),
4647
+ nextCursor: z4.string().optional()
4648
+ }).strict();
4649
+ var AccountDelegationQueryOptionsSchema = z4.object({
4650
+ direction: z4.enum(["granted", "received", "all"]).optional(),
4651
+ status: z4.enum(["active", "pending", "expired", "revoked", "ancestor_revoked"]).optional(),
4652
+ space: z4.string().trim().min(1).optional(),
4653
+ limit: z4.number().int().min(1).max(100).optional(),
4654
+ cursor: z4.string().min(1).optional()
4655
+ }).strict();
3458
4656
  var CapabilityEntrySchema = z4.object({
3459
4657
  /** Resource URI this capability applies to */
3460
4658
  resource: z4.string(),
@@ -3609,6 +4807,8 @@ var GenerateShareParamsSchema = z4.object({
3609
4807
  var DelegationManagerConfigSchema = z4.object({
3610
4808
  /** TinyCloud host URLs */
3611
4809
  hosts: z4.array(z4.string()),
4810
+ /** Account space used by account-wide delegation history queries */
4811
+ accountSpaceId: z4.string().min(1).optional(),
3612
4812
  /** Active session for authentication */
3613
4813
  session: z4.unknown().refine(
3614
4814
  (val) => val !== null && typeof val === "object",
@@ -3665,7 +4865,9 @@ var DelegatedResourceSchema = z4.object({
3665
4865
  /** Resource path; empty string when the resource URI had no path segment. */
3666
4866
  path: z4.string(),
3667
4867
  /** Full-URN ability strings, e.g. ["tinycloud.kv/get", "tinycloud.kv/put"]. */
3668
- actions: z4.array(z4.string())
4868
+ actions: z4.array(z4.string()),
4869
+ /** Exact ReCap caveats that constrain every action in this scope. */
4870
+ caveats: z4.array(z4.record(z4.string(), z4.unknown())).optional()
3669
4871
  });
3670
4872
  var CreateDelegationWasmParamsSchema = z4.object({
3671
4873
  /** The session containing delegation credentials */
@@ -3940,13 +5142,13 @@ function parseSpaceUri(uri) {
3940
5142
  /^tinycloud:pkh:eip155:(\d+):(0x[a-fA-F0-9]{40}):(.+)$/
3941
5143
  );
3942
5144
  if (fullUriMatch) {
3943
- const [, chainId, address, name] = fullUriMatch;
5145
+ const [, chainId, address, name2] = fullUriMatch;
3944
5146
  try {
3945
5147
  const chainIdNumber = Number(chainId);
3946
5148
  const canonicalAddress = canonicalizeAddress(address);
3947
5149
  return {
3948
5150
  owner: pkhDid(canonicalAddress, chainIdNumber),
3949
- name,
5151
+ name: name2,
3950
5152
  chainId: String(chainIdNumber),
3951
5153
  address: canonicalAddress
3952
5154
  };
@@ -3963,12 +5165,12 @@ function parseSpaceUri(uri) {
3963
5165
  }
3964
5166
  return null;
3965
5167
  }
3966
- function buildSpaceUri(owner, name) {
5168
+ function buildSpaceUri(owner, name2) {
3967
5169
  const pkh = parsePkhDid(owner);
3968
5170
  if (pkh) {
3969
- return makePkhSpaceId(pkh.address, pkh.chainId, name);
5171
+ return makePkhSpaceId(pkh.address, pkh.chainId, name2);
3970
5172
  }
3971
- return `tinycloud:${owner}:${name}`;
5173
+ return `tinycloud:${owner}:${name2}`;
3972
5174
  }
3973
5175
  function transformServerDelegations(validatedData, defaultSpaceId) {
3974
5176
  const result = [];
@@ -4233,13 +5435,13 @@ var SpaceService = class {
4233
5435
  *
4234
5436
  * @param name - The name for the new space
4235
5437
  */
4236
- async create(name) {
5438
+ async create(name2) {
4237
5439
  if (!this.session) {
4238
5440
  return err(
4239
5441
  serviceError(SpaceErrorCodes.AUTH_REQUIRED, "Authentication required", SERVICE_NAME)
4240
5442
  );
4241
5443
  }
4242
- if (!name || !/^[a-zA-Z0-9_-]+$/.test(name)) {
5444
+ if (!name2 || !/^[a-zA-Z0-9_-]+$/.test(name2)) {
4243
5445
  return err(
4244
5446
  serviceError(
4245
5447
  SpaceErrorCodes.INVALID_NAME,
@@ -4249,11 +5451,11 @@ var SpaceService = class {
4249
5451
  );
4250
5452
  }
4251
5453
  try {
4252
- const headers = this.invoke(this.session, "space", name, "tinycloud.space/create");
5454
+ const headers = this.invoke(this.session, "space", name2, "tinycloud.space/create");
4253
5455
  const response = await this.fetchFn(`${this.host}/invoke`, {
4254
5456
  method: "POST",
4255
5457
  headers,
4256
- body: JSON.stringify({ name })
5458
+ body: JSON.stringify({ name: name2 })
4257
5459
  });
4258
5460
  if (!response.ok) {
4259
5461
  const errorText = await response.text();
@@ -4261,7 +5463,7 @@ var SpaceService = class {
4261
5463
  return err(
4262
5464
  serviceError(
4263
5465
  SpaceErrorCodes.ALREADY_EXISTS,
4264
- `Space "${name}" already exists`,
5466
+ `Space "${name2}" already exists`,
4265
5467
  SERVICE_NAME
4266
5468
  )
4267
5469
  );
@@ -4289,7 +5491,7 @@ var SpaceService = class {
4289
5491
  }
4290
5492
  const spaceInfo = {
4291
5493
  id: validationResult.data.id,
4292
- name: validationResult.data.name || name,
5494
+ name: validationResult.data.name || name2,
4293
5495
  owner: validationResult.data.owner || this.userDid || "",
4294
5496
  type: "owned",
4295
5497
  permissions: ["*"]
@@ -4328,10 +5530,10 @@ var SpaceService = class {
4328
5530
  return cached;
4329
5531
  }
4330
5532
  const parsed = parseSpaceUri(spaceId);
4331
- const name = parsed?.name ?? this.extractNameFromId(spaceId);
5533
+ const name2 = parsed?.name ?? this.extractNameFromId(spaceId);
4332
5534
  const config = {
4333
5535
  id: spaceId,
4334
- name,
5536
+ name: name2,
4335
5537
  createKV: this.createSpaceScopedKV.bind(this),
4336
5538
  createVault: this.createSpaceScopedVault.bind(this),
4337
5539
  createSecrets: this.createSpaceScopedSecrets.bind(this),
@@ -4775,12 +5977,12 @@ var TinyCloud = class _TinyCloud {
4775
5977
  hooks: HooksService,
4776
5978
  ...this.config.services
4777
5979
  };
4778
- for (const [name, ServiceClass] of Object.entries(serviceConstructors)) {
4779
- const serviceConfig = this.config.serviceConfigs?.[name] ?? {};
5980
+ for (const [name2, ServiceClass] of Object.entries(serviceConstructors)) {
5981
+ const serviceConfig = this.config.serviceConfigs?.[name2] ?? {};
4780
5982
  const service = new ServiceClass(serviceConfig);
4781
5983
  service.initialize(this._serviceContext);
4782
- this._serviceContext.registerService(name, service);
4783
- this._services.set(name, service);
5984
+ this._serviceContext.registerService(name2, service);
5985
+ this._services.set(name2, service);
4784
5986
  }
4785
5987
  this._servicesInitialized = true;
4786
5988
  }
@@ -4796,14 +5998,23 @@ var TinyCloud = class _TinyCloud {
4796
5998
  }
4797
5999
  return this._serviceContext;
4798
6000
  }
6001
+ /** @internal Retire this service graph after its owner replaces a session. */
6002
+ retireServices() {
6003
+ try {
6004
+ this._serviceContext?.retire();
6005
+ } finally {
6006
+ this._services.clear();
6007
+ this._servicesInitialized = false;
6008
+ }
6009
+ }
4799
6010
  /**
4800
6011
  * Get a registered service by name.
4801
6012
  *
4802
6013
  * @param name - Service name (e.g., 'kv')
4803
6014
  * @returns The service instance or undefined
4804
6015
  */
4805
- getService(name) {
4806
- return this._services.get(name);
6016
+ getService(name2) {
6017
+ return this._services.get(name2);
4807
6018
  }
4808
6019
  /**
4809
6020
  * Get the KV service.
@@ -4971,8 +6182,8 @@ var TinyCloud = class _TinyCloud {
4971
6182
  * @param options - Optional per-call SIWE overrides for this sign-in only
4972
6183
  * @returns The new session
4973
6184
  */
4974
- async signIn(options) {
4975
- const session = await this.userAuthorization.signIn(options);
6185
+ async signIn(options2) {
6186
+ const session = await this.userAuthorization.signIn(options2);
4976
6187
  const serviceSession = this.toServiceSession(session);
4977
6188
  this.notifyServicesOfSessionChange(serviceSession);
4978
6189
  return session;
@@ -5515,32 +6726,32 @@ function validateManifestSecrets(secrets) {
5515
6726
  if (secrets === null || typeof secrets !== "object" || Array.isArray(secrets)) {
5516
6727
  throw new ManifestValidationError("manifest.secrets must be an object");
5517
6728
  }
5518
- for (const [name, spec] of Object.entries(secrets)) {
5519
- if (!SECRET_NAME_RE.test(name)) {
6729
+ for (const [name2, spec] of Object.entries(secrets)) {
6730
+ if (!SECRET_NAME_RE.test(name2)) {
5520
6731
  throw new ManifestValidationError(
5521
- `manifest.secrets.${name} must match ${SECRET_NAME_RE.source}`
6732
+ `manifest.secrets.${name2} must match ${SECRET_NAME_RE.source}`
5522
6733
  );
5523
6734
  }
5524
6735
  try {
5525
6736
  resolveSecretPath(
5526
- secretNameFromSpec(name, spec),
6737
+ secretNameFromSpec(name2, spec),
5527
6738
  { scope: secretScopeFromSpec(spec) }
5528
6739
  );
5529
6740
  } catch (error) {
5530
6741
  throw new ManifestValidationError(
5531
- `manifest.secrets.${name}: ${error instanceof Error ? error.message : String(error)}`
6742
+ `manifest.secrets.${name2}: ${error instanceof Error ? error.message : String(error)}`
5532
6743
  );
5533
6744
  }
5534
- const actions = secretActionsFromSpec(name, spec);
6745
+ const actions = secretActionsFromSpec(name2, spec);
5535
6746
  if (actions.length === 0) {
5536
6747
  throw new ManifestValidationError(
5537
- `manifest.secrets.${name} actions must be non-empty`
6748
+ `manifest.secrets.${name2} actions must be non-empty`
5538
6749
  );
5539
6750
  }
5540
6751
  for (const action of actions) {
5541
6752
  if (typeof action !== "string" || action.length === 0) {
5542
6753
  throw new ManifestValidationError(
5543
- `manifest.secrets.${name} actions must be non-empty strings`
6754
+ `manifest.secrets.${name2} actions must be non-empty strings`
5544
6755
  );
5545
6756
  }
5546
6757
  }
@@ -5582,6 +6793,11 @@ function validatePermissionEntry(p, path) {
5582
6793
  vaultActionExpansion(action);
5583
6794
  }
5584
6795
  }
6796
+ if (entry.caveats !== void 0 && (!Array.isArray(entry.caveats) || entry.caveats.some(
6797
+ (caveat) => caveat === null || typeof caveat !== "object" || Array.isArray(caveat)
6798
+ ))) {
6799
+ throw new ManifestValidationError(`${path}.caveats must be an array of objects`);
6800
+ }
5585
6801
  if (entry.expiry !== void 0) {
5586
6802
  parseExpiry(entry.expiry);
5587
6803
  }
@@ -5699,7 +6915,7 @@ function secretScopeFromSpec(spec) {
5699
6915
  }
5700
6916
  return void 0;
5701
6917
  }
5702
- function secretActionsFromSpec(name, spec) {
6918
+ function secretActionsFromSpec(name2, spec) {
5703
6919
  if (spec === true) {
5704
6920
  return ["read"];
5705
6921
  }
@@ -5711,7 +6927,7 @@ function secretActionsFromSpec(name, spec) {
5711
6927
  }
5712
6928
  if (spec === null || typeof spec !== "object") {
5713
6929
  throw new ManifestValidationError(
5714
- `manifest.secrets.${name} must be true, a string action, an actions array, or an object`
6930
+ `manifest.secrets.${name2} must be true, a string action, an actions array, or an object`
5715
6931
  );
5716
6932
  }
5717
6933
  if (spec.actions === void 0) {
@@ -5724,7 +6940,7 @@ function secretActionsFromSpec(name, spec) {
5724
6940
  return spec.actions;
5725
6941
  }
5726
6942
  throw new ManifestValidationError(
5727
- `manifest.secrets.${name}.actions must be a string or array`
6943
+ `manifest.secrets.${name2}.actions must be a string or array`
5728
6944
  );
5729
6945
  }
5730
6946
  function secretEntriesForManifest(secrets) {
@@ -5732,10 +6948,10 @@ function secretEntriesForManifest(secrets) {
5732
6948
  return [];
5733
6949
  }
5734
6950
  const entries = [];
5735
- for (const [name, spec] of Object.entries(secrets)) {
5736
- const actions = secretActionsFromSpec(name, spec);
6951
+ for (const [name2, spec] of Object.entries(secrets)) {
6952
+ const actions = secretActionsFromSpec(name2, spec);
5737
6953
  const secretPath = resolveSecretPath(
5738
- secretNameFromSpec(name, spec),
6954
+ secretNameFromSpec(name2, spec),
5739
6955
  { scope: secretScopeFromSpec(spec) }
5740
6956
  );
5741
6957
  const extra = spec !== true && typeof spec === "object" && !Array.isArray(spec) ? spec : {};
@@ -5776,18 +6992,18 @@ function expandVaultPermissionEntry(entry) {
5776
6992
  const byBase = /* @__PURE__ */ new Map();
5777
6993
  for (const action of entry.actions) {
5778
6994
  const expansion = vaultActionExpansion(action);
5779
- for (const base of expansion.bases) {
5780
- const actions = byBase.get(base) ?? [];
6995
+ for (const base3 of expansion.bases) {
6996
+ const actions = byBase.get(base3) ?? [];
5781
6997
  if (!actions.includes(expansion.action)) {
5782
6998
  actions.push(expansion.action);
5783
6999
  }
5784
- byBase.set(base, actions);
7000
+ byBase.set(base3, actions);
5785
7001
  }
5786
7002
  }
5787
- return [...byBase.entries()].map(([base, actions]) => ({
7003
+ return [...byBase.entries()].map(([base3, actions]) => ({
5788
7004
  ...entry,
5789
7005
  service: "tinycloud.kv",
5790
- path: vaultKVPath(base, entry.path),
7006
+ path: vaultKVPath(base3, entry.path),
5791
7007
  actions,
5792
7008
  skipPrefix: true
5793
7009
  }));
@@ -5830,9 +7046,9 @@ function normalizeVaultAction(action) {
5830
7046
  }
5831
7047
  return action;
5832
7048
  }
5833
- function vaultKVPath(base, path) {
7049
+ function vaultKVPath(base3, path) {
5834
7050
  const normalized = path.startsWith("/") ? path.slice(1) : path;
5835
- return `${base}/${normalized}`;
7051
+ return `${base3}/${normalized}`;
5836
7052
  }
5837
7053
  function cloneResourceCapability(entry) {
5838
7054
  return {
@@ -5850,6 +7066,7 @@ function clonePermissionEntry(entry) {
5850
7066
  ...entry.space !== void 0 ? { space: entry.space } : {},
5851
7067
  path: entry.path,
5852
7068
  actions: [...entry.actions],
7069
+ ...entry.caveats !== void 0 ? { caveats: JSON.parse(JSON.stringify(entry.caveats)) } : {},
5853
7070
  ...entry.skipPrefix !== void 0 ? { skipPrefix: entry.skipPrefix } : {},
5854
7071
  ...entry.expiry !== void 0 ? { expiry: entry.expiry } : {},
5855
7072
  ...entry.description !== void 0 ? { description: entry.description } : {}
@@ -5898,12 +7115,20 @@ function withCapabilitiesReadForSpaces(resources) {
5898
7115
  ]);
5899
7116
  }
5900
7117
  function accountRegistryPermissions() {
5901
- return [ACCOUNT_REGISTRY_PATH, "spaces/"].map((path) => ({
5902
- service: "tinycloud.kv",
5903
- space: ACCOUNT_REGISTRY_SPACE,
5904
- path,
5905
- actions: ["tinycloud.kv/get", "tinycloud.kv/put", "tinycloud.kv/list"]
5906
- }));
7118
+ return [
7119
+ ...[ACCOUNT_REGISTRY_PATH, "spaces/"].map((path) => ({
7120
+ service: "tinycloud.kv",
7121
+ space: ACCOUNT_REGISTRY_SPACE,
7122
+ path,
7123
+ actions: ["tinycloud.kv/get", "tinycloud.kv/put", "tinycloud.kv/list"]
7124
+ })),
7125
+ {
7126
+ service: "tinycloud.delegation",
7127
+ space: ACCOUNT_REGISTRY_SPACE,
7128
+ path: "",
7129
+ actions: ["tinycloud.delegation/list"]
7130
+ }
7131
+ ];
5907
7132
  }
5908
7133
  function accountRegistryIndexPermission() {
5909
7134
  return {
@@ -5913,13 +7138,13 @@ function accountRegistryIndexPermission() {
5913
7138
  actions: ["tinycloud.sql/read", "tinycloud.sql/write", "tinycloud.sql/schema"]
5914
7139
  };
5915
7140
  }
5916
- function composeManifestRequest(inputs, options = {}) {
7141
+ function composeManifestRequest(inputs, options2 = {}) {
5917
7142
  if (!Array.isArray(inputs) || inputs.length === 0) {
5918
7143
  throw new ManifestValidationError(
5919
7144
  "composeManifestRequest requires at least one manifest"
5920
7145
  );
5921
7146
  }
5922
- const includeAccountRegistryPermissions = options.includeAccountRegistryPermissions ?? true;
7147
+ const includeAccountRegistryPermissions = options2.includeAccountRegistryPermissions ?? true;
5923
7148
  const manifests = inputs.map(validateManifest);
5924
7149
  const resolved = manifests.map(resolveManifest);
5925
7150
  const resources = resolved.flatMap((entry) => entry.resources);
@@ -6024,13 +7249,13 @@ var AccountService = class {
6024
7249
  constructor(config) {
6025
7250
  this.config = config;
6026
7251
  this.applications = {
6027
- list: async (options = {}) => {
6028
- if (options.preferIndex) {
7252
+ list: async (options2 = {}) => {
7253
+ if (options2.preferIndex) {
6029
7254
  const indexed = await this.index.applications.list();
6030
7255
  if (indexed.ok && indexed.data.length > 0) return indexed;
6031
7256
  if (!indexed.ok && !isMissingIndexError(indexed.error)) return indexed;
6032
7257
  const canonical = await this.applications.list();
6033
- if (canonical.ok && options.refreshIndex !== false) {
7258
+ if (canonical.ok && options2.refreshIndex !== false) {
6034
7259
  await this.replaceApplicationsIndexQuietly(canonical.data);
6035
7260
  }
6036
7261
  return canonical;
@@ -6107,13 +7332,13 @@ var AccountService = class {
6107
7332
  }
6108
7333
  };
6109
7334
  this.spaces = {
6110
- list: async (options = {}) => {
6111
- if (options.preferIndex) {
7335
+ list: async (options2 = {}) => {
7336
+ if (options2.preferIndex) {
6112
7337
  const indexed = await this.index.spaces.list();
6113
7338
  if (indexed.ok && indexed.data.length > 0) return indexed;
6114
7339
  if (!indexed.ok && !isMissingIndexError(indexed.error)) return indexed;
6115
7340
  const canonical = await this.spaces.syncAccessible();
6116
- if (canonical.ok && options.refreshIndex !== false) {
7341
+ if (canonical.ok && options2.refreshIndex !== false) {
6117
7342
  await this.replaceSpacesIndexQuietly(canonical.data);
6118
7343
  }
6119
7344
  return canonical;
@@ -6170,32 +7395,44 @@ var AccountService = class {
6170
7395
  }
6171
7396
  };
6172
7397
  this.delegations = {
6173
- list: async (options = {}) => {
6174
- if (options.preferIndex) {
6175
- const indexed = await this.index.delegations.list(options);
7398
+ query: async (options2 = {}) => {
7399
+ const manager = this.config.getDelegationManager?.();
7400
+ if (!manager) {
7401
+ return err3(serviceError3(
7402
+ "NOT_INITIALIZED",
7403
+ "Delegation history requires an authenticated delegation manager",
7404
+ SERVICE_NAME2
7405
+ ));
7406
+ }
7407
+ const queried = await manager.query(options2);
7408
+ return queried.ok ? ok3(queried.data) : accountErr(queried.error);
7409
+ },
7410
+ list: async (options2 = {}) => {
7411
+ if (options2.preferIndex) {
7412
+ const indexed = await this.index.delegations.list(options2);
6176
7413
  if (indexed.ok && indexed.data.length > 0) return indexed;
6177
7414
  if (!indexed.ok && !isMissingIndexError(indexed.error)) return indexed;
6178
7415
  const live = await this.delegations.list({
6179
- direction: options.direction,
6180
- space: options.space
7416
+ direction: options2.direction,
7417
+ space: options2.space
6181
7418
  });
6182
- if (live.ok && options.refreshIndex !== false) {
7419
+ if (live.ok && options2.refreshIndex !== false) {
6183
7420
  await this.replaceDelegationsIndexQuietly(live.data);
6184
7421
  }
6185
7422
  return live;
6186
7423
  }
6187
7424
  const spaces = await this.config.getSpaces().list();
6188
7425
  if (!spaces.ok) return accountErr(spaces.error);
6189
- const targetSpaces = options.space ? spaces.data.filter((space) => space.id === options.space || space.name === options.space) : spaces.data;
7426
+ const targetSpaces = options2.space ? spaces.data.filter((space) => space.id === options2.space || space.name === options2.space) : spaces.data;
6190
7427
  const delegations = [];
6191
7428
  for (const space of targetSpaces) {
6192
7429
  const scoped = this.config.getSpaces().get(space.id).delegations;
6193
- if (options.direction !== "received") {
7430
+ if (options2.direction !== "received") {
6194
7431
  const granted = await scoped.list();
6195
7432
  if (!granted.ok) return accountErr(granted.error);
6196
7433
  delegations.push(...granted.data.map((d) => mapDelegation(d, space, "granted")));
6197
7434
  }
6198
- if (options.direction !== "granted") {
7435
+ if (options2.direction !== "granted") {
6199
7436
  const received = await scoped.listReceived();
6200
7437
  if (!received.ok) return accountErr(received.error);
6201
7438
  delegations.push(...received.data.map((d) => mapDelegation(d, space, "received")));
@@ -6204,10 +7441,23 @@ var AccountService = class {
6204
7441
  delegations.sort((a, b) => a.spaceId.localeCompare(b.spaceId) || a.cid.localeCompare(b.cid));
6205
7442
  return ok3(delegations);
6206
7443
  },
6207
- revoke: async (options) => {
6208
- const space = await this.resolveSpace(options.space);
7444
+ revoke: async (input) => {
7445
+ const cid = typeof input === "string" ? input : input.cid;
7446
+ const manager = this.config.getDelegationManager?.();
7447
+ if (manager) {
7448
+ const revoked2 = await manager.revoke(cid);
7449
+ return revoked2.ok ? ok3(revoked2.data) : accountErr(revoked2.error);
7450
+ }
7451
+ if (typeof input === "string") {
7452
+ return err3(serviceError3(
7453
+ "NOT_INITIALIZED",
7454
+ "CID-only revocation requires an authenticated delegation manager",
7455
+ SERVICE_NAME2
7456
+ ));
7457
+ }
7458
+ const space = await this.resolveSpace(input.space);
6209
7459
  if (!space.ok) return space;
6210
- const revoked = await this.config.getSpaces().get(space.data.id).delegations.revoke(options.cid);
7460
+ const revoked = await this.config.getSpaces().get(space.data.id).delegations.revoke(cid);
6211
7461
  if (!revoked.ok) return accountErr(revoked.error);
6212
7462
  return ok3(void 0);
6213
7463
  }
@@ -6330,18 +7580,18 @@ var AccountService = class {
6330
7580
  }
6331
7581
  },
6332
7582
  delegations: {
6333
- list: async (options = {}) => {
7583
+ list: async (options2 = {}) => {
6334
7584
  const dbResult = this.accountDb();
6335
7585
  if (!dbResult.ok) return dbResult;
6336
7586
  const where = [];
6337
7587
  const params = [];
6338
- if (options.direction && options.direction !== "all") {
7588
+ if (options2.direction && options2.direction !== "all") {
6339
7589
  where.push("direction = ?");
6340
- params.push(options.direction);
7590
+ params.push(options2.direction);
6341
7591
  }
6342
- if (options.space) {
7592
+ if (options2.space) {
6343
7593
  where.push("(space_id = ? OR space_name = ?)");
6344
- params.push(options.space, options.space);
7594
+ params.push(options2.space, options2.space);
6345
7595
  }
6346
7596
  const queried = await dbResult.data.query(
6347
7597
  `SELECT cid, direction, space_id, space_name, counterparty_did, delegate_did, delegator_did, path, actions_json, expiry, status, created_at FROM delegations${where.length > 0 ? ` WHERE ${where.join(" AND ")}` : ""} ORDER BY space_id, cid`,
@@ -6662,10 +7912,10 @@ function applicationFromRecord(key, record) {
6662
7912
  };
6663
7913
  }
6664
7914
  function indexedApplicationFromRow(row) {
6665
- const [appId, name, description, updatedAt, manifestJson, manifestHash] = row;
7915
+ const [appId, name2, description, updatedAt, manifestJson, manifestHash] = row;
6666
7916
  return {
6667
7917
  appId,
6668
- name: name ?? void 0,
7918
+ name: name2 ?? void 0,
6669
7919
  description: description ?? void 0,
6670
7920
  updatedAt: updatedAt ?? void 0,
6671
7921
  manifests: JSON.parse(manifestJson),
@@ -6716,10 +7966,10 @@ function spaceFromRecord(key, record) {
6716
7966
  };
6717
7967
  }
6718
7968
  function indexedSpaceFromRow(row) {
6719
- const [spaceId, name, ownerDid, type, permissionsJson, status, registeredAt, updatedAt, expiresAt] = row;
7969
+ const [spaceId, name2, ownerDid, type, permissionsJson, status, registeredAt, updatedAt, expiresAt] = row;
6720
7970
  return {
6721
7971
  spaceId,
6722
- name,
7972
+ name: name2,
6723
7973
  ownerDid,
6724
7974
  type,
6725
7975
  permissions: JSON.parse(permissionsJson),
@@ -6842,6 +8092,7 @@ import {
6842
8092
  resolveSecretListPrefix,
6843
8093
  resolveSecretPath as resolveSecretPath2,
6844
8094
  EncryptionService,
8095
+ DecryptTransportResponseError,
6845
8096
  parseNetworkId as parseNetworkId2,
6846
8097
  buildNetworkId as buildNetworkId2,
6847
8098
  isNetworkId,
@@ -6959,9 +8210,9 @@ var DelegationAction = {
6959
8210
  GET: "tinycloud.delegation/get",
6960
8211
  CHECK: "tinycloud.delegation/check"
6961
8212
  };
6962
- function createError(code, message, cause, meta) {
8213
+ function createError(code2, message, cause, meta) {
6963
8214
  return {
6964
- code,
8215
+ code: code2,
6965
8216
  message,
6966
8217
  service: "delegation",
6967
8218
  cause,
@@ -6980,6 +8231,7 @@ var DelegationManager = class {
6980
8231
  this.invoke = config.invoke;
6981
8232
  this.invokeAny = config.invokeAny;
6982
8233
  this.fetchFn = config.fetch ?? globalThis.fetch.bind(globalThis);
8234
+ this.accountSpaceId = config.accountSpaceId;
6983
8235
  }
6984
8236
  /**
6985
8237
  * Updates the session (e.g., after re-authentication).
@@ -7185,7 +8437,19 @@ var DelegationManager = class {
7185
8437
  )
7186
8438
  };
7187
8439
  }
7188
- return { ok: true, data: void 0 };
8440
+ const parsed = DelegationRevocationReceiptSchema.safeParse(await response.json());
8441
+ if (!parsed.success || parsed.data.cid !== cid) {
8442
+ return {
8443
+ ok: false,
8444
+ error: createError(
8445
+ DelegationErrorCodes.REVOCATION_FAILED,
8446
+ "Node returned an invalid delegation revocation receipt",
8447
+ void 0,
8448
+ { cid }
8449
+ )
8450
+ };
8451
+ }
8452
+ return { ok: true, data: parsed.data };
7189
8453
  } catch (error) {
7190
8454
  if (error instanceof Error && error.name === "AbortError") {
7191
8455
  return {
@@ -7282,6 +8546,86 @@ var DelegationManager = class {
7282
8546
  };
7283
8547
  }
7284
8548
  }
8549
+ /** Query lifecycle-complete delegation history for the authenticated account. */
8550
+ async query(options2 = {}) {
8551
+ const validated = AccountDelegationQueryOptionsSchema.safeParse(options2);
8552
+ if (!validated.success) {
8553
+ return {
8554
+ ok: false,
8555
+ error: createError(
8556
+ DelegationErrorCodes.INVALID_INPUT,
8557
+ "Invalid delegation query options",
8558
+ void 0,
8559
+ { issues: validated.error.issues }
8560
+ )
8561
+ };
8562
+ }
8563
+ if (!this.invokeAny) {
8564
+ return {
8565
+ ok: false,
8566
+ error: createError(
8567
+ DelegationErrorCodes.NOT_INITIALIZED,
8568
+ "Delegation query requires an invokeAny function"
8569
+ )
8570
+ };
8571
+ }
8572
+ if (!this.accountSpaceId) {
8573
+ return {
8574
+ ok: false,
8575
+ error: createError(
8576
+ DelegationErrorCodes.NOT_INITIALIZED,
8577
+ "Delegation query requires an account space"
8578
+ )
8579
+ };
8580
+ }
8581
+ try {
8582
+ const invocationHeaders = this.invokeAny(this.session, [{
8583
+ spaceId: this.accountSpaceId,
8584
+ service: "delegation",
8585
+ path: "",
8586
+ action: DelegationAction.LIST
8587
+ }]);
8588
+ const headers = Object.fromEntries(new Headers(invocationHeaders).entries());
8589
+ headers["content-type"] = "application/json";
8590
+ const response = await this.fetchFn(`${this.host}/delegation/query`, {
8591
+ method: "POST",
8592
+ headers,
8593
+ body: JSON.stringify(validated.data)
8594
+ });
8595
+ if (!response.ok) {
8596
+ const errorText = await response.text();
8597
+ return {
8598
+ ok: false,
8599
+ error: createError(
8600
+ DelegationErrorCodes.NETWORK_ERROR,
8601
+ `Failed to query delegations: ${response.status} - ${errorText}`,
8602
+ void 0,
8603
+ { status: response.status }
8604
+ )
8605
+ };
8606
+ }
8607
+ const parsed = AccountDelegationPageSchema.safeParse(await response.json());
8608
+ if (!parsed.success) {
8609
+ return {
8610
+ ok: false,
8611
+ error: createError(
8612
+ DelegationErrorCodes.INVALID_TOKEN,
8613
+ "Node returned an invalid delegation query response"
8614
+ )
8615
+ };
8616
+ }
8617
+ return { ok: true, data: parsed.data };
8618
+ } catch (error) {
8619
+ return {
8620
+ ok: false,
8621
+ error: createError(
8622
+ DelegationErrorCodes.NETWORK_ERROR,
8623
+ `Network error during delegation query: ${String(error)}`,
8624
+ error instanceof Error ? error : void 0
8625
+ )
8626
+ };
8627
+ }
8628
+ }
7285
8629
  /**
7286
8630
  * Lists all delegations for the current session's space.
7287
8631
  *
@@ -7677,6 +9021,17 @@ var SessionExpiredError = class extends Error {
7677
9021
  this.expiredAt = expiredAt;
7678
9022
  }
7679
9023
  };
9024
+ var CaveatedDelegationUnsupportedError = class extends Error {
9025
+ constructor(entries) {
9026
+ super(
9027
+ "Cannot create a caveated delegation because this WASM delegation boundary cannot preserve every ReCap caveat branch exactly."
9028
+ );
9029
+ /** Stable machine-readable error code for fail-closed caveated delegation. */
9030
+ this.code = "CAVEATED_DELEGATION_UNSUPPORTED";
9031
+ this.name = "CaveatedDelegationUnsupportedError";
9032
+ this.entries = entries.map(cloneEntry);
9033
+ }
9034
+ };
7680
9035
  function normalizeSpace(space) {
7681
9036
  if (!space.startsWith("tinycloud:")) {
7682
9037
  return space;
@@ -7717,8 +9072,42 @@ function canonicalizeEntryMatches(requested, granted) {
7717
9072
  return false;
7718
9073
  }
7719
9074
  }
9075
+ if (!recapCaveatsEqual(requested.caveats, granted.caveats)) {
9076
+ return false;
9077
+ }
7720
9078
  return true;
7721
9079
  }
9080
+ function recapCaveatsEqual(left, right) {
9081
+ return canonicalizeRecapCaveats(left) === canonicalizeRecapCaveats(right);
9082
+ }
9083
+ function canonicalizeRecapCaveats(caveats) {
9084
+ const canonicalize = (value) => {
9085
+ if (value === null || typeof value === "boolean" || typeof value === "string") {
9086
+ return JSON.stringify(value);
9087
+ }
9088
+ if (typeof value === "number") {
9089
+ if (Number.isFinite(value)) return JSON.stringify(value);
9090
+ throw new Error("ReCap caveats must contain only JSON values.");
9091
+ }
9092
+ if (Array.isArray(value)) return `[${value.map(canonicalize).join(",")}]`;
9093
+ if (typeof value === "object") {
9094
+ const object = value;
9095
+ const prototype = Object.getPrototypeOf(object);
9096
+ if (prototype !== Object.prototype && prototype !== null) {
9097
+ throw new Error("ReCap caveats must contain only JSON values.");
9098
+ }
9099
+ return `{${Object.keys(object).sort().map(
9100
+ (key) => `${JSON.stringify(key)}:${canonicalize(object[key])}`
9101
+ ).join(",")}}`;
9102
+ }
9103
+ throw new Error("ReCap caveats must contain only JSON values.");
9104
+ };
9105
+ const branches = (caveats ?? []).map(canonicalize).sort();
9106
+ if (branches.length === 0 || branches.length === 1 && branches[0] === "{}") {
9107
+ return "[]";
9108
+ }
9109
+ return `[${branches.join(",")}]`;
9110
+ }
7722
9111
  function actionContains(grantedAction, requestedAction) {
7723
9112
  if (grantedAction === "*" || grantedAction === requestedAction) return true;
7724
9113
  if (!grantedAction.endsWith("/*")) return false;
@@ -7740,6 +9129,7 @@ function cloneEntry(entry) {
7740
9129
  ...entry.space !== void 0 ? { space: entry.space } : {},
7741
9130
  path: entry.path,
7742
9131
  actions: [...entry.actions],
9132
+ ...entry.caveats !== void 0 ? { caveats: JSON.parse(JSON.stringify(entry.caveats)) } : {},
7743
9133
  ...entry.skipPrefix !== void 0 ? { skipPrefix: entry.skipPrefix } : {},
7744
9134
  ...entry.expiry !== void 0 ? { expiry: entry.expiry } : {}
7745
9135
  };
@@ -7763,7 +9153,8 @@ function parseRecapCapabilities(parseWasm, siwe) {
7763
9153
  // returned entries match the shape manifests use.
7764
9154
  space: normalizeSpace(entry.space),
7765
9155
  path: entry.path,
7766
- actions: [...entry.actions]
9156
+ actions: [...entry.actions],
9157
+ ...entry.caveats === void 0 ? {} : { caveats: JSON.parse(JSON.stringify(entry.caveats)) }
7767
9158
  };
7768
9159
  });
7769
9160
  normalized.sort((a, b) => {
@@ -7778,7 +9169,6 @@ function parseRecapCapabilities(parseWasm, siwe) {
7778
9169
  }
7779
9170
 
7780
9171
  // src/delegations/SharingService.ts
7781
- import { bases as bases2 } from "multiformats/basics";
7782
9172
  import { ed25519 as ed255192 } from "@noble/curves/ed25519";
7783
9173
  function inferShortServiceFromActionUrns(actions) {
7784
9174
  let short;
@@ -7799,9 +9189,9 @@ function inferShortServiceFromActionUrns(actions) {
7799
9189
  var DEFAULT_READ_ACTIONS = ["tinycloud.kv/get", "tinycloud.kv/metadata"];
7800
9190
  var DEFAULT_EXPIRY_MS = EXPIRY.SHARE_MS;
7801
9191
  var BASE64_PREFIX = "tc1:";
7802
- function createError2(code, message, cause, meta) {
9192
+ function createError2(code2, message, cause, meta) {
7803
9193
  return {
7804
- code,
9194
+ code: code2,
7805
9195
  message,
7806
9196
  service: "delegation",
7807
9197
  cause,
@@ -7809,25 +9199,25 @@ function createError2(code, message, cause, meta) {
7809
9199
  };
7810
9200
  }
7811
9201
  function base64UrlEncode2(data) {
7812
- let base64;
9202
+ let base642;
7813
9203
  if (typeof btoa !== "undefined") {
7814
- base64 = btoa(unescape(encodeURIComponent(data)));
9204
+ base642 = btoa(unescape(encodeURIComponent(data)));
7815
9205
  } else if (typeof Buffer !== "undefined") {
7816
- base64 = Buffer.from(data, "utf-8").toString("base64");
9206
+ base642 = Buffer.from(data, "utf-8").toString("base64");
7817
9207
  } else {
7818
9208
  throw new Error("No base64 encoding available");
7819
9209
  }
7820
- return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
9210
+ return base642.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
7821
9211
  }
7822
9212
  function base64UrlDecode2(encoded) {
7823
- let base64 = encoded.replace(/-/g, "+").replace(/_/g, "/");
7824
- while (base64.length % 4) {
7825
- base64 += "=";
9213
+ let base642 = encoded.replace(/-/g, "+").replace(/_/g, "/");
9214
+ while (base642.length % 4) {
9215
+ base642 += "=";
7826
9216
  }
7827
9217
  if (typeof atob !== "undefined") {
7828
- return decodeURIComponent(escape(atob(base64)));
9218
+ return decodeURIComponent(escape(atob(base642)));
7829
9219
  } else if (typeof Buffer !== "undefined") {
7830
- return Buffer.from(base64, "base64").toString("utf-8");
9220
+ return Buffer.from(base642, "base64").toString("utf-8");
7831
9221
  } else {
7832
9222
  throw new Error("No base64 decoding available");
7833
9223
  }
@@ -7852,6 +9242,7 @@ var SharingService = class {
7852
9242
  this.pathPrefix = config.pathPrefix ?? "";
7853
9243
  this.sessionExpiry = config.sessionExpiry;
7854
9244
  this.onRootDelegationNeeded = config.onRootDelegationNeeded;
9245
+ this.assertActiveFn = config.assertActive;
7855
9246
  }
7856
9247
  /**
7857
9248
  * Gets the primary host URL.
@@ -7863,6 +9254,7 @@ var SharingService = class {
7863
9254
  * Updates the session (e.g., after re-authentication).
7864
9255
  */
7865
9256
  updateSession(session) {
9257
+ this.assertActiveFn?.();
7866
9258
  this.session = session;
7867
9259
  }
7868
9260
  /**
@@ -7870,6 +9262,7 @@ var SharingService = class {
7870
9262
  * Used to add full capabilities (session, delegationManager, createDelegation, createDelegationWasm) after signIn.
7871
9263
  */
7872
9264
  updateConfig(config) {
9265
+ this.assertActiveFn?.();
7873
9266
  if (config.session !== void 0) {
7874
9267
  this.session = config.session;
7875
9268
  }
@@ -7888,6 +9281,9 @@ var SharingService = class {
7888
9281
  if (config.onRootDelegationNeeded !== void 0) {
7889
9282
  this.onRootDelegationNeeded = config.onRootDelegationNeeded;
7890
9283
  }
9284
+ if (config.assertActive !== void 0) {
9285
+ this.assertActiveFn = config.assertActive;
9286
+ }
7891
9287
  }
7892
9288
  /**
7893
9289
  * Generate a sharing link with an embedded private key.
@@ -7900,6 +9296,8 @@ var SharingService = class {
7900
9296
  * 5. Return link string
7901
9297
  */
7902
9298
  async generate(params) {
9299
+ const activeError = this.retiredGraphError();
9300
+ if (activeError) return { ok: false, error: activeError };
7903
9301
  if (!this.session) {
7904
9302
  return {
7905
9303
  ok: false,
@@ -7947,7 +9345,11 @@ var SharingService = class {
7947
9345
  try {
7948
9346
  const shareKeyName = `share:${Date.now()}:${Math.random().toString(36).substring(2, 10)}`;
7949
9347
  keyId = await this.keyProvider.createSessionKey(shareKeyName);
9348
+ const keyCreationActiveError = this.retiredGraphError();
9349
+ if (keyCreationActiveError) return { ok: false, error: keyCreationActiveError };
7950
9350
  keyDid = await this.keyProvider.getDID(keyId);
9351
+ const keyDidActiveError = this.retiredGraphError();
9352
+ if (keyDidActiveError) return { ok: false, error: keyDidActiveError };
7951
9353
  keyJwk = this.keyProvider.getJWK(keyId);
7952
9354
  if (!keyJwk.d) {
7953
9355
  return {
@@ -7983,6 +9385,8 @@ var SharingService = class {
7983
9385
  );
7984
9386
  if (canSatisfyFromRegistry) {
7985
9387
  const delegationResult = await this.createSessionDelegation(plainDID, fullPath, actions, expiry);
9388
+ const childDelegationActiveError = this.retiredGraphError();
9389
+ if (childDelegationActiveError) return { ok: false, error: childDelegationActiveError };
7986
9390
  const parsed = handleDelegationResult(delegationResult);
7987
9391
  if ("ok" in parsed && parsed.ok === false) {
7988
9392
  return parsed;
@@ -7997,39 +9401,41 @@ var SharingService = class {
7997
9401
  actions,
7998
9402
  requestedExpiry
7999
9403
  });
9404
+ const rootDelegationActiveError = this.retiredGraphError();
9405
+ if (rootDelegationActiveError) return { ok: false, error: rootDelegationActiveError };
8000
9406
  if (rootDelegation) {
8001
9407
  delegation = rootDelegation;
8002
9408
  expiry = requestedExpiry;
8003
9409
  } else {
8004
- const fallbackResult = await this.handleSessionExtensionFallback(requestedExpiry);
8005
- expiry = fallbackResult.expiry;
8006
- const delegationResult = await this.createSessionDelegation(plainDID, fullPath, actions, expiry);
8007
- const parsed = handleDelegationResult(delegationResult);
8008
- if ("ok" in parsed && parsed.ok === false) {
8009
- return parsed;
8010
- }
8011
- delegation = parsed;
9410
+ return {
9411
+ ok: false,
9412
+ error: createError2(
9413
+ DelegationErrorCodes.PERMISSION_DENIED,
9414
+ "The active session ReCap does not authorize this sharing delegation."
9415
+ )
9416
+ };
8012
9417
  }
8013
9418
  } catch (err6) {
8014
- const fallbackResult = await this.handleSessionExtensionFallback(requestedExpiry);
8015
- expiry = fallbackResult.expiry;
8016
- const delegationResult = await this.createSessionDelegation(plainDID, fullPath, actions, expiry);
8017
- const parsed = handleDelegationResult(delegationResult);
8018
- if ("ok" in parsed && parsed.ok === false) {
8019
- return parsed;
8020
- }
8021
- delegation = parsed;
9419
+ return {
9420
+ ok: false,
9421
+ error: createError2(
9422
+ DelegationErrorCodes.PERMISSION_DENIED,
9423
+ "The active session ReCap does not authorize this sharing delegation.",
9424
+ err6 instanceof Error ? err6 : void 0
9425
+ )
9426
+ };
8022
9427
  }
8023
9428
  } else {
8024
- const fallbackResult = await this.handleSessionExtensionFallback(requestedExpiry);
8025
- expiry = fallbackResult.expiry;
8026
- const delegationResult = await this.createSessionDelegation(plainDID, fullPath, actions, expiry);
8027
- const parsed = handleDelegationResult(delegationResult);
8028
- if ("ok" in parsed && parsed.ok === false) {
8029
- return parsed;
8030
- }
8031
- delegation = parsed;
9429
+ return {
9430
+ ok: false,
9431
+ error: createError2(
9432
+ DelegationErrorCodes.PERMISSION_DENIED,
9433
+ "The active session ReCap does not authorize this sharing delegation."
9434
+ )
9435
+ };
8032
9436
  }
9437
+ const finalActiveError = this.retiredGraphError();
9438
+ if (finalActiveError) return { ok: false, error: finalActiveError };
8033
9439
  const shareData = {
8034
9440
  key: keyJwk,
8035
9441
  keyDid,
@@ -8062,13 +9468,16 @@ var SharingService = class {
8062
9468
  * @internal
8063
9469
  */
8064
9470
  findSuitableKeyForDelegation(path, actions, requestedExpiry) {
8065
- if (this.sessionExpiry && requestedExpiry <= this.sessionExpiry) {
8066
- return true;
8067
- }
8068
9471
  const allKeys = this.registry.getAllKeys();
8069
9472
  for (const key of allKeys) {
8070
9473
  const delegations = this.registry.getDelegationsForKey(key.id);
8071
9474
  for (const delegation of delegations) {
9475
+ if (delegation.spaceId !== this.session?.spaceId) {
9476
+ continue;
9477
+ }
9478
+ if ((delegation.caveats?.length ?? 0) > 0) {
9479
+ continue;
9480
+ }
8072
9481
  if (!this.registry.isDelegationValid(delegation)) {
8073
9482
  continue;
8074
9483
  }
@@ -8094,6 +9503,18 @@ var SharingService = class {
8094
9503
  }
8095
9504
  return false;
8096
9505
  }
9506
+ retiredGraphError() {
9507
+ try {
9508
+ this.assertActiveFn?.();
9509
+ return void 0;
9510
+ } catch (err6) {
9511
+ return createError2(
9512
+ DelegationErrorCodes.NOT_INITIALIZED,
9513
+ "The session service graph has been retired.",
9514
+ err6 instanceof Error ? err6 : void 0
9515
+ );
9516
+ }
9517
+ }
8097
9518
  /**
8098
9519
  * Check if a delegation path matches/covers the requested path.
8099
9520
  * A delegation path covers the request if:
@@ -8116,19 +9537,14 @@ var SharingService = class {
8116
9537
  }
8117
9538
  return false;
8118
9539
  }
8119
- /**
8120
- * Handle fallback to session extension when root delegation is not available.
8121
- * @internal
8122
- */
8123
- async handleSessionExtensionFallback(requestedExpiry) {
8124
- return { expiry: this.sessionExpiry ?? requestedExpiry };
8125
- }
8126
9540
  /**
8127
9541
  * Create a delegation from the current session to a share key.
8128
9542
  * This is the fallback path when root delegation is not available.
8129
9543
  * @internal
8130
9544
  */
8131
9545
  async createSessionDelegation(delegateDID, path, actions, expiry) {
9546
+ const activeError = this.retiredGraphError();
9547
+ if (activeError) return { ok: false, error: activeError };
8132
9548
  if (!this.session) {
8133
9549
  return {
8134
9550
  ok: false,
@@ -8170,14 +9586,20 @@ var SharingService = class {
8170
9586
  },
8171
9587
  expirationSecs: Math.floor(expiry.getTime() / 1e3)
8172
9588
  });
9589
+ const childSigningActiveError = this.retiredGraphError();
9590
+ if (childSigningActiveError) return { ok: false, error: childSigningActiveError };
8173
9591
  const registerRes = await this.fetchFn(`${this.host}/delegate`, {
8174
9592
  method: "POST",
8175
9593
  headers: {
8176
9594
  Authorization: wasmResult.delegation
8177
9595
  }
8178
9596
  });
9597
+ const registrationActiveError = this.retiredGraphError();
9598
+ if (registrationActiveError) return { ok: false, error: registrationActiveError };
8179
9599
  if (!registerRes.ok) {
8180
9600
  const errorText = await registerRes.text();
9601
+ const registrationTextActiveError = this.retiredGraphError();
9602
+ if (registrationTextActiveError) return { ok: false, error: registrationTextActiveError };
8181
9603
  return {
8182
9604
  ok: false,
8183
9605
  error: createError2(
@@ -8227,6 +9649,8 @@ var SharingService = class {
8227
9649
  disableSubDelegation: false
8228
9650
  };
8229
9651
  const delegationResult = this.createDelegationFn ? await this.createDelegationFn(delegationParams) : await this.delegationManager.create(delegationParams);
9652
+ const delegationCreationActiveError = this.retiredGraphError();
9653
+ if (delegationCreationActiveError) return { ok: false, error: delegationCreationActiveError };
8230
9654
  if (!delegationResult.ok) {
8231
9655
  return {
8232
9656
  ok: false,
@@ -8252,12 +9676,14 @@ var SharingService = class {
8252
9676
  * - Register sub-delegation capabilities
8253
9677
  * 4. Return ShareAccess with pre-configured KV service
8254
9678
  */
8255
- async receive(link, options = {}) {
9679
+ async receive(link, options2 = {}) {
9680
+ const activeError = this.retiredGraphError();
9681
+ if (activeError) return { ok: false, error: activeError };
8256
9682
  const {
8257
9683
  autoSubdelegate = true,
8258
9684
  useSessionKey = true,
8259
9685
  ingestOptions
8260
- } = options;
9686
+ } = options2;
8261
9687
  const decodeResult = this.decodeLinkWithValidation(link);
8262
9688
  if (!decodeResult.ok) {
8263
9689
  return decodeResult;
@@ -8343,9 +9769,12 @@ var SharingService = class {
8343
9769
  * be logged or stored insecurely.
8344
9770
  */
8345
9771
  async delegateReceivedShare(link, params) {
9772
+ const activeError = this.retiredGraphError();
9773
+ if (activeError) return { ok: false, error: activeError };
8346
9774
  const decoded = this.decodeLinkWithValidation(link);
8347
9775
  if (!decoded.ok) return decoded;
8348
9776
  const shareData = decoded.data;
9777
+ this.assertDelegationCaveatsPreservable(shareData.delegation);
8349
9778
  const parentExpiry = new Date(shareData.delegation.expiry);
8350
9779
  const now = /* @__PURE__ */ new Date();
8351
9780
  if (parentExpiry <= now) {
@@ -8479,6 +9908,8 @@ var SharingService = class {
8479
9908
  abilities: { [service]: { [path]: actions } },
8480
9909
  expirationSecs: Math.floor(expiry.getTime() / 1e3)
8481
9910
  });
9911
+ const childSigningActiveError = this.retiredGraphError();
9912
+ if (childSigningActiveError) return { ok: false, error: childSigningActiveError };
8482
9913
  const verifiedChild = verifySignedChild(result, {
8483
9914
  delegateDID,
8484
9915
  issuerDID: principalDid(shareData.keyDid),
@@ -8505,6 +9936,8 @@ var SharingService = class {
8505
9936
  redirect: "error"
8506
9937
  };
8507
9938
  const registration = await this.fetchFn(new URL("/delegate", trustedHost).toString(), registrationInit);
9939
+ const registrationActiveError = this.retiredGraphError();
9940
+ if (registrationActiveError) return { ok: false, error: registrationActiveError };
8508
9941
  if (!registration.ok) {
8509
9942
  throw new Error(`node rejected child delegation (${registration.status})`);
8510
9943
  }
@@ -8550,6 +9983,22 @@ var SharingService = class {
8550
9983
  };
8551
9984
  }
8552
9985
  }
9986
+ /**
9987
+ * The child-delegation WASM boundary accepts action-only abilities. Reject
9988
+ * every constrained parent branch before that boundary can broaden it.
9989
+ */
9990
+ assertDelegationCaveatsPreservable(delegation) {
9991
+ if (recapCaveatsEqual(delegation.caveats, void 0)) return;
9992
+ const service = delegation.actions[0]?.split("/", 1)[0] ?? "tinycloud.unknown";
9993
+ const entry = {
9994
+ service,
9995
+ space: delegation.spaceId,
9996
+ path: delegation.path,
9997
+ actions: [...delegation.actions],
9998
+ caveats: delegation.caveats ?? []
9999
+ };
10000
+ throw new CaveatedDelegationUnsupportedError([entry]);
10001
+ }
8553
10002
  /**
8554
10003
  * Encode sharing data into a link string.
8555
10004
  *
@@ -8718,7 +10167,7 @@ function capabilityPathContains(parent, child) {
8718
10167
  function shareKeyMatchesDid(key, didUrl) {
8719
10168
  if (key.kty !== "OKP" || key.crv !== "Ed25519" || typeof key.x !== "string" || typeof key.d !== "string") return false;
8720
10169
  try {
8721
- const didBytes = bases2.base58btc.decode(principalDid(didUrl).slice("did:key:".length));
10170
+ const didBytes = bases.base58btc.decode(principalDid(didUrl).slice("did:key:".length));
8722
10171
  const publicKey = didBytes.length === 34 && didBytes[0] === 237 && didBytes[1] === 1 ? didBytes.slice(2) : null;
8723
10172
  if (!publicKey) return false;
8724
10173
  const jwkBytes = decodeBase64UrlBytes(key.x);
@@ -8830,7 +10279,14 @@ var CapabilityKeyRegistry = class {
8830
10279
  removeKey(keyId) {
8831
10280
  const delegations = this.store.byKey.get(keyId) || [];
8832
10281
  for (const delegation of delegations) {
8833
- this.store.byCid.delete(delegation.cid);
10282
+ const chains = this.store.byCid.get(delegation.cid);
10283
+ if (!chains) continue;
10284
+ const remaining = chains.filter((chain) => chain.keyId !== keyId);
10285
+ if (remaining.length === 0) {
10286
+ this.store.byCid.delete(delegation.cid);
10287
+ } else {
10288
+ this.store.byCid.set(delegation.cid, remaining);
10289
+ }
8834
10290
  }
8835
10291
  for (const [capKey, entries] of this.store.byCapability) {
8836
10292
  const filtered = entries.filter(
@@ -8920,8 +10376,8 @@ var CapabilityKeyRegistry = class {
8920
10376
  * @param delegation - Delegation to associate with the key
8921
10377
  * @param options - Ingestion options
8922
10378
  */
8923
- ingestKey(key, delegation, options) {
8924
- const keyToStore = options?.priority !== void 0 ? { ...key, priority: options.priority } : key;
10379
+ ingestKey(key, delegation, options2) {
10380
+ const keyToStore = options2?.priority !== void 0 ? { ...key, priority: options2.priority } : key;
8925
10381
  this.keys.set(keyToStore.id, keyToStore);
8926
10382
  if (!this.store.byKey.has(keyToStore.id)) {
8927
10383
  this.store.byKey.set(keyToStore.id, []);
@@ -8990,7 +10446,7 @@ var CapabilityKeyRegistry = class {
8990
10446
  */
8991
10447
  revokeDelegation(cid) {
8992
10448
  const stored = this.store.byCid.get(cid);
8993
- if (!stored) {
10449
+ if (!stored || stored.length === 0) {
8994
10450
  return err4(
8995
10451
  serviceError4(
8996
10452
  CapabilityKeyRegistryErrorCodes.KEY_NOT_FOUND,
@@ -8999,12 +10455,10 @@ var CapabilityKeyRegistry = class {
8999
10455
  )
9000
10456
  );
9001
10457
  }
9002
- stored.delegation.isRevoked = true;
9003
- const keyDelegations = this.store.byKey.get(stored.keyId);
9004
- if (keyDelegations) {
9005
- const delegation = keyDelegations.find((d) => d.cid === cid);
9006
- if (delegation) {
9007
- delegation.isRevoked = true;
10458
+ for (const chain of stored) chain.delegation.isRevoked = true;
10459
+ for (const keyDelegations of this.store.byKey.values()) {
10460
+ for (const delegation of keyDelegations) {
10461
+ if (delegation.cid === cid) delegation.isRevoked = true;
9008
10462
  }
9009
10463
  }
9010
10464
  for (const entries of this.store.byCapability.values()) {
@@ -9051,22 +10505,28 @@ var CapabilityKeyRegistry = class {
9051
10505
  */
9052
10506
  addDelegation(key, delegation) {
9053
10507
  const keyDelegations = this.store.byKey.get(key.id) || [];
9054
- if (!keyDelegations.some((d) => d.cid === delegation.cid)) {
10508
+ if (!keyDelegations.some((d) => this.sameDelegationScope(d, delegation))) {
9055
10509
  keyDelegations.push(delegation);
9056
10510
  this.store.byKey.set(key.id, keyDelegations);
9057
10511
  }
9058
- if (!this.store.byCid.has(delegation.cid)) {
9059
- this.store.byCid.set(delegation.cid, {
10512
+ const chains = this.store.byCid.get(delegation.cid) ?? [];
10513
+ if (!chains.some(
10514
+ (chain) => chain.keyId === key.id && this.sameDelegationScope(chain.delegation, delegation)
10515
+ )) {
10516
+ chains.push({
9060
10517
  delegation,
9061
10518
  parentCid: delegation.parentCid,
9062
10519
  keyId: key.id,
9063
10520
  storedAt: /* @__PURE__ */ new Date()
9064
10521
  });
10522
+ this.store.byCid.set(delegation.cid, chains);
9065
10523
  }
9066
10524
  for (const action of delegation.actions) {
9067
10525
  const capKey = this.makeCapabilityKey(delegation.path, action);
9068
10526
  const entries = this.store.byCapability.get(capKey) || [];
9069
- const existingEntry = entries.find((e) => e.delegation.cid === delegation.cid);
10527
+ const existingEntry = entries.find(
10528
+ (e) => this.sameDelegationScope(e.delegation, delegation)
10529
+ );
9070
10530
  if (existingEntry) {
9071
10531
  if (!existingEntry.keys.some((k) => k.id === key.id)) {
9072
10532
  existingEntry.keys.push(key);
@@ -9095,6 +10555,9 @@ var CapabilityKeyRegistry = class {
9095
10555
  makeCapabilityKey(resource, action) {
9096
10556
  return `${resource}|${action}`;
9097
10557
  }
10558
+ sameDelegationScope(left, right) {
10559
+ return left.cid === right.cid && left.spaceId === right.spaceId && left.path === right.path && left.actions.length === right.actions.length && left.actions.every((action) => right.actions.includes(action)) && recapCaveatsEqual(left.caveats, right.caveats);
10560
+ }
9098
10561
  /**
9099
10562
  * Find capability entries that match a resource and action.
9100
10563
  *
@@ -9116,7 +10579,9 @@ var CapabilityKeyRegistry = class {
9116
10579
  continue;
9117
10580
  }
9118
10581
  if (this.resourceMatchesPattern(resource, entry.resource)) {
9119
- if (!results.some((r) => r.delegation.cid === entry.delegation.cid)) {
10582
+ if (!results.some(
10583
+ (r) => this.sameDelegationScope(r.delegation, entry.delegation)
10584
+ )) {
9120
10585
  results.push(entry);
9121
10586
  }
9122
10587
  }
@@ -9197,24 +10662,24 @@ function openKeyApprovalReason(body) {
9197
10662
  }
9198
10663
  return "OpenKey explicit approval required";
9199
10664
  }
9200
- function createOpenKeyCallbackSigningStrategy(options) {
10665
+ function createOpenKeyCallbackSigningStrategy(options2) {
9201
10666
  return {
9202
10667
  type: "callback",
9203
10668
  openKeyAutoSign: true,
9204
10669
  handler: async (request) => {
9205
- const fetchImpl = options.fetch ?? globalThis.fetch;
10670
+ const fetchImpl = options2.fetch ?? globalThis.fetch;
9206
10671
  if (!fetchImpl) {
9207
10672
  throw new Error("OpenKey signing strategy requires a fetch implementation");
9208
10673
  }
9209
- const token = await resolveOpenKeyToken(options.token);
9210
- const extraHeaders = await resolveOpenKeyHeaders(options.headers);
10674
+ const token = await resolveOpenKeyToken(options2.token);
10675
+ const extraHeaders = await resolveOpenKeyHeaders(options2.headers);
9211
10676
  const body = {
9212
10677
  ...request,
9213
- ...options.keyId ? { keyId: options.keyId } : {}
10678
+ ...options2.keyId ? { keyId: options2.keyId } : {}
9214
10679
  };
9215
- const response = await fetchImpl(options.endpoint, {
10680
+ const response = await fetchImpl(options2.endpoint, {
9216
10681
  method: "POST",
9217
- credentials: options.credentials,
10682
+ credentials: options2.credentials,
9218
10683
  headers: {
9219
10684
  "content-type": "application/json",
9220
10685
  ...token ? { authorization: `Bearer ${token}` } : {},
@@ -9361,12 +10826,1459 @@ import {
9361
10826
  CAPABILITY_REGISTRY as CAPABILITY_REGISTRY2
9362
10827
  } from "@tinycloud/bootstrap";
9363
10828
 
10829
+ // ../../node_modules/uint8arrays/dist/src/equals.js
10830
+ function equals3(a, b) {
10831
+ if (a === b) {
10832
+ return true;
10833
+ }
10834
+ if (a.byteLength !== b.byteLength) {
10835
+ return false;
10836
+ }
10837
+ for (let i = 0; i < a.byteLength; i++) {
10838
+ if (a[i] !== b[i]) {
10839
+ return false;
10840
+ }
10841
+ }
10842
+ return true;
10843
+ }
10844
+
10845
+ // ../../node_modules/uint8arrays/dist/src/alloc.node.js
10846
+ import { Buffer as Buffer2 } from "buffer";
10847
+
10848
+ // ../../node_modules/uint8arrays/dist/src/util/as-uint8array.node.js
10849
+ function asUint8Array(buf) {
10850
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
10851
+ }
10852
+
10853
+ // ../../node_modules/uint8arrays/dist/src/alloc.node.js
10854
+ function allocUnsafe(size = 0) {
10855
+ return asUint8Array(Buffer2.allocUnsafe(size));
10856
+ }
10857
+
10858
+ // ../../node_modules/uint8-varint/dist/src/index.js
10859
+ var N12 = Math.pow(2, 7);
10860
+ var N22 = Math.pow(2, 14);
10861
+ var N32 = Math.pow(2, 21);
10862
+ var N42 = Math.pow(2, 28);
10863
+ var N52 = Math.pow(2, 35);
10864
+ var N62 = Math.pow(2, 42);
10865
+ var N72 = Math.pow(2, 49);
10866
+ var MSB2 = 128;
10867
+ var REST2 = 127;
10868
+ function encodingLength2(value) {
10869
+ if (value < N12) {
10870
+ return 1;
10871
+ }
10872
+ if (value < N22) {
10873
+ return 2;
10874
+ }
10875
+ if (value < N32) {
10876
+ return 3;
10877
+ }
10878
+ if (value < N42) {
10879
+ return 4;
10880
+ }
10881
+ if (value < N52) {
10882
+ return 5;
10883
+ }
10884
+ if (value < N62) {
10885
+ return 6;
10886
+ }
10887
+ if (value < N72) {
10888
+ return 7;
10889
+ }
10890
+ if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {
10891
+ throw new RangeError("Could not encode varint");
10892
+ }
10893
+ return 8;
10894
+ }
10895
+ function encodeUint8Array(value, buf, offset = 0) {
10896
+ switch (encodingLength2(value)) {
10897
+ case 8: {
10898
+ buf[offset++] = value & 255 | MSB2;
10899
+ value /= 128;
10900
+ }
10901
+ case 7: {
10902
+ buf[offset++] = value & 255 | MSB2;
10903
+ value /= 128;
10904
+ }
10905
+ case 6: {
10906
+ buf[offset++] = value & 255 | MSB2;
10907
+ value /= 128;
10908
+ }
10909
+ case 5: {
10910
+ buf[offset++] = value & 255 | MSB2;
10911
+ value /= 128;
10912
+ }
10913
+ case 4: {
10914
+ buf[offset++] = value & 255 | MSB2;
10915
+ value >>>= 7;
10916
+ }
10917
+ case 3: {
10918
+ buf[offset++] = value & 255 | MSB2;
10919
+ value >>>= 7;
10920
+ }
10921
+ case 2: {
10922
+ buf[offset++] = value & 255 | MSB2;
10923
+ value >>>= 7;
10924
+ }
10925
+ case 1: {
10926
+ buf[offset++] = value & 255;
10927
+ value >>>= 7;
10928
+ break;
10929
+ }
10930
+ default:
10931
+ throw new Error("unreachable");
10932
+ }
10933
+ return buf;
10934
+ }
10935
+ function decodeUint8Array(buf, offset) {
10936
+ let b = buf[offset];
10937
+ let res = 0;
10938
+ res += b & REST2;
10939
+ if (b < MSB2) {
10940
+ return res;
10941
+ }
10942
+ b = buf[offset + 1];
10943
+ res += (b & REST2) << 7;
10944
+ if (b < MSB2) {
10945
+ return res;
10946
+ }
10947
+ b = buf[offset + 2];
10948
+ res += (b & REST2) << 14;
10949
+ if (b < MSB2) {
10950
+ return res;
10951
+ }
10952
+ b = buf[offset + 3];
10953
+ res += (b & REST2) << 21;
10954
+ if (b < MSB2) {
10955
+ return res;
10956
+ }
10957
+ b = buf[offset + 4];
10958
+ res += (b & REST2) * N42;
10959
+ if (b < MSB2) {
10960
+ return res;
10961
+ }
10962
+ b = buf[offset + 5];
10963
+ res += (b & REST2) * N52;
10964
+ if (b < MSB2) {
10965
+ return res;
10966
+ }
10967
+ b = buf[offset + 6];
10968
+ res += (b & REST2) * N62;
10969
+ if (b < MSB2) {
10970
+ return res;
10971
+ }
10972
+ b = buf[offset + 7];
10973
+ res += (b & REST2) * N72;
10974
+ if (b < MSB2) {
10975
+ return res;
10976
+ }
10977
+ throw new RangeError("Could not decode varint");
10978
+ }
10979
+ function decodeUint8ArrayList(buf, offset) {
10980
+ let b = buf.get(offset);
10981
+ let res = 0;
10982
+ res += b & REST2;
10983
+ if (b < MSB2) {
10984
+ return res;
10985
+ }
10986
+ b = buf.get(offset + 1);
10987
+ res += (b & REST2) << 7;
10988
+ if (b < MSB2) {
10989
+ return res;
10990
+ }
10991
+ b = buf.get(offset + 2);
10992
+ res += (b & REST2) << 14;
10993
+ if (b < MSB2) {
10994
+ return res;
10995
+ }
10996
+ b = buf.get(offset + 3);
10997
+ res += (b & REST2) << 21;
10998
+ if (b < MSB2) {
10999
+ return res;
11000
+ }
11001
+ b = buf.get(offset + 4);
11002
+ res += (b & REST2) * N42;
11003
+ if (b < MSB2) {
11004
+ return res;
11005
+ }
11006
+ b = buf.get(offset + 5);
11007
+ res += (b & REST2) * N52;
11008
+ if (b < MSB2) {
11009
+ return res;
11010
+ }
11011
+ b = buf.get(offset + 6);
11012
+ res += (b & REST2) * N62;
11013
+ if (b < MSB2) {
11014
+ return res;
11015
+ }
11016
+ b = buf.get(offset + 7);
11017
+ res += (b & REST2) * N72;
11018
+ if (b < MSB2) {
11019
+ return res;
11020
+ }
11021
+ throw new RangeError("Could not decode varint");
11022
+ }
11023
+ function decode6(buf, offset = 0) {
11024
+ if (buf instanceof Uint8Array) {
11025
+ return decodeUint8Array(buf, offset);
11026
+ } else {
11027
+ return decodeUint8ArrayList(buf, offset);
11028
+ }
11029
+ }
11030
+
11031
+ // ../../node_modules/uint8arrays/dist/src/concat.node.js
11032
+ import { Buffer as Buffer3 } from "buffer";
11033
+ function concat(arrays, length2) {
11034
+ return asUint8Array(Buffer3.concat(arrays, length2));
11035
+ }
11036
+
11037
+ // ../../node_modules/uint8arrays/dist/src/from-string.node.js
11038
+ import { Buffer as Buffer4 } from "buffer";
11039
+
11040
+ // ../../node_modules/uint8arrays/dist/src/util/bases.js
11041
+ function createCodec(name2, prefix, encode5, decode7) {
11042
+ return {
11043
+ name: name2,
11044
+ prefix,
11045
+ encoder: {
11046
+ name: name2,
11047
+ prefix,
11048
+ encode: encode5
11049
+ },
11050
+ decoder: {
11051
+ decode: decode7
11052
+ }
11053
+ };
11054
+ }
11055
+ var string = createCodec("utf8", "u", (buf) => {
11056
+ const decoder = new TextDecoder("utf8");
11057
+ return "u" + decoder.decode(buf);
11058
+ }, (str) => {
11059
+ const encoder = new TextEncoder();
11060
+ return encoder.encode(str.substring(1));
11061
+ });
11062
+ var ascii = createCodec("ascii", "a", (buf) => {
11063
+ let string2 = "a";
11064
+ for (let i = 0; i < buf.length; i++) {
11065
+ string2 += String.fromCharCode(buf[i]);
11066
+ }
11067
+ return string2;
11068
+ }, (str) => {
11069
+ str = str.substring(1);
11070
+ const buf = allocUnsafe(str.length);
11071
+ for (let i = 0; i < str.length; i++) {
11072
+ buf[i] = str.charCodeAt(i);
11073
+ }
11074
+ return buf;
11075
+ });
11076
+ var BASES = {
11077
+ utf8: string,
11078
+ "utf-8": string,
11079
+ hex: bases.base16,
11080
+ latin1: ascii,
11081
+ ascii,
11082
+ binary: ascii,
11083
+ ...bases
11084
+ };
11085
+ var bases_default = BASES;
11086
+
11087
+ // ../../node_modules/uint8arrays/dist/src/from-string.node.js
11088
+ function fromString2(string2, encoding = "utf8") {
11089
+ const base3 = bases_default[encoding];
11090
+ if (base3 == null) {
11091
+ throw new Error(`Unsupported encoding "${encoding}"`);
11092
+ }
11093
+ if (encoding === "utf8" || encoding === "utf-8") {
11094
+ return asUint8Array(Buffer4.from(string2, "utf-8"));
11095
+ }
11096
+ return base3.decoder.decode(`${base3.prefix}${string2}`);
11097
+ }
11098
+
11099
+ // ../../node_modules/uint8arrays/dist/src/to-string.node.js
11100
+ import { Buffer as Buffer5 } from "buffer";
11101
+ function toString2(array, encoding = "utf8") {
11102
+ const base3 = bases_default[encoding];
11103
+ if (base3 == null) {
11104
+ throw new Error(`Unsupported encoding "${encoding}"`);
11105
+ }
11106
+ if (encoding === "utf8" || encoding === "utf-8") {
11107
+ return Buffer5.from(array.buffer, array.byteOffset, array.byteLength).toString("utf8");
11108
+ }
11109
+ return base3.encoder.encode(array).substring(1);
11110
+ }
11111
+
11112
+ // ../../node_modules/@multiformats/multiaddr/dist/src/errors.js
11113
+ var InvalidMultiaddrError = class extends Error {
11114
+ constructor() {
11115
+ super(...arguments);
11116
+ __publicField(this, "name", "InvalidMultiaddrError");
11117
+ }
11118
+ };
11119
+ __publicField(InvalidMultiaddrError, "name", "InvalidMultiaddrError");
11120
+ var ValidationError = class extends Error {
11121
+ constructor() {
11122
+ super(...arguments);
11123
+ __publicField(this, "name", "ValidationError");
11124
+ }
11125
+ };
11126
+ __publicField(ValidationError, "name", "ValidationError");
11127
+ var InvalidParametersError = class extends Error {
11128
+ constructor() {
11129
+ super(...arguments);
11130
+ __publicField(this, "name", "InvalidParametersError");
11131
+ }
11132
+ };
11133
+ __publicField(InvalidParametersError, "name", "InvalidParametersError");
11134
+ var UnknownProtocolError = class extends Error {
11135
+ constructor() {
11136
+ super(...arguments);
11137
+ __publicField(this, "name", "UnknownProtocolError");
11138
+ }
11139
+ };
11140
+ __publicField(UnknownProtocolError, "name", "UnknownProtocolError");
11141
+
11142
+ // ../../node_modules/@chainsafe/is-ip/lib/is-ip.node.js
11143
+ import { isIPv4, isIPv6, isIP as ipVersion } from "net";
11144
+
11145
+ // ../../node_modules/@multiformats/multiaddr/dist/src/constants.js
11146
+ var CODE_IP4 = 4;
11147
+ var CODE_TCP = 6;
11148
+ var CODE_UDP = 273;
11149
+ var CODE_DCCP = 33;
11150
+ var CODE_IP6 = 41;
11151
+ var CODE_IP6ZONE = 42;
11152
+ var CODE_IPCIDR = 43;
11153
+ var CODE_DNS = 53;
11154
+ var CODE_DNS4 = 54;
11155
+ var CODE_DNS6 = 55;
11156
+ var CODE_DNSADDR = 56;
11157
+ var CODE_SCTP = 132;
11158
+ var CODE_UDT = 301;
11159
+ var CODE_UTP = 302;
11160
+ var CODE_UNIX = 400;
11161
+ var CODE_P2P = 421;
11162
+ var CODE_ONION = 444;
11163
+ var CODE_ONION3 = 445;
11164
+ var CODE_GARLIC64 = 446;
11165
+ var CODE_GARLIC32 = 447;
11166
+ var CODE_TLS = 448;
11167
+ var CODE_SNI = 449;
11168
+ var CODE_NOISE = 454;
11169
+ var CODE_QUIC = 460;
11170
+ var CODE_QUIC_V1 = 461;
11171
+ var CODE_WEBTRANSPORT = 465;
11172
+ var CODE_CERTHASH = 466;
11173
+ var CODE_HTTP = 480;
11174
+ var CODE_HTTP_PATH = 481;
11175
+ var CODE_HTTPS = 443;
11176
+ var CODE_WS = 477;
11177
+ var CODE_WSS = 478;
11178
+ var CODE_P2P_WEBSOCKET_STAR = 479;
11179
+ var CODE_P2P_STARDUST = 277;
11180
+ var CODE_P2P_WEBRTC_STAR = 275;
11181
+ var CODE_P2P_WEBRTC_DIRECT = 276;
11182
+ var CODE_WEBRTC_DIRECT = 280;
11183
+ var CODE_WEBRTC = 281;
11184
+ var CODE_P2P_CIRCUIT = 290;
11185
+ var CODE_MEMORY = 777;
11186
+
11187
+ // ../../node_modules/@multiformats/multiaddr/dist/src/utils.js
11188
+ function bytesToString(base3) {
11189
+ return (buf) => {
11190
+ return toString2(buf, base3);
11191
+ };
11192
+ }
11193
+ function stringToBytes(base3) {
11194
+ return (buf) => {
11195
+ return fromString2(buf, base3);
11196
+ };
11197
+ }
11198
+ function bytes2port(buf) {
11199
+ const view = new DataView(buf.buffer);
11200
+ return view.getUint16(buf.byteOffset).toString();
11201
+ }
11202
+ function port2bytes(port) {
11203
+ const buf = new ArrayBuffer(2);
11204
+ const view = new DataView(buf);
11205
+ view.setUint16(0, typeof port === "string" ? parseInt(port) : port);
11206
+ return new Uint8Array(buf);
11207
+ }
11208
+ function onion2bytes(str) {
11209
+ const addr = str.split(":");
11210
+ if (addr.length !== 2) {
11211
+ throw new Error(`failed to parse onion addr: ["'${addr.join('", "')}'"]' does not contain a port number`);
11212
+ }
11213
+ if (addr[0].length !== 16) {
11214
+ throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`);
11215
+ }
11216
+ const buf = fromString2(addr[0], "base32");
11217
+ const port = parseInt(addr[1], 10);
11218
+ if (port < 1 || port > 65536) {
11219
+ throw new Error("Port number is not in range(1, 65536)");
11220
+ }
11221
+ const portBuf = port2bytes(port);
11222
+ return concat([buf, portBuf], buf.length + portBuf.length);
11223
+ }
11224
+ function onion32bytes(str) {
11225
+ const addr = str.split(":");
11226
+ if (addr.length !== 2) {
11227
+ throw new Error(`failed to parse onion addr: ["'${addr.join('", "')}'"]' does not contain a port number`);
11228
+ }
11229
+ if (addr[0].length !== 56) {
11230
+ throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`);
11231
+ }
11232
+ const buf = base32.decode(`b${addr[0]}`);
11233
+ const port = parseInt(addr[1], 10);
11234
+ if (port < 1 || port > 65536) {
11235
+ throw new Error("Port number is not in range(1, 65536)");
11236
+ }
11237
+ const portBuf = port2bytes(port);
11238
+ return concat([buf, portBuf], buf.length + portBuf.length);
11239
+ }
11240
+ function bytes2onion(buf) {
11241
+ const addrBytes = buf.subarray(0, buf.length - 2);
11242
+ const portBytes = buf.subarray(buf.length - 2);
11243
+ const addr = toString2(addrBytes, "base32");
11244
+ const port = bytes2port(portBytes);
11245
+ return `${addr}:${port}`;
11246
+ }
11247
+ var ip4ToBytes = function(ip) {
11248
+ ip = ip.toString().trim();
11249
+ const bytes = new Uint8Array(4);
11250
+ ip.split(/\./g).forEach((byte, index) => {
11251
+ const value = parseInt(byte, 10);
11252
+ if (isNaN(value) || value < 0 || value > 255) {
11253
+ throw new InvalidMultiaddrError("Invalid byte value in IP address");
11254
+ }
11255
+ bytes[index] = value;
11256
+ });
11257
+ return bytes;
11258
+ };
11259
+ var ip6ToBytes = function(ip) {
11260
+ let offset = 0;
11261
+ ip = ip.toString().trim();
11262
+ const sections = ip.split(":", 8);
11263
+ let i;
11264
+ for (i = 0; i < sections.length; i++) {
11265
+ const isv4 = isIPv4(sections[i]);
11266
+ let v4Buffer;
11267
+ if (isv4) {
11268
+ v4Buffer = ip4ToBytes(sections[i]);
11269
+ sections[i] = toString2(v4Buffer.subarray(0, 2), "base16");
11270
+ }
11271
+ if (v4Buffer != null && ++i < 8) {
11272
+ sections.splice(i, 0, toString2(v4Buffer.subarray(2, 4), "base16"));
11273
+ }
11274
+ }
11275
+ if (sections[0] === "") {
11276
+ while (sections.length < 8) {
11277
+ sections.unshift("0");
11278
+ }
11279
+ } else if (sections[sections.length - 1] === "") {
11280
+ while (sections.length < 8) {
11281
+ sections.push("0");
11282
+ }
11283
+ } else if (sections.length < 8) {
11284
+ for (i = 0; i < sections.length && sections[i] !== ""; i++) {
11285
+ }
11286
+ const argv = [i, 1];
11287
+ for (i = 9 - sections.length; i > 0; i--) {
11288
+ argv.push("0");
11289
+ }
11290
+ sections.splice.apply(sections, argv);
11291
+ }
11292
+ const bytes = new Uint8Array(offset + 16);
11293
+ for (i = 0; i < sections.length; i++) {
11294
+ if (sections[i] === "") {
11295
+ sections[i] = "0";
11296
+ }
11297
+ const word2 = parseInt(sections[i], 16);
11298
+ if (isNaN(word2) || word2 < 0 || word2 > 65535) {
11299
+ throw new InvalidMultiaddrError("Invalid byte value in IP address");
11300
+ }
11301
+ bytes[offset++] = word2 >> 8 & 255;
11302
+ bytes[offset++] = word2 & 255;
11303
+ }
11304
+ return bytes;
11305
+ };
11306
+ var ip4ToString = function(buf) {
11307
+ if (buf.byteLength !== 4) {
11308
+ throw new InvalidMultiaddrError("IPv4 address was incorrect length");
11309
+ }
11310
+ const result = [];
11311
+ for (let i = 0; i < buf.byteLength; i++) {
11312
+ result.push(buf[i]);
11313
+ }
11314
+ return result.join(".");
11315
+ };
11316
+ var ip6ToString = function(buf) {
11317
+ if (buf.byteLength !== 16) {
11318
+ throw new InvalidMultiaddrError("IPv6 address was incorrect length");
11319
+ }
11320
+ const result = [];
11321
+ for (let i = 0; i < buf.byteLength; i += 2) {
11322
+ const byte1 = buf[i];
11323
+ const byte2 = buf[i + 1];
11324
+ const tuple = `${byte1.toString(16).padStart(2, "0")}${byte2.toString(16).padStart(2, "0")}`;
11325
+ result.push(tuple);
11326
+ }
11327
+ const ip = result.join(":");
11328
+ try {
11329
+ const url = new URL(`http://[${ip}]`);
11330
+ return url.hostname.substring(1, url.hostname.length - 1);
11331
+ } catch {
11332
+ throw new InvalidMultiaddrError(`Invalid IPv6 address "${ip}"`);
11333
+ }
11334
+ };
11335
+ function ip6StringToValue(str) {
11336
+ try {
11337
+ const url = new URL(`http://[${str}]`);
11338
+ return url.hostname.substring(1, url.hostname.length - 1);
11339
+ } catch {
11340
+ throw new InvalidMultiaddrError(`Invalid IPv6 address "${str}"`);
11341
+ }
11342
+ }
11343
+ var decoders = Object.values(bases).map((c) => c.decoder);
11344
+ var anybaseDecoder = (function() {
11345
+ let acc = decoders[0].or(decoders[1]);
11346
+ decoders.slice(2).forEach((d) => acc = acc.or(d));
11347
+ return acc;
11348
+ })();
11349
+ function mb2bytes(mbstr) {
11350
+ return anybaseDecoder.decode(mbstr);
11351
+ }
11352
+ function bytes2mb(base3) {
11353
+ return (buf) => {
11354
+ return base3.encoder.encode(buf);
11355
+ };
11356
+ }
11357
+
11358
+ // ../../node_modules/@multiformats/multiaddr/dist/src/validation.js
11359
+ function integer(value) {
11360
+ const int = parseInt(value);
11361
+ if (int.toString() !== value) {
11362
+ throw new ValidationError("Value must be an integer");
11363
+ }
11364
+ }
11365
+ function positive(value) {
11366
+ if (value < 0) {
11367
+ throw new ValidationError("Value must be a positive integer, or zero");
11368
+ }
11369
+ }
11370
+ function maxValue(max) {
11371
+ return (value) => {
11372
+ if (value > max) {
11373
+ throw new ValidationError(`Value must be smaller than or equal to ${max}`);
11374
+ }
11375
+ };
11376
+ }
11377
+ function validate(...funcs) {
11378
+ return (value) => {
11379
+ for (const fn of funcs) {
11380
+ fn(value);
11381
+ }
11382
+ };
11383
+ }
11384
+ var validatePort = validate(integer, positive, maxValue(65535));
11385
+
11386
+ // ../../node_modules/@multiformats/multiaddr/dist/src/registry.js
11387
+ var V = -1;
11388
+ var Registry = class {
11389
+ constructor() {
11390
+ __publicField(this, "protocolsByCode", /* @__PURE__ */ new Map());
11391
+ __publicField(this, "protocolsByName", /* @__PURE__ */ new Map());
11392
+ }
11393
+ getProtocol(key) {
11394
+ let codec;
11395
+ if (typeof key === "string") {
11396
+ codec = this.protocolsByName.get(key);
11397
+ } else {
11398
+ codec = this.protocolsByCode.get(key);
11399
+ }
11400
+ if (codec == null) {
11401
+ throw new UnknownProtocolError(`Protocol ${key} was unknown`);
11402
+ }
11403
+ return codec;
11404
+ }
11405
+ addProtocol(codec) {
11406
+ this.protocolsByCode.set(codec.code, codec);
11407
+ this.protocolsByName.set(codec.name, codec);
11408
+ codec.aliases?.forEach((alias) => {
11409
+ this.protocolsByName.set(alias, codec);
11410
+ });
11411
+ }
11412
+ removeProtocol(code2) {
11413
+ const codec = this.protocolsByCode.get(code2);
11414
+ if (codec == null) {
11415
+ return;
11416
+ }
11417
+ this.protocolsByCode.delete(codec.code);
11418
+ this.protocolsByName.delete(codec.name);
11419
+ codec.aliases?.forEach((alias) => {
11420
+ this.protocolsByName.delete(alias);
11421
+ });
11422
+ }
11423
+ };
11424
+ var registry = new Registry();
11425
+ var codecs = [{
11426
+ code: CODE_IP4,
11427
+ name: "ip4",
11428
+ size: 32,
11429
+ valueToBytes: ip4ToBytes,
11430
+ bytesToValue: ip4ToString,
11431
+ validate: (value) => {
11432
+ if (!isIPv4(value)) {
11433
+ throw new ValidationError(`Invalid IPv4 address "${value}"`);
11434
+ }
11435
+ }
11436
+ }, {
11437
+ code: CODE_TCP,
11438
+ name: "tcp",
11439
+ size: 16,
11440
+ valueToBytes: port2bytes,
11441
+ bytesToValue: bytes2port,
11442
+ validate: validatePort
11443
+ }, {
11444
+ code: CODE_UDP,
11445
+ name: "udp",
11446
+ size: 16,
11447
+ valueToBytes: port2bytes,
11448
+ bytesToValue: bytes2port,
11449
+ validate: validatePort
11450
+ }, {
11451
+ code: CODE_DCCP,
11452
+ name: "dccp",
11453
+ size: 16,
11454
+ valueToBytes: port2bytes,
11455
+ bytesToValue: bytes2port,
11456
+ validate: validatePort
11457
+ }, {
11458
+ code: CODE_IP6,
11459
+ name: "ip6",
11460
+ size: 128,
11461
+ valueToBytes: ip6ToBytes,
11462
+ bytesToValue: ip6ToString,
11463
+ stringToValue: ip6StringToValue,
11464
+ validate: (value) => {
11465
+ if (!isIPv6(value)) {
11466
+ throw new ValidationError(`Invalid IPv6 address "${value}"`);
11467
+ }
11468
+ }
11469
+ }, {
11470
+ code: CODE_IP6ZONE,
11471
+ name: "ip6zone",
11472
+ size: V
11473
+ }, {
11474
+ code: CODE_IPCIDR,
11475
+ name: "ipcidr",
11476
+ size: 8,
11477
+ bytesToValue: bytesToString("base10"),
11478
+ valueToBytes: stringToBytes("base10")
11479
+ }, {
11480
+ code: CODE_DNS,
11481
+ name: "dns",
11482
+ size: V
11483
+ }, {
11484
+ code: CODE_DNS4,
11485
+ name: "dns4",
11486
+ size: V
11487
+ }, {
11488
+ code: CODE_DNS6,
11489
+ name: "dns6",
11490
+ size: V
11491
+ }, {
11492
+ code: CODE_DNSADDR,
11493
+ name: "dnsaddr",
11494
+ size: V
11495
+ }, {
11496
+ code: CODE_SCTP,
11497
+ name: "sctp",
11498
+ size: 16,
11499
+ valueToBytes: port2bytes,
11500
+ bytesToValue: bytes2port,
11501
+ validate: validatePort
11502
+ }, {
11503
+ code: CODE_UDT,
11504
+ name: "udt"
11505
+ }, {
11506
+ code: CODE_UTP,
11507
+ name: "utp"
11508
+ }, {
11509
+ code: CODE_UNIX,
11510
+ name: "unix",
11511
+ size: V,
11512
+ stringToValue: (str) => decodeURIComponent(str),
11513
+ valueToString: (val) => encodeURIComponent(val)
11514
+ }, {
11515
+ code: CODE_P2P,
11516
+ name: "p2p",
11517
+ aliases: ["ipfs"],
11518
+ size: V,
11519
+ bytesToValue: bytesToString("base58btc"),
11520
+ valueToBytes: (val) => {
11521
+ if (val.startsWith("Q") || val.startsWith("1")) {
11522
+ return stringToBytes("base58btc")(val);
11523
+ }
11524
+ return CID.parse(val).multihash.bytes;
11525
+ }
11526
+ }, {
11527
+ code: CODE_ONION,
11528
+ name: "onion",
11529
+ size: 96,
11530
+ bytesToValue: bytes2onion,
11531
+ valueToBytes: onion2bytes
11532
+ }, {
11533
+ code: CODE_ONION3,
11534
+ name: "onion3",
11535
+ size: 296,
11536
+ bytesToValue: bytes2onion,
11537
+ valueToBytes: onion32bytes
11538
+ }, {
11539
+ code: CODE_GARLIC64,
11540
+ name: "garlic64",
11541
+ size: V
11542
+ }, {
11543
+ code: CODE_GARLIC32,
11544
+ name: "garlic32",
11545
+ size: V
11546
+ }, {
11547
+ code: CODE_TLS,
11548
+ name: "tls"
11549
+ }, {
11550
+ code: CODE_SNI,
11551
+ name: "sni",
11552
+ size: V
11553
+ }, {
11554
+ code: CODE_NOISE,
11555
+ name: "noise"
11556
+ }, {
11557
+ code: CODE_QUIC,
11558
+ name: "quic"
11559
+ }, {
11560
+ code: CODE_QUIC_V1,
11561
+ name: "quic-v1"
11562
+ }, {
11563
+ code: CODE_WEBTRANSPORT,
11564
+ name: "webtransport"
11565
+ }, {
11566
+ code: CODE_CERTHASH,
11567
+ name: "certhash",
11568
+ size: V,
11569
+ bytesToValue: bytes2mb(base64url),
11570
+ valueToBytes: mb2bytes
11571
+ }, {
11572
+ code: CODE_HTTP,
11573
+ name: "http"
11574
+ }, {
11575
+ code: CODE_HTTP_PATH,
11576
+ name: "http-path",
11577
+ size: V,
11578
+ stringToValue: (str) => `/${decodeURIComponent(str)}`,
11579
+ valueToString: (val) => encodeURIComponent(val.substring(1))
11580
+ }, {
11581
+ code: CODE_HTTPS,
11582
+ name: "https"
11583
+ }, {
11584
+ code: CODE_WS,
11585
+ name: "ws"
11586
+ }, {
11587
+ code: CODE_WSS,
11588
+ name: "wss"
11589
+ }, {
11590
+ code: CODE_P2P_WEBSOCKET_STAR,
11591
+ name: "p2p-websocket-star"
11592
+ }, {
11593
+ code: CODE_P2P_STARDUST,
11594
+ name: "p2p-stardust"
11595
+ }, {
11596
+ code: CODE_P2P_WEBRTC_STAR,
11597
+ name: "p2p-webrtc-star"
11598
+ }, {
11599
+ code: CODE_P2P_WEBRTC_DIRECT,
11600
+ name: "p2p-webrtc-direct"
11601
+ }, {
11602
+ code: CODE_WEBRTC_DIRECT,
11603
+ name: "webrtc-direct"
11604
+ }, {
11605
+ code: CODE_WEBRTC,
11606
+ name: "webrtc"
11607
+ }, {
11608
+ code: CODE_P2P_CIRCUIT,
11609
+ name: "p2p-circuit"
11610
+ }, {
11611
+ code: CODE_MEMORY,
11612
+ name: "memory",
11613
+ size: V
11614
+ }];
11615
+ codecs.forEach((codec) => {
11616
+ registry.addProtocol(codec);
11617
+ });
11618
+
11619
+ // ../../node_modules/@multiformats/multiaddr/dist/src/components.js
11620
+ function bytesToComponents(bytes) {
11621
+ const components = [];
11622
+ let i = 0;
11623
+ while (i < bytes.length) {
11624
+ const code2 = decode6(bytes, i);
11625
+ const codec = registry.getProtocol(code2);
11626
+ const codeLength = encodingLength2(code2);
11627
+ const size = sizeForAddr(codec, bytes, i + codeLength);
11628
+ let sizeLength = 0;
11629
+ if (size > 0 && codec.size === V) {
11630
+ sizeLength = encodingLength2(size);
11631
+ }
11632
+ const componentLength = codeLength + sizeLength + size;
11633
+ const component = {
11634
+ code: code2,
11635
+ name: codec.name,
11636
+ bytes: bytes.subarray(i, i + componentLength)
11637
+ };
11638
+ if (size > 0) {
11639
+ const valueOffset = i + codeLength + sizeLength;
11640
+ const valueBytes = bytes.subarray(valueOffset, valueOffset + size);
11641
+ component.value = codec.bytesToValue?.(valueBytes) ?? toString2(valueBytes);
11642
+ }
11643
+ components.push(component);
11644
+ i += componentLength;
11645
+ }
11646
+ return components;
11647
+ }
11648
+ function componentsToBytes(components) {
11649
+ let length2 = 0;
11650
+ const bytes = [];
11651
+ for (const component of components) {
11652
+ if (component.bytes == null) {
11653
+ const codec = registry.getProtocol(component.code);
11654
+ const codecLength = encodingLength2(component.code);
11655
+ let valueBytes;
11656
+ let valueLength = 0;
11657
+ let valueLengthLength = 0;
11658
+ if (component.value != null) {
11659
+ valueBytes = codec.valueToBytes?.(component.value) ?? fromString2(component.value);
11660
+ valueLength = valueBytes.byteLength;
11661
+ if (codec.size === V) {
11662
+ valueLengthLength = encodingLength2(valueLength);
11663
+ }
11664
+ }
11665
+ const bytes2 = new Uint8Array(codecLength + valueLengthLength + valueLength);
11666
+ let offset = 0;
11667
+ encodeUint8Array(component.code, bytes2, offset);
11668
+ offset += codecLength;
11669
+ if (valueBytes != null) {
11670
+ if (codec.size === V) {
11671
+ encodeUint8Array(valueLength, bytes2, offset);
11672
+ offset += valueLengthLength;
11673
+ }
11674
+ bytes2.set(valueBytes, offset);
11675
+ }
11676
+ component.bytes = bytes2;
11677
+ }
11678
+ bytes.push(component.bytes);
11679
+ length2 += component.bytes.byteLength;
11680
+ }
11681
+ return concat(bytes, length2);
11682
+ }
11683
+ function stringToComponents(string2) {
11684
+ if (string2.charAt(0) !== "/") {
11685
+ throw new InvalidMultiaddrError('String multiaddr must start with "/"');
11686
+ }
11687
+ const components = [];
11688
+ let collecting = "protocol";
11689
+ let value = "";
11690
+ let protocol = "";
11691
+ for (let i = 1; i < string2.length; i++) {
11692
+ const char = string2.charAt(i);
11693
+ if (char !== "/") {
11694
+ if (collecting === "protocol") {
11695
+ protocol += string2.charAt(i);
11696
+ } else {
11697
+ value += string2.charAt(i);
11698
+ }
11699
+ }
11700
+ const ended = i === string2.length - 1;
11701
+ if (char === "/" || ended) {
11702
+ const codec = registry.getProtocol(protocol);
11703
+ if (collecting === "protocol") {
11704
+ if (codec.size == null || codec.size === 0) {
11705
+ components.push({
11706
+ code: codec.code,
11707
+ name: codec.name
11708
+ });
11709
+ value = "";
11710
+ protocol = "";
11711
+ collecting = "protocol";
11712
+ continue;
11713
+ } else if (ended) {
11714
+ throw new InvalidMultiaddrError(`Component ${protocol} was missing value`);
11715
+ }
11716
+ collecting = "value";
11717
+ } else if (collecting === "value") {
11718
+ const component = {
11719
+ code: codec.code,
11720
+ name: codec.name
11721
+ };
11722
+ if (codec.size != null && codec.size !== 0) {
11723
+ if (value === "") {
11724
+ throw new InvalidMultiaddrError(`Component ${protocol} was missing value`);
11725
+ }
11726
+ component.value = codec.stringToValue?.(value) ?? value;
11727
+ }
11728
+ components.push(component);
11729
+ value = "";
11730
+ protocol = "";
11731
+ collecting = "protocol";
11732
+ }
11733
+ }
11734
+ }
11735
+ if (protocol !== "" && value !== "") {
11736
+ throw new InvalidMultiaddrError("Incomplete multiaddr");
11737
+ }
11738
+ return components;
11739
+ }
11740
+ function componentsToString(components) {
11741
+ return `/${components.flatMap((component) => {
11742
+ if (component.value == null) {
11743
+ return component.name;
11744
+ }
11745
+ const codec = registry.getProtocol(component.code);
11746
+ if (codec == null) {
11747
+ throw new InvalidMultiaddrError(`Unknown protocol code ${component.code}`);
11748
+ }
11749
+ return [
11750
+ component.name,
11751
+ codec.valueToString?.(component.value) ?? component.value
11752
+ ];
11753
+ }).join("/")}`;
11754
+ }
11755
+ function sizeForAddr(codec, bytes, offset) {
11756
+ if (codec.size == null || codec.size === 0) {
11757
+ return 0;
11758
+ }
11759
+ if (codec.size > 0) {
11760
+ return codec.size / 8;
11761
+ }
11762
+ return decode6(bytes, offset);
11763
+ }
11764
+
11765
+ // ../../node_modules/@multiformats/multiaddr/dist/src/multiaddr.js
11766
+ var inspect = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
11767
+ var symbol = /* @__PURE__ */ Symbol.for("@multiformats/multiaddr");
11768
+ function toComponents(addr) {
11769
+ if (addr == null) {
11770
+ addr = "/";
11771
+ }
11772
+ if (isMultiaddr(addr)) {
11773
+ return addr.getComponents();
11774
+ }
11775
+ if (addr instanceof Uint8Array) {
11776
+ return bytesToComponents(addr);
11777
+ }
11778
+ if (typeof addr === "string") {
11779
+ addr = addr.replace(/\/(\/)+/, "/").replace(/(\/)+$/, "");
11780
+ if (addr === "") {
11781
+ addr = "/";
11782
+ }
11783
+ return stringToComponents(addr);
11784
+ }
11785
+ if (Array.isArray(addr)) {
11786
+ return addr;
11787
+ }
11788
+ throw new InvalidMultiaddrError("Must be a string, Uint8Array, Component[], or another Multiaddr");
11789
+ }
11790
+ var _a2, _components, _string, _bytes;
11791
+ var _Multiaddr = class _Multiaddr {
11792
+ constructor(addr = "/", options2 = {}) {
11793
+ __publicField(this, _a2, true);
11794
+ __privateAdd(this, _components);
11795
+ // cache string representation
11796
+ __privateAdd(this, _string);
11797
+ // cache byte representation
11798
+ __privateAdd(this, _bytes);
11799
+ __privateSet(this, _components, toComponents(addr));
11800
+ if (options2.validate !== false) {
11801
+ validate2(this);
11802
+ }
11803
+ }
11804
+ get bytes() {
11805
+ if (__privateGet(this, _bytes) == null) {
11806
+ __privateSet(this, _bytes, componentsToBytes(__privateGet(this, _components)));
11807
+ }
11808
+ return __privateGet(this, _bytes);
11809
+ }
11810
+ toString() {
11811
+ if (__privateGet(this, _string) == null) {
11812
+ __privateSet(this, _string, componentsToString(__privateGet(this, _components)));
11813
+ }
11814
+ return __privateGet(this, _string);
11815
+ }
11816
+ toJSON() {
11817
+ return this.toString();
11818
+ }
11819
+ getComponents() {
11820
+ return [
11821
+ ...__privateGet(this, _components).map((c) => ({ ...c }))
11822
+ ];
11823
+ }
11824
+ encapsulate(addr) {
11825
+ const ma = new _Multiaddr(addr);
11826
+ return new _Multiaddr([
11827
+ ...__privateGet(this, _components),
11828
+ ...ma.getComponents()
11829
+ ], {
11830
+ validate: false
11831
+ });
11832
+ }
11833
+ decapsulate(addr) {
11834
+ const addrString = addr.toString();
11835
+ const s = this.toString();
11836
+ const i = s.lastIndexOf(addrString);
11837
+ if (i < 0) {
11838
+ throw new InvalidParametersError(`Address ${this.toString()} does not contain subaddress: ${addrString}`);
11839
+ }
11840
+ return new _Multiaddr(s.slice(0, i), {
11841
+ validate: false
11842
+ });
11843
+ }
11844
+ decapsulateCode(code2) {
11845
+ let index;
11846
+ for (let i = __privateGet(this, _components).length - 1; i > -1; i--) {
11847
+ if (__privateGet(this, _components)[i].code === code2) {
11848
+ index = i;
11849
+ break;
11850
+ }
11851
+ }
11852
+ return new _Multiaddr(__privateGet(this, _components).slice(0, index), {
11853
+ validate: false
11854
+ });
11855
+ }
11856
+ equals(addr) {
11857
+ return equals3(this.bytes, addr.bytes);
11858
+ }
11859
+ /**
11860
+ * Returns Multiaddr as a human-readable string
11861
+ * https://nodejs.org/api/util.html#utilinspectcustom
11862
+ *
11863
+ * @example
11864
+ * ```js
11865
+ * import { multiaddr } from '@multiformats/multiaddr'
11866
+ *
11867
+ * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))
11868
+ * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'
11869
+ * ```
11870
+ */
11871
+ [(_a2 = symbol, inspect)]() {
11872
+ return `Multiaddr(${this.toString()})`;
11873
+ }
11874
+ };
11875
+ _components = new WeakMap();
11876
+ _string = new WeakMap();
11877
+ _bytes = new WeakMap();
11878
+ var Multiaddr = _Multiaddr;
11879
+ function validate2(addr) {
11880
+ addr.getComponents().forEach((component) => {
11881
+ const codec = registry.getProtocol(component.code);
11882
+ if (component.value == null) {
11883
+ return;
11884
+ }
11885
+ codec.validate?.(component.value);
11886
+ });
11887
+ }
11888
+
11889
+ // ../../node_modules/@multiformats/multiaddr/dist/src/index.js
11890
+ function isMultiaddr(value) {
11891
+ return Boolean(value?.[symbol]);
11892
+ }
11893
+ function multiaddr(addr) {
11894
+ return new Multiaddr(addr);
11895
+ }
11896
+
11897
+ // ../../node_modules/@multiformats/multiaddr-to-uri/dist/src/index.js
11898
+ var ASSUME_HTTP_CODES = [
11899
+ CODE_TCP,
11900
+ CODE_DNS,
11901
+ CODE_DNSADDR,
11902
+ CODE_DNS4,
11903
+ CODE_DNS6
11904
+ ];
11905
+ function extractSNI(ma) {
11906
+ return extractTuple("sni", ma)?.value;
11907
+ }
11908
+ function extractPort(ma) {
11909
+ const port = extractTuple("tcp", ma)?.value;
11910
+ if (port == null) {
11911
+ return "";
11912
+ }
11913
+ return `:${port}`;
11914
+ }
11915
+ function extractTuple(name2, ma) {
11916
+ return ma.find((component) => component.name === name2);
11917
+ }
11918
+ function hasTLS(ma) {
11919
+ return ma.some(({ code: code2 }) => code2 === CODE_TLS);
11920
+ }
11921
+ function interpretNext(head, rest) {
11922
+ const interpreter = interpreters[head.name];
11923
+ if (interpreter == null) {
11924
+ throw new Error(`Can't interpret protocol ${head.name}`);
11925
+ }
11926
+ const restVal = interpreter(head, rest);
11927
+ if (head.code === CODE_IP6) {
11928
+ return `[${restVal}]`;
11929
+ }
11930
+ return restVal;
11931
+ }
11932
+ var interpreters = {
11933
+ ip4: (head, rest) => head.value,
11934
+ ip6: (head, rest) => {
11935
+ if (rest.length === 0) {
11936
+ return head.value;
11937
+ }
11938
+ return `[${head.value}]`;
11939
+ },
11940
+ tcp: (head, rest) => {
11941
+ const tail = rest.pop();
11942
+ if (tail == null) {
11943
+ throw new Error("Unexpected end of multiaddr");
11944
+ }
11945
+ return `tcp://${interpretNext(tail, rest)}:${head.value}`;
11946
+ },
11947
+ udp: (head, rest) => {
11948
+ const tail = rest.pop();
11949
+ if (tail == null) {
11950
+ throw new Error("Unexpected end of multiaddr");
11951
+ }
11952
+ return `udp://${interpretNext(tail, rest)}:${head.value}`;
11953
+ },
11954
+ dnsaddr: (head, rest) => head.value,
11955
+ dns4: (head, rest) => head.value,
11956
+ dns6: (head, rest) => head.value,
11957
+ dns: (head, rest) => head.value,
11958
+ ipfs: (head, rest) => {
11959
+ const tail = rest.pop();
11960
+ if (tail == null) {
11961
+ throw new Error("Unexpected end of multiaddr");
11962
+ }
11963
+ return `${interpretNext(tail, rest)}`;
11964
+ },
11965
+ p2p: (head, rest) => {
11966
+ const tail = rest.pop();
11967
+ if (tail == null) {
11968
+ throw new Error("Unexpected end of multiaddr");
11969
+ }
11970
+ return `${interpretNext(tail, rest)}`;
11971
+ },
11972
+ http: (head, rest) => {
11973
+ const maHasTLS = hasTLS(rest);
11974
+ const sni = extractSNI(rest);
11975
+ const port = extractPort(rest);
11976
+ if (maHasTLS && sni != null) {
11977
+ return `https://${sni}${port}`;
11978
+ }
11979
+ const protocol = maHasTLS ? "https://" : "http://";
11980
+ const tail = rest.pop();
11981
+ if (tail == null) {
11982
+ throw new Error("Unexpected end of multiaddr");
11983
+ }
11984
+ let baseVal = interpretNext(tail, rest);
11985
+ baseVal = baseVal?.replace("tcp://", "");
11986
+ return `${protocol}${baseVal}`;
11987
+ },
11988
+ "http-path": (head, rest) => {
11989
+ const tail = rest.pop();
11990
+ if (tail == null) {
11991
+ throw new Error("Unexpected end of multiaddr");
11992
+ }
11993
+ const baseVal = interpretNext(tail, rest);
11994
+ const decodedValue = decodeURIComponent(head.value ?? "");
11995
+ return `${baseVal}${decodedValue}`;
11996
+ },
11997
+ tls: (head, rest) => {
11998
+ const tail = rest.pop();
11999
+ if (tail == null) {
12000
+ throw new Error("Unexpected end of multiaddr");
12001
+ }
12002
+ return interpretNext(tail, rest);
12003
+ },
12004
+ sni: (head, rest) => {
12005
+ const tail = rest.pop();
12006
+ if (tail == null) {
12007
+ throw new Error("Unexpected end of multiaddr");
12008
+ }
12009
+ return interpretNext(tail, rest);
12010
+ },
12011
+ https: (head, rest) => {
12012
+ const tail = rest.pop();
12013
+ if (tail == null) {
12014
+ throw new Error("Unexpected end of multiaddr");
12015
+ }
12016
+ let baseVal = interpretNext(tail, rest);
12017
+ baseVal = baseVal?.replace("tcp://", "");
12018
+ return `https://${baseVal}`;
12019
+ },
12020
+ ws: (head, rest) => {
12021
+ const maHasTLS = hasTLS(rest);
12022
+ const sni = extractSNI(rest);
12023
+ const port = extractPort(rest);
12024
+ if (maHasTLS && sni != null) {
12025
+ return `wss://${sni}${port}`;
12026
+ }
12027
+ const protocol = maHasTLS ? "wss://" : "ws://";
12028
+ const tail = rest.pop();
12029
+ if (tail == null) {
12030
+ throw new Error("Unexpected end of multiaddr");
12031
+ }
12032
+ let baseVal = interpretNext(tail, rest);
12033
+ baseVal = baseVal?.replace("tcp://", "");
12034
+ return `${protocol}${baseVal}`;
12035
+ },
12036
+ wss: (head, rest) => {
12037
+ const tail = rest.pop();
12038
+ if (tail == null) {
12039
+ throw new Error("Unexpected end of multiaddr");
12040
+ }
12041
+ let baseVal = interpretNext(tail, rest);
12042
+ baseVal = baseVal?.replace("tcp://", "");
12043
+ return `wss://${baseVal}`;
12044
+ }
12045
+ };
12046
+ function multiaddrToUri(input, opts) {
12047
+ const ma = multiaddr(input);
12048
+ const components = ma.getComponents();
12049
+ const head = components.pop();
12050
+ if (head == null) {
12051
+ throw new Error("Unexpected end of multiaddr");
12052
+ }
12053
+ const interpreter = interpreters[head.name];
12054
+ if (interpreter == null) {
12055
+ throw new Error(`No interpreter found for ${head.name}`);
12056
+ }
12057
+ let uri = interpreter(head, components) ?? "";
12058
+ if (opts?.assumeHttp !== false && ASSUME_HTTP_CODES.includes(head.code)) {
12059
+ uri = uri.replace(/^.*:\/\//, "");
12060
+ if (head.value === "443") {
12061
+ uri = `https://${uri}`;
12062
+ } else {
12063
+ uri = `http://${uri}`;
12064
+ }
12065
+ }
12066
+ if (uri.startsWith("http://") || uri.startsWith("https://") || uri.startsWith("ws://") || uri.startsWith("wss://")) {
12067
+ uri = new URL(uri).toString();
12068
+ if (uri.endsWith("/")) {
12069
+ uri = uri.substring(0, uri.length - 1);
12070
+ }
12071
+ }
12072
+ return uri;
12073
+ }
12074
+
12075
+ // ../../node_modules/ip-regex/index.js
12076
+ var word = "[a-fA-F\\d:]";
12077
+ var boundry = (options2) => options2 && options2.includeBoundaries ? `(?:(?<=\\s|^)(?=${word})|(?<=${word})(?=\\s|$))` : "";
12078
+ var v4 = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}";
12079
+ var v6segment = "[a-fA-F\\d]{1,4}";
12080
+ var v6 = `
12081
+ (?:
12082
+ (?:${v6segment}:){7}(?:${v6segment}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
12083
+ (?:${v6segment}:){6}(?:${v4}|:${v6segment}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
12084
+ (?:${v6segment}:){5}(?::${v4}|(?::${v6segment}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4
12085
+ (?:${v6segment}:){4}(?:(?::${v6segment}){0,1}:${v4}|(?::${v6segment}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4
12086
+ (?:${v6segment}:){3}(?:(?::${v6segment}){0,2}:${v4}|(?::${v6segment}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4
12087
+ (?:${v6segment}:){2}(?:(?::${v6segment}){0,3}:${v4}|(?::${v6segment}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4
12088
+ (?:${v6segment}:){1}(?:(?::${v6segment}){0,4}:${v4}|(?::${v6segment}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
12089
+ (?::(?:(?::${v6segment}){0,5}:${v4}|(?::${v6segment}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
12090
+ )(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
12091
+ `.replace(/\s*\/\/.*$/gm, "").replace(/\n/g, "").trim();
12092
+ var v46Exact = new RegExp(`(?:^${v4}$)|(?:^${v6}$)`);
12093
+ var v4exact = new RegExp(`^${v4}$`);
12094
+ var v6exact = new RegExp(`^${v6}$`);
12095
+ var ipRegex = (options2) => options2 && options2.exact ? v46Exact : new RegExp(`(?:${boundry(options2)}${v4}${boundry(options2)})|(?:${boundry(options2)}${v6}${boundry(options2)})`, "g");
12096
+ ipRegex.v4 = (options2) => options2 && options2.exact ? v4exact : new RegExp(`${boundry(options2)}${v4}${boundry(options2)}`, "g");
12097
+ ipRegex.v6 = (options2) => options2 && options2.exact ? v6exact : new RegExp(`${boundry(options2)}${v6}${boundry(options2)}`, "g");
12098
+ var ip_regex_default = ipRegex;
12099
+
12100
+ // ../../node_modules/function-timeout/index.js
12101
+ import vm from "vm";
12102
+ function functionTimeout(function_, { timeout } = {}) {
12103
+ const script = new vm.Script("returnValue = function_()");
12104
+ const wrappedFunction = (...arguments_) => {
12105
+ const context = {
12106
+ function_: () => function_(...arguments_)
12107
+ };
12108
+ script.runInNewContext(context, { timeout });
12109
+ return context.returnValue;
12110
+ };
12111
+ Object.defineProperty(wrappedFunction, "name", {
12112
+ value: `functionTimeout(${function_.name || "<anonymous>"})`,
12113
+ configurable: true
12114
+ });
12115
+ return wrappedFunction;
12116
+ }
12117
+ function isTimeoutError(error) {
12118
+ return error?.code === "ERR_SCRIPT_EXECUTION_TIMEOUT";
12119
+ }
12120
+
12121
+ // ../../node_modules/clone-regexp/node_modules/is-regexp/index.js
12122
+ var { toString: toString3 } = Object.prototype;
12123
+ function isRegexp(value) {
12124
+ return toString3.call(value) === "[object RegExp]";
12125
+ }
12126
+
12127
+ // ../../node_modules/clone-regexp/index.js
12128
+ var flagMap = {
12129
+ global: "g",
12130
+ ignoreCase: "i",
12131
+ multiline: "m",
12132
+ dotAll: "s",
12133
+ sticky: "y",
12134
+ unicode: "u"
12135
+ };
12136
+ function clonedRegexp(regexp, options2 = {}) {
12137
+ if (!isRegexp(regexp)) {
12138
+ throw new TypeError("Expected a RegExp instance");
12139
+ }
12140
+ const flags = Object.keys(flagMap).map((flag) => (typeof options2[flag] === "boolean" ? options2[flag] : regexp[flag]) ? flagMap[flag] : "").join("");
12141
+ const clonedRegexp2 = new RegExp(options2.source || regexp.source, flags);
12142
+ clonedRegexp2.lastIndex = typeof options2.lastIndex === "number" ? options2.lastIndex : regexp.lastIndex;
12143
+ return clonedRegexp2;
12144
+ }
12145
+
12146
+ // ../../node_modules/super-regex/index.js
12147
+ function isMatch(regex, string2, { timeout } = {}) {
12148
+ try {
12149
+ return functionTimeout(() => clonedRegexp(regex).test(string2), { timeout })();
12150
+ } catch (error) {
12151
+ if (isTimeoutError(error)) {
12152
+ return false;
12153
+ }
12154
+ throw error;
12155
+ }
12156
+ }
12157
+
12158
+ // ../../node_modules/is-ip/index.js
12159
+ var maxIPv4Length = 15;
12160
+ var maxIPv6Length = 45;
12161
+ var options = {
12162
+ timeout: 400
12163
+ };
12164
+ function isIPv62(string2) {
12165
+ if (string2.length > maxIPv6Length) {
12166
+ return false;
12167
+ }
12168
+ return isMatch(ip_regex_default.v6({ exact: true }), string2, options);
12169
+ }
12170
+ function isIPv42(string2) {
12171
+ if (string2.length > maxIPv4Length) {
12172
+ return false;
12173
+ }
12174
+ return isMatch(ip_regex_default.v4({ exact: true }), string2, options);
12175
+ }
12176
+
12177
+ // ../../node_modules/@multiformats/uri-to-multiaddr/dist/src/index.js
12178
+ var portFor = {
12179
+ http: "80",
12180
+ https: "443",
12181
+ ws: "80",
12182
+ wss: "443"
12183
+ };
12184
+ var BROWSER_SCHEMES = ["http", "https", "ws", "wss"];
12185
+ function uriToMultiaddr(uriStr, opts) {
12186
+ opts = opts ?? {};
12187
+ const defaultDnsType = opts.defaultDnsType ?? "dns";
12188
+ const { scheme, hostname, port, path } = parseUri(uriStr);
12189
+ const parts = [
12190
+ tupleForHostname(hostname, defaultDnsType),
12191
+ tupleForPort(port, scheme),
12192
+ tupleForScheme(scheme)
12193
+ ];
12194
+ if (path != null) {
12195
+ parts.push(tupleForPath(path));
12196
+ }
12197
+ const multiaddrStr = "/" + parts.filter((x) => Boolean(x)).reduce((a, b) => a.concat(b), []).join("/");
12198
+ return multiaddr(multiaddrStr);
12199
+ }
12200
+ function parseUri(uriStr) {
12201
+ const [scheme] = uriStr.split(":");
12202
+ if (!BROWSER_SCHEMES.includes(scheme)) {
12203
+ uriStr = "http" + uriStr.substring(scheme.length);
12204
+ }
12205
+ let { protocol, hostname, port, pathname, search } = new URL(uriStr);
12206
+ if (port == null || port === "") {
12207
+ const protocolPort = portForProtocol(scheme);
12208
+ if (protocolPort != null) {
12209
+ port = protocolPort;
12210
+ }
12211
+ if (protocolPort == null && protocol === "http:") {
12212
+ port = "80";
12213
+ }
12214
+ }
12215
+ let path;
12216
+ if (pathname != null && pathname !== "" && pathname !== "/") {
12217
+ if (pathname.startsWith("/")) {
12218
+ pathname = pathname.substring(1);
12219
+ }
12220
+ path = pathname;
12221
+ }
12222
+ if (search != null && search !== "") {
12223
+ path = path ?? "";
12224
+ path += search;
12225
+ }
12226
+ return { scheme, hostname, port, path };
12227
+ }
12228
+ function tupleForHostname(hostname, defaultDnsType) {
12229
+ if (hostname == null || hostname === "") {
12230
+ return void 0;
12231
+ }
12232
+ if (isIPv42(hostname)) {
12233
+ return ["ip4", hostname];
12234
+ }
12235
+ if (isIPv62(hostname)) {
12236
+ return ["ip6", hostname];
12237
+ }
12238
+ if (hostname[0] === "[") {
12239
+ const trimmed = hostname.substring(1, hostname.length - 1);
12240
+ if (isIPv62(trimmed)) {
12241
+ return ["ip6", trimmed];
12242
+ }
12243
+ }
12244
+ return [defaultDnsType, hostname];
12245
+ }
12246
+ function tupleForPort(port, scheme) {
12247
+ if (port == null || port === "") {
12248
+ return void 0;
12249
+ }
12250
+ if (scheme === "udp") {
12251
+ return ["udp", port];
12252
+ }
12253
+ return ["tcp", port];
12254
+ }
12255
+ function tupleForScheme(scheme) {
12256
+ if (scheme.match(/^tcp$|^udp$/) != null) {
12257
+ return void 0;
12258
+ }
12259
+ if (scheme === "https") {
12260
+ return ["/tls/http"];
12261
+ }
12262
+ if (scheme === "wss") {
12263
+ return ["/tls/ws"];
12264
+ }
12265
+ return [scheme];
12266
+ }
12267
+ function tupleForPath(path) {
12268
+ if (path == null || path === "") {
12269
+ return void 0;
12270
+ }
12271
+ return ["http-path", encodeURIComponent(path)];
12272
+ }
12273
+ function portForProtocol(protocol) {
12274
+ if (protocol == null || protocol === "" || portFor[protocol] == null) {
12275
+ return void 0;
12276
+ }
12277
+ return portFor[protocol];
12278
+ }
12279
+
9364
12280
  // src/location.ts
9365
- import { multiaddr } from "@multiformats/multiaddr";
9366
- import { multiaddrToUri } from "@multiformats/multiaddr-to-uri";
9367
- import { uriToMultiaddr } from "@multiformats/uri-to-multiaddr";
9368
12281
  import { ed25519 as ed255193 } from "@noble/curves/ed25519";
9369
- import { bases as bases3 } from "multiformats/basics";
9370
12282
  import { verifyMessage as verifyMessage2 } from "viem";
9371
12283
  var DEFAULT_TINYCLOUD_LOCATION_REGISTRY_URL = "https://registry.tinycloud.xyz";
9372
12284
  var DEFAULT_TINYCLOUD_FALLBACK_HOST = "https://node.tinycloud.xyz";
@@ -9473,14 +12385,14 @@ async function fetchLocationRecord(registryUrl, subject, fetchFn = globalThis.fe
9473
12385
  }
9474
12386
  return validateLocationRecord(body.record);
9475
12387
  }
9476
- async function resolveCloudLocation(subject, options = {}) {
12388
+ async function resolveCloudLocation(subject, options2 = {}) {
9477
12389
  validateSubject(subject);
9478
- const verifyRecords = options.verifyRecords ?? true;
12390
+ const verifyRecords = options2.verifyRecords ?? true;
9479
12391
  const attempts = await Promise.all([
9480
- resolveExplicit(subject, options.explicitMultiaddrs),
9481
- resolveBlockchain(subject, options.blockchain, verifyRecords),
9482
- resolveCentralized(subject, options, verifyRecords),
9483
- resolveFallback(subject, options.fallbackMultiaddrs)
12392
+ resolveExplicit(subject, options2.explicitMultiaddrs),
12393
+ resolveBlockchain(subject, options2.blockchain, verifyRecords),
12394
+ resolveCentralized(subject, options2, verifyRecords),
12395
+ resolveFallback(subject, options2.fallbackMultiaddrs)
9484
12396
  ]);
9485
12397
  const winner = attempts.find((attempt) => attempt.candidate)?.candidate;
9486
12398
  if (!winner) {
@@ -9495,16 +12407,16 @@ async function resolveCloudLocation(subject, options = {}) {
9495
12407
  resolvedAt: (/* @__PURE__ */ new Date()).toISOString()
9496
12408
  };
9497
12409
  }
9498
- async function resolveTinyCloudHosts(subject, options = {}) {
12410
+ async function resolveTinyCloudHosts(subject, options2 = {}) {
9499
12411
  const location = await resolveCloudLocation(subject, {
9500
- explicitMultiaddrs: hostsToMultiaddrs(options.explicitHosts),
9501
- blockchain: options.blockchain,
9502
- centralizedRegistryUrl: options.registryUrl === null ? void 0 : options.registryUrl ?? DEFAULT_TINYCLOUD_LOCATION_REGISTRY_URL,
12412
+ explicitMultiaddrs: hostsToMultiaddrs(options2.explicitHosts),
12413
+ blockchain: options2.blockchain,
12414
+ centralizedRegistryUrl: options2.registryUrl === null ? void 0 : options2.registryUrl ?? DEFAULT_TINYCLOUD_LOCATION_REGISTRY_URL,
9503
12415
  fallbackMultiaddrs: hostsToMultiaddrs(
9504
- options.fallbackHosts === null ? void 0 : options.fallbackHosts ?? [DEFAULT_TINYCLOUD_FALLBACK_HOST]
12416
+ options2.fallbackHosts === null ? void 0 : options2.fallbackHosts ?? [DEFAULT_TINYCLOUD_FALLBACK_HOST]
9505
12417
  ),
9506
- fetch: options.fetch,
9507
- verifyRecords: options.verifyRecords
12418
+ fetch: options2.fetch,
12419
+ verifyRecords: options2.verifyRecords
9508
12420
  });
9509
12421
  return {
9510
12422
  hosts: location.multiaddrs.map((addr) => multiaddrToHttpUrl(addr)),
@@ -9556,15 +12468,15 @@ async function resolveBlockchain(subject, resolver, verifyRecords) {
9556
12468
  );
9557
12469
  });
9558
12470
  }
9559
- async function resolveCentralized(subject, options, verifyRecords) {
12471
+ async function resolveCentralized(subject, options2, verifyRecords) {
9560
12472
  return resolveAttempt("centralized", async () => {
9561
- if (!options.centralizedRegistryUrl) {
12473
+ if (!options2.centralizedRegistryUrl) {
9562
12474
  return null;
9563
12475
  }
9564
12476
  const record = await fetchLocationRecord(
9565
- options.centralizedRegistryUrl,
12477
+ options2.centralizedRegistryUrl,
9566
12478
  subject,
9567
- options.fetch
12479
+ options2.fetch
9568
12480
  );
9569
12481
  return toCandidate(subject, "centralized", record, verifyRecords);
9570
12482
  });
@@ -9704,7 +12616,7 @@ function ed25519PublicKeyFromDidKey2(did) {
9704
12616
  "did:key must use base58btc multibase"
9705
12617
  );
9706
12618
  }
9707
- const bytes = bases3.base58btc.decode(identifier);
12619
+ const bytes = bases.base58btc.decode(identifier);
9708
12620
  if (bytes.length === 34 && bytes[0] === 237 && bytes[1] === 1) {
9709
12621
  return bytes.slice(2);
9710
12622
  }
@@ -9716,31 +12628,31 @@ function ed25519PublicKeyFromDidKey2(did) {
9716
12628
  );
9717
12629
  }
9718
12630
  function base64UrlEncode3(bytes) {
9719
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
12631
+ const alphabet2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
9720
12632
  let output = "";
9721
12633
  for (let i = 0; i < bytes.length; i += 3) {
9722
12634
  const a = bytes[i];
9723
12635
  const b = bytes[i + 1];
9724
12636
  const c = bytes[i + 2];
9725
12637
  const triplet = a << 16 | (b ?? 0) << 8 | (c ?? 0);
9726
- output += alphabet[triplet >> 18 & 63];
9727
- output += alphabet[triplet >> 12 & 63];
12638
+ output += alphabet2[triplet >> 18 & 63];
12639
+ output += alphabet2[triplet >> 12 & 63];
9728
12640
  if (i + 1 < bytes.length) {
9729
- output += alphabet[triplet >> 6 & 63];
12641
+ output += alphabet2[triplet >> 6 & 63];
9730
12642
  }
9731
12643
  if (i + 2 < bytes.length) {
9732
- output += alphabet[triplet & 63];
12644
+ output += alphabet2[triplet & 63];
9733
12645
  }
9734
12646
  }
9735
12647
  return output;
9736
12648
  }
9737
12649
  function decodeBase64Url(value) {
9738
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
12650
+ const alphabet2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
9739
12651
  const bytes = [];
9740
12652
  let buffer = 0;
9741
12653
  let bits = 0;
9742
12654
  for (const char of value) {
9743
- const index = alphabet.indexOf(char);
12655
+ const index = alphabet2.indexOf(char);
9744
12656
  if (index < 0) {
9745
12657
  throw new LocationRecordValidationError(
9746
12658
  "did:key signature must be base64url"
@@ -9775,6 +12687,7 @@ export {
9775
12687
  CAPABILITY_REGISTRY2 as CAPABILITY_REGISTRY,
9776
12688
  CapabilityKeyRegistry,
9777
12689
  CapabilityKeyRegistryErrorCodes,
12690
+ CaveatedDelegationUnsupportedError,
9778
12691
  ClientSessionSchema,
9779
12692
  CloudLocationResolutionError,
9780
12693
  DECRYPT_ACTION,
@@ -9793,6 +12706,7 @@ export {
9793
12706
  DUCKDB,
9794
12707
  DataVaultService,
9795
12708
  DatabaseHandle,
12709
+ DecryptTransportResponseError,
9796
12710
  DelegationErrorCodes,
9797
12711
  DelegationManager,
9798
12712
  DuckDbAction,
@@ -9900,6 +12814,7 @@ export {
9900
12814
  canonicalizeDidUrl,
9901
12815
  canonicalizeEncryptionJson,
9902
12816
  canonicalizeNetworkId,
12817
+ canonicalizeRecapCaveats,
9903
12818
  canonicalizeSecretScope,
9904
12819
  canonicalizeSignedObjectUnsigned,
9905
12820
  checkDecryptInvocationInput,
@@ -9973,6 +12888,7 @@ export {
9973
12888
  pkhDid,
9974
12889
  principalDid,
9975
12890
  principalDidEquals,
12891
+ recapCaveatsEqual,
9976
12892
  resolveCloudLocation,
9977
12893
  resolveManifest,
9978
12894
  resolveManifestKnowledgeRoot,