@solvapay/next 1.0.0-preview.18 → 1.0.0-preview.19

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/index.d.ts CHANGED
@@ -3,6 +3,128 @@ import * as _solvapay_server from '@solvapay/server';
3
3
  import { AuthenticatedUser, SolvaPay } from '@solvapay/server';
4
4
  import { AuthAdapter } from '@solvapay/auth';
5
5
 
6
+ /**
7
+ * Subscription Cache Utilities
8
+ *
9
+ * Cache management functions for subscription data.
10
+ * Separated from index.ts to avoid circular dependencies.
11
+ */
12
+ /**
13
+ * Request deduplication and caching options
14
+ */
15
+ interface RequestDeduplicationOptions {
16
+ /**
17
+ * Time-to-live for cached results in milliseconds (default: 2000)
18
+ * Set to 0 to disable caching (only deduplicate concurrent requests)
19
+ */
20
+ cacheTTL?: number;
21
+ /**
22
+ * Maximum cache size before cleanup (default: 1000)
23
+ * When exceeded, oldest entries are removed
24
+ */
25
+ maxCacheSize?: number;
26
+ /**
27
+ * Whether to cache error results (default: true)
28
+ * When false, only successful results are cached
29
+ */
30
+ cacheErrors?: boolean;
31
+ }
32
+ /**
33
+ * Subscription check result
34
+ */
35
+ interface SubscriptionCheckResult {
36
+ customerRef: string;
37
+ email?: string;
38
+ name?: string;
39
+ subscriptions: Array<{
40
+ reference: string;
41
+ planName?: string;
42
+ agentName?: string;
43
+ status?: string;
44
+ startDate?: string;
45
+ [key: string]: unknown;
46
+ }>;
47
+ }
48
+ /**
49
+ * Clear subscription cache for a specific user.
50
+ *
51
+ * Useful when you know subscription status has changed (e.g., after a successful
52
+ * checkout, subscription update, or cancellation). This forces the next
53
+ * `checkSubscription()` call to fetch fresh data from the backend.
54
+ *
55
+ * @param userId - User ID to clear cache for
56
+ *
57
+ * @example
58
+ * ```typescript
59
+ * import { clearSubscriptionCache } from '@solvapay/next';
60
+ *
61
+ * // After successful payment
62
+ * await processPayment(request, body);
63
+ * clearSubscriptionCache(userId); // Force refresh on next check
64
+ * ```
65
+ *
66
+ * @see {@link checkSubscription} for subscription checking
67
+ * @see {@link clearAllSubscriptionCache} to clear all cache entries
68
+ * @since 1.0.0
69
+ */
70
+ declare function clearSubscriptionCache(userId: string): void;
71
+ /**
72
+ * Clear all subscription cache entries.
73
+ *
74
+ * Useful for testing, debugging, or when you need to force fresh lookups
75
+ * for all users. This clears both the in-flight request cache and the
76
+ * result cache.
77
+ *
78
+ * @example
79
+ * ```typescript
80
+ * import { clearAllSubscriptionCache } from '@solvapay/next';
81
+ *
82
+ * // In a test setup
83
+ * beforeEach(() => {
84
+ * clearAllSubscriptionCache();
85
+ * });
86
+ * ```
87
+ *
88
+ * @see {@link clearSubscriptionCache} to clear cache for a specific user
89
+ * @see {@link getSubscriptionCacheStats} for cache monitoring
90
+ * @since 1.0.0
91
+ */
92
+ declare function clearAllSubscriptionCache(): void;
93
+ /**
94
+ * Get subscription cache statistics for monitoring and debugging.
95
+ *
96
+ * Returns the current state of the subscription cache, including:
97
+ * - Number of in-flight requests (being deduplicated)
98
+ * - Number of cached results
99
+ *
100
+ * @returns Cache statistics object
101
+ * @returns inFlight - Number of currently in-flight requests
102
+ * @returns cached - Number of cached results
103
+ *
104
+ * @example
105
+ * ```typescript
106
+ * import { getSubscriptionCacheStats } from '@solvapay/next';
107
+ *
108
+ * // In a monitoring endpoint
109
+ * export async function GET() {
110
+ * const stats = getSubscriptionCacheStats();
111
+ * return Response.json({
112
+ * cache: {
113
+ * inFlight: stats.inFlight,
114
+ * cached: stats.cached
115
+ * }
116
+ * });
117
+ * }
118
+ * ```
119
+ *
120
+ * @see {@link checkSubscription} for subscription checking
121
+ * @since 1.0.0
122
+ */
123
+ declare function getSubscriptionCacheStats(): {
124
+ inFlight: number;
125
+ cached: number;
126
+ };
127
+
6
128
  /**
7
129
  * Next.js Authentication Helpers
8
130
  *
@@ -10,11 +132,37 @@ import { AuthAdapter } from '@solvapay/auth';
10
132
  */
