better-auth-streampay 3.3.0 → 3.4.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.
@@ -1,5 +1,5 @@
1
1
  import * as better_auth from 'better-auth';
2
- import { Where, GenericEndpointContext, User, UnionToIntersection } from 'better-auth';
2
+ import { GenericEndpointContext, User, UnionToIntersection, Where } from 'better-auth';
3
3
  import * as _streamsdk_typescript from '@streamsdk/typescript';
4
4
  import { SubscriptionDetailed, CurrencyCode, CreatePaymentLinkDto, FreezeListResponse, PaymentRefundRequest, SubscriptionUpdate, ConsumerCreate, ConsumerResponse, PaginationParams, ConsumerListResponse, ConsumerUpdate, PaymentLinkDetailed, PaymentLinkListResponse, UpdatePaymentLinkStatusDto, ProductCreate, ProductDto, ProductListResponse, ProductUpdate, CouponCreate, CouponDetailed, CouponListResponse, CouponUpdate, SubscriptionCreate, SubscriptionListResponse, SubscriptionCancel, FreezeSubscriptionCreateRequest, FreezeSubscriptionBase, FreezeSubscriptionUpdateRequest, InvoiceListResponse, InvoiceDetailed, PaymentListResponse, PaymentResponse } from '@streamsdk/typescript';
5
5
  import * as zod from 'zod';
