better-auth-streampay 3.0.2 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { s as streampay, E as ErrorCodeEntry } from './streampay-uhs67tYl.cjs';
2
- export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-uhs67tYl.cjs';
1
+ import { s as streampay, E as ErrorCodeEntry } from './streampay-Bij1FvXa.cjs';
2
+ export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-Bij1FvXa.cjs';
3
3
  import 'better-auth';
4
4
  import '@streamsdk/typescript';
5
5
  import 'zod';
package/dist/client.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { s as streampay, E as ErrorCodeEntry } from './streampay-uhs67tYl.js';
2
- export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-uhs67tYl.js';
1
+ import { s as streampay, E as ErrorCodeEntry } from './streampay-Bij1FvXa.js';
2
+ export { $ as $ERROR_CODES, S as StreamPayErrorCode } from './streampay-Bij1FvXa.js';
3
3
  import 'better-auth';
4
4
  import '@streamsdk/typescript';
5
5
  import 'zod';
package/dist/index.cjs CHANGED
@@ -915,6 +915,40 @@ function isUniqueConstraintError(err) {
915
915
  }
916
916
  var WEBHOOK_PROCESSING_LEASE_MS = 2 * 60 * 1e3;
917
917
  var WEBHOOK_RETRY_DELAYS_MS = [5, 30, 120, 360, 720].map((minutes) => minutes * 60 * 1e3);