11
133
 
12
134
  /**
13
- * Get authenticated user - Next.js wrapper
135
+ * Get authenticated user information from a Next.js request.
14
136
  *
15
- * @param request - Next.js request object
137
+ * This is a Next.js-specific wrapper around `getAuthenticatedUserCore` that
138
+ * returns NextResponse for errors instead of ErrorResult. Extracts user ID,
139
+ * email, and name from authenticated requests.
140
+ *
141
+ * @param request - Next.js request object (NextRequest or Request)
16
142
  * @param options - Configuration options
143
+ * @param options.includeEmail - Whether to extract email from JWT token (default: true)
144
+ * @param options.includeName - Whether to extract name from JWT token (default: true)
17
145
  * @returns Authenticated user info or NextResponse error
146
+ *
147
+ * @example
148
+ * ```typescript
149
+ * import { NextRequest, NextResponse } from 'next/server';
150
+ * import { getAuthenticatedUser } from '@solvapay/next';
151
+ *
152
+ * export async function GET(request: NextRequest) {
153
+ * const userResult = await getAuthenticatedUser(request);
154
+ *
155
+ * if (userResult instanceof NextResponse) {
156
+ * return userResult; // Error response
157
+ * }
158
+ *
159
+ * const { userId, email, name } = userResult;
160
+ * return NextResponse.json({ userId, email, name });
161
+ * }
162
+ * ```
163
+ *
164
+ * @see {@link getAuthenticatedUserCore} for the core implementation
165
+ * @since 1.0.0
18
166
  */
