@covia/covia-sdk 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -62,8 +62,10 @@ var JobFailedError = class extends CoviaError {
62
62
  const id = jobData.id ?? "unknown";
63
63
  const status = jobData.status ?? "unknown";
64
64
  let msg = `Job ${id} ${status}`;
65
- if (jobData.output?.error) {
66
- msg += `: ${jobData.output.error}`;
65
+ const output = jobData.output;
66
+ const errText = output && typeof output === "object" && "error" in output ? output.error : void 0;
67
+ if (typeof errText === "string") {
68
+ msg += `: ${errText}`;
67
69
  }
68
70
  super(msg);
69
71
  this.name = "JobFailedError";
@@ -91,26 +93,44 @@ var JobNotFoundError = class extends NotFoundError {
91
93
  }
92
94
  };
93
95
 
94
- // node_modules/@noble/ed25519/index.js
95
- var ed25519_CURVE = {
96
+ // node_modules/.pnpm/@noble+ed25519@3.1.0/node_modules/@noble/ed25519/index.js
97
+ var ed25519_CURVE = Object.freeze({
96
98
  p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
97
99
  n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
100
+ h: 8n,
98
101
  a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,
99
102
  d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
100
103
  Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
101
104
  Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n
102
- };
103
- var { p: P, n: N, Gx, Gy, a: _a, d: _d } = ed25519_CURVE;
104
- var h = 8n;
105
+ });
106
+ var { p: P, n: N, Gx, Gy, a: _a, d: _d, h } = ed25519_CURVE;
105
107
  var L = 32;
106
- var L2 = 64;
107
- var err = (m = "") => {
108
- throw new Error(m);
108
+ var captureTrace = (...args) => {
109
+ if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") {
110
+ Error.captureStackTrace(...args);
111
+ }
112
+ };
113
+ var err = (message = "") => {
114
+ const e = new Error(message);
115
+ captureTrace(e, err);
116
+ throw e;
109
117
  };
110
118
  var isBig = (n) => typeof n === "bigint";
111
119
  var isStr = (s) => typeof s === "string";
112
- var isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
113
- var abytes = (a, l) => !isBytes(a) || typeof l === "number" && l > 0 && a.length !== l ? err("Uint8Array expected") : a;
120
+ var isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
121
+ var abytes = (value, length, title = "") => {
122
+ const bytes = isBytes(value);
123
+ const len = value?.length;
124
+ const needsLen = length !== void 0;
125
+ if (!bytes || needsLen && len !== length) {
126
+ const prefix = title && `"${title}" `;
127
+ const ofLen = needsLen ? ` of length ${length}` : "";
128
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
129
+ const msg = prefix + "expected Uint8Array" + ofLen + ", got " + got;
130
+ throw bytes ? new RangeError(msg) : new TypeError(msg);
131
+ }
132
+ return value;
133
+ };
114
134
  var u8n = (len) => new Uint8Array(len);
115
135
  var u8fr = (buf) => Uint8Array.from(buf);
116
136
  var padh = (n, pad) => n.toString(16).padStart(pad, "0");
@@ -143,11 +163,13 @@ var hexToBytes = (hex) => {
143
163
  }
144
164
  return array;
145
165
  };
146
- var toU8 = (a, len) => abytes(isStr(a) ? hexToBytes(a) : u8fr(abytes(a)), len);
147
166
  var cr = () => globalThis?.crypto;
148
- var subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined");
167
+ var subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined, consider polyfill");
149
168
  var concatBytes = (...arrs) => {
150
- const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0));
169
+ let len = 0;
170
+ for (const a of arrs)
171
+ len += abytes(a).length;
172
+ const r = u8n(len);
151
173
  let pad = 0;