@@ -55,32 +55,6 @@ declare const $ERROR_CODES: {
55
55
  type StreamPayErrorCode = keyof typeof $ERROR_CODES;
56
56
  declare function mapToErrorCode(rawCode: string | undefined, status: number | undefined): StreamPayErrorCode;
57
57
 
58
- interface StreamPayLoggerContext {
59
- context: {
60
- adapter?: {
61
- findOne: <T = unknown>(input: {
62
- model: string;
63
- where: Where[];
64
- }) => Promise<T | null>;
65
- update?: (input: {
66
- model: string;
67
- update: Record<string, unknown>;
68
- where: Where[];
69
- }) => Promise<unknown>;
70
- };
71
- internalAdapter?: {
72
- updateUser?: (userId: string, data: Record<string, unknown>) => Promise<unknown>;
73
- listUsers?: (limit: number, offset: number, sortBy: undefined, where: Where[]) => Promise<Record<string, unknown>[]>;
74
- };
75
- logger: {
76
- error: (message: string) => void;
77
- warn: (message: string) => void;
78
- info: (message: string) => void;
79
- debug: (message: string) => void;
80
- };
81
- };
82
- }
83
-
84
58
  interface StreamPaySessionUser {
85
59
  id: string;
86
60
  email?: string;
@@ -89,10 +63,72 @@ interface StreamPaySessionUser {
89
63
  streampayConsumerId?: string | null;
90
64
  }
91
65
 
92
- declare const SUBSCRIPTION_STATUSES: readonly ["incomplete", "incomplete_expired", "trial_pending", "trialing", "active", "inactive", "expired", "canceled", "frozen", "past_due"];
93
- type SubscriptionStatus = (typeof SUBSCRIPTION_STATUSES)[number];
94
- type StreamPaySubscriptionStatus = NonNullable<SubscriptionDetailed["status"]>;
95
- declare const DEFAULT_ACCESS_STATUSES: readonly ["active", "trialing", "frozen", "past_due"];
66
+ interface PluginAdapter {
67
+ create: <T = unknown, D extends object = Record<string, unknown>>(args: {
68
+ model: string;
69
+ data: D;
70
+ }) => Promise<T>;
71
+ update: <T = unknown, D extends object = Record<string, unknown>>(args: {
72
+ model: string;
73
+ update: D;
74
+ where: Array<{
75
+ field: string;
76
+ value: unknown;
77
+ }>;
78
+ }) => Promise<T | null>;
79
+ findOne: <T = unknown>(args: {
80
+ model: string;
81
+ where: Array<{
82
+ field: string;
83
+ value: unknown;
84
+ }>;
85
+ }) => Promise<T | null>;
86
+ findMany: <T = unknown>(args: {
87
+ model: string;
88
+ where?: Array<{
89
+ field: string;
90
+ value: unknown;
91
+ operator?: "lt" | "lte";
92
+ }>;
93
+ limit?: number;
94
+ offset?: number;
95
+ sortBy?: {
96
+ field: string;
97
+ direction: "asc" | "desc";
98
+ };
99
+ }) => Promise<T[]>;
100
+ delete: (args: {
101
+ model: string;
102
+ where: Array<{
103
+ field: string;
104
+ value: unknown;
105
+ }>;
106
+ }) => Promise<void>;
107
+ count: (args: {
108
+ model: string;
109
+ where?: Array<{
110
+ field: string;
111
+ value: unknown;
112
+ }>;
113
+ }) => Promise<number>;
114
+ }
115
+ interface SyncContext {
116
+ context: {
117
+ adapter: PluginAdapter;
118
+ logger: {
119
+ error: (msg: string) => void;
120
+ warn: (msg: string) => void;
121
+ info: (msg: string) => void;
122
+ debug: (msg: string) => void;
123
+ };
124
+ session?: {
125
+ user?: unknown;
126
+ };
127
+ internalAdapter?: {
128
+ findUserById?: (userId: string) => Promise<unknown>;
129
+ };
130
+ };
131
+ }
96
132
 
97
133
  type StreamPayEntityType = "PAYMENT" | "INVOICE" | "SUBSCRIPTION" | "PAYMENT_LINK";
98
134
  declare const STREAMPAY_EVENT_ENTITY_TYPES: {
@@ -182,6 +218,84 @@ type StreamPayWebhookPayload<TEvent extends StreamPayEventType = StreamPayEventT
182
218
  entity_type: TEntity;
183
219
  }>;
184
220
 
221
+ type WebhookEventStatus = "pending" | "completed" | "dead_letter";
222
+ interface WebhookEventRow {
223
+ id: string;
224
+ eventId: string;
225
+ eventType: string;
226
+ status: WebhookEventStatus;
227
+ attemptCount: number;
228
+ receivedAt: Date;
229
+ lastAttemptAt: Date | null;
230
+ nextAttemptAt: Date | null;
231
+ completedAt: Date | null;
232
+ deadLetteredAt: Date | null;
233
+ lockedAt: Date | null;
234
+ lockedBy: string | null;
235
+ rawPayload: string | null;
236
+ signatureHeader: string | null;
237
+ lastError: string | null;
238
+ lastErrorCode: string | null;
239
+ }
240
+ /** What a scope learns about the attempt it is running. */
241
+ interface WebhookInboxAttempt {
242
+ previousError: string | null;
243
+ previousErrorCode: string | null;
244
+ }
245
+ type WebhookEventRunner = (ctx: SyncContext, attempt: WebhookInboxAttempt) => Promise<void>;
246
+ /**
247
+ * One kind of work the inbox runs for a StreamPay event. Subscription sync and generic handlers are
248
+ * the two scopes; each keeps its own inbox row per event, distinguished by `eventIdPrefix`.
249
+ */
250
+ interface WebhookInboxScope {
251
+ /** `null` keeps the unprefixed event IDs that subscription sync has always stored. */
252
+ eventIdPrefix: string | null;
253
+ maxAttempts: number;
254
+ /** Returns the work for an event this scope handles, or `null` to leave the event alone. */
255
+ prepare: (payload: StreamPayWebhookEnvelope) => WebhookEventRunner | null;
256
+ isPermanentFailure: (err: unknown) => boolean;
257
+ /** Releases scope-owned state that waits on the event before an operator discards it. */
258
+ onDiscard?: (ctx: SyncContext, row: WebhookEventRow) => Promise<void>;
259
+ }
260
+ interface ProcessDueWebhookEventsResult {
261
+ succeeded: string[];
262
+ failed: Array<{
263
+ eventId: string;
264
+ error: string;
265
+ }>;
266
+ }
267
+ interface WebhookInbox {
268
+ /**
269
+ * Adds a scope. A scope that is not `replayable` keeps its discard hook for rows it stored
270
+ * earlier, but its events are neither replayed nor retried.
271
+ *
272
+ * @throws TypeError for a prefix other than `null` or `HANDLERS_EVENT_ID_PREFIX`, which replay
273
+ * could not route.
274
+ */
275
+ register: (scope: WebhookInboxScope, options?: {
276
+ replayable?: boolean;
277
+ }) => void;
278
+ isEnabled: () => boolean;
279
+ /** With `dueAttemptCount`, replays only while the event is still that pending, due attempt. */
280
+ replay: (ctx: SyncContext, eventId: string, options?: {
281
+ dueAttemptCount?: number;
282
+ }) => Promise<{
283
+ replayed: true;
284
+ eventId: string;
285
+ }>;
286
+ /** @throws APIError `CONFLICT` while a worker holds the event or claims it during the discard. */
287
+ discard: (ctx: SyncContext, eventId: string) => Promise<{
288
+ discarded: true;
289
+ eventId: string;
290
+ }>;
291
+ processDue: (ctx: SyncContext, limit: number) => Promise<ProcessDueWebhookEventsResult>;
292
+ }
293
+
294
+ declare const SUBSCRIPTION_STATUSES: readonly ["incomplete", "incomplete_expired", "trial_pending", "trialing", "active", "inactive", "expired", "canceled", "frozen", "past_due"];
295
+ type SubscriptionStatus = (typeof SUBSCRIPTION_STATUSES)[number];
296
+ type StreamPaySubscriptionStatus = NonNullable<SubscriptionDetailed["status"]>;
297
+ declare const DEFAULT_ACCESS_STATUSES: readonly ["active", "trialing", "frozen", "past_due"];
298
+
185
299
  type SubscriptionRecurringInterval = NonNullable<SubscriptionDetailed["recurring_interval"]>;
186
300
  type SubscriptionBillingStatus = "current" | "past_due";
187
301
  type SubscriptionReferenceType = "user" | "organization" | "custom";
@@ -329,56 +443,6 @@ declare const REFERENCE_ID_METADATA_KEY = "streampay_plugin_reference_id";
329
443
  declare const REFERENCE_TYPE_METADATA_KEY = "streampay_plugin_reference_type";
330
444
  declare const SUBSCRIPTION_ROW_ID_METADATA_KEY = "streampay_plugin_subscription_row_id";
331
445
 
332
- interface PluginAdapter {
333
- create: <T = unknown, D extends object = Record<string, unknown>>(args: {
334
- model: string;
335
- data: D;
336
- }) => Promise<T>;
337
- update: <T = unknown, D extends object = Record<string, unknown>>(args: {
338
- model: string;
339
- update: D;
340
- where: Array<{
341
- field: string;
342
- value: unknown;
343
- }>;
344
- }) => Promise<T | null>;
345
- findOne: <T = unknown>(args: {
346
- model: string;
347
- where: Array<{
348
- field: string;
349
- value: unknown;
350
- }>;
351
- }) => Promise<T | null>;
352
- findMany: <T = unknown>(args: {
353
- model: string;
354
- where?: Array<{
355
- field: string;
356
- value: unknown;
357
- operator?: "lt" | "lte";
358
- }>;
359
- limit?: number;
360
- offset?: number;
361
- sortBy?: {
362
- field: string;
363
- direction: "asc" | "desc";
364
- };
365
- }) => Promise<T[]>;
366
- delete: (args: {
367
- model: string;
368
- where: Array<{
369
- field: string;
370
- value: unknown;
371
- }>;
372
- }) => Promise<void>;
373
- count: (args: {
374
- model: string;
375
- where?: Array<{
376
- field: string;
377
- value: unknown;
378
- }>;
379
- }) => Promise<number>;
380
- }
381
-
382
446
  interface ResolvedPlans {
383
447
  list: readonly StreamPayPlanLike[];
384
448
  byName: Map<string, StreamPayPlanLike>;
@@ -395,48 +459,12 @@ interface LimitCheckResult {
395
459
  }
396
460
  declare function checkLimit<P extends StreamPayPlanLike>(subscription: Subscription, plan: P | undefined, feature: FeatureKey<P>, requested: number, accessStatuses?: readonly SubscriptionStatus[]): LimitCheckResult;
397
461
 
398
- interface SyncContext {
399
- context: {
400
- adapter: PluginAdapter;
401
- logger: {
402
- error: (msg: string) => void;
403
- warn: (msg: string) => void;
404
- info: (msg: string) => void;
405
- debug: (msg: string) => void;
406
- };
407
- session?: {
408
- user?: unknown;
409
- };
410
- internalAdapter?: {
411
- findUserById?: (userId: string) => Promise<unknown>;
412
- };
413
- };
414
- }
415
- type WebhookEventStatus = "pending" | "completed" | "dead_letter";
416
- interface WebhookEventRow {
417
- id: string;
418
- eventId: string;
419
- eventType: string;
420
- status: WebhookEventStatus;
421
- attemptCount: number;
422
- receivedAt: Date;
423
- lastAttemptAt: Date | null;
424
- nextAttemptAt: Date | null;
425
- completedAt: Date | null;
426
- deadLetteredAt: Date | null;
427
- lockedAt: Date | null;
428
- lockedBy: string | null;
429
- rawPayload: string | null;
430
- signatureHeader: string | null;
431
- lastError: string | null;
432
- lastErrorCode: string | null;
433
- }
434
462
  interface WebhookReplayOptions {
435
463
  /** @deprecated No effect: a failed replay keeps a pending event retryable until its attempts are spent. */
436
464
  retryUntilExhausted?: boolean;
437
465
  /**
438
- * Set by `processDueStreampayWebhookEvents`: replay only if the event is still pending at this
439
- * attempt and due. Otherwise the replay fails with `CONFLICT`.
466
+ * Replay only if the event is still pending at this attempt and due. Otherwise the replay fails
467
+ * with `CONFLICT`. `processDueStreampayWebhookEvents` applies this check itself.
440
468
  */
441
469
  dueAttemptCount?: number;
442
470
  }
@@ -458,12 +486,23 @@ interface StreamPayPluginRegistry {
458
486
  rawBody?: string;
459
487
  signatureHeader?: string | null;
460
488
  }) => Promise<void>;
461
- replayWebhookEvent?: (ctx: GenericEndpointContext, eventId: string,
462
- /** @deprecated No effect. */
463
- options?: WebhookReplayOptions) => Promise<{
489
+ /** Shared by every plugin that stores events in the webhook inbox table. */
490
+ webhookInbox?: WebhookInbox;
491
+ /**
492
+ * Re-projects a local subscription row from StreamPay after an out-of-band provider change,
493
+ * using the configured plan catalog. Never throws: a failed projection reconciles on the next
494
+ * webhook.
495
+ */
496
+ refreshSubscriptionProjection?: (ctx: GenericEndpointContext, subscription: {
497
+ streampaySubscriptionId: string;
498
+ } | {
499
+ snapshot: SubscriptionDetailed;
500
+ }, source: string) => Promise<void>;
501
+ replayWebhookEvent?: (ctx: GenericEndpointContext, eventId: string, options?: WebhookReplayOptions) => Promise<{
464
502
  replayed: true;
465
503
  eventId: string;
466
504
  }>;
505
+ /** @deprecated Use `replayWebhookEvent`; both replay any inbox event. */
467
506
  replayWebhookHandler?: NonNullable<StreamPayPluginRegistry["replayWebhookEvent"]>;
468
507
  }
469
508
  declare function subscriptions(subsOptions: SubscriptionsOptions): (options: StreamPayOptions, registry?: StreamPayPluginRegistry) => {
@@ -2988,7 +3027,7 @@ declare const admin: (adminOptions?: AdminOptions) => (options: StreamPayOptions
2988
3027
  };
2989
3028
  }>>[];
2990
3029
  }, {
2991
- discarded: boolean;
3030
+ discarded: true;
2992
3031
  eventId: string;
2993
3032
  }>;
2994
3033
  adminListPaymentLinks: better_auth.StrictEndpoint<"/admin/streampay/payment-links", {
@@ -6972,6 +7011,8 @@ interface WebhooksOptions extends WebhookHandlers {
6972
7011
  toleranceSeconds?: number;
6973
7012
  /** Persist and deduplicate callback deliveries. Requires the webhook inbox migration. */
6974
7013
  deduplicate?: boolean;
7014
+ /** Deliveries of a deduplicated callback event before it is dead-lettered. Defaults to 5. */
7015
+ maxWebhookAttempts?: number;
6975
7016
  }
6976
7017
  declare const webhooks: (webhooksOptions: WebhooksOptions) => (_options: StreamPayOptions, registry?: StreamPayPluginRegistry) => {
6977
7018
  schema: {};
@@ -7109,6 +7150,33 @@ interface StreamPayOptions {
7109
7150
  use: StreamPayPlugins;
7110
7151
  }
7111
7152
 
7153
+ interface UserLinkStore {
7154
+ findOne: <T = unknown>(input: {
7155
+ model: string;
7156
+ where: Where[];
7157
+ }) => Promise<T | null>;
7158
+ update?: (input: {
7159
+ model: string;
7160
+ update: Record<string, unknown>;
7161
+ where: Where[];
7162
+ }) => Promise<unknown>;
7163
+ }
7164
+ interface StreamPayLoggerContext {
7165
+ context: {
7166
+ adapter?: UserLinkStore;
7167
+ internalAdapter?: {
7168
+ updateUser?: (userId: string, data: Record<string, unknown>) => Promise<unknown>;
7169
+ listUsers?: (limit: number, offset: number, sortBy: undefined, where: Where[]) => Promise<Record<string, unknown>[]>;
7170
+ };
7171
+ logger: {
7172
+ error: (message: string) => void;
7173
+ warn: (message: string) => void;
7174
+ info: (message: string) => void;
7175
+ debug: (message: string) => void;
7176
+ };
7177
+ };
7178
+ }
7179
+
7112
7180
  type StreamPayHookContext = StreamPayLoggerContext;
7113
7181
 
7114
7182
  declare const streampay: <O extends StreamPayOptions>(options: O) => {
@@ -7239,7 +7307,7 @@ declare const streampay: <O extends StreamPayOptions>(options: O) => {
7239
7307
  };
7240
7308
  }>>[];
7241
7309
  }, {
7242
- discarded: boolean;
7310
+ discarded: true;
7243
7311
  eventId: string;
7244
7312
  }>;
7245
7313
  adminListPaymentLinks: better_auth.StrictEndpoint<"/admin/streampay/payment-links", {