19
167
  declare function getAuthenticatedUser(request: globalThis.Request, options?: {
20
168
  includeEmail?: boolean;
@@ -126,7 +274,6 @@ declare function createCustomerSession(request: globalThis.Request, options?: {
126
274
  *
127
275
  * Next.js-specific wrappers for subscription helpers.
128
276
  */
129
-
130
277
  /**
131
278
  * Cancel subscription - Next.js wrapper
132
279
  *
@@ -140,7 +287,7 @@ declare function cancelSubscription(request: globalThis.Request, body: {
140
287
  reason?: string;
141
288
  }, options?: {
142
289
  solvaPay?: SolvaPay;
143
- }): Promise<any | NextResponse>;
290
+ }): Promise<Record<string, unknown> | NextResponse>;
144
291
 
145
292
  /**
146
293
  * Next.js Plans Helper
@@ -148,7 +295,6 @@ declare function cancelSubscription(request: globalThis.Request, body: {
148
295
  * Next.js-specific wrapper for plans helper.
149
296
  * This is a public route - no authentication required.
150
297
  */
151
-
152
298
  /**
153
299
  * List plans - Next.js wrapper
154
300
  *
@@ -156,7 +302,7 @@ declare function cancelSubscription(request: globalThis.Request, body: {
156
302
  * @returns Plans response or NextResponse error
157
303
  */
158
304
  declare function listPlans(request: globalThis.Request): Promise<{
159
- plans: any[];
305
+ plans: Array<Record<string, unknown>>;
160
306
  agentRef: string;
161
307
  } | NextResponse>;
162
308
 
@@ -342,49 +488,17 @@ declare function createSupabaseAuthMiddleware(options?: SupabaseAuthMiddlewareOp
342
488
  * like request deduplication and caching.
343
489
  */
344
490
 
345
- /**
346
- * Request deduplication and caching options
347
- */
348
- interface RequestDeduplicationOptions {
349
- /**
350
- * Time-to-live for cached results in milliseconds (default: 2000)
351
- * Set to 0 to disable caching (only deduplicate concurrent requests)
352
- */
353
- cacheTTL?: number;
354
- /**
355
- * Maximum cache size before cleanup (default: 1000)
356
- * When exceeded, oldest entries are removed
357
- */
358
- maxCacheSize?: number;
359
- /**
360
- * Whether to cache error results (default: true)
361
- * When false, only successful results are cached
362
- */
363
- cacheErrors?: boolean;
364
- }
365
- /**
366
- * Subscription check result
367
- */
368
- interface SubscriptionCheckResult {
369
- customerRef: string;
370
- email?: string;
371
- name?: string;
372
- subscriptions: Array<{
373
- reference: string;
374
- planName?: string;
375
- agentName?: string;
376
- status?: string;
377
- startDate?: string;
378
- [key: string]: unknown;
379
- }>;
380
- }
381
491
  /**
382
492
  * Options for checking subscriptions
383
493
  */
384
494
  interface CheckSubscriptionOptions {
385
495
  /**
386
496
  * Request deduplication options
387
- * Default: { cacheTTL: 2000, maxCacheSize: 1000, cacheErrors: true }
497
+ *
498
+ * Default values:
499
+ * - `cacheTTL`: 2000ms
500
+ * - `maxCacheSize`: 1000
501
+ * - `cacheErrors`: true
388
502
  */
389
503
  deduplication?: RequestDeduplicationOptions;
390
504
  /**
@@ -404,59 +518,49 @@ interface CheckSubscriptionOptions {
404
518
  includeName?: boolean;
405
519
  }
406
520
  /**
407
- * Check user subscription status
521
+ * Check user subscription status with automatic deduplication and caching.
408
522
  *
409
- * This helper function:
523
+ * This Next.js helper function provides optimized subscription checking with:
524
+ * - Automatic request deduplication (concurrent requests share the same promise)
525
+ * - Short-term caching (2 seconds) to prevent duplicate sequential requests
526
+ * - Fast path optimization using cached customer references from client
527
+ * - Automatic customer creation if needed
528
+ *
529
+ * The function:
410
530
  * 1. Extracts user ID from request (via requireUserId from @solvapay/auth)
411
- * 2. Gets user email and name from Supabase JWT token
412
- * 3. Ensures customer exists in SolvaPay
413
- * 4. Returns customer subscription information
414
- * 5. Handles deduplication automatically
531
+ * 2. Gets user email and name from Supabase JWT token (if available)
532
+ * 3. Validates cached customer reference (if provided via header)
533
+ * 4. Ensures customer exists in SolvaPay backend
534
+ * 5. Returns customer subscription information
415
535
  *
416
- * @param request - Next.js request object (NextRequest extends Request, so Request is accepted)
536
+ * @param request - Next.js request object (NextRequest extends Request)
417
537
  * @param options - Configuration options
418
- * @returns Subscription check result or error response
538
+ * @param options.deduplication - Request deduplication options (see {@link RequestDeduplicationOptions})
539
+ * @param options.solvaPay - Optional SolvaPay instance (creates new one if not provided)
540
+ * @param options.includeEmail - Whether to include email in response (default: true)
541
+ * @param options.includeName - Whether to include name in response (default: true)
542
+ * @returns Subscription check result with customer data and subscriptions, or NextResponse error
419
543
  *
420
544
  * @example
421
545
  * ```typescript
422
- * import { NextRequest } from 'next/server';
546
+ * import { NextRequest, NextResponse } from 'next/server';
423
547
  * import { checkSubscription } from '@solvapay/next';
424
548
  *
425
549
  * export async function GET(request: NextRequest) {
426
550
  * const result = await checkSubscription(request);
551
+ *
427
552
  * if (result instanceof NextResponse) {
428
553
  * return result; // Error response
429
554
  * }
555
+ *
430
556
  * return NextResponse.json(result);
431
557
  * }
432
558
  * ```
433
- */
434
- declare function checkSubscription(request: Request, options?: CheckSubscriptionOptions): Promise<SubscriptionCheckResult | NextResponse>;
435
- /**
436
- * Clear subscription cache for a specific user
437
- *
438
- * Useful when you know subscription status has changed
439
- * (e.g., after a successful checkout or subscription update)
440
- *
441
- * @param userId - User ID to clear cache for
442
- */
443
- declare function clearSubscriptionCache(userId: string): void;
444
- /**
445
- * Clear all subscription cache entries
446
- *
447
- * Useful for testing or when you need to force fresh lookups
448
- */
449
- declare function clearAllSubscriptionCache(): void;
450
- /**
451
- * Get subscription cache statistics
452
559
  *
453
- * Useful for monitoring and debugging
454
- *
455
- * @returns Cache statistics
560
+ * @see {@link clearSubscriptionCache} for cache management
561
+ * @see {@link getSubscriptionCacheStats} for cache monitoring
562
+ * @since 1.0.0
456
563
  */
457
- declare function getSubscriptionCacheStats(): {
458
- inFlight: number;
459
- cached: number;
460
- };
564
+ declare function checkSubscription(request: Request, options?: CheckSubscriptionOptions): Promise<SubscriptionCheckResult | NextResponse>;
461
565
 
462
566
  export { type AuthMiddlewareOptions, type CheckSubscriptionOptions, type RequestDeduplicationOptions, type SubscriptionCheckResult, type SupabaseAuthMiddlewareOptions, cancelSubscription, checkSubscription, clearAllSubscriptionCache, clearSubscriptionCache, createAuthMiddleware, createCheckoutSession, createCustomerSession, createPaymentIntent, createSupabaseAuthMiddleware, getAuthenticatedUser, getSubscriptionCacheStats, listPlans, processPayment, syncCustomer };