@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
@@ -3748,7 +3748,7 @@ function getTrustLevel(score) {
3748
3748
  }
3749
3749
 
3750
3750
  // src/version.ts
3751
- var SDK_VERSION = "5.11.0";
3751
+ var SDK_VERSION = "5.13.0";
3752
3752
 
3753
3753
  // src/http.ts
3754
3754
  var SDK_USER_AGENT = `astrasync-sdk/${SDK_VERSION}`;
@@ -3775,6 +3775,14 @@ function getCachedWellKnownUrls(apiBaseUrl) {
3775
3775
  return cache.get(apiBaseUrl)?.data;
3776
3776
  }
3777
3777
 
3778
+ // src/failure-posture.ts
3779
+ var REJECTED_IDENTITY_DIMENSIONS = /* @__PURE__ */ new Set([
3780
+ "identity.invalid_agent_id",
3781
+ "identity.unknown_agent",
3782
+ "agent.lookup"
3783
+ ]);
3784
+ 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.";
3785
+
3778
3786
  // src/verify.ts
3779
3787
  var DEFAULT_CONFIG = {
3780
3788
  apiBaseUrl: "https://astrasync.ai/api",
@@ -3787,7 +3795,7 @@ var DEFAULT_CONFIG = {
3787
3795
  };
3788
3796
  var initCheckPerformed = false;
3789
3797
  var deprecationWarningShown = false;
3790
- async function performInitCheck(apiBaseUrl, debug, strictInit, apiKey) {
3798
+ async function performInitCheck(apiBaseUrl, debug, strictInit, apiKey, counterparty) {
3791
3799
  initCheckPerformed = true;
3792
3800
  try {
3793
3801
  const probeUrl = `${apiBaseUrl}/agents/verify-access`;
@@ -3805,7 +3813,8 @@ async function performInitCheck(apiBaseUrl, debug, strictInit, apiKey) {
3805
3813
  );
3806
3814
  }
3807
3815
  if (apiKey) {
3808
- const selfCheck = await sdkFetch(`${apiBaseUrl}/agents/verify-access/self-check`, {
3816
+ const q = counterparty?.id ? `?counterpartyId=${encodeURIComponent(counterparty.id)}` : counterparty?.url ? `?counterpartyUrl=${encodeURIComponent(counterparty.url)}` : "";
3817
+ const selfCheck = await sdkFetch(`${apiBaseUrl}/agents/verify-access/self-check${q}`, {
3809
3818
  headers: { Authorization: `Bearer ${apiKey}` }
3810
3819
  });
3811
3820
  if (selfCheck.status === 401) {
@@ -3817,6 +3826,13 @@ async function performInitCheck(apiBaseUrl, debug, strictInit, apiKey) {
3817
3826
  console.error(message);
3818
3827
  } else if (selfCheck.ok) {
3819
3828
  const body = await selfCheck.json().catch(() => ({}));
3829
+ if (body.counterparty && body.counterparty.canVerify === false) {
3830
+ 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.`;
3831
+ if (strictInit) {
3832
+ throw new Error(`${message} (strictInit=true)`);
3833
+ }
3834
+ console.error(message);
3835
+ }
3820
3836
  if (typeof body.daysToExpiry === "number" && body.daysToExpiry <= 7) {
3821
3837
  console.warn(
3822
3838
  `[VerificationGateway] the configured AstraSync API key expires in ${body.daysToExpiry} day(s) \u2014 rotate it at Settings \u2192 Developer Tools before integrations start failing.`
@@ -3921,11 +3937,11 @@ function createGuidanceResponse(_config, reason, options = {}) {
3921
3937
  const isMisconfig = source === "merchant_misconfig";
3922
3938
  const urls = options.urls;
3923
3939
  const guidance = isMisconfig ? {
3924
- 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.",
3940
+ 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.",
3925
3941
  registrationUrl: urls?.registrationUrl ?? "",
3926
3942
  documentationUrl: options.remediation?.docsUrl ?? urls?.documentationUrl ?? "",
3927
3943
  steps: [
3928
- "Report the failure to the site operator \u2014 their AstraSync API key needs rotating",
3944
+ "Report the failure to the site operator \u2014 their AstraSync API key needs replacing",
3929
3945
  "Do not retry: the failure is deterministic until the operator updates their key"
3930
3946
  ]
3931
3947
  } : isApiError ? {
@@ -3986,11 +4002,44 @@ function createGuidanceResponse(_config, reason, options = {}) {
3986
4002
  // coercing the absent recommendation to a policy 'deny'. Misconfig is
3987
4003
  // deterministic and intentionally NOT marked retryable.
3988
4004
  ...isApiError && { retryable: true },
4005
+ ...options.httpStatus !== void 0 && { httpStatus: options.httpStatus },
4006
+ ...options.retryAfterMs !== void 0 && { retryAfterMs: options.retryAfterMs },
3989
4007
  correlationId: options.correlationId,
3990
4008
  attemptId: options.attemptId,
3991
4009
  verifiedAt: /* @__PURE__ */ new Date()
3992
4010
  };
3993
4011
  }
4012
+ async function readJsonSafe(response) {
4013
+ try {
4014
+ const parsed = await response.json();
4015
+ return parsed && typeof parsed === "object" ? parsed : {};
4016
+ } catch {
4017
+ return {};
4018
+ }
4019
+ }
4020
+ function rejectedIdentityGuidance(failures) {
4021
+ const f = failures?.find((x) => REJECTED_IDENTITY_DIMENSIONS.has(x.dimension));
4022
+ if (!f) return void 0;
4023
+ if (f.dimension === "agent.lookup") {
4024
+ return `The presented agent identifier is not registered with AstraSync. ${UNKNOWN_AGENT_GUIDANCE}`;
4025
+ }
4026
+ return f.guidance ? `${f.message} ${f.guidance}` : f.message;
4027
+ }
4028
+ var MAX_RETRY_AFTER_MS = 15 * 60 * 1e3;
4029
+ function parseRetryAfterMs(response) {
4030
+ const raw = response.headers?.get?.("retry-after");
4031
+ if (!raw) return void 0;
4032
+ const trimmed = raw.trim();
4033
+ let ms;
4034
+ if (/^\d+(\.\d+)?$/.test(trimmed)) {
4035
+ ms = Number(trimmed) * 1e3;
4036
+ } else {
4037
+ const at = Date.parse(trimmed);
4038
+ if (Number.isNaN(at)) return void 0;
4039
+ ms = at - Date.now();
4040
+ }
4041
+ return Math.min(MAX_RETRY_AFTER_MS, Math.max(0, Math.round(ms)));
4042
+ }
3994
4043
  async function callVerifyAccessAPI(config, request) {
3995
4044
  const { credentials, ...requestData } = request;
3996
4045
  const body = {
@@ -4047,7 +4096,8 @@ async function callVerifyAccessAPI(config, request) {
4047
4096
  body: JSON.stringify(body),
4048
4097
  signal: AbortSignal.timeout(config.verifyTimeoutMs ?? 1e4)
4049
4098
  });
4050
- const data = await response.json();
4099
+ const data = await readJsonSafe(response);
4100
+ const retryAfterMs = parseRetryAfterMs(response);
4051
4101
  if (response.status === 410) {
4052
4102
  return {
4053
4103
  success: true,
@@ -4085,13 +4135,31 @@ async function callVerifyAccessAPI(config, request) {
4085
4135
  }
4086
4136
  };
4087
4137
  }
4138
+ if (response.status === 404 && credentials.astraId && (data?.error === "AGENT_NOT_FOUND" || typeof data?.message === "string" && /agent/i.test(data.message))) {
4139
+ return {
4140
+ success: true,
4141
+ attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
4142
+ access: {
4143
+ allowed: false,
4144
+ reason: "unknown_agent",
4145
+ failures: [
4146
+ {
4147
+ dimension: "identity.unknown_agent",
4148
+ message: "The presented agent identifier is not registered with AstraSync.",
4149
+ guidance: UNKNOWN_AGENT_GUIDANCE
4150
+ }
4151
+ ]
4152
+ }
4153
+ };
4154
+ }
4088
4155
  if (!response.ok) {
4089
- if (response.status === 401) {
4156
+ const keyMismatch = response.status === 403 && data?.error === "COUNTERPARTY_KEY_MISMATCH";
4157
+ if (response.status === 401 || keyMismatch) {
4090
4158
  return {
4091
4159
  success: false,
4092
4160
  error: data.message || data.error || "Integration API key rejected",
4093
4161
  misconfig: true,
4094
- misconfigCode: typeof data?.code === "string" ? data.code : void 0,
4162
+ misconfigCode: keyMismatch ? "counterparty_key_mismatch" : typeof data?.code === "string" ? data.code : void 0,
4095
4163
  remediation: data?.remediation && typeof data.remediation === "object" ? data.remediation : void 0,
4096
4164
  correlationId: typeof data?.correlationId === "string" ? data.correlationId : void 0,
4097
4165
  attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0
@@ -4099,9 +4167,11 @@ async function callVerifyAccessAPI(config, request) {
4099
4167
  }
4100
4168
  return {
4101
4169
  success: false,
4102
- error: data.message || data.error || `API returned ${response.status}`,
4170
+ error: typeof data?.message === "string" && data.message || typeof data?.error === "string" && data.error || `API returned ${response.status}`,
4103
4171
  correlationId: typeof data?.correlationId === "string" ? data.correlationId : void 0,
4104
- attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0
4172
+ attemptId: typeof data?.attemptId === "string" ? data.attemptId : void 0,
4173
+ httpStatus: response.status,
4174
+ ...retryAfterMs !== void 0 && { retryAfterMs }
4105
4175
  };
4106
4176
  }
4107
4177
  return data;
@@ -4122,14 +4192,22 @@ async function verify(config, request, options) {
4122
4192
  mergedConfig.apiBaseUrl,
4123
4193
  mergedConfig.debug,
4124
4194
  true,
4125
- mergedConfig.apiKey
4195
+ mergedConfig.apiKey,
4196
+ {
4197
+ id: mergedConfig.counterpartyId,
4198
+ url: mergedConfig.counterpartyUrl ?? request.counterpartyUrl
4199
+ }
4126
4200
  );
4127
4201
  } else {
4128
4202
  void performInitCheck(
4129
4203
  mergedConfig.apiBaseUrl,
4130
4204
  mergedConfig.debug,
4131
4205
  false,
4132
- mergedConfig.apiKey
4206
+ mergedConfig.apiKey,
4207
+ {
4208
+ id: mergedConfig.counterpartyId,
4209
+ url: mergedConfig.counterpartyUrl ?? request.counterpartyUrl
4210
+ }
4133
4211
  );
4134
4212
  }
4135
4213
  }
@@ -4173,12 +4251,14 @@ async function verify(config, request, options) {
4173
4251
  correlationId: apiResponse.correlationId,
4174
4252
  attemptId: apiResponse.attemptId,
4175
4253
  remediation: apiResponse.remediation,
4254
+ httpStatus: apiResponse.httpStatus,
4255
+ retryAfterMs: apiResponse.retryAfterMs,
4176
4256
  urls
4177
4257
  });
4178
4258
  }
4179
4259
  if (!apiResponse.access?.allowed) {
4180
4260
  const aggregatedFailures = apiResponse.access?.failures;
4181
- const idVerifiedFromBackend = apiResponse.verificationContext?.idVerified === true;
4261
+ const idVerifiedFromBackend = apiResponse.verificationContext?.idVerified === true && !aggregatedFailures?.some((f) => REJECTED_IDENTITY_DIMENSIONS.has(f.dimension));
4182
4262
  const result2 = {
4183
4263
  identityVerified: idVerifiedFromBackend,
4184
4264
  policyAllowed: false,
@@ -4190,7 +4270,10 @@ async function verify(config, request, options) {
4190
4270
  requiresStepUp: apiResponse.access?.requiresStepUp,
4191
4271
  requiresApproval: apiResponse.access?.requiresApproval,
4192
4272
  guidance: {
4193
- message: apiResponse.access?.reason || "Access denied by PDLSS policy",
4273
+ // 5.12.0: a presented-but-rejected id (malformed / unknown) carries
4274
+ // actionable registration guidance on its failure — surface it
4275
+ // instead of the bare machine reason ('unknown_agent').
4276
+ message: rejectedIdentityGuidance(aggregatedFailures) ?? (apiResponse.access?.reason || "Access denied by PDLSS policy"),
4194
4277
  registrationUrl: urls?.registrationUrl ?? "",
4195
4278
  documentationUrl: urls?.documentationUrl ?? "",
4196
4279
  // 5.1.0: anonymous callers land on this branch — steer MCP-hosted
@@ -4290,7 +4373,7 @@ async function verify(config, request, options) {
4290
4373
  registrationUrl: urls?.registrationUrl ?? "",
4291
4374
  documentationUrl: urls?.documentationUrl ?? ""
4292
4375
  };
4293
- } else if (result.recommendation === "step_up_required") {
4376
+ } else if (result.recommendation === "step_up_required" && result.identityVerified) {
4294
4377
  result.requiresStepUp = true;
4295
4378
  result.denialReasons = serverDenialReasons ?? result.recommendationReasons ?? ["Step-up verification required"];
4296
4379
  }
@@ -4319,6 +4402,217 @@ var DEFAULT_EDGE_CONFIG = Object.freeze({
4319
4402
  var DEFAULT_TTL_MS = 60 * 1e3;
4320
4403
  var DEFAULT_MAX_STALE_MS = 24 * 60 * 60 * 1e3;
4321
4404
 
4405
+ // src/edge-core/events.ts
4406
+ async function withBudget(promise, ms) {
4407
+ let timer;
4408
+ try {
4409
+ return await Promise.race([
4410
+ promise,
4411
+ new Promise((resolve) => {
4412
+ timer = setTimeout(() => resolve(void 0), ms);
4413
+ })
4414
+ ]);
4415
+ } catch {
4416
+ return void 0;
4417
+ } finally {
4418
+ if (timer) clearTimeout(timer);
4419
+ }
4420
+ }
4421
+ var destKeyOf = (d) => `${d.apiBaseUrl}\0${d.apiKey ?? ""}\0${d.counterparty}\0${d.adapter ?? ""}`;
4422
+ var BeaconBuffer = class {
4423
+ constructor(options = {}) {
4424
+ this.queue = [];
4425
+ this.droppedSinceLast = 0;
4426
+ this.droppedTotal = 0;
4427
+ this.deliveredTotal = 0;
4428
+ this.backoffUntil = 0;
4429
+ this.collapse = /* @__PURE__ */ new Map();
4430
+ /** Keys the backend answered 401 for — later batches go unauthenticated. */
4431
+ this.rejectedKeys = /* @__PURE__ */ new Set();
4432
+ this.opts = {
4433
+ maxItems: options.maxItems ?? 1e3,
4434
+ maxBatch: options.maxBatch ?? 100,
4435
+ maxAttempts: options.maxAttempts ?? 3,
4436
+ collapseWindowMs: options.collapseWindowMs ?? 6e4,
4437
+ collapseMaxKeys: options.collapseMaxKeys ?? 1e3,
4438
+ requestTimeoutMs: options.requestTimeoutMs ?? 1e4,
4439
+ retryBackoffMs: options.retryBackoffMs ?? 1e3,
4440
+ now: options.now ?? Date.now
4441
+ };
4442
+ }
4443
+ /**
4444
+ * Queue one beacon. With a `collapseKey`, a repeat inside the window is
4445
+ * merged into a held aggregate (sent when the window closes) instead of
4446
+ * becoming its own item.
4447
+ */
4448
+ enqueue(dest, item, collapseKey) {
4449
+ const now = this.opts.now();
4450
+ if (collapseKey) {
4451
+ const entry = this.collapse.get(collapseKey);
4452
+ if (entry && now - entry.firstSeenAt < this.opts.collapseWindowMs) {
4453
+ for (const target of [entry.first, entry.held]) {
4454
+ if (target && !target.inFlight && this.queue.includes(target)) {
4455
+ target.item.repeatCount = (target.item.repeatCount ?? 1) + 1;
4456
+ return;
4457
+ }
4458
+ }
4459
+ const held = this.push(
4460
+ dest,
4461
+ { ...item, repeatCount: 1 },
4462
+ entry.firstSeenAt + this.opts.collapseWindowMs
4463
+ );
4464
+ entry.held = held;
4465
+ return;
4466
+ }
4467
+ this.collapse.delete(collapseKey);
4468
+ if (this.collapse.size >= this.opts.collapseMaxKeys) {
4469
+ const oldest = this.collapse.keys().next().value;
4470
+ if (oldest !== void 0) this.collapse.delete(oldest);
4471
+ }
4472
+ const fresh = { firstSeenAt: now };
4473
+ this.collapse.set(collapseKey, fresh);
4474
+ fresh.first = this.push(dest, item, now);
4475
+ return;
4476
+ }
4477
+ this.push(dest, item, now);
4478
+ }
4479
+ /**
4480
+ * Deliver every eligible queued item. Concurrent callers share ONE
4481
+ * in-flight drain (it survives the caller's budget and a Lambda freeze),
4482
+ * so nothing in flight is ever sent twice; items queued while it runs are
4483
+ * picked up by the same drain.
4484
+ */
4485
+ flush() {
4486
+ if (!this.inFlight) {
4487
+ this.inFlight = this.drain().finally(() => {
4488
+ this.inFlight = void 0;
4489
+ });
4490
+ }
4491
+ return this.inFlight;
4492
+ }
4493
+ /** Counters for tests and diagnostics. */
4494
+ stats() {
4495
+ return {
4496
+ queueDepth: this.queue.length,
4497
+ droppedSinceLast: this.droppedSinceLast,
4498
+ droppedTotal: this.droppedTotal,
4499
+ deliveredTotal: this.deliveredTotal,
4500
+ flushing: this.inFlight !== void 0
4501
+ };
4502
+ }
4503
+ push(dest, item, eligibleAt) {
4504
+ while (this.queue.length >= this.opts.maxItems) this.dropOldest();
4505
+ const entry = {
4506
+ dest,
4507
+ destKey: destKeyOf(dest),
4508
+ item,
4509
+ attempts: 0,
4510
+ eligibleAt,
4511
+ inFlight: false
4512
+ };
4513
+ this.queue.push(entry);
4514
+ return entry;
4515
+ }
4516
+ dropOldest() {
4517
+ if (this.queue.shift()) this.countDropped(1);
4518
+ }
4519
+ countDropped(n) {
4520
+ this.droppedSinceLast += n;
4521
+ this.droppedTotal += n;
4522
+ }
4523
+ async drain() {
4524
+ for (; ; ) {
4525
+ const now = this.opts.now();
4526
+ if (now < this.backoffUntil) return;
4527
+ const batch = this.takeBatch(now);
4528
+ if (batch.length === 0) return;
4529
+ const ok = await this.send(batch);
4530
+ if (!ok) return;
4531
+ }
4532
+ }
4533
+ /** Oldest eligible item + up to maxBatch-1 more for the same destination. */
4534
+ takeBatch(now) {
4535
+ const first = this.queue.find((q) => q.eligibleAt <= now);
4536
+ if (!first) return [];
4537
+ const batch = [];
4538
+ const rest = [];
4539
+ for (const q of this.queue) {
4540
+ if (batch.length < this.opts.maxBatch && q.destKey === first.destKey && q.eligibleAt <= now) {
4541
+ q.inFlight = true;
4542
+ batch.push(q);
4543
+ } else {
4544
+ rest.push(q);
4545
+ }
4546
+ }
4547
+ this.queue = rest;
4548
+ return batch;
4549
+ }
4550
+ /** POST one batch. Returns false when the drain should pause (backoff). */
4551
+ async send(batch) {
4552
+ const dest = batch[0].dest;
4553
+ const useKey = dest.apiKey && !this.rejectedKeys.has(dest.apiKey) ? dest.apiKey : void 0;
4554
+ const reportedDropped = this.droppedSinceLast;
4555
+ const meta = {
4556
+ droppedSinceLast: reportedDropped,
4557
+ queueDepth: this.queue.length,
4558
+ adapter: dest.adapter ?? "edge-core",
4559
+ version: SDK_VERSION
4560
+ };
4561
+ const controller = typeof AbortController !== "undefined" ? new AbortController() : void 0;
4562
+ const response = await withBudget(
4563
+ sdkFetch(`${dest.apiBaseUrl}/verification-activity/edge-events`, {
4564
+ method: "POST",
4565
+ headers: {
4566
+ "Content-Type": "application/json",
4567
+ ...useKey && { Authorization: `Bearer ${useKey}` }
4568
+ },
4569
+ body: JSON.stringify({ events: batch.map((q) => q.item), meta }),
4570
+ ...controller && { signal: controller.signal }
4571
+ }),
4572
+ this.opts.requestTimeoutMs
4573
+ );
4574
+ if (!response) controller?.abort();
4575
+ const status = response?.status;
4576
+ for (const q of batch) q.inFlight = false;
4577
+ if (status !== void 0 && status >= 200 && status < 300) {
4578
+ this.droppedSinceLast = Math.max(0, this.droppedSinceLast - reportedDropped);
4579
+ this.deliveredTotal += batch.length;
4580
+ return true;
4581
+ }
4582
+ if (status === 401 && useKey) {
4583
+ this.rejectedKeys.add(useKey);
4584
+ this.requeue(batch, false);
4585
+ return true;
4586
+ }
4587
+ if (status === 429) {
4588
+ const retryAfter = Number(response?.headers.get("retry-after"));
4589
+ const waitMs = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 120) * 1e3 : 3e4;
4590
+ this.backoffUntil = this.opts.now() + waitMs;
4591
+ this.requeue(batch, false);
4592
+ return false;
4593
+ }
4594
+ if (status !== void 0 && status >= 400 && status < 500) {
4595
+ this.countDropped(batch.length);
4596
+ return true;
4597
+ }
4598
+ this.backoffUntil = this.opts.now() + this.opts.retryBackoffMs;
4599
+ this.requeue(batch, true);
4600
+ return false;
4601
+ }
4602
+ /** Put a failed batch back at the head of the queue (order preserved). */
4603
+ requeue(batch, countAttempt) {
4604
+ const keep = [];
4605
+ for (const q of batch) {
4606
+ if (countAttempt) q.attempts += 1;
4607
+ if (q.attempts >= this.opts.maxAttempts) this.countDropped(1);
4608
+ else keep.push(q);
4609
+ }
4610
+ this.queue = [...keep, ...this.queue];
4611
+ while (this.queue.length > this.opts.maxItems) this.dropOldest();
4612
+ }
4613
+ };
4614
+ var beaconBuffer = new BeaconBuffer();
4615
+
4322
4616
  // src/adapters/express.ts
4323
4617
  var DEFAULT_ROUTES_REFRESH_MS = 5 * 60 * 1e3;
4324
4618