918
+ var WebhookEventInProgressError = class extends Error {
919
+ constructor(eventType) {
920
+ super(`Webhook ${eventType} is already being processed; retry later.`);
921
+ this.name = "WebhookEventInProgressError";
922
+ }
923
+ };
924
+ async function findDueWebhookEvents(ctx, now, limit) {
925
+ const [retryDue, abandoned] = await Promise.all([
926
+ ctx.context.adapter.findMany({
927
+ model: WEBHOOK_EVENT_MODEL,
928
+ where: [
929
+ { field: "status", value: "pending" },
930
+ { field: "nextAttemptAt", operator: "lte", value: now }
931
+ ],
932
+ limit,
933
+ sortBy: { field: "nextAttemptAt", direction: "asc" }
934
+ }),
935
+ ctx.context.adapter.findMany({
936
+ model: WEBHOOK_EVENT_MODEL,
937
+ where: [
938
+ { field: "status", value: "pending" },
939
+ {
940
+ field: "lockedAt",
941
+ operator: "lt",
942
+ value: new Date(now.getTime() - WEBHOOK_PROCESSING_LEASE_MS)
943
+ }
944
+ ],
945
+ limit,
946
+ sortBy: { field: "lockedAt", direction: "asc" }
947
+ })
948
+ ]);
949
+ const byId = new Map([...retryDue, ...abandoned].map((row) => [row.id, row]));
950
+ return [...byId.values()].slice(0, limit);
951
+ }
918
952
  async function claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts, scope) {
919
953
  const sourceEventId = extractEventId(payload);
920
954
  const eventId = sourceEventId && (scope ? `${scope}:${sourceEventId}` : sourceEventId);
@@ -1380,6 +1414,9 @@ async function syncWebhookPayload(ctx, payload, client, plans, callbacks, option
1380
1414
  let claim = { action: "process", row: null };
1381
1415
  if (dedupe) {
1382
1416
  claim = await claimOrAdvanceWebhookEvent(ctx, payload, rawBody, signatureHeader, maxAttempts);
1417
+ if (claim.action === "skip" && claim.reason === "in_progress") {
1418
+ throw new WebhookEventInProgressError(payload.event_type);
1419
+ }
1383
1420
  if (claim.action === "skip") return;
1384
1421
  if (claim.action === "dead_letter") {
1385
1422
  logger(ctx).warn(
@@ -5068,9 +5105,9 @@ function subscriptions(subsOptions) {
5068
5105
  }
5069
5106
  };
5070
5107
  if (dedupeEnabled) {
5071
- registry.replayWebhookEvent = async (ctx, eventId) => {
5108
+ registry.replayWebhookEvent = async (ctx, eventId, replayOptions) => {
5072
5109
  if (eventId.startsWith("handlers:") && registry.replayWebhookHandler) {
5073
- return registry.replayWebhookHandler(ctx, eventId);
5110
+ return registry.replayWebhookHandler(ctx, eventId, replayOptions);
5074
5111
  }
5075
5112
  const syncCtx = {
5076
5113
  context: ctx.context
@@ -5122,6 +5159,7 @@ function subscriptions(subsOptions) {
5122
5159
  await markWebhookEventCompleted(syncCtx, claimed.id, claimed.lockedBy);
5123
5160
  return { replayed: true, eventId };
5124
5161
  } catch (err) {
5162
+ const maxAttempts = subsOptions.maxWebhookAttempts ?? DEFAULT_MAX_WEBHOOK_ATTEMPTS;
5125
5163
  await recordWebhookEventFailure(
5126
5164
  syncCtx,
5127
5165
  claimed.id,
@@ -5129,7 +5167,7 @@ function subscriptions(subsOptions) {
5129
5167
  null,
5130
5168
  err,
5131
5169
  claimed.lockedBy,
5132
- true
5170
+ !replayOptions?.retryUntilExhausted || classifyWebhookFailure(err) === "PERMANENT" || claimed.attemptCount >= maxAttempts
5133
5171
  );
5134
5172
  throw err;
5135
5173
  }
@@ -5308,6 +5346,13 @@ function verifyWebhookOrThrow(input) {
5308
5346
  }
5309
5347
 
5310
5348
  // src/plugins/webhooks.ts
5349
+ var DEFAULT_DUE_WEBHOOK_BATCH = 25;
5350
+ var ProcessDueWebhookEventsBody = zod.z.object({ limit: zod.z.number().int().min(1).max(100).optional() }).optional();
5351
+ function inProgressError() {
5352
+ return new api.APIError("SERVICE_UNAVAILABLE", {
5353
+ message: "Webhook event is already being processed. Retry later."
5354
+ });
5355
+ }
5311
5356
  function toErrorCode(reason) {
5312
5357
  return reason === "MISSING_HEADER" || reason === "INVALID_SIGNATURE" || reason === "EXPIRED" ? "UNAUTHORIZED" : "BAD_REQUEST";
5313
5358
  }
@@ -5322,7 +5367,7 @@ var webhooks = (webhooksOptions) => {
5322
5367
  return (_options, registry) => {
5323
5368
  const { secret, toleranceSeconds, deduplicate = false, ...handlers } = webhooksOptions;
5324
5369
  if (deduplicate && registry) {
5325
- registry.replayWebhookHandler = async (ctx, eventId) => {
5370
+ registry.replayWebhookHandler = async (ctx, eventId, replayOptions) => {
5326
5371
  const syncContext = { context: ctx.context };
5327
5372
  const row = await syncContext.context.adapter.findOne({
5328
5373
  model: WEBHOOK_EVENT_MODEL,
@@ -5360,7 +5405,7 @@ var webhooks = (webhooksOptions) => {
5360
5405
  row.signatureHeader,
5361
5406
  err,
5362
5407
  claimed.lockedBy,
5363
- true
5408
+ !replayOptions?.retryUntilExhausted || claimed.attemptCount >= DEFAULT_MAX_WEBHOOK_ATTEMPTS
5364
5409
  );
5365
5410
  throw err;
5366
5411
  }
@@ -5422,6 +5467,7 @@ var webhooks = (webhooksOptions) => {
5422
5467
  signatureHeader
5423
5468
  });
5424
5469
  } catch (err) {
5470
+ if (err instanceof WebhookEventInProgressError) throw inProgressError();
5425
5471
  const message = err instanceof Error ? err.message : String(err);
5426
5472
  logger2.error(`subscription sync failed: ${message}`);
5427
5473
  throw new api.APIError("INTERNAL_SERVER_ERROR", {
@@ -5438,6 +5484,7 @@ var webhooks = (webhooksOptions) => {
5438
5484
  DEFAULT_MAX_WEBHOOK_ATTEMPTS,
5439
5485
  "handlers"
5440
5486
  ) : null;
5487
+ if (claim?.action === "skip" && claim.reason === "in_progress") throw inProgressError();
5441
5488
  if (claim && claim.action !== "process") return ctx.json({ received: true });
5442
5489
  const row = claim?.action === "process" ? claim.row : null;
5443
5490
  try {
@@ -5463,6 +5510,48 @@ var webhooks = (webhooksOptions) => {
5463
5510
  }
5464
5511
  return ctx.json({ received: true });
5465
5512
  }
5513
+ ),
5514
+ processDueStreampayWebhookEvents: api.createAuthEndpoint(
5515
+ "/streampay/webhooks/process-due",
5516
+ {
5517
+ method: "POST",
5518
+ body: ProcessDueWebhookEventsBody,
5519
+ metadata: { SERVER_ONLY: true }
5520
+ },
5521
+ async (ctx) => {
5522
+ const replay = registry?.replayWebhookEvent;
5523
+ if (!replay) {
5524
+ throw new api.APIError("BAD_REQUEST", {
5525
+ message: "Retry processing requires the webhook inbox: enable subscriptions or webhooks({ deduplicate: true })."
5526
+ });
5527
+ }
5528
+ const syncContext = { context: ctx.context };
5529
+ const due = await findDueWebhookEvents(
5530
+ syncContext,
5531
+ /* @__PURE__ */ new Date(),
5532
+ ctx.body?.limit ?? DEFAULT_DUE_WEBHOOK_BATCH
5533
+ );
5534
+ const succeeded = [];
5535
+ const failed = [];
5536
+ for (const row of due) {
5537
+ try {
5538
+ await replay(ctx, row.eventId, { retryUntilExhausted: true });
5539
+ succeeded.push(row.eventId);
5540
+ } catch (err) {
5541
+ if (err instanceof api.APIError && err.status === "CONFLICT") continue;
5542
+ failed.push({
5543
+ eventId: row.eventId,
5544
+ error: err instanceof Error ? err.message : String(err)
5545
+ });
5546
+ }
5547
+ }
5548
+ if (failed.length > 0) {
5549
+ getLogger(ctx).error(
5550
+ `webhook retry: ${failed.length} of ${due.length} due events failed again`
5551
+ );
5552
+ }
5553
+ return ctx.json({ succeeded, failed });
5554
+ }
5466
5555
  )
5467
5556
  }
5468
5557
  };
@@ -5587,7 +5676,7 @@ var onUserDelete = (options) => async (user, context) => {
5587
5676
 
5588
5677
  // package.json
5589
5678
  var package_default = {
5590
- version: "3.0.2"};
5679
+ version: "3.1.0"};
5591
5680
 
5592
5681
  // src/version.ts
5593
5682
  var version = package_default.version;