@naylence/agent-sdk 0.3.5 → 0.3.8

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.
@@ -11,21 +11,30 @@
11
11
  });
12
12
  function $constructor(name, initializer, params) {
13
13
  function init(inst, def) {
14
- var _a;
15
- Object.defineProperty(inst, "_zod", {
16
- value: inst._zod ?? {},
17
- enumerable: false,
18
- });
19
- (_a = inst._zod).traits ?? (_a.traits = new Set());
14
+ if (!inst._zod) {
15
+ Object.defineProperty(inst, "_zod", {
16
+ value: {
17
+ def,
18
+ constr: _,
19
+ traits: new Set(),
20
+ },
21
+ enumerable: false,
22
+ });
23
+ }
24
+ if (inst._zod.traits.has(name)) {
25
+ return;
26
+ }
20
27
  inst._zod.traits.add(name);
21
28
  initializer(inst, def);
22
29
  // support prototype modifications
23
- for (const k in _.prototype) {
24
- if (!(k in inst))
25
- Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) });
30
+ const proto = _.prototype;
31
+ const keys = Object.keys(proto);
32
+ for (let i = 0; i < keys.length; i++) {
33
+ const k = keys[i];
34
+ if (!(k in inst)) {
35
+ inst[k] = proto[k].bind(inst);
36
+ }
26
37
  }
27
- inst._zod.constr = _;
28
- inst._zod.def = def;
29
38
  }
30
39
  // doesn't work if Parent has a constructor with arguments
31
40
  const Parent = params?.Parent ?? Object;
@@ -160,6 +169,14 @@
160
169
  function esc(str) {
161
170
  return JSON.stringify(str);
162
171
  }
172
+ function slugify(input) {
173
+ return input
174
+ .toLowerCase()
175
+ .trim()
176
+ .replace(/[^\w\s-]/g, "")
177
+ .replace(/[\s_-]+/g, "-")
178
+ .replace(/^-+|-+$/g, "");
179
+ }
163
180
  const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { });
164
181
  function isObject$2(data) {
165
182
  return typeof data === "object" && data !== null && !Array.isArray(data);
@@ -185,6 +202,8 @@
185
202
  const ctor = o.constructor;
186
203
  if (ctor === undefined)
187
204
  return true;
205
+ if (typeof ctor !== "function")
206
+ return true;
188
207
  // modified prototype
189
208
  const prot = ctor.prototype;
190
209
  if (isObject$2(prot) === false)
@@ -648,9 +667,6 @@
648
667
  // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
649
668
  const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
650
669
  const base64url$1 = /^[A-Za-z0-9_-]*$/;
651
- // based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
652
- // export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
653
- const hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
654
670
  // https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)
655
671
  const e164 = /^\+(?:[0-9]){6,14}[0-9]$/;
656
672
  // const dateSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
@@ -1142,7 +1158,7 @@
1142
1158
  const version = {
1143
1159
  major: 4,
1144
1160
  minor: 1,
1145
- patch: 12,
1161
+ patch: 13,
1146
1162
  };
1147
1163
 
1148
1164
  const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
@@ -1345,7 +1361,7 @@
1345
1361
  code: "invalid_format",
1346
1362
  format: "url",
1347
1363
  note: "Invalid hostname",
1348
- pattern: hostname.source,
1364
+ pattern: def.hostname.source,
1349
1365
  input: payload.value,
1350
1366
  inst,
1351
1367
  continue: !def.abort,
@@ -1435,18 +1451,12 @@
1435
1451
  const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => {
1436
1452
  def.pattern ?? (def.pattern = ipv4);
1437
1453
  $ZodStringFormat.init(inst, def);
1438
- inst._zod.onattach.push((inst) => {
1439
- const bag = inst._zod.bag;
1440
- bag.format = `ipv4`;
1441
- });
1454
+ inst._zod.bag.format = `ipv4`;
1442
1455
  });
