@astrasyncai/verification-gateway 5.11.0 → 5.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +4 -0
  2. package/dist/adapters/express.d.mts +1 -1
  3. package/dist/adapters/express.d.ts +1 -1
  4. package/dist/adapters/express.js +394 -39
  5. package/dist/adapters/express.js.map +1 -1
  6. package/dist/adapters/express.mjs +394 -39
  7. package/dist/adapters/express.mjs.map +1 -1
  8. package/dist/adapters/mcp.d.mts +5 -1
  9. package/dist/adapters/mcp.d.ts +5 -1
  10. package/dist/adapters/mcp.js +193 -49
  11. package/dist/adapters/mcp.js.map +1 -1
  12. package/dist/adapters/mcp.mjs +193 -49
  13. package/dist/adapters/mcp.mjs.map +1 -1
  14. package/dist/adapters/nextjs.d.mts +1 -1
  15. package/dist/adapters/nextjs.d.ts +1 -1
  16. package/dist/adapters/nextjs.js +387 -22
  17. package/dist/adapters/nextjs.js.map +1 -1
  18. package/dist/adapters/nextjs.mjs +387 -22
  19. package/dist/adapters/nextjs.mjs.map +1 -1
  20. package/dist/adapters/sdk.d.mts +9 -1
  21. package/dist/adapters/sdk.d.ts +9 -1
  22. package/dist/adapters/sdk.js +125 -16
  23. package/dist/adapters/sdk.js.map +1 -1
  24. package/dist/adapters/sdk.mjs +125 -16
  25. package/dist/adapters/sdk.mjs.map +1 -1
  26. package/dist/agent/index.js +1 -1
  27. package/dist/agent/index.js.map +1 -1
  28. package/dist/agent/index.mjs +1 -1
  29. package/dist/agent/index.mjs.map +1 -1
  30. package/dist/bin/astrasync-claude-hook.js +309 -15
  31. package/dist/bin/astrasync-codex-hook.js +309 -15
  32. package/dist/bin/astrasync-guard.js +309 -15
  33. package/dist/bin/astrasync.js +322 -17
  34. package/dist/browser/background.js +309 -15
  35. package/dist/browser/background.js.map +1 -1
  36. package/dist/browser/background.mjs +309 -15
  37. package/dist/browser/background.mjs.map +1 -1
  38. package/dist/cli/index.js +1 -1
  39. package/dist/cli/index.js.map +1 -1
  40. package/dist/cli/index.mjs +1 -1
  41. package/dist/cli/index.mjs.map +1 -1
  42. package/dist/codex/index.js +309 -15
  43. package/dist/codex/index.js.map +1 -1
  44. package/dist/codex/index.mjs +309 -15
  45. package/dist/codex/index.mjs.map +1 -1
  46. package/dist/cursor/extension.js +309 -15
  47. package/dist/cursor/extension.js.map +1 -1
  48. package/dist/cursor/extension.mjs +309 -15
  49. package/dist/cursor/extension.mjs.map +1 -1
  50. package/dist/edge-config.d.mts +1 -1
  51. package/dist/edge-config.d.ts +1 -1
  52. package/dist/edge-config.js +1 -1
  53. package/dist/edge-config.js.map +1 -1
  54. package/dist/edge-config.mjs +1 -1
  55. package/dist/edge-config.mjs.map +1 -1
  56. package/dist/edge-core/index.d.mts +128 -13
  57. package/dist/edge-core/index.d.ts +128 -13
  58. package/dist/edge-core/index.js +362 -63
  59. package/dist/edge-core/index.js.map +1 -1
  60. package/dist/edge-core/index.mjs +359 -63
  61. package/dist/edge-core/index.mjs.map +1 -1
  62. package/dist/gateway/gateway.js +309 -15
  63. package/dist/gateway/gateway.js.map +1 -1
  64. package/dist/gateway/gateway.mjs +309 -15
  65. package/dist/gateway/gateway.mjs.map +1 -1
  66. package/dist/git-trigger/git-hooks.d.mts +1 -1
  67. package/dist/git-trigger/git-hooks.d.ts +1 -1
  68. package/dist/index.d.mts +118 -15
  69. package/dist/index.d.ts +118 -15
  70. package/dist/index.js +521 -72
  71. package/dist/index.js.map +1 -1
  72. package/dist/index.mjs +515 -72
  73. package/dist/index.mjs.map +1 -1
  74. package/dist/platform-signatures.js +4 -1
  75. package/dist/platform-signatures.js.map +1 -1
  76. package/dist/platform-signatures.mjs +4 -1
  77. package/dist/platform-signatures.mjs.map +1 -1
  78. package/dist/registration/index.js +1 -1
  79. package/dist/registration/index.js.map +1 -1
  80. package/dist/registration/index.mjs +1 -1
  81. package/dist/registration/index.mjs.map +1 -1
  82. package/dist/transport/index.js +1 -1
  83. package/dist/transport/index.js.map +1 -1
  84. package/dist/transport/index.mjs +1 -1
  85. package/dist/transport/index.mjs.map +1 -1
  86. package/dist/{types-CTmUpNpS.d.mts → types-BCkwBA84.d.mts} +12 -0
  87. package/dist/{types-CTmUpNpS.d.ts → types-BCkwBA84.d.ts} +12 -0
  88. package/dist/{types-CtFXmDzm.d.ts → types-C_b4QTyO.d.ts} +18 -0
  89. package/dist/{types-DQrn_kei.d.mts → types-DlshIIR-.d.mts} +18 -0
  90. package/dist/ui/index.d.mts +1 -1
  91. package/dist/ui/index.d.ts +1 -1
  92. package/dist/verify.d.mts +35 -14
  93. package/dist/verify.d.ts +35 -14
  94. package/dist/verify.js +165 -25
  95. package/dist/verify.js.map +1 -1
  96. package/dist/verify.mjs +164 -25
  97. package/dist/verify.mjs.map +1 -1
  98. package/package.json +3 -2