152
174
  arrs.forEach((a) => {
153
175
  r.set(a, pad);
@@ -160,11 +182,25 @@ var randomBytes = (len = L) => {
160
182
  return c.getRandomValues(u8n(len));
161
183
  };
162
184
  var big = BigInt;
163
- var arange = (n, min, max, msg = "bad number: out of range") => isBig(n) && min <= n && n < max ? n : err(msg);
185
+ var assertRange = (n, min, max, msg = "bad number: out of range") => {
186
+ if (!isBig(n))
187
+ throw new TypeError(msg);
188
+ if (min <= n && n < max)
189
+ return n;
190
+ throw new RangeError(msg);
191
+ };
164
192
  var M = (a, b = P) => {
165
193
  const r = a % b;
166
194
  return r >= 0n ? r : b + r;
167
195
  };
196
+ var P_MASK = (1n << 255n) - 1n;
197
+ var modP = (num) => {
198
+ if (num < 0n)
199
+ err("negative coordinate");
200
+ let r = (num >> 255n) * 19n + (num & P_MASK);
201
+ r = (r >> 255n) * 19n + (r & P_MASK);
202
+ return r % P;
203
+ };
168
204
  var modN = (a) => M(a, N);
169
205
  var invert = (num, md) => {
170
206
  if (num === 0n || md <= 0n)
@@ -178,41 +214,47 @@ var invert = (num, md) => {
178
214
  return b === 1n ? M(x, md) : err("no inverse");
179
215
  };
180
216
  var callHash = (name) => {
181
- const fn = etc[name];
217
+ const fn = hashes[name];
182
218
  if (typeof fn !== "function")
183
219
  err("hashes." + name + " not set");
184
220
  return fn;
185
221
  };
222
+ var checkDigest = (value) => abytes(value, 64, "digest");
186
223
  var apoint = (p) => p instanceof Point ? p : err("Point expected");
187
224
  var B256 = 2n ** 256n;
188
225
  var _Point = class _Point {
189
- constructor(ex, ey, ez, et) {
190
- __publicField(this, "ex");
191
- __publicField(this, "ey");
192
- __publicField(this, "ez");
193
- __publicField(this, "et");
226
+ // Constructor only bounds-checks and freezes XYZT coordinates; it does not prove the point is
227
+ // on-curve or that T matches X*Y/Z.
228
+ constructor(X, Y, Z, T) {
229
+ __publicField(this, "X");
230
+ __publicField(this, "Y");
231
+ __publicField(this, "Z");
232
+ __publicField(this, "T");
194
233
  const max = B256;
195
- this.ex = arange(ex, 0n, max);
196
- this.ey = arange(ey, 0n, max);
197
- this.ez = arange(ez, 1n, max);
198
- this.et = arange(et, 0n, max);
234
+ this.X = assertRange(X, 0n, max);
235
+ this.Y = assertRange(Y, 0n, max);
236
+ this.Z = assertRange(Z, 1n, max);
237
+ this.T = assertRange(T, 0n, max);
199
238
  Object.freeze(this);
200
239
  }
240
+ static CURVE() {
241
+ return ed25519_CURVE;
242
+ }
201
243
  static fromAffine(p) {
202
- return new _Point(p.x, p.y, 1n, M(p.x * p.y));
244
+ return new _Point(p.x, p.y, 1n, modP(p.x * p.y));
203
245
  }
204
- /** RFC8032 5.1.3: Uint8Array to Point. */
246
+ /** RFC8032 5.1.3: Bytes to Point. */
205
247
  static fromBytes(hex, zip215 = false) {
206
248
  const d = _d;
207
249
  const normed = u8fr(abytes(hex, L));
208
250
  const lastByte = hex[31];
209
251
  normed[31] = lastByte & -129;
210
- const y = bytesToNumLE(normed);
252
+ const y = bytesToNumberLE(normed);
211
253
  const max = zip215 ? B256 : P;
212
- arange(y, 0n, max);
213
- const y2 = M(y * y);
254
+ assertRange(y, 0n, max);
255
+ const y2 = modP(y * y);
214
256
  const u = M(y2 - 1n);
215
- const v = M(d * y2 + 1n);
257
+ const v = modP(d * y2 + 1n);
216
258
  let { isValid, value: x } = uvRatio(u, v);
217
259
  if (!isValid)
218
260
  err("bad point: y not sqrt");
@@ -222,7 +264,16 @@ var _Point = class _Point {
222
264
  err("bad point: x==0, isLastByteOdd");
223
265
  if (isLastByteOdd !== isXOdd)
224
266
  x = M(-x);
225
- return new _Point(x, y, 1n, M(x * y));
267
+ return new _Point(x, y, 1n, modP(x * y));
268
+ }
269
+ static fromHex(hex, zip215) {
270
+ return _Point.fromBytes(hexToBytes(hex), zip215);
271
+ }
272
+ get x() {
273
+ return this.toAffine().x;
274
+ }
275
+ get y() {
276
+ return this.toAffine().y;
226
277
  }
227
278
  /** Checks if the point is valid and on-curve. */
228
279
  assertValidity() {
@@ -230,31 +281,31 @@ var _Point = class _Point {
230
281
  const d = _d;
231
282
  const p = this;
232
283
  if (p.is0())
233
- throw new Error("bad point: ZERO");
234
- const { ex: X, ey: Y, ez: Z, et: T } = p;
235
- const X2 = M(X * X);
236
- const Y2 = M(Y * Y);
237
- const Z2 = M(Z * Z);
238
- const Z4 = M(Z2 * Z2);
239
- const aX2 = M(X2 * a);
240
- const left = M(Z2 * M(aX2 + Y2));
241
- const right = M(Z4 + M(d * M(X2 * Y2)));
284
+ return err("bad point: ZERO");
285
+ const { X, Y, Z, T } = p;
286
+ const X2 = modP(X * X);
287
+ const Y2 = modP(Y * Y);
288
+ const Z2 = modP(Z * Z);
289
+ const Z4 = modP(Z2 * Z2);
290
+ const aX2 = modP(X2 * a);
291
+ const left = modP(Z2 * (aX2 + Y2));
292
+ const right = M(Z4 + modP(d * modP(X2 * Y2)));
242
293
  if (left !== right)
243
- throw new Error("bad point: equation left != right (1)");
244
- const XY = M(X * Y);
245
- const ZT = M(Z * T);
294
+ return err("bad point: equation left != right (1)");
295
+ const XY = modP(X * Y);
296
+ const ZT = modP(Z * T);
246
297
  if (XY !== ZT)
247
- throw new Error("bad point: equation left != right (2)");
298
+ return err("bad point: equation left != right (2)");
248
299
  return this;
249
300
  }
250
301
  /** Equality check: compare points P&Q. */
251
302
  equals(other) {
252
- const { ex: X1, ey: Y1, ez: Z1 } = this;
253
- const { ex: X2, ey: Y2, ez: Z2 } = apoint(other);
254
- const X1Z2 = M(X1 * Z2);
255
- const X2Z1 = M(X2 * Z1);
256
- const Y1Z2 = M(Y1 * Z2);
257
- const Y2Z1 = M(Y2 * Z1);
303
+ const { X: X1, Y: Y1, Z: Z1 } = this;
304
+ const { X: X2, Y: Y2, Z: Z2 } = apoint(other);
305
+ const X1Z2 = modP(X1 * Z2);
306
+ const X2Z1 = modP(X2 * Z1);
307
+ const Y1Z2 = modP(Y1 * Z2);
308
+ const Y2Z1 = modP(Y2 * Z1);
258
309
  return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
259
310
  }
260
311
  is0() {
@@ -262,58 +313,64 @@ var _Point = class _Point {
262
313
  }
263
314
  /** Flip point over y coordinate. */
264
315
  negate() {
265
- return new _Point(M(-this.ex), this.ey, this.ez, M(-this.et));
316
+ return new _Point(M(-this.X), this.Y, this.Z, M(-this.T));
266
317
  }
267
318
  /** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */
268
319
  double() {
269
- const { ex: X1, ey: Y1, ez: Z1 } = this;
320
+ const { X: X1, Y: Y1, Z: Z1 } = this;
270
321
  const a = _a;
271
- const A = M(X1 * X1);
272
- const B = M(Y1 * Y1);
273
- const C2 = M(2n * M(Z1 * Z1));
274
- const D = M(a * A);
275
- const x1y1 = X1 + Y1;
276
- const E = M(M(x1y1 * x1y1) - A - B);
277
- const G2 = D + B;
278
- const F = G2 - C2;
279
- const H = D - B;
280
- const X3 = M(E * F);
281
- const Y3 = M(G2 * H);
282
- const T3 = M(E * H);
283
- const Z3 = M(F * G2);
322
+ const A = modP(X1 * X1);
323
+ const B = modP(Y1 * Y1);
324
+ const C2 = modP(2n * Z1 * Z1);
325
+ const D = modP(a * A);
326
+ const x1y1 = M(X1 + Y1);
327
+ const E = M(modP(x1y1 * x1y1) - A - B);
328
+ const G2 = M(D + B);
329
+ const F = M(G2 - C2);
330
+ const H = M(D - B);
331
+ const X3 = modP(E * F);
332
+ const Y3 = modP(G2 * H);
333
+ const T3 = modP(E * H);
334
+ const Z3 = modP(F * G2);
284
335
  return new _Point(X3, Y3, Z3, T3);
285
336
  }
286
337
  /** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */
287
338
  add(other) {
288
- const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
289
- const { ex: X2, ey: Y2, ez: Z2, et: T2 } = apoint(other);
339
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
340
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = apoint(other);
290
341
  const a = _a;
291
342
  const d = _d;
292
- const A = M(X1 * X2);
293
- const B = M(Y1 * Y2);
294
- const C2 = M(T1 * d * T2);
295
- const D = M(Z1 * Z2);
296
- const E = M((X1 + Y1) * (X2 + Y2) - A - B);
343
+ const A = modP(X1 * X2);
344
+ const B = modP(Y1 * Y2);
345
+ const C2 = modP(modP(T1 * d) * T2);
346
+ const D = modP(Z1 * Z2);
347
+ const E = M(modP(M(X1 + Y1) * M(X2 + Y2)) - A - B);
297
348
  const F = M(D - C2);
298
349
  const G2 = M(D + C2);
299
- const H = M(B - a * A);
300
- const X3 = M(E * F);
301
- const Y3 = M(G2 * H);
302
- const T3 = M(E * H);
303
- const Z3 = M(F * G2);
350
+ const H = M(B - modP(a * A));
351
+ const X3 = modP(E * F);
352
+ const Y3 = modP(G2 * H);
353
+ const T3 = modP(E * H);
354
+ const Z3 = modP(F * G2);
304
355
  return new _Point(X3, Y3, Z3, T3);
305
356
  }
357
+ subtract(other) {
358
+ return this.add(apoint(other).negate());
359
+ }
306
360
  /**
307
- * Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
361
+ * Point-by-scalar multiplication. Safe mode requires `1 <= n < CURVE.n`.
362
+ * Unsafe mode additionally permits `n = 0` and returns the identity point for that case.
308
363
  * Uses {@link wNAF} for base point.
309
364
  * Uses fake point to mitigate side-channel leakage.
310
- * @param n scalar by which point is multiplied
311
- * @param safe safe mode guards against timing attacks; unsafe mode is faster
365
+ * @param n - scalar by which point is multiplied
366
+ * @param safe - safe mode guards against timing attacks; unsafe mode is faster
312
367
  */
313
368
  multiply(n, safe = true) {
314
- if (!safe && (n === 0n || this.is0()))
369
+ if (!safe && n === 0n)
370
+ return I;
371
+ assertRange(n, 1n, N);
372
+ if (!safe && this.is0())
315
373
  return I;
316
- arange(n, 1n, N);
317
374
  if (n === 1n)
318
375
  return this;
319
376
  if (this.equals(G))
@@ -328,18 +385,23 @@ var _Point = class _Point {
328
385
  }
329
386
  return p;
330
387
  }
388
+ multiplyUnsafe(scalar) {
389
+ return this.multiply(scalar, false);
390
+ }
331
391
  /** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
332
392
  toAffine() {
333
- const { ex: x, ey: y, ez: z } = this;
393
+ const { X, Y, Z } = this;
334
394
  if (this.equals(I))
335
395
  return { x: 0n, y: 1n };
336
- const iz = invert(z, P);
337
- if (M(z * iz) !== 1n)
396
+ const iz = invert(Z, P);
397
+ if (modP(Z * iz) !== 1n)
338
398
  err("invalid inverse");
339
- return { x: M(x * iz), y: M(y * iz) };
399
+ const x = modP(X * iz);
400
+ const y = modP(Y * iz);
401
+ return { x, y };
340
402
  }
341
403
  toBytes() {
342
- const { x, y } = this.assertValidity().toAffine();
404
+ const { x, y } = this.toAffine();
343
405
  const b = numTo32bLE(y);
344
406
  b[31] |= x & 1n ? 128 : 0;
345
407
  return b;
@@ -347,7 +409,6 @@ var _Point = class _Point {
347
409
  toHex() {
348
410
  return bytesToHex(this.toBytes());
349
411
  }
350
- // encode to hex string
351
412
  clearCofactor() {
352
413
  return this.multiply(big(h), false);
353
414
  }
@@ -360,18 +421,6 @@ var _Point = class _Point {
360
421
  p = p.add(this);
361
422
  return p.is0();
362
423
  }
363
- static fromHex(hex, zip215) {
364
- return _Point.fromBytes(toU8(hex), zip215);
365
- }
366
- get x() {
367
- return this.toAffine().x;
368
- }
369
- get y() {
370
- return this.toAffine().y;
371
- }
372
- toRawBytes() {
373
- return this.toBytes();
374
- }
375
424
  };
376
425
  __publicField(_Point, "BASE");
377
426
  __publicField(_Point, "ZERO");
@@ -380,40 +429,39 @@ var G = new Point(Gx, Gy, 1n, M(Gx * Gy));
380
429
  var I = new Point(0n, 1n, 1n, 0n);
381
430
  Point.BASE = G;
382
431
  Point.ZERO = I;
383
- var numTo32bLE = (num) => hexToBytes(padh(arange(num, 0n, B256), L2)).reverse();
384
- var bytesToNumLE = (b) => big("0x" + bytesToHex(u8fr(abytes(b)).reverse()));
432
+ var numTo32bLE = (num) => hexToBytes(padh(assertRange(num, 0n, B256), 64)).reverse();
433
+ var bytesToNumberLE = (b) => big("0x" + bytesToHex(u8fr(abytes(b)).reverse()));
385
434
  var pow2 = (x, power) => {
386
435
  let r = x;
387
436
  while (power-- > 0n) {
388
- r *= r;
389
- r %= P;
437
+ r = modP(r * r);
390
438
  }
391
439
  return r;
392
440
  };
393
441
  var pow_2_252_3 = (x) => {
394
- const x2 = x * x % P;
395
- const b2 = x2 * x % P;
396
- const b4 = pow2(b2, 2n) * b2 % P;
397
- const b5 = pow2(b4, 1n) * x % P;
398
- const b10 = pow2(b5, 5n) * b5 % P;
399
- const b20 = pow2(b10, 10n) * b10 % P;
400
- const b40 = pow2(b20, 20n) * b20 % P;
401
- const b80 = pow2(b40, 40n) * b40 % P;
402
- const b160 = pow2(b80, 80n) * b80 % P;
403
- const b240 = pow2(b160, 80n) * b80 % P;
404
- const b250 = pow2(b240, 10n) * b10 % P;
405
- const pow_p_5_8 = pow2(b250, 2n) * x % P;
442
+ const x2 = modP(x * x);
443
+ const b2 = modP(x2 * x);
444
+ const b4 = modP(pow2(b2, 2n) * b2);
445
+ const b5 = modP(pow2(b4, 1n) * x);
446
+ const b10 = modP(pow2(b5, 5n) * b5);
447
+ const b20 = modP(pow2(b10, 10n) * b10);
448
+ const b40 = modP(pow2(b20, 20n) * b20);
449
+ const b80 = modP(pow2(b40, 40n) * b40);
450
+ const b160 = modP(pow2(b80, 80n) * b80);
451
+ const b240 = modP(pow2(b160, 80n) * b80);
452
+ const b250 = modP(pow2(b240, 10n) * b10);
453
+ const pow_p_5_8 = modP(pow2(b250, 2n) * x);
406
454
  return { pow_p_5_8, b2 };
407
455
  };
408
456
  var RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
409
457
  var uvRatio = (u, v) => {
410
- const v3 = M(v * v * v);
411
- const v7 = M(v3 * v3 * v);
412
- const pow = pow_2_252_3(u * v7).pow_p_5_8;
413
- let x = M(u * v3 * pow);
414
- const vx2 = M(v * x * x);
458
+ const v3 = modP(v * modP(v * v));
459
+ const v7 = modP(modP(v3 * v3) * v);
460
+ const pow = pow_2_252_3(modP(u * v7)).pow_p_5_8;
461
+ let x = modP(u * modP(v3 * pow));
462
+ const vx2 = modP(v * modP(x * x));
415
463
  const root1 = x;
416
- const root2 = M(x * RM1);
464
+ const root2 = modP(x * RM1);
417
465
  const useRoot1 = vx2 === u;
418
466
  const useRoot2 = vx2 === M(-u);
419
467
  const noRoot = vx2 === M(-u * RM1);
@@ -425,22 +473,23 @@ var uvRatio = (u, v) => {
425
473
  x = M(-x);
426
474
  return { isValid: useRoot1 || useRoot2, value: x };
427
475
  };
428
- var modL_LE = (hash) => modN(bytesToNumLE(hash));
429
- var sha512a = (...m) => etc.sha512Async(...m);
430
- var sha512s = (...m) => callHash("sha512Sync")(...m);
476
+ var modL_LE = (hash) => modN(bytesToNumberLE(hash));
477
+ var sha512a = (...m) => Promise.resolve(callHash("sha512Async")(concatBytes(...m))).then(checkDigest);
478
+ var sha512s = (...m) => checkDigest(callHash("sha512")(concatBytes(...m)));
431
479
  var hash2extK = (hashed) => {
432
- const head = hashed.slice(0, L);
480
+ const copy = u8fr(hashed);
481
+ const head = copy.slice(0, 32);
433
482
  head[0] &= 248;
434
483
  head[31] &= 127;
435
484
  head[31] |= 64;
436
- const prefix = hashed.slice(L, L2);
485
+ const prefix = copy.slice(32, 64);
437
486
  const scalar = modL_LE(head);
438
487
  const point = G.multiply(scalar);
439
488
  const pointBytes = point.toBytes();
440
489
  return { head, prefix, scalar, point, pointBytes };
441
490
  };
442
- var getExtendedPublicKeyAsync = (priv) => sha512a(toU8(priv, L)).then(hash2extK);
443
- var getExtendedPublicKey = (priv) => hash2extK(sha512s(toU8(priv, L)));
491
+ var getExtendedPublicKeyAsync = (secretKey) => sha512a(abytes(secretKey, L)).then(hash2extK);
492
+ var getExtendedPublicKey = (secretKey) => hash2extK(sha512s(abytes(secretKey, L)));
444
493
  var getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;
445
494
  var hashFinishS = (res) => res.finish(sha512s(res.hashable));
446
495
  var _sign = (e, rBytes, msg) => {
@@ -450,40 +499,33 @@ var _sign = (e, rBytes, msg) => {
450
499
  const hashable = concatBytes(R, P2, msg);
451
500
  const finish = (hashed) => {
452
501
  const S = modN(r + modL_LE(hashed) * s);
453
- return abytes(concatBytes(R, numTo32bLE(S)), L2);
502
+ return abytes(concatBytes(R, numTo32bLE(S)), 64);
454
503
  };
455
504
  return { hashable, finish };
456
505
  };
457
- var sign = (msg, privKey) => {
458
- const m = toU8(msg);
459
- const e = getExtendedPublicKey(privKey);
506
+ var sign = (message, secretKey) => {
507
+ const m = abytes(message);
508
+ const e = getExtendedPublicKey(secretKey);
460
509
  const rBytes = sha512s(e.prefix, m);
461
510
  return hashFinishS(_sign(e, rBytes, m));
462
511
  };
463
- var etc = {
464
- sha512Async: async (...messages) => {
512
+ var hashes = {
513
+ sha512Async: async (message) => {
465
514
  const s = subtle();
466
- const m = concatBytes(...messages);
515
+ const m = concatBytes(message);
467
516
  return u8n(await s.digest("SHA-512", m.buffer));
468
517
  },
469
- sha512Sync: void 0,
470
- bytesToHex,
471
- hexToBytes,
472
- concatBytes,
473
- mod: M,
474
- invert,
475
- randomBytes
518
+ sha512: void 0
476
519
  };
477
- var utils = {
520
+ var randomSecretKey = (seed) => {
521
+ seed = seed === void 0 ? randomBytes(L) : seed;
522
+ return abytes(seed, L);
523
+ };
524
+ var utils = /* @__PURE__ */ Object.freeze({
478
525
  getExtendedPublicKeyAsync,
479
526
  getExtendedPublicKey,
480
- randomPrivateKey: () => randomBytes(L),
481
- precompute: (w = 8, p = G) => {
482
- p.multiply(3n);
483
- return p;
484
- }
485
- // no-op
486
- };
527
+ randomSecretKey
528
+ });
487
529
  var W = 8;
488
530
  var scalarBits = 256;
489
531
  var pwindows = Math.ceil(scalarBits / W) + 1;
@@ -534,18 +576,29 @@ var wNAF = (n) => {
534
576
  p = p.add(ctneg(isNeg, comp[offP]));
535
577
  }
536
578
  }
579
+ if (n !== 0n)
580
+ err("invalid wnaf");
537
581
  return { p, f };
538
582
  };
539
583
 
540
- // node_modules/@noble/hashes/esm/utils.js
584
+ // node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js
541
585
  function isBytes2(a) {
542
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
586
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
543
587
  }
544
- function abytes2(b, ...lengths) {
545
- if (!isBytes2(b))
546
- throw new Error("Uint8Array expected");
547
- if (lengths.length > 0 && !lengths.includes(b.length))
548
- throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
588
+ function abytes2(value, length, title = "") {
589
+ const bytes = isBytes2(value);
590
+ const len = value?.length;
591
+ const needsLen = length !== void 0;
592
+ if (!bytes || needsLen) {
593
+ const prefix = title && `"${title}" `;
594
+ const ofLen = "";
595
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
596
+ const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
597
+ if (!bytes)
598
+ throw new TypeError(message);
599
+ throw new RangeError(message);
600
+ }
601
+ return value;
549
602
  }
550
603
  function aexists(instance, checkFinished = true) {
551
604
  if (instance.destroyed)
@@ -554,10 +607,10 @@ function aexists(instance, checkFinished = true) {
554
607
  throw new Error("Hash#digest() has already been called");
555
608
  }
556
609
  function aoutput(out, instance) {
557
- abytes2(out);
610
+ abytes2(out, void 0, "digestInto() output");
558
611
  const min = instance.outputLen;
559
612
  if (out.length < min) {
560
- throw new Error("digestInto() expects output buffer of length at least " + min);
613
+ throw new RangeError('"digestInto() output" expected to be of length >=' + min);
561
614
  }
562
615
  }
563
616
  function clean(...arrays) {
@@ -568,48 +621,37 @@ function clean(...arrays) {
568
621
  function createView(arr) {
569
622
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
570
623
  }
571
- function utf8ToBytes(str) {
572
- if (typeof str !== "string")
573
- throw new Error("string expected");
574
- return new Uint8Array(new TextEncoder().encode(str));
575
- }
576
- function toBytes(data) {
577
- if (typeof data === "string")
578
- data = utf8ToBytes(data);
579
- abytes2(data);
580
- return data;
581
- }
582
- var Hash = class {
583
- };
584
- function createHasher(hashCons) {
585
- const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
586
- const tmp = hashCons();
624
+ function createHasher(hashCons, info = {}) {
625
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
626
+ const tmp = hashCons(void 0);
587
627
  hashC.outputLen = tmp.outputLen;
588
628
  hashC.blockLen = tmp.blockLen;
589
- hashC.create = () => hashCons();
590
- return hashC;
629
+ hashC.canXOF = tmp.canXOF;
630
+ hashC.create = (opts) => hashCons(opts);
631
+ Object.assign(hashC, info);
632
+ return Object.freeze(hashC);
591
633
  }
634
+ var oidNist = (suffix) => ({
635
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
636
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
637
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
638
+ });
592
639
 
593
- // node_modules/@noble/hashes/esm/_md.js
594
- function setBigUint64(view, byteOffset, value, isLE) {
595
- if (typeof view.setBigUint64 === "function")
596
- return view.setBigUint64(byteOffset, value, isLE);
597
- const _32n2 = BigInt(32);
598
- const _u32_max = BigInt(4294967295);
599
- const wh = Number(value >> _32n2 & _u32_max);
600
- const wl = Number(value & _u32_max);
601
- const h2 = isLE ? 4 : 0;
602
- const l = isLE ? 0 : 4;
603
- view.setUint32(byteOffset + h2, wh, isLE);
604
- view.setUint32(byteOffset + l, wl, isLE);
605
- }
606
- var HashMD = class extends Hash {
640
+ // node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_md.js
641
+ var HashMD = class {
607
642
  constructor(blockLen, outputLen, padOffset, isLE) {
608
- super();
609
- this.finished = false;
610
- this.length = 0;
611
- this.pos = 0;
612
- this.destroyed = false;
643
+ __publicField(this, "blockLen");
644
+ __publicField(this, "outputLen");
645
+ __publicField(this, "canXOF", false);
646
+ __publicField(this, "padOffset");
647
+ __publicField(this, "isLE");
648
+ // For partial updates less than block size
649
+ __publicField(this, "buffer");
650
+ __publicField(this, "view");
651
+ __publicField(this, "finished", false);
652
+ __publicField(this, "length", 0);
653
+ __publicField(this, "pos", 0);
654
+ __publicField(this, "destroyed", false);
613
655
  this.blockLen = blockLen;
614
656
  this.outputLen = outputLen;
615
657
  this.padOffset = padOffset;
@@ -619,7 +661,6 @@ var HashMD = class extends Hash {
619
661
  }
620
662
  update(data) {
621
663
  aexists(this);
622
- data = toBytes(data);
623
664
  abytes2(data);
624
665
  const { view, buffer, blockLen } = this;
625
666
  const len = data.length;
@@ -657,12 +698,12 @@ var HashMD = class extends Hash {
657
698
  }
658
699
  for (let i = pos; i < blockLen; i++)
659
700
  buffer[i] = 0;
660
- setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
701
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
661
702
  this.process(view, 0);
662
703
  const oview = createView(out);
663
704
  const len = this.outputLen;
664
705
  if (len % 4)
665
- throw new Error("_sha2: outputLen should be aligned to 32bit");
706
+ throw new Error("_sha2: outputLen must be aligned to 32bit");
666
707
  const outLen = len / 4;
667
708
  const state = this.get();
668
709
  if (outLen > state.length)
@@ -712,7 +753,7 @@ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
712
753
  327033209
713
754
  ]);
714
755
 
715
- // node_modules/@noble/hashes/esm/_u64.js
756
+ // node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_u64.js
716
757
  var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
717
758
  var _32n = /* @__PURE__ */ BigInt(32);
718
759
  function fromBig(n, le = false) {
@@ -747,7 +788,7 @@ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0
747
788
  var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
748
789
  var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
749
790
 
750
- // node_modules/@noble/hashes/esm/sha2.js
791
+ // node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha2.js
751
792
  var K512 = /* @__PURE__ */ (() => split([
752
793
  "0x428a2f98d728ae22",
753
794
  "0x7137449123ef65cd",
@@ -834,25 +875,9 @@ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
834
875
  var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
835
876
  var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
836
877
  var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
837
- var SHA512 = class extends HashMD {
838
- constructor(outputLen = 64) {
878
+ var SHA2_64B = class extends HashMD {
879
+ constructor(outputLen) {
839
880
  super(128, outputLen, 16, false);
840
- this.Ah = SHA512_IV[0] | 0;
841
- this.Al = SHA512_IV[1] | 0;
842
- this.Bh = SHA512_IV[2] | 0;
843
- this.Bl = SHA512_IV[3] | 0;
844
- this.Ch = SHA512_IV[4] | 0;
845
- this.Cl = SHA512_IV[5] | 0;
846
- this.Dh = SHA512_IV[6] | 0;
847
- this.Dl = SHA512_IV[7] | 0;
848
- this.Eh = SHA512_IV[8] | 0;
849
- this.El = SHA512_IV[9] | 0;
850
- this.Fh = SHA512_IV[10] | 0;
851
- this.Fl = SHA512_IV[11] | 0;
852
- this.Gh = SHA512_IV[12] | 0;
853
- this.Gl = SHA512_IV[13] | 0;
854
- this.Hh = SHA512_IV[14] | 0;
855
- this.Hl = SHA512_IV[15] | 0;
856
881
  }
857
882
  // prettier-ignore
858
883
  get() {
@@ -941,23 +966,41 @@ var SHA512 = class extends HashMD {
941
966
  clean(SHA512_W_H, SHA512_W_L);
942
967
  }
943
968
  destroy() {
969
+ this.destroyed = true;
944
970
  clean(this.buffer);
945
971
  this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
946
972
  }
947
973
  };
948
- var sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
949
-
950
- // node_modules/@noble/hashes/esm/sha512.js
951
- var sha5122 = sha512;
974
+ var _SHA512 = class extends SHA2_64B {
975
+ constructor() {
976
+ super(64);
977
+ __publicField(this, "Ah", SHA512_IV[0] | 0);
978
+ __publicField(this, "Al", SHA512_IV[1] | 0);
979
+ __publicField(this, "Bh", SHA512_IV[2] | 0);
980
+ __publicField(this, "Bl", SHA512_IV[3] | 0);
981
+ __publicField(this, "Ch", SHA512_IV[4] | 0);
982
+ __publicField(this, "Cl", SHA512_IV[5] | 0);
983
+ __publicField(this, "Dh", SHA512_IV[6] | 0);
984
+ __publicField(this, "Dl", SHA512_IV[7] | 0);
985
+ __publicField(this, "Eh", SHA512_IV[8] | 0);
986
+ __publicField(this, "El", SHA512_IV[9] | 0);
987
+ __publicField(this, "Fh", SHA512_IV[10] | 0);
988
+ __publicField(this, "Fl", SHA512_IV[11] | 0);
989
+ __publicField(this, "Gh", SHA512_IV[12] | 0);
990
+ __publicField(this, "Gl", SHA512_IV[13] | 0);
991
+ __publicField(this, "Hh", SHA512_IV[14] | 0);
992
+ __publicField(this, "Hl", SHA512_IV[15] | 0);
993
+ }
994
+ };
995
+ var sha512 = /* @__PURE__ */ createHasher(
996
+ () => new _SHA512(),
997
+ /* @__PURE__ */ oidNist(3)
998
+ );
952
999
 
953
1000
  // src/crypto/keys.ts
954
- etc.sha512Sync = (...m) => {
955
- const h2 = sha5122.create();
956
- for (const msg of m) h2.update(msg);
957
- return h2.digest();
958
- };
1001
+ hashes.sha512 = sha512;
959
1002
  function generateKeyPair() {
960
- const privateKey = utils.randomPrivateKey();
1003
+ const privateKey = utils.randomSecretKey();
961
1004
  const publicKey = getPublicKey(privateKey);
962
1005
  return { privateKey, publicKey };
963
1006
  }
@@ -1061,18 +1104,20 @@ function base64UrlEncode(data) {
1061
1104
  }
1062
1105
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
1063
1106
  }
1064
- function createEdDSAJWT(privateKey, lifetimeSeconds = 300) {
1107
+ function createEdDSAJWT(privateKey, lifetimeSeconds = 300, audience) {
1065
1108
  const publicKey = getPublicKey2(privateKey);
1066
1109
  const multikey = encodePublicKey(publicKey);
1067
1110
  const did = `did:key:${multikey}`;
1068
1111
  const nowSecs = Math.floor(Date.now() / 1e3);
1069
1112
  const header = JSON.stringify({ alg: "EdDSA", typ: "JWT", kid: multikey });
1070
- const payload = JSON.stringify({
1113
+ const claims = {
1071
1114
  sub: did,
1072
1115
  iss: did,
1073
1116
  iat: nowSecs,
1074
1117
  exp: nowSecs + lifetimeSeconds
1075
- });
1118
+ };
1119
+ if (audience) claims.aud = audience;
1120
+ const payload = JSON.stringify(claims);
1076
1121
  const headerB64 = base64UrlEncode(encoder.encode(header));
1077
1122
  const payloadB64 = base64UrlEncode(encoder.encode(payload));
1078
1123
  const signingInput = `${headerB64}.${payloadB64}`;
@@ -1085,7 +1130,7 @@ function createEdDSAJWT(privateKey, lifetimeSeconds = 300) {
1085
1130
  var Auth = class {
1086
1131
  };
1087
1132
  var NoAuth = class extends Auth {
1088
- apply(_headers) {
1133
+ apply(_headers, _audience) {
1089
1134
  }
1090
1135
  };
1091
1136
  var BearerAuth = class extends Auth {
@@ -1093,11 +1138,22 @@ var BearerAuth = class extends Auth {
1093
1138
  super();
1094
1139
  this._token = token;
1095
1140
  }
1096
- apply(headers) {
1141
+ apply(headers, _audience) {
1097
1142
  headers["Authorization"] = `Bearer ${this._token}`;
1098
1143
  }
1099
1144
  };
1100
- var KeyPairAuth = class _KeyPairAuth extends Auth {
1145
+ var BasicAuth = class extends Auth {
1146
+ constructor(username, password) {
1147
+ super();
1148
+ this._username = username;
1149
+ this._password = password;
1150
+ }
1151
+ apply(headers, _audience) {
1152
+ const credentials = Buffer.from(`${this._username}:${this._password}`, "utf-8").toString("base64");
1153
+ headers["Authorization"] = `Basic ${credentials}`;
1154
+ }
1155
+ };
1156
+ var Ed25519Auth = class _Ed25519Auth extends Auth {
1101
1157
  /**
1102
1158
  * @param privateKey - 32-byte Ed25519 private key
1103
1159
  * @param tokenLifetimeSeconds - JWT lifetime in seconds (default 300 = 5 min)
@@ -1109,28 +1165,39 @@ var KeyPairAuth = class _KeyPairAuth extends Auth {
1109
1165
  this._did = didFromPublicKey(this._publicKey);
1110
1166
  this._lifetime = tokenLifetimeSeconds;
1111
1167
  }
1112
- apply(headers) {
1113
- const jwt = createEdDSAJWT(this._privateKey, this._lifetime);
1168
+ apply(headers, audience) {
1169
+ const jwt = createEdDSAJWT(this._privateKey, this._lifetime, this._audience ?? audience);
1114
1170
  headers["Authorization"] = `Bearer ${jwt}`;
1115
1171
  }
1116
1172
  /** The caller's DID derived from the public key. */
1117
1173
  getDID() {
1118
1174
  return this._did;
1119
1175
  }
1176
+ /**
1177
+ * Explicitly pin the JWT `aud` claim. Overrides the venue DID the transport
1178
+ * supplies — normally unnecessary, since the venue DID is the correct audience.
1179
+ */
1180
+ set audience(value) {
1181
+ this._audience = value;
1182
+ }
1183
+ get audience() {
1184
+ return this._audience;
1185
+ }
1120
1186
  /** The 32-byte Ed25519 public key. */
1121
1187
  getPublicKey() {
1122
1188
  return this._publicKey;
1123
1189
  }
1124
- /** Generate a new random keypair and return a KeyPairAuth instance. */
1190
+ /** Generate a new random keypair and return an Ed25519Auth instance. */
1125
1191
  static generate(tokenLifetimeSeconds = 300) {
1126
1192
  const { privateKey } = generateKeyPair();
1127
- return new _KeyPairAuth(privateKey, tokenLifetimeSeconds);
1193
+ return new _Ed25519Auth(privateKey, tokenLifetimeSeconds);
1128
1194
  }
1129
1195
  /** Create from a hex-encoded private key string. */
1130
1196
  static fromHex(privateKeyHex, tokenLifetimeSeconds = 300) {
1131
- return new _KeyPairAuth(hexToPrivateKey(privateKeyHex), tokenLifetimeSeconds);
1197
+ return new _Ed25519Auth(hexToPrivateKey(privateKeyHex), tokenLifetimeSeconds);
1132
1198
  }
1133
1199
  };
1200
+ var KeyPairAuth = Ed25519Auth;
1134
1201
  var CredentialsHTTP = class {
1135
1202
  constructor(venueId, apiKey, userId) {
1136
1203
  this.venueId = venueId;
@@ -1153,14 +1220,70 @@ var logger = {
1153
1220
  }
1154
1221
  };
1155
1222
 
1223
+ // src/did.ts
1224
+ var Namespace = {
1225
+ ASSET: "a",
1226
+ OPERATION: "o",
1227
+ JOB: "j",
1228
+ AGENT: "g",
1229
+ WORKSPACE: "w",
1230
+ SECRET: "s",
1231
+ // Virtual namespaces — resolved against the active request context:
1232
+ AGENT_SCRATCH: "n",
1233
+ SESSION_SCRATCH: "c",
1234
+ JOB_SCRATCH: "t",
1235
+ VENUE: "v"
1236
+ };
1237
+ function isDid(value) {
1238
+ if (value.includes("/")) return false;
1239
+ const parts = value.split(":");
1240
+ return parts.length >= 3 && parts[0] === "did" && parts.slice(1).every((p) => p.length > 0);
1241
+ }
1242
+ function didMethod(value) {
1243
+ return isDid(value) ? value.split(":")[1] : null;
1244
+ }
1245
+ function parseDidUrl(value) {
1246
+ let did = null;
1247
+ let rest;
1248
+ if (value.startsWith("did:")) {
1249
+ const slash2 = value.indexOf("/");
1250
+ if (slash2 === -1) return { did: value, namespace: null, path: "" };
1251
+ did = value.slice(0, slash2);
1252
+ rest = value.slice(slash2 + 1);
1253
+ } else {
1254
+ rest = value.replace(/^\/+/, "");
1255
+ }
1256
+ if (rest === "") return { did, namespace: null, path: "" };
1257
+ const slash = rest.indexOf("/");
1258
+ if (slash === -1) return { did, namespace: rest, path: "" };
1259
+ return { did, namespace: rest.slice(0, slash), path: rest.slice(slash + 1) };
1260
+ }
1261
+ function didUrl(did, namespace, ...segments) {
1262
+ const tail = segments.filter((s) => s !== "").map((s) => s.replace(/^\/+|\/+$/g, "")).join("/");
1263
+ const base = tail ? `${namespace}/${tail}` : namespace;
1264
+ return did ? `${did}/${base}` : base;
1265
+ }
1266
+ function assetHash(ref) {
1267
+ if (!ref.includes("/")) {
1268
+ const s = ref.startsWith("0x") ? ref.slice(2) : ref;
1269
+ return s.length > 0 && /^[0-9a-fA-F]+$/.test(s) ? ref : null;
1270
+ }
1271
+ const parsed = parseDidUrl(ref);
1272
+ if (parsed.namespace === Namespace.ASSET && parsed.path && !parsed.path.includes("/")) {
1273
+ return parsed.path;
1274
+ }
1275
+ return null;
1276
+ }
1277
+
1156
1278
  // src/Utils.ts
1157
1279
  async function parseErrorBody(response) {
1158
1280
  let body = null;
1159
1281
  let message = `Request failed with status ${response.status}`;
1160
1282
  try {
1161
1283
  body = await response.json();
1162
- if (body?.error) {
1163
- message = body.error;
1284
+ if (body && typeof body === "object" && "error" in body) {
1285
+ const err2 = body.error;
1286
+ if (typeof err2 === "string") message = err2;
1164
1287
  }
1165
1288
  } catch {
1166
1289
  try {
@@ -1221,9 +1344,7 @@ async function fetchStreamWithError(url, options) {
1221
1344
  return response;
1222
1345
  }
1223
1346
  function isJobComplete(jobStatus) {
1224
- if (jobStatus == null)
1225
- return false;
1226
- return jobStatus == "COMPLETE" /* COMPLETE */ ? true : false;
1347
+ return jobStatus === "COMPLETE" /* COMPLETE */;
1227
1348
  }
1228
1349
  function isJobPaused(jobStatus) {
1229
1350
  if (jobStatus == null)
@@ -1241,18 +1362,20 @@ function isJobFinished(jobStatus) {
1241
1362
  return false;
1242
1363
  }
1243
1364
  function getParsedAssetId(assetId) {
1244
- if (assetId.startsWith("did:web")) {
1365
+ if (assetId.startsWith("did:")) {
1245
1366
  const parts = assetId.split("/");
1246
1367
  return parts[parts.length - 1];
1247
1368
  }
1248
1369
  return assetId;
1249
1370
  }
1250
1371
  function getAssetIdFromPath(assetHex, assetPath) {
1251
- const venueDid = decodeURIComponent(assetPath.split("/")[4]);
1252
- return venueDid + "/a/" + assetHex;
1372
+ const parts = assetPath.split("/");
1373
+ const i = parts.indexOf("assets");
1374
+ const venueDid = decodeURIComponent(i >= 0 && i + 1 < parts.length ? parts[i + 1] : "");
1375
+ return getAssetIdFromVenueId(assetHex, venueDid);
1253
1376
  }
1254
1377
  function getAssetIdFromVenueId(assetHex, venueId) {
1255
- return venueId + "/a/" + assetHex;
1378
+ return didUrl(venueId, Namespace.ASSET, assetHex);
1256
1379
  }
1257
1380
  function createSSEEvent(fields) {
1258
1381
  const data = fields.data ?? "";
@@ -1372,21 +1495,6 @@ var AgentManager = class {
1372
1495
  async trigger(agentId) {
1373
1496
  return this.venue.operations.run("v/ops/agent/trigger", { agentId });
1374
1497
  }
1375
- async query(agentId) {
1376
- const read = (path) => this.venue.operations.run("v/ops/covia/read", { path }).catch(() => ({ value: null }));
1377
- const [info, timelineRes, stateRes, inboxRes] = await Promise.all([
1378
- this.venue.operations.run("v/ops/agent/info", { agentId }),
1379
- read(`g/${agentId}/timeline`),
1380
- read(`g/${agentId}/state`),
1381
- read(`g/${agentId}/inbox`)
1382
- ]);
1383
- return {
1384
- ...info,
1385
- timeline: Array.isArray(timelineRes.value) ? timelineRes.value : [],
1386
- state: stateRes.value ?? {},
1387
- inbox: Array.isArray(inboxRes.value) ? inboxRes.value : []
1388
- };
1389
- }
1390
1498
  async list(includeTerminated) {
1391
1499
  return this.venue.operations.run("v/ops/agent/list", { includeTerminated });
1392
1500
  }
@@ -1664,13 +1772,12 @@ var JobManager = class {
1664
1772
  }
1665
1773
  _buildHeaders() {
1666
1774
  const headers = { "Content-Type": "application/json" };
1667
- this.venue.auth.apply(headers);
1775
+ this.venue.auth.apply(headers, this.venue.venueId);
1668
1776
  return headers;
1669
1777
  }
1670
1778
  };
1671
1779
 
1672
1780
  // src/Asset.ts
1673
- var cache = /* @__PURE__ */ new Map();
1674
1781
  var Asset = class {
1675
1782
  constructor(id, venue, metadata = {}) {
1676
1783
  this.id = id;
@@ -1683,16 +1790,8 @@ var Asset = class {
1683
1790
  * Get asset metadata
1684
1791
  * @returns {Promise<AssetMetadata>}
1685
1792
  */
1686
- async getMetadata() {
1687
- if (cache.has(this.id)) {
1688
- return Promise.resolve(cache.get(this.id));
1689
- } else {
1690
- const data = this._assets.getMetadata(this.id);
1691
- if (data) {
1692
- cache.set(this.id, data);
1693
- }
1694
- return data;
1695
- }
1793
+ getMetadata() {
1794
+ return this._assets.getMetadata(this.id);
1696
1795
  }
1697
1796
  /**
1698
1797
  * Put content to asset
@@ -1717,20 +1816,22 @@ var Asset = class {
1717
1816
  return `${this.venue.baseUrl}/api/v1/assets/${this.id}/content`;
1718
1817
  }
1719
1818
  /**
1720
- * Execute the operation
1819
+ * Execute the operation and await its result.
1721
1820
  * @param input - Operation input parameters
1722
- * @returns {Promise<any>}
1821
+ * @param options - Invocation options (e.g. UCAN proofs)
1822
+ * @returns {Promise<T>} The operation result, typed as `T` (defaults to `unknown`)
1723
1823
  */
1724
- run(input) {
1725
- return this._operations.run(this.id, input);
1824
+ run(input, options) {
1825
+ return this._operations.run(this.id, input, options);
1726
1826
  }
1727
1827
  /**
1728
- * Execute the operation
1729
- * @param input - Operation input parameters
1730
- * @returns {Promise<Job>}
1731
- */
1732
- invoke(input) {
1733
- return this._operations.invoke(this.id, input);
1828
+ * Execute the operation, returning the Job without awaiting completion.
1829
+ * @param input - Operation input parameters
1830
+ * @param options - Invocation options (e.g. UCAN proofs)
1831
+ * @returns {Promise<Job>}
1832
+ */
1833
+ invoke(input, options) {
1834
+ return this._operations.invoke(this.id, input, options);
1734
1835
  }
1735
1836
  };
1736
1837
 
@@ -1753,20 +1854,25 @@ var DataAsset = class extends Asset {
1753
1854
  };
1754
1855
 
1755
1856
  // src/AssetManager.ts
1756
- var cache2 = /* @__PURE__ */ new Map();
1857
+ var cache = /* @__PURE__ */ new Map();
1757
1858
  var AssetManager = class {
1758
1859
  constructor(venue) {
1759
1860
  this.venue = venue;
1760
1861
  }
1761
1862
  /**
1762
- * Get asset by ID
1763
- * @param assetId - Asset identifier
1863
+ * Get an asset by lattice address.
1864
+ *
1865
+ * `assetId` may be a content hash (`<hash>`, `a/<hash>`, `<DID>/a/<hash>`) or
1866
+ * a mutable lattice path the venue resolves (`w/my-assets/foo`, `o/my-op`,
1867
+ * `<DID>/w/...`). Only content-addressed (immutable) refs are cached;
1868
+ * mutable paths are always re-fetched, so a changed value is never served stale.
1869
+ * @param assetId - Asset identifier or lattice address
1764
1870
  * @returns Returns either an Operation or DataAsset based on the asset's metadata
1765
1871
  */
1766
1872
  async get(assetId) {
1767
- if (cache2.has(assetId)) {
1768
- const cachedData = cache2.get(assetId);
1769
- if (cachedData.metadata?.operation) {
1873
+ if (cache.has(assetId)) {
1874
+ const cachedData = cache.get(assetId);
1875
+ if (cachedData.operation) {
1770
1876
  return new Operation(assetId, this.venue, cachedData);
1771
1877
  } else {
1772
1878
  return new DataAsset(assetId, this.venue, cachedData);
@@ -1774,8 +1880,8 @@ var AssetManager = class {
1774
1880
  }
1775
1881
  try {
1776
1882
  const data = await fetchWithError(`${this.venue.baseUrl}/api/v1/assets/${assetId}`);
1777
- cache2.set(assetId, data);
1778
- if (data.metadata?.operation) {
1883
+ if (assetHash(assetId)) cache.set(assetId, data);
1884
+ if (data.operation) {
1779
1885
  return new Operation(assetId, this.venue, data);
1780
1886
  } else {
1781
1887
  return new DataAsset(assetId, this.venue, data);
@@ -1834,7 +1940,7 @@ var AssetManager = class {
1834
1940
  try {
1835
1941
  return await fetchWithError(`${this.venue.baseUrl}/api/v1/assets/${assetId}/content`, {
1836
1942
  method: "PUT",
1837
- headers: this._buildHeaders(),
1943
+ headers: this._buildHeaders(null),
1838
1944
  body: content
1839
1945
  });
1840
1946
  } catch (error) {
@@ -1871,11 +1977,15 @@ var AssetManager = class {
1871
1977
  * Clear the asset cache.
1872
1978
  */
1873
1979
  clearCache() {
1874
- cache2.clear();
1875
- }
1876
- _buildHeaders() {
1877
- const headers = { "Content-Type": "application/json" };
1878
- this.venue.auth.apply(headers);
1980
+ cache.clear();
1981
+ }
1982
+ // `contentType` defaults to JSON for the metadata/register endpoints. Pass
1983
+ // `undefined` for binary content upload so fetch infers the type from the
1984
+ // body — forcing application/json would mislabel a Blob/ArrayBuffer/stream.
1985
+ _buildHeaders(contentType = "application/json") {
1986
+ const headers = {};
1987
+ if (contentType) headers["Content-Type"] = contentType;
1988
+ this.venue.auth.apply(headers, this.venue.venueId);
1879
1989
  return headers;
1880
1990
  }
1881
1991
  };
@@ -1906,7 +2016,7 @@ var OperationManager = class {
1906
2016
  */
1907
2017
  async run(assetId, input, options) {
1908
2018
  const job = await this.invoke(assetId, input, options);
1909
- return job.result();
2019
+ return await job.result();
1910
2020
  }
1911
2021
  /**
1912
2022
  * Execute an operation and return a Job for tracking
@@ -1927,43 +2037,121 @@ var OperationManager = class {
1927
2037
  headers: this._buildHeaders(),
1928
2038
  body: JSON.stringify(payload)
1929
2039
  });
1930
- return new Job(response?.id, this.venue, response);
2040
+ return new Job(response.id ?? "", this.venue, response);
1931
2041
  }
1932
2042
  _buildHeaders() {
1933
2043
  const headers = { "Content-Type": "application/json" };
1934
- this.venue.auth.apply(headers);
2044
+ this.venue.auth.apply(headers, this.venue.venueId);
1935
2045
  return headers;
1936
2046
  }
1937
2047
  };
1938
2048
 
1939
2049
  // src/WorkspaceManager.ts
2050
+ function versionAtLeast(version, major, minor) {
2051
+ const m = version?.match(/^(\d+)\.(\d+)/);
2052
+ if (!m) return true;
2053
+ const [maj, min] = [Number(m[1]), Number(m[2])];
2054
+ return maj > major || maj === major && min >= minor;
2055
+ }
1940
2056
  var WorkspaceManager = class {
1941
2057
  constructor(venue) {
1942
2058
  this.venue = venue;
2059
+ // Whether this venue serves GET /api/v1/values/* — flipped on the first 404
2060
+ // so pre-0.3 venues pay the probe once, not one failed GET per read.
2061
+ this.valuesSupported = true;
1943
2062
  }
1944
- async read(path, maxSize) {
1945
- return this.venue.operations.run("v/ops/covia/read", { path, maxSize });
2063
+ _headers() {
2064
+ const headers = { "Content-Type": "application/json" };
2065
+ this.venue.auth.apply(headers, this.venue.venueId);
2066
+ return headers;
1946
2067
  }
1947
- async write(path, value) {
1948
- return this.venue.operations.run("v/ops/covia/write", { path, value });
2068
+ /** GET a job-free `/api/v1/values/{op}` read; omit undefined params. */
2069
+ _values(op, params) {
2070
+ const qs = new URLSearchParams();
2071
+ for (const [k, v] of Object.entries(params)) if (v !== void 0) qs.set(k, String(v));
2072
+ return fetchWithError(`${this.venue.baseUrl}/api/v1/values/${op}?${qs.toString()}`, { headers: this._headers() });
1949
2073
  }
1950
- async delete(path) {
1951
- return this.venue.operations.run("v/ops/covia/delete", { path });
2074
+ /**
2075
+ * Whether the venue serves `GET /api/v1/values/*`: no if a probe already
2076
+ * 404'd, or if the venue's last known status identifies it as pre-0.3
2077
+ * (venues that old don't report a `version` at all). Checked per read —
2078
+ * connect/`status()` may populate the status after this manager exists.
2079
+ */
2080
+ supportsValues() {
2081
+ if (!this.valuesSupported) return false;
2082
+ const status = this.venue.lastKnownStatus;
2083
+ if (status && (!status.version || !versionAtLeast(status.version, 0, 3))) {
2084
+ this.valuesSupported = false;
2085
+ }
2086
+ return this.valuesSupported;
2087
+ }
2088
+ /** A job-free values read, falling back to the invoke path on pre-0.3 venues. */
2089
+ async _valuesOr(op, params, fallback) {
2090
+ if (this.supportsValues()) {
2091
+ try {
2092
+ return await this._values(op, params);
2093
+ } catch (e) {
2094
+ if (!(e instanceof NotFoundError)) throw e;
2095
+ this.valuesSupported = false;
2096
+ }
2097
+ }
2098
+ return fallback();
2099
+ }
2100
+ // ── job-free reads (#177) ───────────────────────────────────────────────────
2101
+ async read(path, maxSize, ucans) {
2102
+ if (ucans?.length) return this.venue.operations.run("v/ops/covia/read", { path, maxSize }, { ucans });
2103
+ return this._valuesOr("read", { path, maxSize }, () => this.venue.operations.run("v/ops/covia/read", { path, maxSize }));
2104
+ }
2105
+ async list(path, limit, offset, ucans) {
2106
+ if (ucans?.length || !path) return this.venue.operations.run("v/ops/covia/list", { path, limit, offset }, { ucans });
2107
+ return this._valuesOr("list", { path, limit, offset }, () => this.venue.operations.run("v/ops/covia/list", { path, limit, offset }));
2108
+ }
2109
+ async slice(path, offset, limit, ucans) {
2110
+ if (ucans?.length) return this.venue.operations.run("v/ops/covia/slice", { path, offset, limit }, { ucans });
2111
+ return this._valuesOr("slice", { path, offset, limit }, () => this.venue.operations.run("v/ops/covia/slice", { path, offset, limit }));
1952
2112
  }
1953
- async append(path, value) {
1954
- return this.venue.operations.run("v/ops/covia/append", { path, value });
2113
+ async inspect(paths, budget, compact, ucans) {
2114
+ if (ucans?.length || Array.isArray(paths)) return this.venue.operations.run("v/ops/covia/inspect", { paths, budget, compact }, { ucans });
2115
+ return this._valuesOr("inspect", { path: paths, budget, compact }, () => this.venue.operations.run("v/ops/covia/inspect", { paths, budget, compact }));
2116
+ }
2117
+ /**
2118
+ * Count entries at a depth below `path` — a job-free server-side tally, so the
2119
+ * caller never reads every record to learn "how many".
2120
+ *
2121
+ * `depth` = the exact number of `get`-steps below `path` to visit (default 1 =
2122
+ * direct children). Records nested at `w/x/<bucket>/<record>` are counted with
2123
+ * `depth: 2`. Absent path or a scalar → `{exists:false}`.
2124
+ */
2125
+ async count(path, opts = {}) {
2126
+ const { depth, ucans } = opts;
2127
+ if (ucans?.length) return this.venue.operations.run("v/ops/covia/aggregate", { path, depth }, { ucans });
2128
+ return this._valuesOr("count", { path, depth }, () => this.venue.operations.run("v/ops/covia/aggregate", { path, depth }));
2129
+ }
2130
+ /**
2131
+ * Count entries at a depth below `path`, optionally partitioned by a field —
2132
+ * the job-free, authoritative alternative to counting client-side.
2133
+ *
2134
+ * `groupBy` names the field whose value forms each group key (may be a relative
2135
+ * path, `foo/bar`); an entry missing it groups under `"null"`. Σ(group counts)
2136
+ * equals the top-level `count`.
2137
+ */
2138
+ async aggregate(path, opts = {}) {
2139
+ const { depth, groupBy, ucans } = opts;
2140
+ if (ucans?.length) return this.venue.operations.run("v/ops/covia/aggregate", { path, depth, groupBy }, { ucans });
2141
+ return this._valuesOr("aggregate", { path, depth, groupBy }, () => this.venue.operations.run("v/ops/covia/aggregate", { path, depth, groupBy }));
1955
2142
  }
1956
- async list(path, limit, offset) {
1957
- return this.venue.operations.run("v/ops/covia/list", { path, limit, offset });
2143
+ // ── writes stay on the job path (they should leave an audit record) ─────────
2144
+ async write(path, value, ucans) {
2145
+ return this.venue.operations.run("v/ops/covia/write", { path, value }, { ucans });
1958
2146
  }
1959
- async slice(path, offset, limit) {
1960
- return this.venue.operations.run("v/ops/covia/slice", { path, offset, limit });
2147
+ async delete(path, ucans) {
2148
+ return this.venue.operations.run("v/ops/covia/delete", { path }, { ucans });
1961
2149
  }
1962
- async copy(from, to) {
1963
- return this.venue.operations.run("v/ops/covia/copy", { from, to });
2150
+ async append(path, value, ucans) {
2151
+ return this.venue.operations.run("v/ops/covia/append", { path, value }, { ucans });
1964
2152
  }
1965
- async inspect(paths, budget, compact) {
1966
- return this.venue.operations.run("v/ops/covia/inspect", { paths, budget, compact });
2153
+ async copy(from, to, ucans) {
2154
+ return this.venue.operations.run("v/ops/covia/copy", { from, to }, { ucans });
1967
2155
  }
1968
2156
  };
1969
2157
 
@@ -1987,18 +2175,15 @@ var SecretManager = class {
1987
2175
  }
1988
2176
  /**
1989
2177
  * Extract a secret value by name.
1990
- * NOTE: This operation requires a UCAN capability grant. The backend
1991
- * may reject requests that lack the appropriate capability proof.
2178
+ * Requires a UCAN capability grant pass the proof token(s) as `ucans`.
2179
+ * Extracting another DID's secret needs a grant on that DID's `/s/<name>`.
1992
2180
  */
1993
- async extract(name) {
1994
- return this.venue.operations.run("v/ops/secret/extract", { name });
2181
+ async extract(name, ucans) {
2182
+ return this.venue.operations.run("v/ops/secret/extract", { name }, { ucans });
1995
2183
  }
1996
2184
  async list() {
1997
2185
  return this.venue.listSecrets();
1998
2186
  }
1999
- async put(name, value) {
2000
- return this.venue.putSecret(name, value);
2001
- }
2002
2187
  async delete(name) {
2003
2188
  return this.venue.deleteSecret(name);
2004
2189
  }
@@ -2030,9 +2215,6 @@ var Agent = class _Agent {
2030
2215
  async trigger() {
2031
2216
  return this._agents.trigger(this.id);
2032
2217
  }
2033
- async query() {
2034
- return this._agents.query(this.id);
2035
- }
2036
2218
  async suspend() {
2037
2219
  return this._agents.suspend(this.id);
2038
2220
  }
@@ -2089,6 +2271,33 @@ var ChatSession = class {
2089
2271
  // src/Venue.ts
2090
2272
  var webResolver = webDidResolver.getResolver();
2091
2273
  var resolver = new didResolver.Resolver(webResolver);
2274
+ function stripTrailingSlash(value) {
2275
+ return value.endsWith("/") ? value.slice(0, -1) : value;
2276
+ }
2277
+ function hostIsLocal(host) {
2278
+ const h2 = host.toLowerCase();
2279
+ if (h2 === "localhost" || h2.endsWith(".localhost") || h2.endsWith(".local")) return true;
2280
+ if (h2 === "::1" || h2 === "0.0.0.0") return true;
2281
+ if (/^127\./.test(h2)) return true;
2282
+ if (/^10\./.test(h2)) return true;
2283
+ if (/^192\.168\./.test(h2)) return true;
2284
+ if (/^172\.(1[6-9]|2\d|3[01])\./.test(h2)) return true;
2285
+ if (/^169\.254\./.test(h2)) return true;
2286
+ return false;
2287
+ }
2288
+ function schemelessVenueCandidates(venueId) {
2289
+ const authority = venueId.split("/")[0];
2290
+ const v6 = authority.match(/^\[([^\]]+)\]/);
2291
+ const host = v6 ? v6[1] : authority.split(":")[0];
2292
+ const bare = stripTrailingSlash(venueId);
2293
+ return hostIsLocal(host) ? [`http://${bare}`, `https://${bare}`] : [`https://${bare}`];
2294
+ }
2295
+ function venueBaseUrlCandidates(venueId) {
2296
+ if (venueId.startsWith("http:") || venueId.startsWith("https:")) {
2297
+ return [stripTrailingSlash(venueId)];
2298
+ }
2299
+ return schemelessVenueCandidates(venueId);
2300
+ }
2092
2301
  var Venue = class _Venue {
2093
2302
  get agents() {
2094
2303
  return this._agents ?? (this._agents = new AgentManager(this));
@@ -2115,16 +2324,32 @@ var Venue = class _Venue {
2115
2324
  this.baseUrl = options.baseUrl || "";
2116
2325
  this.venueId = options.venueId || "";
2117
2326
  this.auth = options.auth || new NoAuth();
2327
+ this.lastKnownStatus = options.status;
2118
2328
  this.metadata = {
2119
2329
  name: options.name || "default",
2120
2330
  description: options.description || ""
2121
2331
  };
2122
2332
  }
2123
2333
  /**
2124
- * Static method to connect to a venue
2125
- * @param venueId - Can be a HTTP base URL, DNS name, or existing Venue instance
2126
- * @param credentials - Optional credentials for venue authentication
2127
- * @returns {Promise<Venue>} A new Venue instance configured appropriately
2334
+ * Connect to a venue, validating it with `GET {base}/api/v1/status`. If the
2335
+ * venue is auth-gated (status answers 401/403 public access disabled), the
2336
+ * venue is validated against its public did:web document at
2337
+ * `/.well-known/did.json` instead, whose `id` becomes `venueId` identity is
2338
+ * publicly resolvable by spec even when the API is not.
2339
+ *
2340
+ * The input is permissive: a full `http(s)://` URL, a bare host / IP /
2341
+ * host:port, a `did:web:` id, or an existing Venue instance. Schemeless inputs
2342
+ * pick a scheme by host and may fall back across http/https (see
2343
+ * {@link venueBaseUrlCandidates}); did:web ids resolve to their `Covia.API.v1`
2344
+ * endpoint.
2345
+ *
2346
+ * @param venueId - A venue URL, DNS name / host:port, `did:web:` id, or existing Venue
2347
+ * @param auth - Optional credentials for venue authentication
2348
+ * @returns {Promise<Venue>} A connected venue. The actually resolved/validated
2349
+ * target is on the returned object: `venue.baseUrl` is the origin that
2350
+ * responded (the https candidate if an http fallback failed; the resolved
2351
+ * endpoint for a did:web id), and `venue.venueId` is the DID the venue
2352
+ * reported. The validated API root is `${venue.baseUrl}/api/v1`.
2128
2353
  */
2129
2354
  static async connect(venueId, auth) {
2130
2355
  if (venueId instanceof _Venue) {
@@ -2132,35 +2357,50 @@ var Venue = class _Venue {
2132
2357
  baseUrl: venueId.baseUrl,
2133
2358
  venueId: venueId.venueId,
2134
2359
  name: venueId.metadata.name,
2135
- auth
2360
+ auth,
2361
+ status: venueId.lastKnownStatus
2136
2362
  });
2137
2363
  }
2138
2364
  if (typeof venueId === "string") {
2139
- let baseUrl;
2140
- if (venueId.startsWith("http:") || venueId.startsWith("https:")) {
2141
- baseUrl = venueId;
2142
- if (baseUrl.endsWith("/"))
2143
- baseUrl = baseUrl.substring(0, baseUrl.length - 1);
2144
- } else if (venueId.startsWith("did:web:")) {
2365
+ let candidates;
2366
+ if (venueId.startsWith("did:web:")) {
2145
2367
  const didDoc = await resolver.resolve(venueId);
2146
2368
  if (!didDoc.didDocument) {
2147
2369
  throw new CoviaError("Invalid DID document");
2148
2370
  }
2149
2371
  const endpoint = didDoc.didDocument.service?.find((service) => service.type === "Covia.API.v1")?.serviceEndpoint;
2150
- if (!endpoint) {
2151
- throw new CoviaError("No endpoint found for DID");
2372
+ if (typeof endpoint !== "string") {
2373
+ throw new CoviaError("No (string) endpoint found for DID");
2152
2374
  }
2153
- baseUrl = endpoint.toString().replace(/\/api\/v1/, "");
2375
+ candidates = [endpoint.replace(/\/api\/v1/, "")];
2154
2376
  } else {
2155
- baseUrl = `https://${venueId}`;
2377
+ candidates = venueBaseUrlCandidates(venueId);
2156
2378
  }
2157
- const data = await fetchWithError(baseUrl + "/api/v1/status");
2158
- return new _Venue({
2159
- baseUrl,
2160
- venueId: data.did,
2161
- name: data.name,
2162
- auth
2163
- });
2379
+ let lastError;
2380
+ for (const baseUrl of candidates) {
2381
+ try {
2382
+ const data = await fetchWithError(baseUrl + "/api/v1/status");
2383
+ return new _Venue({
2384
+ baseUrl,
2385
+ venueId: data.did,
2386
+ name: data.name,
2387
+ auth,
2388
+ status: data
2389
+ });
2390
+ } catch (error) {
2391
+ if (error instanceof GridError && (error.statusCode === 401 || error.statusCode === 403)) {
2392
+ try {
2393
+ const doc = await fetchWithError(baseUrl + "/.well-known/did.json");
2394
+ if (doc?.id) {
2395
+ return new _Venue({ baseUrl, venueId: doc.id, auth });
2396
+ }
2397
+ } catch {
2398
+ }
2399
+ }
2400
+ lastError = error;
2401
+ }
2402
+ }
2403
+ throw lastError instanceof Error ? lastError : new CoviaError(`Could not connect to venue: ${venueId}`);
2164
2404
  }
2165
2405
  throw new CoviaError("Invalid venue ID parameter. Must be a string (URL/DNS) or Venue instance.");
2166
2406
  }
@@ -2214,18 +2454,6 @@ var Venue = class _Venue {
2214
2454
  });
2215
2455
  return Array.isArray(result.items) ? result.items : [];
2216
2456
  }
2217
- /**
2218
- * Store a secret value
2219
- * @param name - Secret name
2220
- * @param value - Secret value
2221
- */
2222
- async putSecret(name, value) {
2223
- await fetchWithError(`${this.baseUrl}/api/v1/secrets/${encodeURIComponent(name)}`, {
2224
- method: "PUT",
2225
- headers: this._buildHeaders(),
2226
- body: JSON.stringify({ value })
2227
- });
2228
- }
2229
2457
  /**
2230
2458
  * Delete a secret
2231
2459
  * @param name - Secret name
@@ -2240,8 +2468,39 @@ var Venue = class _Venue {
2240
2468
  * Get venue status
2241
2469
  * @returns {Promise<StatusData>}
2242
2470
  */
2243
- status() {
2244
- return fetchWithError(`${this.baseUrl}/api/v1/status`);
2471
+ async status() {
2472
+ const data = await fetchWithError(`${this.baseUrl}/api/v1/status`);
2473
+ this.lastKnownStatus = data;
2474
+ return data;
2475
+ }
2476
+ /**
2477
+ * Block until the venue is ready to serve operations.
2478
+ *
2479
+ * Polls {@link status} until it responds and reports either no explicit
2480
+ * `status` or `"OK"`. Connection/HTTP errors are treated as "not ready yet"
2481
+ * and retried until `timeoutMs` elapses — useful right after starting a venue,
2482
+ * since a cold venue may answer its root before its invoke layer is up.
2483
+ *
2484
+ * @param options.timeoutMs - Max time to wait (default 60000).
2485
+ * @param options.pollIntervalMs - Delay between polls (default 1000).
2486
+ * @returns The ready {@link StatusData}.
2487
+ * @throws {CoviaTimeoutError} If the venue is not ready within the timeout.
2488
+ */
2489
+ async waitUntilReady(options = {}) {
2490
+ const timeoutMs = options.timeoutMs ?? 6e4;
2491
+ const pollIntervalMs = options.pollIntervalMs ?? 1e3;
2492
+ const start = Date.now();
2493
+ for (; ; ) {
2494
+ try {
2495
+ const data = await this.status();
2496
+ if (data.status == null || data.status.toUpperCase() === "OK") return data;
2497
+ } catch {
2498
+ }
2499
+ if (Date.now() - start >= timeoutMs) {
2500
+ throw new CoviaTimeoutError(`Venue ${this.baseUrl} not ready within ${timeoutMs}ms`);
2501
+ }
2502
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
2503
+ }
2245
2504
  }
2246
2505
  /**
2247
2506
  * Get the full DID document for this venue
@@ -2279,35 +2538,33 @@ var Venue = class _Venue {
2279
2538
  }
2280
2539
  _buildHeaders() {
2281
2540
  const headers = { "Content-Type": "application/json" };
2282
- this.auth.apply(headers);
2541
+ this.auth.apply(headers, this.venueId);
2283
2542
  return headers;
2284
2543
  }
2285
2544
  };
2286
2545
 
2287
2546
  // src/Grid.ts
2288
- var cache3 = /* @__PURE__ */ new Map();
2547
+ var cache2 = /* @__PURE__ */ new Map();
2289
2548
  var Grid = class {
2290
2549
  /**
2291
2550
  * Static method to connect to a venue
2292
2551
  * @param venueId - Can be a HTTP base URL, DNS name, or existing Venue instance
2293
- * @param auth - Optional authentication provider (BearerAuth, KeyPairAuth, etc.)
2552
+ * @param auth - Optional authentication provider (BearerAuth, BasicAuth, Ed25519Auth, etc.)
2294
2553
  * @returns {Promise<Venue>} A new Venue instance configured appropriately
2295
2554
  */
2296
2555
  static async connect(venueId, auth) {
2297
- if (cache3.has(venueId))
2298
- return Promise.resolve(cache3.get(venueId));
2556
+ const cached = cache2.get(venueId);
2557
+ if (cached && cached.auth === auth)
2558
+ return cached.venue;
2299
2559
  const connectedVenue = await Venue.connect(venueId, auth);
2300
- cache3.set(venueId, connectedVenue);
2301
- return Promise.resolve(connectedVenue);
2560
+ cache2.set(venueId, { auth, venue: connectedVenue });
2561
+ return connectedVenue;
2302
2562
  }
2303
2563
  };
2304
2564
  /*! Bundled license information:
2305
2565
 
2306
2566
  @noble/ed25519/index.js:
2307
2567
  (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
2308
-
2309
- @noble/hashes/esm/utils.js:
2310
- (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
2311
2568
  */
2312
2569
 
2313
2570
  exports.Agent = Agent;
@@ -2317,6 +2574,7 @@ exports.Asset = Asset;
2317
2574
  exports.AssetManager = AssetManager;
2318
2575
  exports.AssetNotFoundError = AssetNotFoundError;
2319
2576
  exports.Auth = Auth;
2577
+ exports.BasicAuth = BasicAuth;
2320
2578
  exports.BearerAuth = BearerAuth;
2321
2579
  exports.ChatSession = ChatSession;
2322
2580
  exports.CoviaConnectionError = CoviaConnectionError;
@@ -2324,6 +2582,7 @@ exports.CoviaError = CoviaError;
2324
2582
  exports.CoviaTimeoutError = CoviaTimeoutError;
2325
2583
  exports.CredentialsHTTP = CredentialsHTTP;
2326
2584
  exports.DataAsset = DataAsset;
2585
+ exports.Ed25519Auth = Ed25519Auth;
2327
2586
  exports.Grid = Grid;
2328
2587
  exports.GridError = GridError;
2329
2588
  exports.Job = Job;
@@ -2332,6 +2591,7 @@ exports.JobManager = JobManager;
2332
2591
  exports.JobNotFoundError = JobNotFoundError;
2333
2592
  exports.JobStatus = JobStatus;
2334
2593
  exports.KeyPairAuth = KeyPairAuth;
2594
+ exports.Namespace = Namespace;
2335
2595
  exports.NoAuth = NoAuth;
2336
2596
  exports.NotFoundError = NotFoundError;
2337
2597
  exports.Operation = Operation;
@@ -2341,9 +2601,12 @@ exports.SecretManager = SecretManager;
2341
2601
  exports.UCANManager = UCANManager;
2342
2602
  exports.Venue = Venue;
2343
2603
  exports.WorkspaceManager = WorkspaceManager;
2604
+ exports.assetHash = assetHash;
2344
2605
  exports.createSSEEvent = createSSEEvent;
2345
2606
  exports.decodePublicKey = decodePublicKey;
2346
2607
  exports.didFromPublicKey = didFromPublicKey;
2608
+ exports.didMethod = didMethod;
2609
+ exports.didUrl = didUrl;
2347
2610
  exports.encodePublicKey = encodePublicKey;
2348
2611
  exports.fetchStreamWithError = fetchStreamWithError;
2349
2612
  exports.fetchWithError = fetchWithError;
@@ -2352,9 +2615,12 @@ exports.getAssetIdFromPath = getAssetIdFromPath;
2352
2615
  exports.getAssetIdFromVenueId = getAssetIdFromVenueId;
2353
2616
  exports.getParsedAssetId = getParsedAssetId;
2354
2617
  exports.hexToPrivateKey = hexToPrivateKey;
2618
+ exports.isDid = isDid;
2355
2619
  exports.isJobComplete = isJobComplete;
2356
2620
  exports.isJobFinished = isJobFinished;
2357
2621
  exports.isJobPaused = isJobPaused;
2358
2622
  exports.logger = logger;
2623
+ exports.parseDidUrl = parseDidUrl;
2359
2624
  exports.parseSSEStream = parseSSEStream;
2360
2625
  exports.privateKeyToHex = privateKeyToHex;
2626
+ exports.venueBaseUrlCandidates = venueBaseUrlCandidates;