1443
1456
  const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => {
1444
1457
  def.pattern ?? (def.pattern = ipv6);
1445
1458
  $ZodStringFormat.init(inst, def);
1446
- inst._zod.onattach.push((inst) => {
1447
- const bag = inst._zod.bag;
1448
- bag.format = `ipv6`;
1449
- });
1459
+ inst._zod.bag.format = `ipv6`;
1450
1460
  inst._zod.check = (payload) => {
1451
1461
  try {
1452
1462
  // @ts-ignore
@@ -1516,9 +1526,7 @@
1516
1526
  const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => {
1517
1527
  def.pattern ?? (def.pattern = base64);
1518
1528
  $ZodStringFormat.init(inst, def);
1519
- inst._zod.onattach.push((inst) => {
1520
- inst._zod.bag.contentEncoding = "base64";
1521
- });
1529
+ inst._zod.bag.contentEncoding = "base64";
1522
1530
  inst._zod.check = (payload) => {
1523
1531
  if (isValidBase64(payload.value))
1524
1532
  return;
@@ -1542,9 +1550,7 @@
1542
1550
  const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => {
1543
1551
  def.pattern ?? (def.pattern = base64url$1);
1544
1552
  $ZodStringFormat.init(inst, def);
1545
- inst._zod.onattach.push((inst) => {
1546
- inst._zod.bag.contentEncoding = "base64url";
1547
- });
1553
+ inst._zod.bag.contentEncoding = "base64url";
1548
1554
  inst._zod.check = (payload) => {
1549
1555
  if (isValidBase64URL(payload.value))
1550
1556
  return;
@@ -1628,9 +1634,9 @@
1628
1634
  return payload;
1629
1635
  };
1630
1636
  });
1631
- const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => {
1637
+ const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => {
1632
1638
  $ZodCheckNumberFormat.init(inst, def);
1633
- $ZodNumber.init(inst, def); // no format checksp
1639
+ $ZodNumber.init(inst, def); // no format checks
1634
1640
  });
1635
1641
  const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => {
1636
1642
  $ZodType.init(inst, def);
@@ -1789,7 +1795,7 @@
1789
1795
  const keySet = def.keySet;
1790
1796
  const _catchall = def.catchall._zod;
1791
1797
  const t = _catchall.def.type;
1792
- for (const key of Object.keys(input)) {
1798
+ for (const key in input) {
1793
1799
  if (keySet.has(key))
1794
1800
  continue;
1795
1801
  if (t === "never") {
@@ -2188,11 +2194,13 @@
2188
2194
  return payload;
2189
2195
  }
2190
2196
  const proms = [];
2191
- if (def.keyType._zod.values) {
2192
- const values = def.keyType._zod.values;
2197
+ const values = def.keyType._zod.values;
2198
+ if (values) {
2193
2199
  payload.value = {};
2200
+ const recordKeys = new Set();
2194
2201
  for (const key of values) {
2195
2202
  if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
2203
+ recordKeys.add(typeof key === "number" ? key.toString() : key);
2196
2204
  const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
2197
2205
  if (result instanceof Promise) {
2198
2206
  proms.push(result.then((result) => {
@@ -2212,7 +2220,7 @@
2212
2220
  }
2213
2221
  let unrecognized;
2214
2222
  for (const key in input) {
2215
- if (!values.has(key)) {
2223
+ if (!recordKeys.has(key)) {
2216
2224
  unrecognized = unrecognized ?? [];
2217
2225
  unrecognized.push(key);
2218
2226
  }
@@ -2298,13 +2306,14 @@
2298
2306
  if (def.values.length === 0) {
2299
2307
  throw new Error("Cannot create literal schema with no valid values");
2300
2308
  }
2301
- inst._zod.values = new Set(def.values);
2309
+ const values = new Set(def.values);
2310
+ inst._zod.values = values;
2302
2311
  inst._zod.pattern = new RegExp(`^(${def.values
2303
2312
  .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)))
2304
2313
  .join("|")})$`);
2305
2314
  inst._zod.parse = (payload, _ctx) => {
2306
2315
  const input = payload.value;
2307
- if (inst._zod.values.has(input)) {
2316
+ if (values.has(input)) {
2308
2317
  return payload;
2309
2318
  }
2310
2319
  payload.issues.push({
@@ -2530,8 +2539,8 @@
2530
2539
  $ZodType.init(inst, def);
2531
2540
  defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
2532
2541
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
2533
- defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
2534
- defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
2542
+ defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin);
2543
+ defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout);
2535
2544
  inst._zod.parse = (payload, ctx) => {
2536
2545
  if (ctx.direction === "backward") {
2537
2546
  return def.innerType._zod.run(payload, ctx);
@@ -2579,6 +2588,7 @@
2579
2588
  }
2580
2589
  }
2581
2590
 
2591
+ var _a$1;
2582
2592
  class $ZodRegistry {
2583
2593
  constructor() {
2584
2594
  this._map = new WeakMap();
@@ -2628,7 +2638,8 @@
2628
2638
  function registry() {
2629
2639
  return new $ZodRegistry();
2630
2640
  }
2631
- const globalRegistry = /*@__PURE__*/ registry();
2641
+ (_a$1 = globalThis).__zod_globalRegistry ?? (_a$1.__zod_globalRegistry = registry());
2642
+ const globalRegistry = globalThis.__zod_globalRegistry;
2632
2643
 
2633
2644
  function _string(Class, params) {
2634
2645
  return new Class({
@@ -3059,6 +3070,10 @@
3059
3070
  function _toUpperCase() {
3060
3071
  return _overwrite((input) => input.toUpperCase());
3061
3072
  }
3073
+ // slugify
3074
+ function _slugify() {
3075
+ return _overwrite((input) => slugify(input));
3076
+ }
3062
3077
  function _array(Class, element, params) {
3063
3078
  return new Class({
3064
3079
  type: "array",
@@ -3190,7 +3205,7 @@
3190
3205
  const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
3191
3206
  const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
3192
3207
  // Codec functions
3193
- const encode$1 = /* @__PURE__ */ _encode(ZodRealError);
3208
+ const encode$2 = /* @__PURE__ */ _encode(ZodRealError);
3194
3209
  const decode$1 = /* @__PURE__ */ _decode(ZodRealError);
3195
3210
  const encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
3196
3211
  const decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
@@ -3226,7 +3241,7 @@
3226
3241
  inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
3227
3242
  inst.spa = inst.safeParseAsync;
3228
3243
  // encoding/decoding
3229
- inst.encode = (data, params) => encode$1(inst, data, params);
3244
+ inst.encode = (data, params) => encode$2(inst, data, params);
3230
3245
  inst.decode = (data, params) => decode$1(inst, data, params);
3231
3246
  inst.encodeAsync = async (data, params) => encodeAsync(inst, data, params);
3232
3247
  inst.decodeAsync = async (data, params) => decodeAsync(inst, data, params);
@@ -3302,6 +3317,7 @@
3302
3317
  inst.normalize = (...args) => inst.check(_normalize(...args));
3303
3318
  inst.toLowerCase = () => inst.check(_toLowerCase());
3304
3319
  inst.toUpperCase = () => inst.check(_toUpperCase());
3320
+ inst.slugify = () => inst.check(_slugify());
3305
3321
  });
3306
3322
  const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => {
3307
3323
  $ZodString.init(inst, def);
@@ -9312,7 +9328,7 @@
9312
9328
  data = anchors.get(source);
9313
9329
  }
9314
9330
  /* istanbul ignore if */
9315
- if (!data || data.res === undefined) {
9331
+ if (data?.res === undefined) {
9316
9332
  const msg = 'This should not happen: Alias anchor was not resolved?';
9317
9333
  throw new ReferenceError(msg);
9318
9334
  }
@@ -10324,7 +10340,7 @@
10324
10340
  ws += `\n${indentComment(cs, ctx.indent)}`;
10325
10341
  }
10326
10342
  if (valueStr === '' && !ctx.inFlow) {
10327
- if (ws === '\n')
10343
+ if (ws === '\n' && valueComment)
10328
10344
  ws = '\n\n';
10329
10345
  }
10330
10346
  else {
@@ -10972,7 +10988,7 @@
10972
10988
  const num = typeof value === 'number' ? value : Number(value);
10973
10989
  if (!isFinite(num))
10974
10990
  return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';
10975
- let n = JSON.stringify(value);
10991
+ let n = Object.is(value, -0) ? '-0' : JSON.stringify(value);
10976
10992
  if (!format &&
10977
10993
  minFractionDigits &&
10978
10994
  (!tag || tag === 'tag:yaml.org,2002:float') &&
@@ -12228,7 +12244,7 @@
12228
12244
  if (/[^ ]/.test(lineStr)) {
12229
12245
  let count = 1;
12230
12246
  const end = error.linePos[1];
12231
- if (end && end.line === line && end.col > col) {
12247
+ if (end?.line === line && end.col > col) {
12232
12248
  count = Math.max(1, Math.min(end.col - col, 80 - ci));
12233
12249
  }
12234
12250
  const pointer = ' '.repeat(ci) + '^'.repeat(count);
@@ -12563,7 +12579,7 @@
12563
12579
  });
12564
12580
  if (!props.found) {
12565
12581
  if (props.anchor || props.tag || value) {
12566
- if (value && value.type === 'block-seq')
12582
+ if (value?.type === 'block-seq')
12567
12583
  onError(props.end, 'BAD_INDENT', 'All sequence items must start at the same column');
12568
12584
  else
12569
12585
  onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator');
@@ -12749,7 +12765,7 @@
12749
12765
  }
12750
12766
  }
12751
12767
  else if (value) {
12752
- if ('source' in value && value.source && value.source[0] === ':')
12768
+ if ('source' in value && value.source?.[0] === ':')
12753
12769
  onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`);
12754
12770
  else
12755
12771
  onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`);
@@ -12793,7 +12809,7 @@
12793
12809
  const expectedEnd = isMap ? '}' : ']';
12794
12810
  const [ce, ...ee] = fc.end;
12795
12811
  let cePos = offset;
12796
- if (ce && ce.source === expectedEnd)
12812
+ if (ce?.source === expectedEnd)
12797
12813
  cePos = ce.offset + ce.source.length;
12798
12814
  else {
12799
12815
  const name = fcName[0].toUpperCase() + fcName.substring(1);
@@ -12873,7 +12889,7 @@
12873
12889
  let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType);
12874
12890
  if (!tag) {
12875
12891
  const kt = ctx.schema.knownTags[tagName];
12876
- if (kt && kt.collection === expType) {
12892
+ if (kt?.collection === expType) {
12877
12893
  ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
12878
12894
  tag = kt;
12879
12895
  }
@@ -14804,7 +14820,7 @@
14804
14820
  }
14805
14821
  *step() {
14806
14822
  const top = this.peek(1);
14807
- if (this.type === 'doc-end' && (!top || top.type !== 'doc-end')) {
14823
+ if (this.type === 'doc-end' && top?.type !== 'doc-end') {
14808
14824
  while (this.stack.length > 0)
14809
14825
  yield* this.pop();
14810
14826
  this.stack.push({
@@ -15336,7 +15352,7 @@
15336
15352
  do {
15337
15353
  yield* this.pop();
15338
15354
  top = this.peek(1);
15339
- } while (top && top.type === 'flow-collection');
15355
+ } while (top?.type === 'flow-collection');
15340
15356
  }
15341
15357
  else if (fc.end.length === 0) {
15342
15358
  switch (this.type) {
@@ -15606,7 +15622,9 @@
15606
15622
  if (g.__ENV__ && typeof g.__ENV__ === 'object')
15607
15623
  Object.assign(out, g.__ENV__);
15608
15624
  try {
15609
- // @ts-ignore -- import.meta is only available in ESM builds
15625
+ // import.meta is only available in ESM builds
15626
+ // prettier-ignore
15627
+ // @ts-ignore
15610
15628
  const ie = (typeof ({ url: (typeof document === 'undefined' && typeof location === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : typeof document === 'undefined' ? location.href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.js', document.baseURI).href)) }) !== 'undefined' && undefined) || undefined;
15611
15629
  if (ie && typeof ie === 'object')
15612
15630
  Object.assign(out, ie);
@@ -15674,12 +15692,12 @@
15674
15692
  // --- END ENV SHIM ---
15675
15693
 
15676
15694
  // This file is auto-generated during build - do not edit manually
15677
- // Generated from package.json version: 0.3.6
15695
+ // Generated from package.json version: 0.3.9
15678
15696
  /**
15679
15697
  * The package version, injected at build time.
15680
15698
  * @internal
15681
15699
  */
15682
- const VERSION$1 = '0.3.6';
15700
+ const VERSION$1 = '0.3.9';
15683
15701
 
15684
15702
  /**
15685
15703
  * Fame protocol specific error classes with WebSocket close codes and proper inheritance.
@@ -17275,6 +17293,50 @@
17275
17293
  });
17276
17294
  }
17277
17295
 
17296
+ function isModuleNotFoundError(error) {
17297
+ if (!(error instanceof Error)) {
17298
+ return false;
17299
+ }
17300
+ const message = error.message || '';
17301
+ if (message.includes('Cannot find module') ||
17302
+ message.includes('ERR_MODULE_NOT_FOUND') ||
17303
+ message.includes('MODULE_NOT_FOUND')) {
17304
+ return true;
17305
+ }
17306
+ const code = error.code;
17307
+ if (typeof code === 'string') {
17308
+ return code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND';
17309
+ }
17310
+ return false;
17311
+ }
17312
+ /**
17313
+ * Wraps a dynamic import loader and enriches "module not found" failures with an actionable error message.
17314
+ */
17315
+ async function safeImport(loader, dependencyNameOrOptions, maybeOptions) {
17316
+ const options = typeof dependencyNameOrOptions === 'string'
17317
+ ? { dependencyName: dependencyNameOrOptions, ...(maybeOptions ?? {}) }
17318
+ : dependencyNameOrOptions;
17319
+ const dependencyName = options.dependencyName;
17320
+ try {
17321
+ return await loader();
17322
+ }
17323
+ catch (error) {
17324
+ if (isModuleNotFoundError(error)) {
17325
+ const message = options.helpMessage ??
17326
+ `Missing optional dependency "${dependencyName}". Install it to enable this feature.`;
17327
+ const enrichedError = new Error(message);
17328
+ try {
17329
+ enrichedError.cause = error;
17330
+ }
17331
+ catch {
17332
+ // Ignore environments that do not support attaching a cause.
17333
+ }
17334
+ throw enrichedError;
17335
+ }
17336
+ throw error;
17337
+ }
17338
+ }
17339
+
17278
17340
  /**
17279
17341
  * flow_controller.ts - credit window management with cooperative back-pressure.
17280
17342
  *
@@ -18209,50 +18271,6 @@
18209
18271
  return SecretSource.normalize(value);
18210
18272
  }
18211
18273
 
18212
- function isModuleNotFoundError(error) {
18213
- if (!(error instanceof Error)) {
18214
- return false;
18215
- }
18216
- const message = error.message || '';
18217
- if (message.includes('Cannot find module') ||
18218
- message.includes('ERR_MODULE_NOT_FOUND') ||
18219
- message.includes('MODULE_NOT_FOUND')) {
18220
- return true;
18221
- }
18222
- const code = error.code;
18223
- if (typeof code === 'string') {
18224
- return code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND';
18225
- }
18226
- return false;
18227
- }
18228
- /**
18229
- * Wraps a dynamic import loader and enriches "module not found" failures with an actionable error message.
18230
- */
18231
- async function safeImport(loader, dependencyNameOrOptions, maybeOptions) {
18232
- const options = typeof dependencyNameOrOptions === 'string'
18233
- ? { dependencyName: dependencyNameOrOptions, ...(maybeOptions ?? {}) }
18234
- : dependencyNameOrOptions;
18235
- const dependencyName = options.dependencyName;
18236
- try {
18237
- return await loader();
18238
- }
18239
- catch (error) {
18240
- if (isModuleNotFoundError(error)) {
18241
- const message = options.helpMessage ??
18242
- `Missing optional dependency "${dependencyName}". Install it to enable this feature.`;
18243
- const enrichedError = new Error(message);
18244
- try {
18245
- enrichedError.cause = error;
18246
- }
18247
- catch {
18248
- // Ignore environments that do not support attaching a cause.
18249
- }
18250
- throw enrichedError;
18251
- }
18252
- throw error;
18253
- }
18254
- }
18255
-
18256
18274
  const indexedDBConfigSchema = object({
18257
18275
  type: literal('IndexedDBStorageProvider')
18258
18276
  .default('IndexedDBStorageProvider'),
@@ -21831,9 +21849,6 @@
21831
21849
  this.ackDoneSince = new Map();
21832
21850
  this.replyDoneSince = new Map();
21833
21851
  this.pendingAckDispatches = new Set();
21834
- this.recentlyHandled = new Map();
21835
- this.recentlyHandledOrder = [];
21836
- this.recentlyHandledTtlMs = 60000;
21837
21852
  this.isPreparingToStop = false;
21838
21853
  this.shutdownRequestedAtMs = null;
21839
21854
  this.shutdownRetryGraceMs = 1000;
@@ -22055,22 +22070,6 @@
22055
22070
  }
22056
22071
  }
22057
22072
  else {
22058
- const wasRecentlyHandled = await this.lock.runExclusive(async () => this.wasRecentlyHandled(envelope.id));
22059
- if (wasRecentlyHandled) {
22060
- logger$12.debug('tracker_duplicate_envelope_recently_handled', {
22061
- envp_id: envelope.id,
22062
- });
22063
- return new TrackedEnvelope({
22064
- timeoutAtMs: 0,
22065
- overallTimeoutAtMs: 0,
22066
- expectedResponseType: envelope.rtype ?? FameResponseType.NONE,
22067
- createdAtMs: Date.now(),
22068
- status: EnvelopeStatus.HANDLED,
22069
- mailboxType: MailboxType.INBOX,
22070
- originalEnvelope: envelope,
22071
- serviceName: inboxName,
22072
- });
22073
- }
22074
22073
  tracked = new TrackedEnvelope({
22075
22074
  timeoutAtMs: 0,
22076
22075
  overallTimeoutAtMs: 0,
@@ -22092,12 +22091,8 @@
22092
22091
  async onEnvelopeHandled(envelope) {
22093
22092
  const inbox = this.ensureInbox();
22094
22093
  envelope.status = EnvelopeStatus.HANDLED;
22094
+ // Delete the envelope from inbox to prevent growth
22095
22095
  await inbox.delete(envelope.originalEnvelope.id);
22096
- await this.lock.runExclusive(async () => {
22097
- this.markRecentlyHandled(envelope.originalEnvelope.id);
22098
- });
22099
- // Preserve handled envelope to prevent duplicate redelivery during shutdown drains.
22100
- // await inbox.set(envelope.originalEnvelope.id, envelope);
22101
22096
  }
22102
22097
  async onEnvelopeHandleFailed(inboxName, envelope, context, error, isFinalFailure = false) {
22103
22098
  const inbox = this.ensureInbox();
@@ -22312,9 +22307,9 @@
22312
22307
  });
22313
22308
  await this.markDoneSince(this.replyFutures, trackedEnvelope.originalEnvelope.id, this.replyDoneSince);
22314
22309
  await this.markDoneSince(this.ackFutures, trackedEnvelope.originalEnvelope.id, this.ackDoneSince);
22315
- if (envelope.rtype && Boolean(envelope.rtype & FameResponseType.ACK)) {
22316
- await this.sendAck(envelope);
22317
- }
22310
+ // Note: ACK is already sent in onCorrelatedMessage (lines 655-657)
22311
+ // when the reply envelope is first delivered. No need to send it again here.
22312
+ // Removing this duplicate sendAck call fixes the duplicate DeliveryAck bug.
22318
22313
  for (const handler of this.eventHandlers) {
22319
22314
  await handler.onEnvelopeReplied?.(trackedEnvelope, envelope);
22320
22315
  }
@@ -22464,8 +22459,6 @@
22464
22459
  }
22465
22460
  this.streamDone.clear();
22466
22461
  this.correlationToEnvelope.clear();
22467
- this.recentlyHandled.clear();
22468
- this.recentlyHandledOrder.length = 0;
22469
22462
  return values;
22470
22463
  });
22471
22464
  for (const timer of timers) {
@@ -23047,39 +23040,6 @@
23047
23040
  this.pendingAckDispatches.delete(ackDispatch);
23048
23041
  }
23049
23042
  }
23050
- markRecentlyHandled(envelopeId) {
23051
- const now = Date.now();
23052
- this.recentlyHandled.set(envelopeId, now);
23053
- this.recentlyHandledOrder.push(envelopeId);
23054
- this.trimRecentlyHandled(now);
23055
- }
23056
- wasRecentlyHandled(envelopeId) {
23057
- const now = Date.now();
23058
- const timestamp = this.recentlyHandled.get(envelopeId);
23059
- if (timestamp === undefined) {
23060
- return false;
23061
- }
23062
- if (now - timestamp > this.recentlyHandledTtlMs) {
23063
- this.recentlyHandled.delete(envelopeId);
23064
- return false;
23065
- }
23066
- return true;
23067
- }
23068
- trimRecentlyHandled(now) {
23069
- while (this.recentlyHandledOrder.length > 0) {
23070
- const candidate = this.recentlyHandledOrder[0];
23071
- const timestamp = this.recentlyHandled.get(candidate);
23072
- if (timestamp === undefined) {
23073
- this.recentlyHandledOrder.shift();
23074
- continue;
23075
- }
23076
- if (now - timestamp <= this.recentlyHandledTtlMs) {
23077
- break;
23078
- }
23079
- this.recentlyHandled.delete(candidate);
23080
- this.recentlyHandledOrder.shift();
23081
- }
23082
- }
23083
23043
  getShutdownRetryDeferDelay(nowMs) {
23084
23044
  if (!this.isPreparingToStop || this.shutdownRequestedAtMs === null) {
23085
23045
  return null;
@@ -24573,7 +24533,8 @@
24573
24533
  };
24574
24534
  let BroadcastChannelConnector$2 = class BroadcastChannelConnector extends BaseAsyncConnector {
24575
24535
  static generateConnectorId() {
24576
- const globalCrypto = globalThis.crypto;
24536
+ const globalCrypto = globalThis
24537
+ .crypto;
24577
24538
  if (globalCrypto?.randomUUID) {
24578
24539
  return globalCrypto.randomUUID();
24579
24540
  }
@@ -24628,7 +24589,8 @@
24628
24589
  this.listenerRegistered = false;
24629
24590
  this.visibilityChangeListenerRegistered = false;
24630
24591
  this.channelName =
24631
- typeof config.channelName === 'string' && config.channelName.trim().length > 0
24592
+ typeof config.channelName === 'string' &&
24593
+ config.channelName.trim().length > 0
24632
24594
  ? config.channelName.trim()
24633
24595
  : DEFAULT_CHANNEL$7;
24634
24596
  const preferredCapacity = typeof config.inboxCapacity === 'number' &&
@@ -24652,6 +24614,7 @@
24652
24614
  local_node_id: this.localNodeId,
24653
24615
  target_node_id: this.targetNodeId ?? null,
24654
24616
  inbox_capacity: preferredCapacity,
24617
+ passive: config.passive ?? false,
24655
24618
  timestamp: new Date().toISOString(),
24656
24619
  });
24657
24620
  this.onMsg = (event) => {
@@ -24669,7 +24632,8 @@
24669
24632
  channel: this.channelName,
24670
24633
  connector_id: this.connectorId,
24671
24634
  message_type: message && typeof message === 'object'
24672
- ? message.constructor?.name ?? typeof message
24635
+ ? (message.constructor
24636
+ ?.name ?? typeof message)
24673
24637
  : typeof message,
24674
24638
  has_sender_id: Boolean(message?.senderId),
24675
24639
  has_sender_node_id: Boolean(message?.senderNodeId),
@@ -24899,7 +24863,9 @@
24899
24863
  timestamp: new Date().toISOString(),
24900
24864
  });
24901
24865
  }
24902
- if (this.visibilityChangeListenerRegistered && this.visibilityChangeHandler && typeof document !== 'undefined') {
24866
+ if (this.visibilityChangeListenerRegistered &&
24867
+ this.visibilityChangeHandler &&
24868
+ typeof document !== 'undefined') {
24903
24869
  document.removeEventListener('visibilitychange', this.visibilityChangeHandler);
24904
24870
  this.visibilityChangeListenerRegistered = false;
24905
24871
  this.visibilityChangeHandler = undefined;
@@ -24927,7 +24893,7 @@
24927
24893
  return rawOrEnvelope;
24928
24894
  }
24929
24895
  _isWildcardTarget() {
24930
- return this.targetNodeId === '*' || typeof this.targetNodeId === 'undefined';
24896
+ return (this.targetNodeId === '*' || typeof this.targetNodeId === 'undefined');
24931
24897
  }
24932
24898
  _shouldAcceptMessageFromBus(senderNodeId, targetNodeId) {
24933
24899
  if (this._isWildcardTarget()) {
@@ -24947,7 +24913,9 @@
24947
24913
  return true;
24948
24914
  }
24949
24915
  const expectedSender = this.targetNodeId;
24950
- if (expectedSender && expectedSender !== '*' && senderNodeId !== expectedSender) {
24916
+ if (expectedSender &&
24917
+ expectedSender !== '*' &&
24918
+ senderNodeId !== expectedSender) {
24951
24919
  logger$_.debug('broadcast_channel_message_rejected', {
24952
24920
  channel: this.channelName,
24953
24921
  connector_id: this.connectorId,
@@ -25139,14 +25107,16 @@
25139
25107
  type,
25140
25108
  purpose,
25141
25109
  };
25142
- const channelValue = candidate.channelName ?? candidate['channel_name'];
25110
+ const channelValue = candidate.channelName ??
25111
+ candidate['channel_name'];
25143
25112
  if (channelValue !== undefined) {
25144
25113
  if (typeof channelValue !== 'string' || channelValue.trim().length === 0) {
25145
25114
  throw new TypeError('BroadcastChannelConnectionGrant "channelName" must be a non-empty string when provided');
25146
25115
  }
25147
25116
  result.channelName = channelValue.trim();
25148
25117
  }
25149
- const inboxValue = candidate.inboxCapacity ?? candidate['inbox_capacity'];
25118
+ const inboxValue = candidate.inboxCapacity ??
25119
+ candidate['inbox_capacity'];
25150
25120
  if (inboxValue !== undefined) {
25151
25121
  if (typeof inboxValue !== 'number' ||
25152
25122
  !Number.isFinite(inboxValue) ||
@@ -25155,7 +25125,8 @@
25155
25125
  }
25156
25126
  result.inboxCapacity = Math.floor(inboxValue);
25157
25127
  }
25158
- const windowValue = candidate.initialWindow ?? candidate['initial_window'];
25128
+ const windowValue = candidate.initialWindow ??
25129
+ candidate['initial_window'];
25159
25130
  if (windowValue !== undefined) {
25160
25131
  if (typeof windowValue !== 'number' ||
25161
25132
  !Number.isFinite(windowValue) ||
@@ -25492,25 +25463,56 @@
25492
25463
  await connector.start(this.wrappedHandler);
25493
25464
  this.connector = connector;
25494
25465
  const callbackGrants = this.node.gatherSupportedCallbackGrants();
25466
+ logger$Z.debug('callback_grants_before_augmentation', {
25467
+ count: callbackGrants.length,
25468
+ types: callbackGrants.map((g) => g.type),
25469
+ });
25470
+ // Check if we should create a broadcast callback grant before processing connection grants
25471
+ // This prevents adding duplicate broadcast grants
25472
+ const shouldAddBroadcastGrant = this.shouldAdvertiseBroadcastGrant(grant, callbackGrants);
25473
+ const broadcastCallbackGrant = shouldAddBroadcastGrant
25474
+ ? this.createBroadcastCallbackGrant(grant)
25475
+ : null;
25476
+ logger$Z.debug('broadcast_callback_grant_check', {
25477
+ should_add: shouldAddBroadcastGrant,
25478
+ grant_created: !!broadcastCallbackGrant,
25479
+ });
25495
25480
  // Include admission client's connection grants as callback grants
25496
25481
  // This ensures DirectAdmissionClient grants are available for grant selection
25497
- if (welcome.frame.connectionGrants && Array.isArray(welcome.frame.connectionGrants)) {
25482
+ if (welcome.frame.connectionGrants &&
25483
+ Array.isArray(welcome.frame.connectionGrants)) {
25498
25484
  for (const grant of welcome.frame.connectionGrants) {
25499
25485
  if (grant && typeof grant === 'object') {
25500
25486
  // Avoid duplicates by checking if grant already exists
25501
- const isDuplicate = callbackGrants.some(existing => JSON.stringify(existing) === JSON.stringify(grant));
25487
+ const isDuplicate = callbackGrants.some((existing) => JSON.stringify(existing) === JSON.stringify(grant));
25502
25488
  if (!isDuplicate) {
25503
25489
  callbackGrants.push(grant);
25490
+ logger$Z.debug('added_connection_grant_as_callback', {
25491
+ type: grant.type,
25492
+ });
25493
+ }
25494
+ else {
25495
+ logger$Z.debug('skipped_duplicate_connection_grant', {
25496
+ type: grant.type,
25497
+ });
25504
25498
  }
25505
25499
  }
25506
25500
  }
25507
25501
  }
25508
- if (this.shouldAdvertiseBroadcastGrant(grant, callbackGrants)) {
25509
- const augmented = this.createBroadcastCallbackGrant(grant);
25510
- if (augmented) {
25511
- callbackGrants.push(augmented);
25512
- }
25502
+ // Add broadcast grant after connection grants to ensure we don't duplicate
25503
+ // any broadcast grants that may have been in connectionGrants
25504
+ if (broadcastCallbackGrant &&
25505
+ this.shouldAdvertiseBroadcastGrant(grant, callbackGrants)) {
25506
+ callbackGrants.push(broadcastCallbackGrant);
25507
+ logger$Z.debug('added_broadcast_callback_grant');
25508
+ }
25509
+ else if (broadcastCallbackGrant) {
25510
+ logger$Z.debug('skipped_duplicate_broadcast_callback_grant');
25513
25511
  }
25512
+ logger$Z.debug('callback_grants_after_augmentation', {
25513
+ count: callbackGrants.length,
25514
+ types: callbackGrants.map((g) => g.type),
25515
+ });
25514
25516
  const attachInfo = await this.attachClient.attach(this.node, this.outboundOriginType, connector, welcome.frame, this.wrappedHandler, this.getKeys() ?? undefined, callbackGrants);
25515
25517
  this.targetSystemId = attachInfo.targetSystemId ?? null;
25516
25518
  if (this.targetSystemId) {
@@ -25751,7 +25753,8 @@
25751
25753
  continue;
25752
25754
  }
25753
25755
  // Reset ack time if just resumed from pause (prevents immediate timeout)
25754
- if (previousState === ConnectorState.PAUSED && currentState === ConnectorState.STARTED) {
25756
+ if (previousState === ConnectorState.PAUSED &&
25757
+ currentState === ConnectorState.STARTED) {
25755
25758
  logger$Z.debug('connector_just_resumed_resetting_ack_time', {
25756
25759
  previous_state: previousState,
25757
25760
  current_state: currentState,
@@ -27306,15 +27309,30 @@
27306
27309
  constructor(options = {}) {
27307
27310
  this.buffer = [];
27308
27311
  this.inHandshake = false;
27312
+ this.expectedSystemId = null;
27309
27313
  this.timeoutMs = options.timeoutMs ?? 10000;
27310
27314
  this.attachmentKeyValidator = options.attachmentKeyValidator;
27311
27315
  this.replicaStickinessManager = options.replicaStickinessManager ?? null;
27312
27316
  }
27313
27317
  async attach(node, originType, connector, welcomeFrame, finalHandler, keys, callbackGrants) {
27314
27318
  this.inHandshake = true;
27319
+ this.expectedSystemId = welcomeFrame.systemId;
27315
27320
  const interimHandler = async (envelope, context) => {
27316
27321
  if (this.inHandshake) {
27317
- this.buffer.push(envelope);
27322
+ // Filter: only buffer frames related to our systemId or frames without systemId info
27323
+ const frameSystemId = envelope.frame
27324
+ ?.systemId;
27325
+ if (!frameSystemId || frameSystemId === this.expectedSystemId) {
27326
+ this.buffer.push(envelope);
27327
+ }
27328
+ else {
27329
+ // Silently ignore frames from other agents during concurrent handshakes
27330
+ logger$W.debug('handshake_ignoring_frame_from_different_system', {
27331
+ frame_type: envelope.frame.type,
27332
+ frame_system_id: frameSystemId,
27333
+ expected_system_id: this.expectedSystemId,
27334
+ });
27335
+ }
27318
27336
  return null;
27319
27337
  }
27320
27338
  return finalHandler(envelope, context);
@@ -27441,6 +27459,7 @@
27441
27459
  parent_id: ackFrame.targetSystemId,
27442
27460
  });
27443
27461
  this.inHandshake = false;
27462
+ this.expectedSystemId = null;
27444
27463
  await connector.replaceHandler(finalHandler);
27445
27464
  while (this.buffer.length > 0) {
27446
27465
  const bufferedEnvelope = this.buffer.shift();
@@ -27498,7 +27517,8 @@
27498
27517
  const deadline = Date.now() + this.timeoutMs;
27499
27518
  while (Date.now() < deadline) {
27500
27519
  // Allow both STARTED and PAUSED states (PAUSED = tab hidden but connection alive)
27501
- if (connector.state !== ConnectorState.STARTED && connector.state !== ConnectorState.PAUSED) {
27520
+ if (connector.state !== ConnectorState.STARTED &&
27521
+ connector.state !== ConnectorState.PAUSED) {
27502
27522
  let errorMessage = 'Connector closed while waiting for NodeAttachAck';
27503
27523
  if (connector.closeCode !== undefined) {
27504
27524
  errorMessage += ` (code=${connector.closeCode}`;
@@ -27517,9 +27537,21 @@
27517
27537
  if (envelope.frame.type === 'NodeAttachAck') {
27518
27538
  return envelope;
27519
27539
  }
27520
- logger$W.error('unexpected_frame_during_handshake', {
27521
- frame_type: envelope.frame.type,
27522
- });
27540
+ // NodeAttach frames during handshake are expected in multi-agent scenarios
27541
+ // where multiple agents attach concurrently to the same channel
27542
+ if (envelope.frame.type === 'NodeAttach') {
27543
+ logger$W.debug('handshake_ignoring_concurrent_attach', {
27544
+ frame_type: envelope.frame.type,
27545
+ frame_system_id: envelope.frame?.systemId ??
27546
+ 'unknown',
27547
+ });
27548
+ }
27549
+ else {
27550
+ // Other unexpected frames are still logged as errors
27551
+ logger$W.error('unexpected_frame_during_handshake', {
27552
+ frame_type: envelope.frame.type,
27553
+ });
27554
+ }
27523
27555
  }
27524
27556
  await delay$2(HANDSHAKE_POLL_INTERVAL_MS);
27525
27557
  }
@@ -28235,7 +28267,8 @@
28235
28267
  else if (options &&
28236
28268
  typeof options === 'object' &&
28237
28269
  'encoding' in options &&
28238
- typeof options.encoding === 'string') {
28270
+ typeof options.encoding ===
28271
+ 'string') {
28239
28272
  encoding = options.encoding;
28240
28273
  }
28241
28274
  const data = fsBinding.readFileUtf8(pathOrDescriptor, 0);
@@ -35057,7 +35090,8 @@
35057
35090
  this.listenerRegistered = false;
35058
35091
  this.visibilityChangeListenerRegistered = false;
35059
35092
  this.channelName =
35060
- typeof config.channelName === 'string' && config.channelName.trim().length > 0
35093
+ typeof config.channelName === 'string' &&
35094
+ config.channelName.trim().length > 0
35061
35095
  ? config.channelName.trim()
35062
35096
  : DEFAULT_CHANNEL$6;
35063
35097
  const preferredCapacity = typeof config.inboxCapacity === 'number' &&
@@ -35096,7 +35130,8 @@
35096
35130
  channel: this.channelName,
35097
35131
  connector_id: this.connectorId,
35098
35132
  message_type: message && typeof message === 'object'
35099
- ? message.constructor?.name ?? typeof message
35133
+ ? (message.constructor
35134
+ ?.name ?? typeof message)
35100
35135
  : typeof message,
35101
35136
  has_sender_id: Boolean(message?.senderId),
35102
35137
  has_sender_node_id: Boolean(message?.senderNodeId),
@@ -35105,7 +35140,8 @@
35105
35140
  return;
35106
35141
  }
35107
35142
  const busMessage = message;
35108
- const senderId = typeof busMessage.senderId === 'string' && busMessage.senderId.length > 0
35143
+ const senderId = typeof busMessage.senderId === 'string' &&
35144
+ busMessage.senderId.length > 0
35109
35145
  ? busMessage.senderId
35110
35146
  : null;
35111
35147
  const senderNodeId = InPageConnector.normalizeNodeId(busMessage.senderNodeId);
@@ -35356,7 +35392,9 @@
35356
35392
  timestamp: new Date().toISOString(),
35357
35393
  });
35358
35394
  }
35359
- if (this.visibilityChangeListenerRegistered && this.visibilityChangeHandler && typeof document !== 'undefined') {
35395
+ if (this.visibilityChangeListenerRegistered &&
35396
+ this.visibilityChangeHandler &&
35397
+ typeof document !== 'undefined') {
35360
35398
  document.removeEventListener('visibilitychange', this.visibilityChangeHandler);
35361
35399
  this.visibilityChangeListenerRegistered = false;
35362
35400
  this.visibilityChangeHandler = undefined;
@@ -35373,7 +35411,7 @@
35373
35411
  return rawOrEnvelope;
35374
35412
  }
35375
35413
  _isWildcardTarget() {
35376
- return this.targetNodeId === '*' || typeof this.targetNodeId === 'undefined';
35414
+ return (this.targetNodeId === '*' || typeof this.targetNodeId === 'undefined');
35377
35415
  }
35378
35416
  _shouldAcceptMessageFromBus(senderNodeId, targetNodeId) {
35379
35417
  if (this._isWildcardTarget()) {
@@ -35393,7 +35431,9 @@
35393
35431
  return true;
35394
35432
  }
35395
35433
  const expectedSender = this.targetNodeId;
35396
- if (expectedSender && expectedSender !== '*' && senderNodeId !== expectedSender) {
35434
+ if (expectedSender &&
35435
+ expectedSender !== '*' &&
35436
+ senderNodeId !== expectedSender) {
35397
35437
  logger$G.debug('inpage_message_rejected', {
35398
35438
  channel: this.channelName,
35399
35439
  connector_id: this.connectorId,
@@ -35760,8 +35800,8 @@
35760
35800
  }
35761
35801
  }
35762
35802
 
35763
- const DEFAULT_UNCONFIGURED_MESSAGE = "Trust store is not configured. Set FAME_CA_CERTS to a PEM value, a file path, a data URI, or an HTTPS bundle URL.";
35764
- const TRUST_STORE_PROVIDER_FACTORY_BASE_TYPE = "TrustStoreProviderFactory";
35803
+ const DEFAULT_UNCONFIGURED_MESSAGE = 'Trust store is not configured. Set FAME_CA_CERTS to a PEM value, a file path, a data URI, or an HTTPS bundle URL.';
35804
+ const TRUST_STORE_PROVIDER_FACTORY_BASE_TYPE = 'TrustStoreProviderFactory';
35765
35805
  class TrustStoreProviderFactory extends AbstractResourceFactory {
35766
35806
  createUnconfiguredProvider(reason) {
35767
35807
  return new NoopTrustStoreProvider(reason ?? DEFAULT_UNCONFIGURED_MESSAGE);
@@ -39372,7 +39412,8 @@
39372
39412
  const hasSignature = Boolean(envelope.sec?.sig);
39373
39413
  if (!hasSignature) {
39374
39414
  const nodeSid = node.sid;
39375
- const envelopeSid = envelope.sid;
39415
+ const envelopeSid = envelope
39416
+ .sid;
39376
39417
  const isLocalUnsignedSelfEnvelope = localContext.originType === DeliveryOriginType.LOCAL &&
39377
39418
  typeof nodeSid === 'string' &&
39378
39419
  nodeSid.length > 0 &&
@@ -42352,14 +42393,16 @@
42352
42393
  type,
42353
42394
  purpose,
42354
42395
  };
42355
- const channelValue = candidate.channelName ?? candidate['channel_name'];
42396
+ const channelValue = candidate.channelName ??
42397
+ candidate['channel_name'];
42356
42398
  if (channelValue !== undefined) {
42357
42399
  if (typeof channelValue !== 'string' || channelValue.trim().length === 0) {
42358
42400
  throw new TypeError('InPageConnectionGrant "channelName" must be a non-empty string when provided');
42359
42401
  }
42360
42402
  result.channelName = channelValue.trim();
42361
42403
  }
42362
- const inboxValue = candidate.inboxCapacity ?? candidate['inbox_capacity'];
42404
+ const inboxValue = candidate.inboxCapacity ??
42405
+ candidate['inbox_capacity'];
42363
42406
  if (inboxValue !== undefined) {
42364
42407
  if (typeof inboxValue !== 'number' ||
42365
42408
  !Number.isFinite(inboxValue) ||
@@ -42785,6 +42828,44 @@
42785
42828
 
42786
42829
  getLogger('naylence.fame.welcome.node_welcome_router');
42787
42830
 
42831
+ /**
42832
+ * Fabric Registry
42833
+ *
42834
+ * Provides a mapping from nodes to their associated fabrics.
42835
+ * This allows agents to retrieve the fabric they were registered on
42836
+ * without relying on the global fabric stack.
42837
+ */
42838
+ /**
42839
+ * WeakMap to store the node-to-fabric mapping.
42840
+ * Using WeakMap ensures that nodes can be garbage collected
42841
+ * when no longer referenced elsewhere.
42842
+ */
42843
+ const nodeToFabric = new WeakMap();
42844
+ /**
42845
+ * @internal
42846
+ * Associates a node with its fabric. This should only be called
42847
+ * by fabric implementations when they create or adopt a node.
42848
+ *
42849
+ * @param node - The node to associate
42850
+ * @param fabric - The fabric that owns the node
42851
+ */
42852
+ function _setFabricForNode(node, fabric) {
42853
+ nodeToFabric.set(node, fabric);
42854
+ }
42855
+ /**
42856
+ * Retrieves the fabric associated with a node.
42857
+ *
42858
+ * This is useful for agents that need to access the fabric they
42859
+ * were registered on, particularly in environments where multiple
42860
+ * fabrics exist (e.g., React with multiple FabricProviders).
42861
+ *
42862
+ * @param node - The node to look up
42863
+ * @returns The fabric associated with the node, or undefined if not found
42864
+ */
42865
+ function getFabricForNode(node) {
42866
+ return nodeToFabric.get(node);
42867
+ }
42868
+
42788
42869
  /**
42789
42870
  * Browser-friendly entry point for Naylence Runtime.
42790
42871
  *
@@ -42897,7 +42978,8 @@
42897
42978
  const normalized = this._normalizeConfig(config);
42898
42979
  const options = (factoryArgs[0] ?? {});
42899
42980
  const normalizedLocalNodeFromConfig = this._normalizeNodeId(normalized.localNodeId);
42900
- const localNodeId = this._normalizeNodeId(options.localNodeId) ?? normalizedLocalNodeFromConfig;
42981
+ const localNodeId = this._normalizeNodeId(options.localNodeId) ??
42982
+ normalizedLocalNodeFromConfig;
42901
42983
  if (!localNodeId) {
42902
42984
  throw new Error('InPageConnectorFactory requires a localNodeId from config or create() options');
42903
42985
  }
@@ -43073,10 +43155,12 @@
43073
43155
  type: BROADCAST_CHANNEL_CONNECTOR_TYPE,
43074
43156
  };
43075
43157
  const channelCandidate = record.channelName ?? record['channel_name'];
43076
- if (typeof channelCandidate === 'string' && channelCandidate.trim().length > 0) {
43158
+ if (typeof channelCandidate === 'string' &&
43159
+ channelCandidate.trim().length > 0) {
43077
43160
  config.channelName = channelCandidate.trim();
43078
43161
  }
43079
- const inboxCandidate = record.inboxCapacity ?? record['inbox_capacity'];
43162
+ const inboxCandidate = record.inboxCapacity ??
43163
+ record['inbox_capacity'];
43080
43164
  if (typeof inboxCandidate === 'number' &&
43081
43165
  Number.isFinite(inboxCandidate) &&
43082
43166
  inboxCandidate > 0) {
@@ -43100,9 +43184,11 @@
43100
43184
  throw new Error('BroadcastChannelConnectorFactory requires a configuration');
43101
43185
  }
43102
43186
  const normalized = this._normalizeConfig(config);
43103
- const options = (factoryArgs[0] ?? {});
43187
+ const options = (factoryArgs[0] ??
43188
+ {});
43104
43189
  const normalizedLocalNodeFromConfig = this._normalizeNodeId(normalized.localNodeId);
43105
- const localNodeId = this._normalizeNodeId(options.localNodeId) ?? normalizedLocalNodeFromConfig;
43190
+ const localNodeId = this._normalizeNodeId(options.localNodeId) ??
43191
+ normalizedLocalNodeFromConfig;
43106
43192
  if (!localNodeId) {
43107
43193
  throw new Error('BroadcastChannelConnectorFactory requires a localNodeId from config or create() options');
43108
43194
  }
@@ -43127,6 +43213,7 @@
43127
43213
  inboxCapacity,
43128
43214
  localNodeId,
43129
43215
  initialTargetNodeId: resolvedTarget,
43216
+ passive: normalized.passive,
43130
43217
  };
43131
43218
  const connector = new BroadcastChannelConnector(connectorConfig, baseConfig);
43132
43219
  if (options.authorization) {
@@ -43165,6 +43252,9 @@
43165
43252
  if (normalizedLocalNodeId) {
43166
43253
  normalized.localNodeId = normalizedLocalNodeId;
43167
43254
  }
43255
+ if (typeof candidate.passive === 'boolean') {
43256
+ normalized.passive = candidate.passive;
43257
+ }
43168
43258
  if (typeof candidate.flowControl === 'boolean') {
43169
43259
  normalized.flowControl = candidate.flowControl;
43170
43260
  }
@@ -43590,7 +43680,9 @@
43590
43680
  typeof channelCandidate === 'string' && channelCandidate.trim().length > 0
43591
43681
  ? channelCandidate.trim()
43592
43682
  : DEFAULT_CHANNEL$3;
43593
- const normalizedCapacity = typeof inboxCandidate === 'number' && Number.isFinite(inboxCandidate) && inboxCandidate > 0
43683
+ const normalizedCapacity = typeof inboxCandidate === 'number' &&
43684
+ Number.isFinite(inboxCandidate) &&
43685
+ inboxCandidate > 0
43594
43686
  ? Math.floor(inboxCandidate)
43595
43687
  : DEFAULT_INBOX_CAPACITY$3;
43596
43688
  this._inboxCapacity = normalizedCapacity;
@@ -43865,7 +43957,8 @@
43865
43957
  if (grant.type === INPAGE_CONNECTION_GRANT_TYPE) {
43866
43958
  return inPageGrantToConnectorConfig(grant);
43867
43959
  }
43868
- if (typeof grant?.toConnectorConfig === 'function') {
43960
+ if (typeof grant
43961
+ ?.toConnectorConfig === 'function') {
43869
43962
  return grant.toConnectorConfig();
43870
43963
  }
43871
43964
  throw new Error(`Unsupported grant type: ${grant.type}`);
@@ -44019,7 +44112,9 @@
44019
44112
  : DEFAULT_CHANNEL$2;
44020
44113
  const rawInbox = record.inboxCapacity ?? record['inbox_capacity'];
44021
44114
  let inboxCapacity = DEFAULT_INBOX_CAPACITY$2;
44022
- if (typeof rawInbox === 'number' && Number.isFinite(rawInbox) && rawInbox > 0) {
44115
+ if (typeof rawInbox === 'number' &&
44116
+ Number.isFinite(rawInbox) &&
44117
+ rawInbox > 0) {
44023
44118
  inboxCapacity = Math.floor(rawInbox);
44024
44119
  }
44025
44120
  else if (typeof rawInbox === 'string') {
@@ -44047,9 +44142,7 @@
44047
44142
  }
44048
44143
  async create(config, ...factoryArgs) {
44049
44144
  const normalized = normalizeConfig$r(config);
44050
- const [{ InPageListener }] = await Promise.all([
44051
- getInPageListenerModule(),
44052
- ]);
44145
+ const [{ InPageListener }] = await Promise.all([getInPageListenerModule()]);
44053
44146
  return new InPageListener({
44054
44147
  channelName: normalized.channelName,
44055
44148
  inboxCapacity: normalized.inboxCapacity,
@@ -44067,9 +44160,7 @@
44067
44160
  const logger$o = getLogger('naylence.fame.connector.broadcast_channel_listener');
44068
44161
  const DEFAULT_CHANNEL$1 = 'naylence-fabric';
44069
44162
  const DEFAULT_INBOX_CAPACITY$1 = 2048;
44070
- const RESPONSE_TYPE_MASK = FameResponseType.ACK |
44071
- FameResponseType.REPLY |
44072
- FameResponseType.STREAM;
44163
+ const RESPONSE_TYPE_MASK = FameResponseType.ACK | FameResponseType.REPLY | FameResponseType.STREAM;
44073
44164
  const isBrowserEnvironment$1 = () => typeof window !== 'undefined' &&
44074
44165
  typeof BroadcastChannel !== 'undefined' &&
44075
44166
  typeof MessageEvent !== 'undefined';
@@ -44283,9 +44374,7 @@
44283
44374
  return null;
44284
44375
  }
44285
44376
  })();
44286
- if (error instanceof ZodError &&
44287
- decoded &&
44288
- decoded.length > 0) {
44377
+ if (error instanceof ZodError && decoded && decoded.length > 0) {
44289
44378
  try {
44290
44379
  const reparsed = JSON.parse(decoded);
44291
44380
  const candidate = reparsed.rtype;
@@ -44508,11 +44597,19 @@
44508
44597
  ? Math.floor(initialWindowCandidate)
44509
44598
  : undefined;
44510
44599
  const initialTargetNodeId = this._normalizeNodeId(targetCandidate) ?? targetSystemId;
44600
+ const passive = typeof passiveCandidate === 'boolean' ? passiveCandidate : true;
44601
+ logger$o.debug('broadcast_channel_listener_building_connector_config', {
44602
+ system_id: systemId,
44603
+ channel_name: channelName,
44604
+ passive,
44605
+ has_base_config: !!baseConfig,
44606
+ passive_candidate: passiveCandidate,
44607
+ });
44511
44608
  return {
44512
44609
  type: BROADCAST_CHANNEL_CONNECTOR_TYPE,
44513
44610
  channelName,
44514
44611
  inboxCapacity,
44515
- passive: typeof passiveCandidate === 'boolean' ? passiveCandidate : true,
44612
+ passive,
44516
44613
  initialWindow,
44517
44614
  localNodeId,
44518
44615
  initialTargetNodeId,
@@ -44625,7 +44722,9 @@
44625
44722
  : DEFAULT_CHANNEL;
44626
44723
  const rawInbox = record.inboxCapacity ?? record['inbox_capacity'];
44627
44724
  let inboxCapacity = DEFAULT_INBOX_CAPACITY;
44628
- if (typeof rawInbox === 'number' && Number.isFinite(rawInbox) && rawInbox > 0) {
44725
+ if (typeof rawInbox === 'number' &&
44726
+ Number.isFinite(rawInbox) &&
44727
+ rawInbox > 0) {
44629
44728
  inboxCapacity = Math.floor(rawInbox);
44630
44729
  }
44631
44730
  else if (typeof rawInbox === 'string') {
@@ -45974,6 +46073,8 @@
45974
46073
  this._currentNode = await NodeLikeFactory.createNode(nodeConfig);
45975
46074
  this._ownsNode = true;
45976
46075
  }
46076
+ // Register this fabric in the registry so agents can look it up
46077
+ _setFabricForNode(this._currentNode, this);
45977
46078
  if (this._ownsNode && !this._nodeStarted) {
45978
46079
  await this.getRequiredNode().start();
45979
46080
  this._nodeStarted = true;
@@ -48111,19 +48212,23 @@
48111
48212
  normalized.clientSecretConfig = normalizeSecretSource(clientSecretSource);
48112
48213
  }
48113
48214
  const audienceCandidate = candidate.audience ?? candidate.aud;
48114
- if (typeof audienceCandidate === 'string' && audienceCandidate.trim().length > 0) {
48215
+ if (typeof audienceCandidate === 'string' &&
48216
+ audienceCandidate.trim().length > 0) {
48115
48217
  normalized.audience = audienceCandidate.trim();
48116
48218
  }
48117
48219
  const codeChallengeMethod = candidate.codeChallengeMethod ?? candidate.code_challenge_method;
48118
- if (typeof codeChallengeMethod === 'string' && codeChallengeMethod.trim().length > 0) {
48220
+ if (typeof codeChallengeMethod === 'string' &&
48221
+ codeChallengeMethod.trim().length > 0) {
48119
48222
  normalized.codeChallengeMethod = codeChallengeMethod.trim();
48120
48223
  }
48121
48224
  const codeVerifierLength = candidate.codeVerifierLength ?? candidate.code_verifier_length;
48122
- if (typeof codeVerifierLength === 'number' && Number.isFinite(codeVerifierLength)) {
48225
+ if (typeof codeVerifierLength === 'number' &&
48226
+ Number.isFinite(codeVerifierLength)) {
48123
48227
  normalized.codeVerifierLength = codeVerifierLength;
48124
48228
  }
48125
48229
  const clockSkewSeconds = candidate.clockSkewSeconds ?? candidate.clock_skew_seconds;
48126
- if (typeof clockSkewSeconds === 'number' && Number.isFinite(clockSkewSeconds)) {
48230
+ if (typeof clockSkewSeconds === 'number' &&
48231
+ Number.isFinite(clockSkewSeconds)) {
48127
48232
  normalized.clockSkewSeconds = clockSkewSeconds;
48128
48233
  }
48129
48234
  const loginHintParam = candidate.loginHintParam ?? candidate.login_hint_param;
@@ -48168,8 +48273,8 @@
48168
48273
  options.audience = normalized.audience;
48169
48274
  }
48170
48275
  if (normalized.codeChallengeMethod) {
48171
- options.codeChallengeMethod = normalized.codeChallengeMethod
48172
- .toUpperCase();
48276
+ options.codeChallengeMethod =
48277
+ normalized.codeChallengeMethod.toUpperCase();
48173
48278
  }
48174
48279
  if (normalized.codeVerifierLength) {
48175
48280
  options.codeVerifierLength = normalized.codeVerifierLength;
@@ -49926,14 +50031,14 @@
49926
50031
 
49927
50032
  const FACTORY_META$d = {
49928
50033
  base: TRUST_STORE_PROVIDER_FACTORY_BASE_TYPE,
49929
- key: "NoopTrustStoreProvider",
50034
+ key: 'NoopTrustStoreProvider',
49930
50035
  isDefault: true,
49931
50036
  priority: 10,
49932
50037
  };
49933
50038
  class NoopTrustStoreProviderFactory extends TrustStoreProviderFactory {
49934
50039
  constructor() {
49935
50040
  super(...arguments);
49936
- this.type = "NoopTrustStoreProvider";
50041
+ this.type = 'NoopTrustStoreProvider';
49937
50042
  this.isDefault = true;
49938
50043
  this.priority = 10;
49939
50044
  }
@@ -53327,8 +53432,7 @@
53327
53432
  const scopes = normalizeScopes(camel.scopes) ??
53328
53433
  normalizeScopes(snake.scopes ?? snake.scope) ??
53329
53434
  DEFAULT_SCOPES.slice();
53330
- const audience = coerceString(camel.audience) ??
53331
- coerceString(snake.audience ?? snake.aud);
53435
+ const audience = coerceString(camel.audience) ?? coerceString(snake.audience ?? snake.aud);
53332
53436
  const fetchImpl = (camel.fetchImpl ?? snake.fetch_impl);
53333
53437
  const clockSkewSeconds = coerceNumber(camel.clockSkewSeconds) ??
53334
53438
  coerceNumber(snake.clock_skew_seconds) ??
@@ -55767,6 +55871,7 @@
55767
55871
  this._subscriptions = new Map();
55768
55872
  this._stateLock = new AsyncLock();
55769
55873
  this._node = null;
55874
+ this._fabric = null;
55770
55875
  this._stateStore = null;
55771
55876
  this._stateCache = null;
55772
55877
  this._name = name ?? camelToSnakeCase(this.constructor.name);
@@ -55806,8 +55911,18 @@
55806
55911
  }
55807
55912
  return this._storageProvider;
55808
55913
  }
55914
+ /**
55915
+ * Returns the fabric this agent is registered with.
55916
+ * This is set during onRegister() and should be used instead of FameFabric.current()
55917
+ * when the agent needs to make calls to other agents.
55918
+ */
55919
+ get fabric() {
55920
+ return this._fabric;
55921
+ }
55809
55922
  async onRegister(node) {
55810
55923
  this._node = node;
55924
+ // Look up the fabric from the registry (set by InProcessFameFabric.start())
55925
+ this._fabric = getFabricForNode(node) ?? null;
55811
55926
  }
55812
55927
  async acquireStateLock() {
55813
55928
  let acquiredResolve;
@@ -56054,7 +56169,8 @@
56054
56169
  envelopeOptions.corrId = String(rpcRequest.id);
56055
56170
  }
56056
56171
  const envelope = createFameEnvelope(envelopeOptions);
56057
- await FameFabric.current().send(envelope);
56172
+ const fabricToUse = this._fabric ?? FameFabric.current();
56173
+ await fabricToUse.send(envelope);
56058
56174
  }
56059
56175
  }
56060
56176
  catch (error) {
@@ -56949,6 +57065,17 @@
56949
57065
  writeUInt32BE(buf, value);
56950
57066
  return buf;
56951
57067
  }
57068
+ function encode$1(string) {
57069
+ const bytes = new Uint8Array(string.length);
57070
+ for (let i = 0; i < string.length; i++) {
57071
+ const code = string.charCodeAt(i);
57072
+ if (code > 127) {
57073
+ throw new TypeError('non-ASCII string encountered in encode()');
57074
+ }
57075
+ bytes[i] = code;
57076
+ }
57077
+ return bytes;
57078
+ }
56952
57079
 
56953
57080
  function encodeBase64(input) {
56954
57081
  if (Uint8Array.prototype.toBase64) {
@@ -56983,7 +57110,7 @@
56983
57110
  if (encoded instanceof Uint8Array) {
56984
57111
  encoded = decoder.decode(encoded);
56985
57112
  }
56986
- encoded = encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
57113
+ encoded = encoded.replace(/-/g, '+').replace(/_/g, '/');
56987
57114
  try {
56988
57115
  return decodeBase64(encoded);
56989
57116
  }
@@ -57127,7 +57254,7 @@
57127
57254
  JWTInvalid: JWTInvalid
57128
57255
  });
57129
57256
 
57130
- function bitLength$1(alg) {
57257
+ function bitLength(alg) {
57131
57258
  switch (alg) {
57132
57259
  case 'A128GCM':
57133
57260
  case 'A128GCMKW':
@@ -57144,27 +57271,23 @@
57144
57271
  throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
57145
57272
  }
57146
57273
  }
57147
- var generateIv = (alg) => crypto.getRandomValues(new Uint8Array(bitLength$1(alg) >> 3));
57274
+ const generateIv = (alg) => crypto.getRandomValues(new Uint8Array(bitLength(alg) >> 3));
57148
57275
 
57149
- var checkIvLength = (enc, iv) => {
57150
- if (iv.length << 3 !== bitLength$1(enc)) {
57276
+ function checkIvLength(enc, iv) {
57277
+ if (iv.length << 3 !== bitLength(enc)) {
57151
57278
  throw new JWEInvalid('Invalid Initialization Vector length');
57152
57279
  }
57153
- };
57280
+ }
57154
57281
 
57155
- var checkCekLength = (cek, expected) => {
57282
+ function checkCekLength(cek, expected) {
57156
57283
  const actual = cek.byteLength << 3;
57157
57284
  if (actual !== expected) {
57158
57285
  throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
57159
57286
  }
57160
- };
57161
-
57162
- function unusable(name, prop = 'algorithm.name') {
57163
- return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
57164
- }
57165
- function isAlgorithm(algorithm, name) {
57166
- return algorithm.name === name;
57167
57287
  }
57288
+
57289
+ const unusable = (name, prop = 'algorithm.name') => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
57290
+ const isAlgorithm = (algorithm, name) => algorithm.name === name;
57168
57291
  function getHashLength(hash) {
57169
57292
  return parseInt(hash.name.slice(4), 10);
57170
57293
  }
@@ -57332,27 +57455,26 @@
57332
57455
  }
57333
57456
  return msg;
57334
57457
  }
57335
- var invalidKeyInput = (actual, ...types) => {
57336
- return message('Key must be ', actual, ...types);
57337
- };
57338
- function withAlg(alg, actual, ...types) {
57339
- return message(`Key for the ${alg} algorithm must be `, actual, ...types);
57340
- }
57458
+ const invalidKeyInput = (actual, ...types) => message('Key must be ', actual, ...types);
57459
+ const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
57341
57460
 
57342
57461
  function assertCryptoKey(key) {
57343
57462
  if (!isCryptoKey(key)) {
57344
57463
  throw new Error('CryptoKey instance expected');
57345
57464
  }
57346
57465
  }
57347
- function isCryptoKey(key) {
57348
- return key?.[Symbol.toStringTag] === 'CryptoKey';
57349
- }
57350
- function isKeyObject(key) {
57351
- return key?.[Symbol.toStringTag] === 'KeyObject';
57352
- }
57353
- var isKeyLike = (key) => {
57354
- return isCryptoKey(key) || isKeyObject(key);
57466
+ const isCryptoKey = (key) => {
57467
+ if (key?.[Symbol.toStringTag] === 'CryptoKey')
57468
+ return true;
57469
+ try {
57470
+ return key instanceof CryptoKey;
57471
+ }
57472
+ catch {
57473
+ return false;
57474
+ }
57355
57475
  };
57476
+ const isKeyObject = (key) => key?.[Symbol.toStringTag] === 'KeyObject';
57477
+ const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
57356
57478
 
57357
57479
  async function timingSafeEqual(a, b) {
57358
57480
  if (!(a instanceof Uint8Array)) {
@@ -57395,7 +57517,7 @@
57395
57517
  }
57396
57518
  let plaintext;
57397
57519
  try {
57398
- plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: 'AES-CBC' }, encKey, ciphertext));
57520
+ plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv: iv, name: 'AES-CBC' }, encKey, ciphertext));
57399
57521
  }
57400
57522
  catch {
57401
57523
  }
@@ -57416,7 +57538,7 @@
57416
57538
  try {
57417
57539
  return new Uint8Array(await crypto.subtle.decrypt({
57418
57540
  additionalData: aad,
57419
- iv,
57541
+ iv: iv,
57420
57542
  name: 'AES-GCM',
57421
57543
  tagLength: 128,
57422
57544
  }, encKey, concat(ciphertext, tag)));
@@ -57425,7 +57547,7 @@
57425
57547
  throw new JWEDecryptionFailed();
57426
57548
  }
57427
57549
  }
57428
- var decrypt$1 = async (enc, cek, ciphertext, iv, tag, aad) => {
57550
+ async function decrypt$1(enc, cek, ciphertext, iv, tag, aad) {
57429
57551
  if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
57430
57552
  throw new TypeError(invalidKeyInput(cek, 'CryptoKey', 'KeyObject', 'Uint8Array', 'JSON Web Key'));
57431
57553
  }
@@ -57452,9 +57574,9 @@
57452
57574
  default:
57453
57575
  throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm');
57454
57576
  }
57455
- };
57577
+ }
57456
57578
 
57457
- var isDisjoint = (...headers) => {
57579
+ function isDisjoint(...headers) {
57458
57580
  const sources = headers.filter(Boolean);
57459
57581
  if (sources.length === 0 || sources.length === 1) {
57460
57582
  return true;
@@ -57474,12 +57596,10 @@
57474
57596
  }
57475
57597
  }
57476
57598
  return true;
57477
- };
57478
-
57479
- function isObjectLike(value) {
57480
- return typeof value === 'object' && value !== null;
57481
57599
  }
57482
- var isObject = (input) => {
57600
+
57601
+ const isObjectLike = (value) => typeof value === 'object' && value !== null;
57602
+ function isObject(input) {
57483
57603
  if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {
57484
57604
  return false;
57485
57605
  }
@@ -57491,7 +57611,7 @@
57491
57611
  proto = Object.getPrototypeOf(proto);
57492
57612
  }
57493
57613
  return Object.getPrototypeOf(input) === proto;
57494
- };
57614
+ }
57495
57615
 
57496
57616
  function checkKeySize(key, alg) {
57497
57617
  if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) {
@@ -57518,10 +57638,10 @@
57518
57638
  return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek));
57519
57639
  }
57520
57640
 
57521
- var digest = async (algorithm, data) => {
57641
+ async function digest(algorithm, data) {
57522
57642
  const subtleDigest = `SHA-${algorithm.slice(-3)}`;
57523
57643
  return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
57524
- };
57644
+ }
57525
57645
 
57526
57646
  function lengthAndInput(input) {
57527
57647
  return concat(uint32be(input.length), input);
@@ -57541,14 +57661,14 @@
57541
57661
  }
57542
57662
  return dk.slice(0, dkLen);
57543
57663
  }
57544
- async function deriveKey$1(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {
57664
+ async function deriveKey$1(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) {
57545
57665
  checkEncCryptoKey(publicKey, 'ECDH');
57546
57666
  checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits');
57547
- const algorithmID = lengthAndInput(encoder.encode(algorithm));
57667
+ const algorithmID = lengthAndInput(encode$1(algorithm));
57548
57668
  const partyUInfo = lengthAndInput(apu);
57549
57669
  const partyVInfo = lengthAndInput(apv);
57550
57670
  const suppPubInfo = uint32be(keyLength);
57551
- const suppPrivInfo = new Uint8Array(0);
57671
+ const suppPrivInfo = new Uint8Array();
57552
57672
  const otherInfo = concat(algorithmID, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo);
57553
57673
  const Z = new Uint8Array(await crypto.subtle.deriveBits({
57554
57674
  name: publicKey.algorithm.name,
@@ -57575,12 +57695,14 @@
57575
57695
 
57576
57696
  function getCryptoKey(key, alg) {
57577
57697
  if (key instanceof Uint8Array) {
57578
- return crypto.subtle.importKey('raw', key, 'PBKDF2', false, ['deriveBits']);
57698
+ return crypto.subtle.importKey('raw', key, 'PBKDF2', false, [
57699
+ 'deriveBits',
57700
+ ]);
57579
57701
  }
57580
57702
  checkEncCryptoKey(key, alg, 'deriveBits');
57581
57703
  return key;
57582
57704
  }
57583
- const concatSalt = (alg, p2sInput) => concat(encoder.encode(alg), new Uint8Array([0]), p2sInput);
57705
+ const concatSalt = (alg, p2sInput) => concat(encode$1(alg), Uint8Array.of(0x00), p2sInput);
57584
57706
  async function deriveKey(p2s, alg, p2c, key) {
57585
57707
  if (!(p2s instanceof Uint8Array) || p2s.length < 8) {
57586
57708
  throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets');
@@ -57606,14 +57728,14 @@
57606
57728
  return unwrap$2(alg.slice(-6), derived, encryptedKey);
57607
57729
  }
57608
57730
 
57609
- var checkKeyLength = (alg, key) => {
57731
+ function checkKeyLength(alg, key) {
57610
57732
  if (alg.startsWith('RS') || alg.startsWith('PS')) {
57611
57733
  const { modulusLength } = key.algorithm;
57612
57734
  if (typeof modulusLength !== 'number' || modulusLength < 2048) {
57613
57735
  throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
57614
57736
  }
57615
57737
  }
57616
- };
57738
+ }
57617
57739
 
57618
57740
  const subtleAlgorithm$1 = (alg) => {
57619
57741
  switch (alg) {
@@ -57637,7 +57759,7 @@
57637
57759
  return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm$1(alg), key, encryptedKey));
57638
57760
  }
57639
57761
 
57640
- function bitLength(alg) {
57762
+ function cekLength(alg) {
57641
57763
  switch (alg) {
57642
57764
  case 'A128GCM':
57643
57765
  return 128;
@@ -57654,7 +57776,7 @@
57654
57776
  throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);
57655
57777
  }
57656
57778
  }
57657
- var generateCek = (alg) => crypto.getRandomValues(new Uint8Array(bitLength(alg) >> 3));
57779
+ const generateCek = (alg) => crypto.getRandomValues(new Uint8Array(cekLength(alg) >> 3));
57658
57780
 
57659
57781
  const formatPEM = (b64, descriptor) => {
57660
57782
  const newlined = (b64.match(/.{1,64}/g) || []).join('\n');
@@ -57678,12 +57800,8 @@
57678
57800
  }
57679
57801
  return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);
57680
57802
  };
57681
- const toSPKI = (key) => {
57682
- return genericExport('public', 'spki', key);
57683
- };
57684
- const toPKCS8 = (key) => {
57685
- return genericExport('private', 'pkcs8', key);
57686
- };
57803
+ const toSPKI = (key) => genericExport('public', 'spki', key);
57804
+ const toPKCS8 = (key) => genericExport('private', 'pkcs8', key);
57687
57805
  const bytesEqual = (a, b) => {
57688
57806
  if (a.byteLength !== b.length)
57689
57807
  return false;
@@ -57996,7 +58114,7 @@
57996
58114
  }
57997
58115
  return { algorithm, keyUsages };
57998
58116
  }
57999
- var importJWK$1 = async (jwk) => {
58117
+ async function jwkToKey(jwk) {
58000
58118
  if (!jwk.alg) {
58001
58119
  throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
58002
58120
  }
@@ -58007,7 +58125,7 @@
58007
58125
  }
58008
58126
  delete keyData.use;
58009
58127
  return crypto.subtle.importKey('jwk', keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
58010
- };
58128
+ }
58011
58129
 
58012
58130
  async function importSPKI(spki, alg, options) {
58013
58131
  if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {
@@ -58044,7 +58162,7 @@
58044
58162
  if ('oth' in jwk && jwk.oth !== undefined) {
58045
58163
  throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
58046
58164
  }
58047
- return importJWK$1({ ...jwk, alg, ext });
58165
+ return jwkToKey({ ...jwk, alg, ext });
58048
58166
  case 'AKP': {
58049
58167
  if (typeof jwk.alg !== 'string' || !jwk.alg) {
58050
58168
  throw new TypeError('missing "alg" (Algorithm) Parameter value');
@@ -58052,11 +58170,11 @@
58052
58170
  if (alg !== undefined && alg !== jwk.alg) {
58053
58171
  throw new TypeError('JWK alg and alg option value mismatch');
58054
58172
  }
58055
- return importJWK$1({ ...jwk, ext });
58173
+ return jwkToKey({ ...jwk, ext });
58056
58174
  }
58057
58175
  case 'EC':
58058
58176
  case 'OKP':
58059
- return importJWK$1({ ...jwk, alg, ext });
58177
+ return jwkToKey({ ...jwk, alg, ext });
58060
58178
  default:
58061
58179
  throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
58062
58180
  }
@@ -58073,7 +58191,7 @@
58073
58191
  name: 'HMAC',
58074
58192
  }, false, ['sign']);
58075
58193
  const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
58076
- iv,
58194
+ iv: iv,
58077
58195
  name: 'AES-CBC',
58078
58196
  }, encKey, plaintext));
58079
58197
  const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
@@ -58091,7 +58209,7 @@
58091
58209
  }
58092
58210
  const encrypted = new Uint8Array(await crypto.subtle.encrypt({
58093
58211
  additionalData: aad,
58094
- iv,
58212
+ iv: iv,
58095
58213
  name: 'AES-GCM',
58096
58214
  tagLength: 128,
58097
58215
  }, encKey, plaintext));
@@ -58099,7 +58217,7 @@
58099
58217
  const ciphertext = encrypted.slice(0, -16);
58100
58218
  return { ciphertext, tag, iv };
58101
58219
  }
58102
- var encrypt = async (enc, plaintext, cek, iv, aad) => {
58220
+ async function encrypt(enc, plaintext, cek, iv, aad) {
58103
58221
  if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {
58104
58222
  throw new TypeError(invalidKeyInput(cek, 'CryptoKey', 'KeyObject', 'Uint8Array', 'JSON Web Key'));
58105
58223
  }
@@ -58127,11 +58245,11 @@
58127
58245
  default:
58128
58246
  throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm');
58129
58247
  }
58130
- };
58248
+ }
58131
58249
 
58132
58250
  async function wrap(alg, key, cek, iv) {
58133
58251
  const jweAlgorithm = alg.slice(0, 7);
58134
- const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array(0));
58252
+ const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array());
58135
58253
  return {
58136
58254
  encryptedKey: wrapped.ciphertext,
58137
58255
  iv: encode(wrapped.iv),
@@ -58140,10 +58258,10 @@
58140
58258
  }
58141
58259
  async function unwrap(alg, key, encryptedKey, iv, tag) {
58142
58260
  const jweAlgorithm = alg.slice(0, 7);
58143
- return decrypt$1(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0));
58261
+ return decrypt$1(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array());
58144
58262
  }
58145
58263
 
58146
- var decryptKeyManagement = async (alg, key, encryptedKey, joseHeader, options) => {
58264
+ async function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) {
58147
58265
  switch (alg) {
58148
58266
  case 'dir': {
58149
58267
  if (encryptedKey !== undefined)
@@ -58185,7 +58303,7 @@
58185
58303
  throw new JWEInvalid('Failed to base64url decode the apv');
58186
58304
  }
58187
58305
  }
58188
- const sharedSecret = await deriveKey$1(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? bitLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);
58306
+ const sharedSecret = await deriveKey$1(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);
58189
58307
  if (alg === 'ECDH-ES')
58190
58308
  return sharedSecret;
58191
58309
  if (encryptedKey === undefined)
@@ -58258,9 +58376,9 @@
58258
58376
  throw new JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value');
58259
58377
  }
58260
58378
  }
58261
- };
58379
+ }
58262
58380
 
58263
- var validateCrit = (Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) => {
58381
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
58264
58382
  if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
58265
58383
  throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
58266
58384
  }
@@ -58291,9 +58409,9 @@
58291
58409
  }
58292
58410
  }
58293
58411
  return new Set(protectedHeader.crit);
58294
- };
58412
+ }
58295
58413
 
58296
- var validateAlgorithms = (option, algorithms) => {
58414
+ function validateAlgorithms(option, algorithms) {
58297
58415
  if (algorithms !== undefined &&
58298
58416
  (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {
58299
58417
  throw new TypeError(`"${option}" option must be an array of strings`);
@@ -58302,22 +58420,14 @@
58302
58420
  return undefined;
58303
58421
  }
58304
58422
  return new Set(algorithms);
58305
- };
58306
-
58307
- function isJWK(key) {
58308
- return isObject(key) && typeof key.kty === 'string';
58309
- }
58310
- function isPrivateJWK(key) {
58311
- return (key.kty !== 'oct' &&
58312
- ((key.kty === 'AKP' && typeof key.priv === 'string') || typeof key.d === 'string'));
58313
- }
58314
- function isPublicJWK(key) {
58315
- return key.kty !== 'oct' && typeof key.d === 'undefined' && typeof key.priv === 'undefined';
58316
- }
58317
- function isSecretJWK(key) {
58318
- return key.kty === 'oct' && typeof key.k === 'string';
58319
58423
  }
58320
58424
 
58425
+ const isJWK = (key) => isObject(key) && typeof key.kty === 'string';
58426
+ const isPrivateJWK = (key) => key.kty !== 'oct' &&
58427
+ ((key.kty === 'AKP' && typeof key.priv === 'string') || typeof key.d === 'string');
58428
+ const isPublicJWK = (key) => key.kty !== 'oct' && key.d === undefined && key.priv === undefined;
58429
+ const isSecretJWK = (key) => key.kty === 'oct' && typeof key.k === 'string';
58430
+
58321
58431
  let cache;
58322
58432
  const handleJWK = async (key, jwk, alg, freeze = false) => {
58323
58433
  cache ||= new WeakMap();
@@ -58325,7 +58435,7 @@
58325
58435
  if (cached?.[alg]) {
58326
58436
  return cached[alg];
58327
58437
  }
58328
- const cryptoKey = await importJWK$1({ ...jwk, alg });
58438
+ const cryptoKey = await jwkToKey({ ...jwk, alg });
58329
58439
  if (freeze)
58330
58440
  Object.freeze(key);
58331
58441
  if (!cached) {
@@ -58458,7 +58568,7 @@
58458
58568
  }
58459
58569
  return cryptoKey;
58460
58570
  };
58461
- var normalizeKey = async (key, alg) => {
58571
+ async function normalizeKey(key, alg) {
58462
58572
  if (key instanceof Uint8Array) {
58463
58573
  return key;
58464
58574
  }
@@ -58489,7 +58599,7 @@
58489
58599
  return handleJWK(key, key, alg, true);
58490
58600
  }
58491
58601
  throw new Error('unreachable');
58492
- };
58602
+ }
58493
58603
 
58494
58604
  const tag = (key) => key?.[Symbol.toStringTag];
58495
58605
  const jwkMatchesOp = (alg, key, usage) => {
@@ -58566,12 +58676,12 @@
58566
58676
  case 'sign':
58567
58677
  if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
58568
58678
  return;
58569
- throw new TypeError(`JSON Web Key for this operation be a private JWK`);
58679
+ throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
58570
58680
  case 'encrypt':
58571
58681
  case 'verify':
58572
58682
  if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
58573
58683
  return;
58574
- throw new TypeError(`JSON Web Key for this operation be a public JWK`);
58684
+ throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
58575
58685
  }
58576
58686
  }
58577
58687
  if (!isKeyLike(key)) {
@@ -58597,19 +58707,19 @@
58597
58707
  }
58598
58708
  }
58599
58709
  };
58600
- var checkKeyType = (alg, key, usage) => {
58601
- const symmetric = alg.startsWith('HS') ||
58602
- alg === 'dir' ||
58603
- alg.startsWith('PBES2') ||
58604
- /^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(alg) ||
58605
- /^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(alg);
58606
- if (symmetric) {
58607
- symmetricTypeCheck(alg, key, usage);
58608
- }
58609
- else {
58610
- asymmetricTypeCheck(alg, key, usage);
58710
+ function checkKeyType(alg, key, usage) {
58711
+ switch (alg.substring(0, 2)) {
58712
+ case 'A1':
58713
+ case 'A2':
58714
+ case 'di':
58715
+ case 'HS':
58716
+ case 'PB':
58717
+ symmetricTypeCheck(alg, key, usage);
58718
+ break;
58719
+ default:
58720
+ asymmetricTypeCheck(alg, key, usage);
58611
58721
  }
58612
- };
58722
+ }
58613
58723
 
58614
58724
  async function flattenedDecrypt(jwe, key, options) {
58615
58725
  if (!isObject(jwe)) {
@@ -58725,10 +58835,10 @@
58725
58835
  throw new JWEInvalid('Failed to base64url decode the tag');
58726
58836
  }
58727
58837
  }
58728
- const protectedHeader = encoder.encode(jwe.protected ?? '');
58838
+ const protectedHeader = jwe.protected !== undefined ? encode$1(jwe.protected) : new Uint8Array();
58729
58839
  let additionalData;
58730
58840
  if (jwe.aad !== undefined) {
58731
- additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(jwe.aad));
58841
+ additionalData = concat(protectedHeader, encode$1('.'), encode$1(jwe.aad));
58732
58842
  }
58733
58843
  else {
58734
58844
  additionalData = protectedHeader;
@@ -58859,7 +58969,7 @@
58859
58969
  return keyToJWK(key);
58860
58970
  }
58861
58971
 
58862
- var encryptKeyManagement = async (alg, enc, key, providedCek, providedParameters = {}) => {
58972
+ async function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) {
58863
58973
  let encryptedKey;
58864
58974
  let parameters;
58865
58975
  let cek;
@@ -58885,7 +58995,7 @@
58885
58995
  ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ['deriveBits'])).privateKey;
58886
58996
  }
58887
58997
  const { x, y, crv, kty } = await exportJWK(ephemeralKey);
58888
- const sharedSecret = await deriveKey$1(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? bitLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
58998
+ const sharedSecret = await deriveKey$1(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);
58889
58999
  parameters = { epk: { x, crv, kty } };
58890
59000
  if (kty === 'EC')
58891
59001
  parameters.epk.y = y;
@@ -58939,7 +59049,7 @@
58939
59049
  }
58940
59050
  }
58941
59051
  return { cek, encryptedKey, parameters };
58942
- };
59052
+ }
58943
59053
 
58944
59054
  class FlattenedEncrypt {
58945
59055
  #plaintext;
@@ -59053,20 +59163,24 @@
59053
59163
  }
59054
59164
  }
59055
59165
  let additionalData;
59056
- let protectedHeader;
59166
+ let protectedHeaderS;
59167
+ let protectedHeaderB;
59057
59168
  let aadMember;
59058
59169
  if (this.#protectedHeader) {
59059
- protectedHeader = encoder.encode(encode(JSON.stringify(this.#protectedHeader)));
59170
+ protectedHeaderS = encode(JSON.stringify(this.#protectedHeader));
59171
+ protectedHeaderB = encode$1(protectedHeaderS);
59060
59172
  }
59061
59173
  else {
59062
- protectedHeader = encoder.encode('');
59174
+ protectedHeaderS = '';
59175
+ protectedHeaderB = new Uint8Array();
59063
59176
  }
59064
59177
  if (this.#aad) {
59065
59178
  aadMember = encode(this.#aad);
59066
- additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember));
59179
+ const aadMemberBytes = encode$1(aadMember);
59180
+ additionalData = concat(protectedHeaderB, encode$1('.'), aadMemberBytes);
59067
59181
  }
59068
59182
  else {
59069
- additionalData = protectedHeader;
59183
+ additionalData = protectedHeaderB;
59070
59184
  }
59071
59185
  const { ciphertext, tag, iv } = await encrypt(enc, this.#plaintext, cek, this.#iv, additionalData);
59072
59186
  const jwe = {
@@ -59085,7 +59199,7 @@
59085
59199
  jwe.aad = aadMember;
59086
59200
  }
59087
59201
  if (this.#protectedHeader) {
59088
- jwe.protected = decoder.decode(protectedHeader);
59202
+ jwe.protected = protectedHeaderS;
59089
59203
  }
59090
59204
  if (this.#sharedUnprotectedHeader) {
59091
59205
  jwe.unprotected = this.#sharedUnprotectedHeader;
@@ -59100,6 +59214,7 @@
59100
59214
  class IndividualRecipient {
59101
59215
  #parent;
59102
59216
  unprotectedHeader;
59217
+ keyManagementParameters;
59103
59218
  key;
59104
59219
  options;
59105
59220
  constructor(enc, key, options) {
@@ -59114,6 +59229,13 @@
59114
59229
  this.unprotectedHeader = unprotectedHeader;
59115
59230
  return this;
59116
59231
  }
59232
+ setKeyManagementParameters(parameters) {
59233
+ if (this.keyManagementParameters) {
59234
+ throw new TypeError('setKeyManagementParameters can only be called once');
59235
+ }
59236
+ this.keyManagementParameters = parameters;
59237
+ return this;
59238
+ }
59117
59239
  addRecipient(...args) {
59118
59240
  return this.#parent.addRecipient(...args);
59119
59241
  }
@@ -59221,20 +59343,12 @@
59221
59343
  const cek = generateCek(enc);
59222
59344
  const jwe = {
59223
59345
  ciphertext: '',
59224
- iv: '',
59225
59346
  recipients: [],
59226
- tag: '',
59227
59347
  };
59228
59348
  for (let i = 0; i < this.#recipients.length; i++) {
59229
59349
  const recipient = this.#recipients[i];
59230
59350
  const target = {};
59231
59351
  jwe.recipients.push(target);
59232
- const joseHeader = {
59233
- ...this.#protectedHeader,
59234
- ...this.#unprotectedHeader,
59235
- ...recipient.unprotectedHeader,
59236
- };
59237
- const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined;
59238
59352
  if (i === 0) {
59239
59353
  const flattened = await new FlattenedEncrypt(this.#plaintext)
59240
59354
  .setAdditionalAuthenticatedData(this.#aad)
@@ -59242,7 +59356,7 @@
59242
59356
  .setProtectedHeader(this.#protectedHeader)
59243
59357
  .setSharedUnprotectedHeader(this.#unprotectedHeader)
59244
59358
  .setUnprotectedHeader(recipient.unprotectedHeader)
59245
- .setKeyManagementParameters({ p2c })
59359
+ .setKeyManagementParameters(recipient.keyManagementParameters)
59246
59360
  .encrypt(recipient.key, {
59247
59361
  ...recipient.options,
59248
59362
  [unprotected]: true,
@@ -59266,7 +59380,7 @@
59266
59380
  this.#unprotectedHeader?.alg;
59267
59381
  checkKeyType(alg === 'dir' ? enc : alg, recipient.key, 'encrypt');
59268
59382
  const k = await normalizeKey(recipient.key, alg);
59269
- const { encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, cek, { p2c });
59383
+ const { encryptedKey, parameters } = await encryptKeyManagement(alg, enc, k, cek, recipient.keyManagementParameters);
59270
59384
  target.encrypted_key = encode(encryptedKey);
59271
59385
  if (recipient.unprotectedHeader || parameters)
59272
59386
  target.header = { ...recipient.unprotectedHeader, ...parameters };
@@ -59275,7 +59389,7 @@
59275
59389
  }
59276
59390
  }
59277
59391
 
59278
- var subtleAlgorithm = (alg, algorithm) => {
59392
+ function subtleAlgorithm(alg, algorithm) {
59279
59393
  const hash = `SHA-${alg.slice(-3)}`;
59280
59394
  switch (alg) {
59281
59395
  case 'HS256':
@@ -59304,9 +59418,9 @@
59304
59418
  default:
59305
59419
  throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
59306
59420
  }
59307
- };
59421
+ }
59308
59422
 
59309
- var getSignKey = async (alg, key, usage) => {
59423
+ async function getSigKey(alg, key, usage) {
59310
59424
  if (key instanceof Uint8Array) {
59311
59425
  if (!alg.startsWith('HS')) {
59312
59426
  throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));
@@ -59315,10 +59429,10 @@
59315
59429
  }
59316
59430
  checkSigCryptoKey(key, alg, usage);
59317
59431
  return key;
59318
- };
59432
+ }
59319
59433
 
59320
- var verify = async (alg, key, signature, data) => {
59321
- const cryptoKey = await getSignKey(alg, key, 'verify');
59434
+ async function verify(alg, key, signature, data) {
59435
+ const cryptoKey = await getSigKey(alg, key, 'verify');
59322
59436
  checkKeyLength(alg, cryptoKey);
59323
59437
  const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
59324
59438
  try {
@@ -59327,7 +59441,7 @@
59327
59441
  catch {
59328
59442
  return false;
59329
59443
  }
59330
- };
59444
+ }
59331
59445
 
59332
59446
  async function flattenedVerify(jws, key, options) {
59333
59447
  if (!isObject(jws)) {
@@ -59395,7 +59509,11 @@
59395
59509
  resolvedKey = true;
59396
59510
  }
59397
59511
  checkKeyType(alg, key, 'verify');
59398
- const data = concat(encoder.encode(jws.protected ?? ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload);
59512
+ const data = concat(jws.protected !== undefined ? encode$1(jws.protected) : new Uint8Array(), encode$1('.'), typeof jws.payload === 'string'
59513
+ ? b64
59514
+ ? encode$1(jws.payload)
59515
+ : encoder.encode(jws.payload)
59516
+ : jws.payload);
59399
59517
  let signature;
59400
59518
  try {
59401
59519
  signature = decode(jws.signature);
@@ -59477,15 +59595,14 @@
59477
59595
  throw new JWSSignatureVerificationFailed();
59478
59596
  }
59479
59597
 
59480
- var epoch = (date) => Math.floor(date.getTime() / 1000);
59481
-
59598
+ const epoch = (date) => Math.floor(date.getTime() / 1000);
59482
59599
  const minute = 60;
59483
59600
  const hour = minute * 60;
59484
59601
  const day = hour * 24;
59485
59602
  const week = day * 7;
59486
59603
  const year = day * 365.25;
59487
59604
  const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
59488
- var secs = (str) => {
59605
+ function secs(str) {
59489
59606
  const matched = REGEX.exec(str);
59490
59607
  if (!matched || (matched[4] && matched[1])) {
59491
59608
  throw new TypeError('Invalid time period format');
@@ -59533,8 +59650,7 @@
59533
59650
  return -numericDate;
59534
59651
  }
59535
59652
  return numericDate;
59536
- };
59537
-
59653
+ }
59538
59654
  function validateInput(label, input) {
59539
59655
  if (!Number.isFinite(input)) {
59540
59656
  throw new TypeError(`Invalid ${label} input`);
@@ -59700,7 +59816,7 @@
59700
59816
  }
59701
59817
  }
59702
59818
  set iat(value) {
59703
- if (typeof value === 'undefined') {
59819
+ if (value === undefined) {
59704
59820
  this.#payload.iat = epoch(new Date());
59705
59821
  }
59706
59822
  else if (value instanceof Date) {
@@ -59776,12 +59892,12 @@
59776
59892
  }
59777
59893
  }
59778
59894
 
59779
- var sign = async (alg, key, data) => {
59780
- const cryptoKey = await getSignKey(alg, key, 'sign');
59895
+ async function sign(alg, key, data) {
59896
+ const cryptoKey = await getSigKey(alg, key, 'sign');
59781
59897
  checkKeyLength(alg, cryptoKey);
59782
59898
  const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);
59783
59899
  return new Uint8Array(signature);
59784
- };
59900
+ }
59785
59901
 
59786
59902
  class FlattenedSign {
59787
59903
  #payload;
@@ -59831,32 +59947,38 @@
59831
59947
  throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
59832
59948
  }
59833
59949
  checkKeyType(alg, key, 'sign');
59834
- let payload = this.#payload;
59950
+ let payloadS;
59951
+ let payloadB;
59835
59952
  if (b64) {
59836
- payload = encoder.encode(encode(payload));
59953
+ payloadS = encode(this.#payload);
59954
+ payloadB = encode$1(payloadS);
59955
+ }
59956
+ else {
59957
+ payloadB = this.#payload;
59958
+ payloadS = '';
59837
59959
  }
59838
- let protectedHeader;
59960
+ let protectedHeaderString;
59961
+ let protectedHeaderBytes;
59839
59962
  if (this.#protectedHeader) {
59840
- protectedHeader = encoder.encode(encode(JSON.stringify(this.#protectedHeader)));
59963
+ protectedHeaderString = encode(JSON.stringify(this.#protectedHeader));
59964
+ protectedHeaderBytes = encode$1(protectedHeaderString);
59841
59965
  }
59842
59966
  else {
59843
- protectedHeader = encoder.encode('');
59967
+ protectedHeaderString = '';
59968
+ protectedHeaderBytes = new Uint8Array();
59844
59969
  }
59845
- const data = concat(protectedHeader, encoder.encode('.'), payload);
59970
+ const data = concat(protectedHeaderBytes, encode$1('.'), payloadB);
59846
59971
  const k = await normalizeKey(key, alg);
59847
59972
  const signature = await sign(alg, k, data);
59848
59973
  const jws = {
59849
59974
  signature: encode(signature),
59850
- payload: '',
59975
+ payload: payloadS,
59851
59976
  };
59852
- if (b64) {
59853
- jws.payload = decoder.decode(payload);
59854
- }
59855
59977
  if (this.#unprotectedHeader) {
59856
59978
  jws.header = this.#unprotectedHeader;
59857
59979
  }
59858
59980
  if (this.#protectedHeader) {
59859
- jws.protected = decoder.decode(protectedHeader);
59981
+ jws.protected = protectedHeaderString;
59860
59982
  }
59861
59983
  return jws;
59862
59984
  }
@@ -60161,7 +60283,7 @@
60161
60283
  default:
60162
60284
  throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
60163
60285
  }
60164
- const data = encoder.encode(JSON.stringify(components));
60286
+ const data = encode$1(JSON.stringify(components));
60165
60287
  return encode(await digest(digestAlgorithm, data));
60166
60288
  }
60167
60289
  async function calculateJwkThumbprintUri(key, digestAlgorithm) {
@@ -60310,7 +60432,7 @@
60310
60432
  let USER_AGENT;
60311
60433
  if (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {
60312
60434
  const NAME = 'jose';
60313
- const VERSION = 'v6.1.0';
60435
+ const VERSION = 'v6.1.3';
60314
60436
  USER_AGENT = `${NAME}/${VERSION}`;
60315
60437
  }
60316
60438
  const customFetch = Symbol();
@@ -60616,7 +60738,7 @@
60616
60738
  algorithm = {
60617
60739
  name: 'RSA-PSS',
60618
60740
  hash: `SHA-${alg.slice(-3)}`,
60619
- publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
60741
+ publicExponent: Uint8Array.of(0x01, 0x00, 0x01),
60620
60742
  modulusLength: getModulusLengthOption(options),
60621
60743
  };
60622
60744
  keyUsages = ['sign', 'verify'];
@@ -60627,7 +60749,7 @@
60627
60749
  algorithm = {
60628
60750
  name: 'RSASSA-PKCS1-v1_5',
60629
60751
  hash: `SHA-${alg.slice(-3)}`,
60630
- publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
60752
+ publicExponent: Uint8Array.of(0x01, 0x00, 0x01),
60631
60753
  modulusLength: getModulusLengthOption(options),
60632
60754
  };
60633
60755
  keyUsages = ['sign', 'verify'];
@@ -60639,7 +60761,7 @@
60639
60761
  algorithm = {
60640
60762
  name: 'RSA-OAEP',
60641
60763
  hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,
60642
- publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
60764
+ publicExponent: Uint8Array.of(0x01, 0x00, 0x01),
60643
60765
  modulusLength: getModulusLengthOption(options),
60644
60766
  };
60645
60767
  keyUsages = ['decrypt', 'unwrapKey', 'encrypt', 'wrapKey'];