@@ -3751,7 +3751,7 @@ function getTrustLevel(score) {
3751
3751
  }
3752
3752
 
3753
3753
  // src/version.ts
3754
- var SDK_VERSION = "5.11.0";
3754
+ var SDK_VERSION = "5.13.0";
3755
3755
 
3756
3756
  // src/http.ts
3757
3757
  var SDK_USER_AGENT = `astrasync-sdk/${SDK_VERSION}`;
@@ -3778,6 +3778,14 @@ function getCachedWellKnownUrls(apiBaseUrl) {
3778
3778
  return cache.get(apiBaseUrl)?.data;
3779
3779
  }
3780
3780
 
3781
+ // src/failure-posture.ts
3782
+ var REJECTED_IDENTITY_DIMENSIONS = /* @__PURE__ */ new Set([
3783
+ "identity.invalid_agent_id",
3784
+ "identity.unknown_agent",
3785
+ "agent.lookup"
3786
+ ]);
3787
+ var UNKNOWN_AGENT_GUIDANCE = "Register your agent with AstraSync (or, inside an MCP host, add the AstraSync MCP connector for keyless, human-approved registration), then present the canonical ASTRA-* id issued after owner approval.";
3788
+
3781
3789
  // src/verify.ts
3782
3790
  var DEFAULT_CONFIG = {
3783
3791
  apiBaseUrl: "https://astrasync.ai/api",
@@ -3790,7 +3798,7 @@ var DEFAULT_CONFIG = {
3790
3798
  };
3791
3799
  var initCheckPerformed = false;
3792
3800
  var deprecationWarningShown = false;
3793
- async function performInitCheck(apiBaseUrl, debug, strictInit, apiKey) {
3801
+ async function performInitCheck(apiBaseUrl, debug, strictInit, apiKey, counterparty) {
3794
3802
  initCheckPerformed = true;
3795
3803
  try {
3796
3804
  const probeUrl = `${apiBaseUrl}/agents/verify-access`;
@@ -3808,7 +3816,8 @@ async function performInitCheck(apiBaseUrl, debug, strictInit, apiKey) {
3808
3816
  );
3809
3817
  }
3810
3818
  if (apiKey) {
3811
- const selfCheck = await sdkFetch(`${apiBaseUrl}/agents/verify-access/self-check`, {
3819
+ const q = counterparty?.id ? `?counterpartyId=${encodeURIComponent(counterparty.id)}` : counterparty?.url ? `?counterpartyUrl=${encodeURIComponent(counterparty.url)}` : "";
3820
+ const selfCheck = await sdkFetch(`${apiBaseUrl}/agents/verify-access/self-check${q}`, {
3812
3821
  headers: { Authorization: `Bearer ${apiKey}` }
3813
3822
  });
3814
3823
  if (selfCheck.status === 401) {
@@ -3820,6 +3829,13 @@ async function performInitCheck(apiBaseUrl, debug, strictInit, apiKey) {
3820
3829
  console.error(message);
3821
3830
  } else if (selfCheck.ok) {
3822
3831
  const body = await selfCheck.json().catch(() => ({}));
3832
+ if (body.counterparty && body.counterparty.canVerify === false) {
3833
+ const message = `[VerificationGateway] the configured AstraSync API key cannot verify for this endpoint (${body.counterparty.message ?? "endpoint not found or owned by another account"}). Every inbound agent will be turned away until the key or counterparty is corrected.`;
3834
+ if (strictInit) {
3835
+ throw new Error(`${message} (strictInit=true)`);
3836
+ }
3837
+ console.error(message);
3838
+ }
3823
3839
  if (typeof body.daysToExpiry === "number" && body.daysToExpiry <= 7) {
3824
3840
  console.warn(
3825
3841
  `[VerificationGateway] the configured AstraSync API key expires in ${body.daysToExpiry} day(s) \u2014 rotate it at Settings \u2192 Developer Tools before integrations start failing.`
@@ -3924,11 +3940,11 @@ function createGuidanceResponse(_config, reason, options = {}) {
3924
3940
  const isMisconfig = source === "merchant_misconfig";
3925
3941
  const urls = options.urls;
3926
3942
  const guidance = isMisconfig ? {
3927
- message: "This site's AstraSync integration is misconfigured (its API key was revoked, expired, or rotated). Your identity and the AstraSync platform are fine \u2014 contact the site operator. Retrying will not help.",
3943
+ message: "This site's AstraSync integration is misconfigured (its API key was revoked, expired, rotated, or belongs to another account). Your identity and the AstraSync platform are fine \u2014 contact the site operator. Retrying will not help.",
3928
3944
  registrationUrl: urls?.registrationUrl ?? "",
3929
3945
  documentationUrl: options.remediation?.docsUrl ?? urls?.documentationUrl ?? "",
3930
3946
  steps: [
3931
- "Report the failure to the site operator \u2014 their AstraSync API key needs rotating",
3947
+ "Report the failure to the site operator \u2014 their AstraSync API key needs replacing",
3932
3948
  "Do not retry: the failure is deterministic until the operator updates their key"
3933
3949
  ]
3934
3950
  } : isApiError ? {
@@ -3989,11 +4005,44 @@ function createGuidanceResponse(_config, reason, options = {}) {
3989
4005
  // coercing the absent recommendation to a policy 'deny'. Misconfig is
3990
4006
  // deterministic and intentionally NOT marked retryable.
3991
4007
  ...isApiError && { retryable: true },
4008
+ ...options.httpStatus !== void 0 && { httpStatus: options.httpStatus },
4009
+ ...options.retryAfterMs !== void 0 && { retryAfterMs: options.retryAfterMs },
3992
4010
  correlationId: options.correlationId,
3993
4011
  attemptId: options.attemptId,
3994
4012
  verifiedAt: /* @__PURE__ */ new Date()
3995
4013
  };
3996
4014
  }
4015
+ async function readJsonSafe(response) {
4016
+ try {
4017
+ const parsed = await response.json();
4018
+ return parsed && typeof parsed === "object" ? parsed : {};
4019
+ } catch {
4020
+ return {};
4021
+ }
4022
+ }
4023
+ function rejectedIdentityGuidance(failures) {
4024
+ const f = failures?.find((x) => REJECTED_IDENTITY_DIMENSIONS.has(x.dimension));
4025
+ if (!f) return void 0;
4026
+ if (f.dimension === "agent.lookup") {
4027
+ return `The presented agent identifier is not registered with AstraSync. ${UNKNOWN_AGENT_GUIDANCE}`;
4028
+ }
4029
+ return f.guidance ? `${f.message} ${f.guidance}` : f.message;
4030
+ }
4031
+ var MAX_RETRY_AFTER_MS = 15 * 60 * 1e3;
4032
+ function parseRetryAfterMs(response) {
4033
+ const raw = response.headers?.get?.("retry-after");
4034
+ if (!raw) return void 0;
4035
+ const trimmed = raw.trim();
4036
+ let ms;
4037
+ if (/^\d+(\.\d+)?$/.test(trimmed)) {
4038
+ ms = Number(trimmed) * 1e3;
4039
+ } else {
4040
+ const at = Date.parse(trimmed);
4041
+ if (Number.isNaN(at)) return void 0;
4042
+ ms = at - Date.now();
4043
+ }
4044
+ return Math.min(MAX_RETRY_AFTER_MS, Math.max(0, Math.round(ms)));
4045
+ }
3997
4046
  async function callVerifyAccessAPI(config, request) {
3998
4047
  const { credentials, ...requestData } = request;
3999
4048
  const body = {
@@ -4050,7 +4099,8 @@ async function callVerifyAccessAPI(config, request) {
4050
4099
  body: JSON.stringify(body),
4051
4100
  signal: AbortSignal.timeout(config.verifyTimeoutMs ?? 1e4)
4052
4101
  });
4053
- const data = await response.json();
4102
+ const data = await readJsonSafe(response);
4103
+ const retryAfterMs = parseRetryAfterMs(response);
4054
4104
  if (response.status === 410) {
4055
4105
  return {
4056
4106
  success: true,
@@ -4088,13 +4138,31 @@ async function callVerifyAccessAPI(config, request) {
4088
4138
  }
4089
4139
  };
4090
4140
  }
4141
+ if (response.status === 404 && credentials.astraId && (data?.error === "AGENT_NOT_FOUND" || typeof data?.message === "string" && /agent/i.test(data.message))) {
4142
+ return {
4143
+ success: true,
4144
+ attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
4145
+ access: {
4146
+ allowed: false,
4147
+ reason: "unknown_agent",
4148
+ failures: [
4149
+ {
4150
+ dimension: "identity.unknown_agent",
4151
+ message: "The presented agent identifier is not registered with AstraSync.",
4152
+ guidance: UNKNOWN_AGENT_GUIDANCE
4153
+ }
4154
+ ]
4155
+ }
4156
+ };
4157
+ }
4091
4158
  if (!response.ok) {
4092
- if (response.status === 401) {
4159
+ const keyMismatch = response.status === 403 && data?.error === "COUNTERPARTY_KEY_MISMATCH";
4160
+ if (response.status === 401 || keyMismatch) {
4093
4161
  return {
4094
4162
  success: false,
4095
4163
  error: data.message || data.error || "Integration API key rejected",
4096
4164
  misconfig: true,
4097
- misconfigCode: typeof data?.code === "string" ? data.code : void 0,
4165
+ misconfigCode: keyMismatch ? "counterparty_key_mismatch" : typeof data?.code === "string" ? data.code : void 0,
4098
4166
  remediation: data?.remediation && typeof data.remediation === "object" ? data.remediation : void 0,
4099
4167
  correlationId: typeof data?.correlationId === "string" ? data.correlationId : void 0,
4100
4168
  attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0
@@ -4102,9 +4170,11 @@ async function callVerifyAccessAPI(config, request) {
4102
4170
  }
4103
4171
  return {
4104
4172
  success: false,
4105
- error: data.message || data.error || `API returned ${response.status}`,
4173
+ error: typeof data?.message === "string" && data.message || typeof data?.error === "string" && data.error || `API returned ${response.status}`,
4106
4174
  correlationId: typeof data?.correlationId === "string" ? data.correlationId : void 0,
4107
- attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0
4175
+ attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
4176
+ httpStatus: response.status,
4177
+ ...retryAfterMs !== void 0 && { retryAfterMs }
4108
4178
  };
4109
4179
  }
4110
4180
  return data;
@@ -4125,14 +4195,22 @@ async function verify(config, request, options) {
4125
4195
  mergedConfig.apiBaseUrl,
4126
4196
  mergedConfig.debug,
4127
4197
  true,
4128
- mergedConfig.apiKey
4198
+ mergedConfig.apiKey,
4199
+ {
4200
+ id: mergedConfig.counterpartyId,
4201
+ url: mergedConfig.counterpartyUrl ?? request.counterpartyUrl
4202
+ }
4129
4203
  );
4130
4204
  } else {
4131
4205
  void performInitCheck(
4132
4206
  mergedConfig.apiBaseUrl,
4133
4207
  mergedConfig.debug,
4134
4208
  false,
4135
- mergedConfig.apiKey
4209
+ mergedConfig.apiKey,
4210
+ {
4211
+ id: mergedConfig.counterpartyId,
4212
+ url: mergedConfig.counterpartyUrl ?? request.counterpartyUrl
4213
+ }
4136
4214
  );
4137
4215
  }
4138
4216
  }
@@ -4176,12 +4254,14 @@ async function verify(config, request, options) {
4176
4254
  correlationId: apiResponse.correlationId,
4177
4255
  attemptId: apiResponse.attemptId,
4178
4256
  remediation: apiResponse.remediation,
4257
+ httpStatus: apiResponse.httpStatus,
4258
+ retryAfterMs: apiResponse.retryAfterMs,
4179
4259
  urls
4180
4260
  });
4181
4261
  }
4182
4262
  if (!apiResponse.access?.allowed) {
4183
4263
  const aggregatedFailures = apiResponse.access?.failures;
4184
- const idVerifiedFromBackend = apiResponse.verificationContext?.idVerified === true;
4264
+ const idVerifiedFromBackend = apiResponse.verificationContext?.idVerified === true && !aggregatedFailures?.some((f) => REJECTED_IDENTITY_DIMENSIONS.has(f.dimension));
4185
4265
  const result2 = {
4186
4266
  identityVerified: idVerifiedFromBackend,
4187
4267
  policyAllowed: false,
@@ -4193,7 +4273,10 @@ async function verify(config, request, options) {
4193
4273
  requiresStepUp: apiResponse.access?.requiresStepUp,
4194
4274
  requiresApproval: apiResponse.access?.requiresApproval,
4195
4275
  guidance: {
4196
- message: apiResponse.access?.reason || "Access denied by PDLSS policy",
4276
+ // 5.12.0: a presented-but-rejected id (malformed / unknown) carries
4277
+ // actionable registration guidance on its failure — surface it
4278
+ // instead of the bare machine reason ('unknown_agent').
4279
+ message: rejectedIdentityGuidance(aggregatedFailures) ?? (apiResponse.access?.reason || "Access denied by PDLSS policy"),
4197
4280
  registrationUrl: urls?.registrationUrl ?? "",
4198
4281
  documentationUrl: urls?.documentationUrl ?? "",
4199
4282
  // 5.1.0: anonymous callers land on this branch — steer MCP-hosted
@@ -4293,7 +4376,7 @@ async function verify(config, request, options) {
4293
4376
  registrationUrl: urls?.registrationUrl ?? "",
4294
4377
  documentationUrl: urls?.documentationUrl ?? ""
4295
4378
  };
4296
- } else if (result.recommendation === "step_up_required") {
4379
+ } else if (result.recommendation === "step_up_required" && result.identityVerified) {
4297
4380
  result.requiresStepUp = true;
4298
4381
  result.denialReasons = serverDenialReasons ?? result.recommendationReasons ?? ["Step-up verification required"];
4299
4382
  }
@@ -4322,6 +4405,217 @@ var DEFAULT_EDGE_CONFIG = Object.freeze({
4322
4405
  var DEFAULT_TTL_MS = 60 * 1e3;
4323
4406
  var DEFAULT_MAX_STALE_MS = 24 * 60 * 60 * 1e3;
4324
4407
 
4408
+ // src/edge-core/events.ts
4409
+ async function withBudget(promise, ms) {
4410
+ let timer;
4411
+ try {
4412
+ return await Promise.race([
4413
+ promise,
4414
+ new Promise((resolve) => {
4415
+ timer = setTimeout(() => resolve(void 0), ms);
4416
+ })
4417
+ ]);
4418
+ } catch {
4419
+ return void 0;
4420
+ } finally {
4421
+ if (timer) clearTimeout(timer);
4422
+ }
4423
+ }
4424
+ var destKeyOf = (d) => `${d.apiBaseUrl}\0${d.apiKey ?? ""}\0${d.counterparty}\0${d.adapter ?? ""}`;
4425
+ var BeaconBuffer = class {
4426
+ constructor(options = {}) {
4427
+ this.queue = [];
4428
+ this.droppedSinceLast = 0;
4429
+ this.droppedTotal = 0;
4430
+ this.deliveredTotal = 0;
4431
+ this.backoffUntil = 0;
4432
+ this.collapse = /* @__PURE__ */ new Map();
4433
+ /** Keys the backend answered 401 for — later batches go unauthenticated. */
4434
+ this.rejectedKeys = /* @__PURE__ */ new Set();
4435
+ this.opts = {
4436
+ maxItems: options.maxItems ?? 1e3,
4437
+ maxBatch: options.maxBatch ?? 100,
4438
+ maxAttempts: options.maxAttempts ?? 3,
4439
+ collapseWindowMs: options.collapseWindowMs ?? 6e4,
4440
+ collapseMaxKeys: options.collapseMaxKeys ?? 1e3,
4441
+ requestTimeoutMs: options.requestTimeoutMs ?? 1e4,
4442
+ retryBackoffMs: options.retryBackoffMs ?? 1e3,
4443
+ now: options.now ?? Date.now
4444
+ };
4445
+ }
4446
+ /**
4447
+ * Queue one beacon. With a `collapseKey`, a repeat inside the window is
4448
+ * merged into a held aggregate (sent when the window closes) instead of
4449
+ * becoming its own item.
4450
+ */
4451
+ enqueue(dest, item, collapseKey) {
4452
+ const now = this.opts.now();
4453
+ if (collapseKey) {
4454
+ const entry = this.collapse.get(collapseKey);
4455
+ if (entry && now - entry.firstSeenAt < this.opts.collapseWindowMs) {
4456
+ for (const target of [entry.first, entry.held]) {
4457
+ if (target && !target.inFlight && this.queue.includes(target)) {
4458
+ target.item.repeatCount = (target.item.repeatCount ?? 1) + 1;
4459
+ return;
4460
+ }
4461
+ }
4462
+ const held = this.push(
4463
+ dest,
4464
+ { ...item, repeatCount: 1 },
4465
+ entry.firstSeenAt + this.opts.collapseWindowMs
4466
+ );
4467
+ entry.held = held;
4468
+ return;
4469
+ }
4470
+ this.collapse.delete(collapseKey);
4471
+ if (this.collapse.size >= this.opts.collapseMaxKeys) {
4472
+ const oldest = this.collapse.keys().next().value;
4473
+ if (oldest !== void 0) this.collapse.delete(oldest);
4474
+ }
4475
+ const fresh = { firstSeenAt: now };
4476
+ this.collapse.set(collapseKey, fresh);
4477
+ fresh.first = this.push(dest, item, now);
4478
+ return;
4479
+ }
4480
+ this.push(dest, item, now);
4481
+ }
4482
+ /**
4483
+ * Deliver every eligible queued item. Concurrent callers share ONE
4484
+ * in-flight drain (it survives the caller's budget and a Lambda freeze),
4485
+ * so nothing in flight is ever sent twice; items queued while it runs are
4486
+ * picked up by the same drain.
4487
+ */
4488
+ flush() {
4489
+ if (!this.inFlight) {
4490
+ this.inFlight = this.drain().finally(() => {
4491
+ this.inFlight = void 0;
4492
+ });
4493
+ }
4494
+ return this.inFlight;
4495
+ }
4496
+ /** Counters for tests and diagnostics. */
4497
+ stats() {
4498
+ return {
4499
+ queueDepth: this.queue.length,
4500
+ droppedSinceLast: this.droppedSinceLast,
4501
+ droppedTotal: this.droppedTotal,
4502
+ deliveredTotal: this.deliveredTotal,
4503
+ flushing: this.inFlight !== void 0
4504
+ };
4505
+ }
4506
+ push(dest, item, eligibleAt) {
4507
+ while (this.queue.length >= this.opts.maxItems) this.dropOldest();
4508
+ const entry = {
4509
+ dest,
4510
+ destKey: destKeyOf(dest),
4511
+ item,
4512
+ attempts: 0,
4513
+ eligibleAt,
4514
+ inFlight: false
4515
+ };
4516
+ this.queue.push(entry);
4517
+ return entry;
4518
+ }
4519
+ dropOldest() {
4520
+ if (this.queue.shift()) this.countDropped(1);
4521
+ }
4522
+ countDropped(n) {
4523
+ this.droppedSinceLast += n;
4524
+ this.droppedTotal += n;
4525
+ }
4526
+ async drain() {
4527
+ for (; ; ) {
4528
+ const now = this.opts.now();
4529
+ if (now < this.backoffUntil) return;
4530
+ const batch = this.takeBatch(now);
4531
+ if (batch.length === 0) return;
4532
+ const ok = await this.send(batch);
4533
+ if (!ok) return;
4534
+ }
4535
+ }
4536
+ /** Oldest eligible item + up to maxBatch-1 more for the same destination. */
4537
+ takeBatch(now) {
4538
+ const first = this.queue.find((q) => q.eligibleAt <= now);
4539
+ if (!first) return [];
4540
+ const batch = [];
4541
+ const rest = [];
4542
+ for (const q of this.queue) {
4543
+ if (batch.length < this.opts.maxBatch && q.destKey === first.destKey && q.eligibleAt <= now) {
4544
+ q.inFlight = true;
4545
+ batch.push(q);
4546
+ } else {
4547
+ rest.push(q);
4548
+ }
4549
+ }
4550
+ this.queue = rest;
4551
+ return batch;
4552
+ }
4553
+ /** POST one batch. Returns false when the drain should pause (backoff). */
4554
+ async send(batch) {
4555
+ const dest = batch[0].dest;
4556
+ const useKey = dest.apiKey && !this.rejectedKeys.has(dest.apiKey) ? dest.apiKey : void 0;
4557
+ const reportedDropped = this.droppedSinceLast;
4558
+ const meta = {
4559
+ droppedSinceLast: reportedDropped,
4560
+ queueDepth: this.queue.length,
4561
+ adapter: dest.adapter ?? "edge-core",
4562
+ version: SDK_VERSION
4563
+ };
4564
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
4565
+ const response = await withBudget(
4566
+ sdkFetch(`${dest.apiBaseUrl}/verification-activity/edge-events`, {
4567
+ method: "POST",
4568
+ headers: {
4569
+ "Content-Type": "application/json",
4570
+ ...useKey && { Authorization: `Bearer ${useKey}` }
4571
+ },
4572
+ body: JSON.stringify({ events: batch.map((q) => q.item), meta }),
4573
+ ...controller && { signal: controller.signal }
4574
+ }),
4575
+ this.opts.requestTimeoutMs
4576
+ );
4577
+ if (!response) controller?.abort();
4578
+ const status = response?.status;
4579
+ for (const q of batch) q.inFlight = false;
4580
+ if (status !== void 0 && status >= 200 && status < 300) {
4581
+ this.droppedSinceLast = Math.max(0, this.droppedSinceLast - reportedDropped);
4582
+ this.deliveredTotal += batch.length;
4583
+ return true;
4584
+ }
4585
+ if (status === 401 && useKey) {
4586
+ this.rejectedKeys.add(useKey);
4587
+ this.requeue(batch, false);
4588
+ return true;
4589
+ }
4590
+ if (status === 429) {
4591
+ const retryAfter = Number(response?.headers.get("retry-after"));
4592
+ const waitMs = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 120) * 1e3 : 3e4;
4593
+ this.backoffUntil = this.opts.now() + waitMs;
4594
+ this.requeue(batch, false);
4595
+ return false;
4596
+ }
4597
+ if (status !== void 0 && status >= 400 && status < 500) {
4598
+ this.countDropped(batch.length);
4599
+ return true;
4600
+ }
4601
+ this.backoffUntil = this.opts.now() + this.opts.retryBackoffMs;
4602
+ this.requeue(batch, true);
4603
+ return false;
4604
+ }
4605
+ /** Put a failed batch back at the head of the queue (order preserved). */
4606
+ requeue(batch, countAttempt) {
4607
+ const keep = [];
4608
+ for (const q of batch) {
4609
+ if (countAttempt) q.attempts += 1;
4610
+ if (q.attempts >= this.opts.maxAttempts) this.countDropped(1);
4611
+ else keep.push(q);
4612
+ }
4613
+ this.queue = [...keep, ...this.queue];
4614
+ while (this.queue.length > this.opts.maxItems) this.dropOldest();
4615
+ }
4616
+ };
4617
+ var beaconBuffer = new BeaconBuffer();
4618
+
4325
4619
  // src/adapters/express.ts
4326
4620
  var DEFAULT_ROUTES_REFRESH_MS = 5 * 60 * 1e3;
4327
4621