@scalemule/nextjs 0.1.61 → 0.1.63

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 (41) hide show
  1. package/dist/audio.css +857 -0
  2. package/dist/audio.d.mts +334 -0
  3. package/dist/audio.d.ts +334 -0
  4. package/dist/audio.js +2178 -0
  5. package/dist/audio.mjs +2156 -0
  6. package/dist/client.d.mts +240 -0
  7. package/dist/client.d.ts +240 -0
  8. package/dist/client.js +938 -0
  9. package/dist/client.mjs +935 -0
  10. package/dist/index-CEi5Nd4L.d.mts +980 -0
  11. package/dist/index-CEi5Nd4L.d.ts +980 -0
  12. package/dist/index.d.mts +1354 -0
  13. package/dist/index.d.ts +1354 -0
  14. package/dist/index.js +6070 -0
  15. package/dist/index.mjs +6006 -0
  16. package/dist/ledvery-CxPzZpxP.d.mts +44 -0
  17. package/dist/ledvery-CxPzZpxP.d.ts +44 -0
  18. package/dist/listening-hub.global.js +1 -0
  19. package/dist/server/auth.d.mts +43 -0
  20. package/dist/server/auth.d.ts +43 -0
  21. package/dist/server/auth.js +2015 -0
  22. package/dist/server/auth.mjs +2009 -0
  23. package/dist/server/index.d.mts +1303 -0
  24. package/dist/server/index.d.ts +1303 -0
  25. package/dist/server/index.js +3660 -0
  26. package/dist/server/index.mjs +3581 -0
  27. package/dist/server/ledvery.d.mts +1 -0
  28. package/dist/server/ledvery.d.ts +1 -0
  29. package/dist/server/ledvery.js +336 -0
  30. package/dist/server/ledvery.mjs +333 -0
  31. package/dist/server/webhook-handler.d.mts +4 -0
  32. package/dist/server/webhook-handler.d.ts +4 -0
  33. package/dist/server/webhook-handler.js +60 -0
  34. package/dist/server/webhook-handler.mjs +58 -0
  35. package/dist/testing.d.mts +109 -0
  36. package/dist/testing.d.ts +109 -0
  37. package/dist/testing.js +144 -0
  38. package/dist/testing.mjs +138 -0
  39. package/dist/webhook-handler-CJm0sIZG.d.mts +856 -0
  40. package/dist/webhook-handler-CnQe9hm5.d.ts +856 -0
  41. package/package.json +2 -2
@@ -0,0 +1,856 @@
1
+ import { ExperimentAssignment } from '@scalemule/sdk';
2
+ import { MoneyClient } from '@scalemule/money';
3
+ import { A as ApiError, a3 as RegisterRequest, q as ClientContext, U as User, L as LoginResponse, y as LoginRequest, c as ListFilesParams, w as ListFilesResponse, ad as StorageFile, aj as UploadResponse } from './index-CEi5Nd4L.mjs';
4
+
5
+ /**
6
+ * Server-Side ScaleMule Client
7
+ *
8
+ * Stateless client for use in Next.js API routes.
9
+ * Does not manage sessions - that's handled by cookies.
10
+ */
11
+
12
+ type ScaleMuleEnvironment = 'dev' | 'prod';
13
+ interface ServerConfig {
14
+ /** Your ScaleMule API key (use env var, never hardcode) */
15
+ apiKey: string;
16
+ /** Environment: 'dev' or 'prod' - automatically sets gateway URL */
17
+ environment?: ScaleMuleEnvironment;
18
+ /** Custom gateway URL (overrides environment preset) */
19
+ gatewayUrl?: string;
20
+ /** Enable debug logging */
21
+ debug?: boolean;
22
+ /** Callback when a 401 auto-refresh starts */
23
+ onRefreshStart?: () => void;
24
+ /** Callback when a 401 auto-refresh finishes */
25
+ onRefreshEnd?: () => void;
26
+ /** Callback when a 401 auto-refresh fails */
27
+ onAutoRefreshFailed?: (error: ApiError) => void;
28
+ }
29
+ declare function resolveGatewayUrl(config: ServerConfig): string;
30
+ declare class ScaleMuleServer {
31
+ private apiKey;
32
+ private gatewayUrl;
33
+ private debug;
34
+ private onRefreshStart?;
35
+ private onRefreshEnd?;
36
+ private onAutoRefreshFailed?;
37
+ money: MoneyClient;
38
+ constructor(config: ServerConfig);
39
+ moneyWithSession(sessionToken: string): MoneyClient;
40
+ /**
41
+ * Make a request to the ScaleMule API
42
+ *
43
+ * @param method - HTTP method
44
+ * @param path - API path (e.g., /v1/auth/login)
45
+ * @param options - Request options
46
+ * @param options.body - Request body (will be JSON stringified)
47
+ * @param options.userId - User ID (passed through for storage operations)
48
+ * @param options.sessionToken - Session token sent as Authorization: Bearer header
49
+ * @param options.clientContext - End user context to forward (IP, user agent, etc.)
50
+ */
51
+ private request;
52
+ auth: {
53
+ /** Issue a 60-second, single-use transfer code after a server OAuth callback. */
54
+ createSessionHandoff: (sessionToken: string, audience: string) => Promise<{
55
+ code: string;
56
+ expires_in: number;
57
+ }>;
58
+ /** Exchange only on the server; write the returned session into an HTTP-only cookie. */
59
+ exchangeSessionHandoff: (code: string, audience: string) => Promise<{
60
+ session_token: string;
61
+ user_id: string;
62
+ }>;
63
+ /**
64
+ * Register a new user
65
+ */
66
+ register: (data: RegisterRequest, options?: {
67
+ clientContext?: ClientContext;
68
+ }) => Promise<User>;
69
+ /**
70
+ * Login user - returns session token (store in HTTP-only cookie)
71
+ */
72
+ sendMfaCode: (pending_token: string, method: string, options?: {
73
+ clientContext?: ClientContext;
74
+ }) => Promise<{
75
+ success: boolean;
76
+ }>;
77
+ completeMfa: (pending_token: string, code: string, method: string, options?: {
78
+ clientContext?: ClientContext;
79
+ }) => Promise<LoginResponse>;
80
+ login: (data: LoginRequest, options?: {
81
+ clientContext?: ClientContext;
82
+ }) => Promise<LoginResponse>;
83
+ /**
84
+ * Logout user
85
+ */
86
+ logout: (sessionToken: string, options?: {
87
+ onTokenRotated?: (newToken: string) => void;
88
+ }) => Promise<void>;
89
+ /**
90
+ * Get current user from session token
91
+ */
92
+ me: (sessionToken: string, options?: {
93
+ onTokenRotated?: (newToken: string) => void;
94
+ }) => Promise<User>;
95
+ /**
96
+ * Refresh session token
97
+ */
98
+ refresh: (sessionToken: string, options?: {
99
+ clientContext?: ClientContext;
100
+ isAutoRefresh?: boolean;
101
+ onTokenRotated?: (newToken: string) => void;
102
+ }) => Promise<{
103
+ session_token: string;
104
+ expires_at: string;
105
+ }>;
106
+ /**
107
+ * Request password reset email
108
+ */
109
+ forgotPassword: (email: string, options?: {
110
+ clientContext?: ClientContext;
111
+ }) => Promise<{
112
+ message: string;
113
+ }>;
114
+ /**
115
+ * Reset password with token
116
+ */
117
+ resetPassword: (token: string, newPassword: string, options?: {
118
+ clientContext?: ClientContext;
119
+ }) => Promise<{
120
+ message: string;
121
+ }>;
122
+ /**
123
+ * Verify email with token
124
+ */
125
+ verifyEmail: (token: string) => Promise<{
126
+ message?: string;
127
+ verified?: boolean;
128
+ session_token?: string;
129
+ user?: User;
130
+ expires_at?: string;
131
+ }>;
132
+ /**
133
+ * Resend verification email.
134
+ * Can be called with a session token (authenticated) or email (unauthenticated).
135
+ */
136
+ resendVerification: (sessionTokenOrEmail: string, options?: {
137
+ email?: string;
138
+ onTokenRotated?: (newToken: string) => void;
139
+ }) => Promise<{
140
+ message: string;
141
+ }>;
142
+ };
143
+ user: {
144
+ /**
145
+ * Update user profile
146
+ */
147
+ update: (sessionToken: string, data: {
148
+ full_name?: string;
149
+ avatar_url?: string;
150
+ }, options?: {
151
+ onTokenRotated?: (newToken: string) => void;
152
+ }) => Promise<User>;
153
+ /**
154
+ * Change password
155
+ */
156
+ changePassword: (sessionToken: string, currentPassword: string, newPassword: string, options?: {
157
+ onTokenRotated?: (newToken: string) => void;
158
+ }) => Promise<{
159
+ message: string;
160
+ }>;
161
+ /**
162
+ * Change email
163
+ */
164
+ changeEmail: (sessionToken: string, newEmail: string, password: string, options?: {
165
+ onTokenRotated?: (newToken: string) => void;
166
+ }) => Promise<{
167
+ message: string;
168
+ }>;
169
+ /**
170
+ * Delete account
171
+ */
172
+ deleteAccount: (sessionToken: string, password: string, options?: {
173
+ onTokenRotated?: (newToken: string) => void;
174
+ }) => Promise<{
175
+ message: string;
176
+ }>;
177
+ };
178
+ secrets: {
179
+ /**
180
+ * Get a secret from the tenant vault
181
+ *
182
+ * @example
183
+ * ```typescript
184
+ * const result = await scalemule.secrets.get('ANONYMOUS_USER_SALT')
185
+ * if (result.success) {
186
+ * console.log('Salt:', result.data.value)
187
+ * }
188
+ * ```
189
+ */
190
+ get: (key: string) => Promise<{
191
+ value: string;
192
+ version: number;
193
+ }>;
194
+ /**
195
+ * Set a secret in the tenant vault
196
+ *
197
+ * @example
198
+ * ```typescript
199
+ * await scalemule.secrets.set('ANONYMOUS_USER_SALT', 'my-secret-salt')
200
+ * ```
201
+ */
202
+ set: (key: string, value: string) => Promise<{
203
+ value: string;
204
+ version: number;
205
+ }>;
206
+ /**
207
+ * Delete a secret from the tenant vault
208
+ */
209
+ delete: (key: string) => Promise<void>;
210
+ /**
211
+ * List all secrets in the tenant vault
212
+ */
213
+ list: () => Promise<{
214
+ secrets: Array<{
215
+ path: string;
216
+ version: number;
217
+ }>;
218
+ }>;
219
+ /**
220
+ * Get secret version history
221
+ */
222
+ versions: (key: string) => Promise<{
223
+ versions: Array<{
224
+ version: number;
225
+ created_at: string;
226
+ }>;
227
+ }>;
228
+ /**
229
+ * Rollback to a specific version
230
+ */
231
+ rollback: (key: string, version: number) => Promise<{
232
+ value: string;
233
+ version: number;
234
+ }>;
235
+ /**
236
+ * Rotate a secret (copy current version as new version)
237
+ */
238
+ rotate: (key: string, newValue: string) => Promise<{
239
+ value: string;
240
+ version: number;
241
+ }>;
242
+ };
243
+ bundles: {
244
+ /**
245
+ * Get a bundle (structured secret like database credentials)
246
+ *
247
+ * @param key - Bundle key (e.g., 'database/prod')
248
+ * @param resolve - Whether to resolve inheritance (default: true)
249
+ *
250
+ * @example
251
+ * ```typescript
252
+ * const result = await scalemule.bundles.get('database/prod')
253
+ * if (result.success) {
254
+ * console.log('DB Host:', result.data.data.host)
255
+ * }
256
+ * ```
257
+ */
258
+ get: <T = Record<string, unknown>>(key: string, resolve?: boolean) => Promise<{
259
+ type: string;
260
+ data: T;
261
+ version: number;
262
+ inherits_from?: string;
263
+ }>;
264
+ /**
265
+ * Set a bundle (structured secret)
266
+ *
267
+ * @param key - Bundle key
268
+ * @param type - Bundle type: 'mysql', 'postgres', 'redis', 's3', 'oauth', 'smtp', 'generic'
269
+ * @param data - Bundle data (structure depends on type)
270
+ * @param inheritsFrom - Optional parent bundle key for inheritance
271
+ *
272
+ * @example
273
+ * ```typescript
274
+ * // Create a MySQL bundle
275
+ * await scalemule.bundles.set('database/prod', 'mysql', {
276
+ * host: 'db.example.com',
277
+ * port: 3306,
278
+ * username: 'app',
279
+ * password: 'secret',
280
+ * database: 'myapp'
281
+ * })
282
+ *
283
+ * // Create a bundle that inherits from another
284
+ * await scalemule.bundles.set('database/staging', 'mysql', {
285
+ * host: 'staging-db.example.com', // Override just the host
286
+ * }, 'database/prod')
287
+ * ```
288
+ */
289
+ set: <T = Record<string, unknown>>(key: string, type: string, data: T, inheritsFrom?: string) => Promise<{
290
+ type: string;
291
+ data: T;
292
+ version: number;
293
+ }>;
294
+ /**
295
+ * Delete a bundle
296
+ */
297
+ delete: (key: string) => Promise<void>;
298
+ /**
299
+ * List all bundles
300
+ */
301
+ list: () => Promise<{
302
+ bundles: Array<{
303
+ path: string;
304
+ type: string;
305
+ version: number;
306
+ inherits_from?: string;
307
+ }>;
308
+ }>;
309
+ /**
310
+ * Get connection URL for a database bundle
311
+ *
312
+ * @example
313
+ * ```typescript
314
+ * const result = await scalemule.bundles.connectionUrl('database/prod')
315
+ * if (result.success) {
316
+ * const client = mysql.createConnection(result.data.url)
317
+ * }
318
+ * ```
319
+ */
320
+ connectionUrl: (key: string) => Promise<{
321
+ url: string;
322
+ }>;
323
+ };
324
+ vaultAudit: {
325
+ /**
326
+ * Query audit logs for your tenant's vault operations
327
+ *
328
+ * @example
329
+ * ```typescript
330
+ * const result = await scalemule.vaultAudit.query({
331
+ * action: 'read',
332
+ * path: 'database/*',
333
+ * since: '2026-01-01'
334
+ * })
335
+ * ```
336
+ */
337
+ query: (options?: {
338
+ action?: "read" | "write" | "delete" | "list";
339
+ path?: string;
340
+ since?: string;
341
+ until?: string;
342
+ limit?: number;
343
+ }) => Promise<{
344
+ logs: Array<{
345
+ timestamp: string;
346
+ action: string;
347
+ resource_path: string;
348
+ success: boolean;
349
+ error_message?: string;
350
+ }>;
351
+ }>;
352
+ };
353
+ storage: {
354
+ /**
355
+ * List user's files
356
+ */
357
+ list: (userId: string, params?: ListFilesParams) => Promise<ListFilesResponse>;
358
+ /**
359
+ * Get file info
360
+ */
361
+ get: (fileId: string) => Promise<StorageFile>;
362
+ /**
363
+ * Delete file
364
+ */
365
+ delete: (userId: string, fileId: string) => Promise<void>;
366
+ /**
367
+ * Upload file (from server - use FormData)
368
+ *
369
+ * @param userId - The user ID who owns this file
370
+ * @param file - File data to upload
371
+ * @param options - Upload options
372
+ * @param options.clientContext - End user context to forward (IP, user agent, etc.)
373
+ *
374
+ * @example
375
+ * ```typescript
376
+ * // Forward end user context for proper attribution
377
+ * const result = await scalemule.storage.upload(
378
+ * userId,
379
+ * { buffer, filename, contentType },
380
+ * { clientContext: extractClientContext(request) }
381
+ * )
382
+ * ```
383
+ */
384
+ upload: (userId: string, file: {
385
+ buffer: BlobPart;
386
+ filename: string;
387
+ contentType: string;
388
+ }, options?: {
389
+ clientContext?: ClientContext;
390
+ }) => Promise<UploadResponse>;
391
+ };
392
+ webhooks: {
393
+ /**
394
+ * Create a new webhook subscription
395
+ *
396
+ * @example
397
+ * ```typescript
398
+ * const result = await scalemule.webhooks.create({
399
+ * webhook_name: 'Video Status Webhook',
400
+ * url: 'https://myapp.com/api/webhooks/scalemule',
401
+ * events: ['video.ready', 'video.failed']
402
+ * })
403
+ *
404
+ * // Store the secret for signature verification
405
+ * console.log('Webhook secret:', result.secret)
406
+ * ```
407
+ */
408
+ create: (data: {
409
+ webhook_name: string;
410
+ url: string;
411
+ events: string[];
412
+ }) => Promise<{
413
+ id: string;
414
+ secret: string;
415
+ url: string;
416
+ events: string[];
417
+ }>;
418
+ /**
419
+ * List all webhook subscriptions
420
+ */
421
+ list: () => Promise<{
422
+ webhooks: Array<{
423
+ id: string;
424
+ webhook_name: string;
425
+ url: string;
426
+ events: string[];
427
+ is_enabled: boolean;
428
+ }>;
429
+ }>;
430
+ /**
431
+ * Delete a webhook subscription
432
+ */
433
+ delete: (id: string) => Promise<void>;
434
+ /**
435
+ * Update a webhook subscription
436
+ */
437
+ update: (id: string, data: {
438
+ url?: string;
439
+ events?: string[];
440
+ is_enabled?: boolean;
441
+ }) => Promise<{
442
+ id: string;
443
+ url: string;
444
+ events: string[];
445
+ }>;
446
+ /**
447
+ * Get available webhook event types
448
+ */
449
+ eventTypes: () => Promise<{
450
+ events: Array<{
451
+ event_name: string;
452
+ event_description: string;
453
+ payload_schema: Record<string, unknown>;
454
+ }>;
455
+ }>;
456
+ };
457
+ analytics: {
458
+ /**
459
+ * Track an analytics event
460
+ *
461
+ * IMPORTANT: When calling from server-side code (API routes), always pass
462
+ * clientContext to ensure the real end user's IP is recorded, not the server's IP.
463
+ *
464
+ * @example
465
+ * ```typescript
466
+ * // In an API route
467
+ * import { extractClientContext, createServerClient } from '@scalemule/nextjs/server'
468
+ *
469
+ * export async function POST(request: NextRequest) {
470
+ * const clientContext = extractClientContext(request)
471
+ * const scalemule = createServerClient()
472
+ *
473
+ * await scalemule.analytics.trackEvent({
474
+ * event_name: 'button_clicked',
475
+ * properties: { button_id: 'signup' }
476
+ * }, { clientContext })
477
+ * }
478
+ * ```
479
+ */
480
+ trackEvent: (event: {
481
+ event_name: string;
482
+ event_category?: string;
483
+ properties?: Record<string, unknown>;
484
+ user_id?: string;
485
+ session_id?: string;
486
+ anonymous_id?: string;
487
+ session_duration_seconds?: number;
488
+ page_url?: string;
489
+ page_title?: string;
490
+ referrer?: string;
491
+ landing_page?: string;
492
+ device_type?: string;
493
+ device_brand?: string;
494
+ device_model?: string;
495
+ browser?: string;
496
+ browser_version?: string;
497
+ os?: string;
498
+ os_version?: string;
499
+ screen_resolution?: string;
500
+ viewport_size?: string;
501
+ utm_source?: string;
502
+ utm_medium?: string;
503
+ utm_campaign?: string;
504
+ utm_term?: string;
505
+ utm_content?: string;
506
+ client_timestamp?: string;
507
+ timestamp?: string;
508
+ }, options?: {
509
+ clientContext?: ClientContext;
510
+ }) => Promise<{
511
+ tracked: number;
512
+ session_id?: string;
513
+ }>;
514
+ /**
515
+ * Track that a visitor saw an experiment variant (once per visitor and flag). The event carries
516
+ * `properties.experiments` so the analytics experiment report attributes it.
517
+ */
518
+ trackExposure: (flagKey: string, variant: string, data?: {
519
+ session_id?: string;
520
+ anonymous_id?: string;
521
+ user_id?: string;
522
+ page_url?: string;
523
+ }, options?: {
524
+ clientContext?: ClientContext;
525
+ }) => Promise<{
526
+ tracked: number;
527
+ session_id?: string;
528
+ }>;
529
+ /**
530
+ * Track a page view
531
+ *
532
+ * @example
533
+ * ```typescript
534
+ * await scalemule.analytics.trackPageView({
535
+ * page_url: 'https://example.com/products',
536
+ * page_title: 'Products',
537
+ * referrer: 'https://google.com'
538
+ * }, { clientContext })
539
+ * ```
540
+ */
541
+ trackPageView: (data: {
542
+ page_url: string;
543
+ page_title?: string;
544
+ referrer?: string;
545
+ session_id?: string;
546
+ user_id?: string;
547
+ }, options?: {
548
+ clientContext?: ClientContext;
549
+ }) => Promise<{
550
+ tracked: number;
551
+ session_id?: string;
552
+ }>;
553
+ /**
554
+ * Track multiple events in a batch (max 100)
555
+ *
556
+ * @example
557
+ * ```typescript
558
+ * await scalemule.analytics.trackBatch([
559
+ * { event_name: 'item_viewed', properties: { item_id: '123' } },
560
+ * { event_name: 'item_added_to_cart', properties: { item_id: '123' } }
561
+ * ], { clientContext })
562
+ * ```
563
+ */
564
+ trackBatch: (events: Array<{
565
+ event_name: string;
566
+ event_category?: string;
567
+ properties?: Record<string, unknown>;
568
+ user_id?: string;
569
+ session_id?: string;
570
+ anonymous_id?: string;
571
+ session_duration_seconds?: number;
572
+ page_url?: string;
573
+ page_title?: string;
574
+ referrer?: string;
575
+ landing_page?: string;
576
+ device_type?: string;
577
+ browser?: string;
578
+ os?: string;
579
+ screen_resolution?: string;
580
+ viewport_size?: string;
581
+ utm_source?: string;
582
+ utm_medium?: string;
583
+ utm_campaign?: string;
584
+ utm_term?: string;
585
+ utm_content?: string;
586
+ client_timestamp?: string;
587
+ timestamp?: string;
588
+ }>, options?: {
589
+ clientContext?: ClientContext;
590
+ }) => Promise<{
591
+ tracked: number;
592
+ }>;
593
+ };
594
+ flags: {
595
+ /**
596
+ * Assign a visitor to an experiment (a flag with weighted variants). Pass a stable identifier
597
+ * (`session_id` or `user_id`) so the assignment is sticky. Attach the returned assignment to
598
+ * every analytics event as `properties.experiments` and track one `experiment_exposed` with
599
+ * `analytics.trackExposure` when the variant is shown.
600
+ *
601
+ * @example
602
+ * ```typescript
603
+ * const { variant } = await scalemule.flags.experiment('front_page_layout', { session_id: visitorId })
604
+ * ```
605
+ */
606
+ experiment: <T = unknown>(flagKey: string, context?: Record<string, unknown>, environment?: string, options?: {
607
+ clientContext?: ClientContext;
608
+ }) => Promise<ExperimentAssignment<T>>;
609
+ evaluate: <T = unknown>(flagKey: string, context?: Record<string, unknown>, environment?: string, options?: {
610
+ clientContext?: ClientContext;
611
+ }) => Promise<{
612
+ flag_id: string;
613
+ flag_key: string;
614
+ environment: string;
615
+ value: T;
616
+ reason: string;
617
+ matched_rule_id?: string | null;
618
+ variant_key?: string | null;
619
+ bucket?: number | null;
620
+ }>;
621
+ evaluateBatch: (flagKeys: string[], context?: Record<string, unknown>, environment?: string, options?: {
622
+ clientContext?: ClientContext;
623
+ }) => Promise<Record<string, {
624
+ flag_id: string;
625
+ flag_key: string;
626
+ environment: string;
627
+ value: unknown;
628
+ reason: string;
629
+ matched_rule_id?: string | null;
630
+ variant_key?: string | null;
631
+ bucket?: number | null;
632
+ }>>;
633
+ evaluateAll: (context?: Record<string, unknown>, environment?: string, options?: {
634
+ clientContext?: ClientContext;
635
+ }) => Promise<Record<string, {
636
+ flag_id: string;
637
+ flag_key: string;
638
+ environment: string;
639
+ value: unknown;
640
+ reason: string;
641
+ matched_rule_id?: string | null;
642
+ variant_key?: string | null;
643
+ bucket?: number | null;
644
+ }>>;
645
+ };
646
+ }
647
+ /**
648
+ * Create a server client with environment-based defaults
649
+ */
650
+ declare function createServerClient(config?: Partial<ServerConfig>): ScaleMuleServer;
651
+
652
+ /**
653
+ * ScaleMule Webhook Helpers
654
+ *
655
+ * Provides utilities for webhook signature verification and route handlers
656
+ * for video processing events and other ScaleMule webhooks.
657
+ *
658
+ * @example
659
+ * ```typescript
660
+ * // app/api/webhooks/scalemule/route.ts
661
+ * import { createWebhookRoutes } from '@scalemule/nextjs/server'
662
+ *
663
+ * export const { POST } = createWebhookRoutes({
664
+ * secret: process.env.SCALEMULE_WEBHOOK_SECRET,
665
+ * onVideoReady: async (event) => {
666
+ * console.log('Video ready:', event.video_id)
667
+ * await updateDocument('videos', event.video_id, { status: 'ready' })
668
+ * },
669
+ * onVideoFailed: async (event) => {
670
+ * console.log('Video failed:', event.video_id, event.reason)
671
+ * }
672
+ * })
673
+ * ```
674
+ */
675
+
676
+ interface WebhookEvent<T = Record<string, unknown>> {
677
+ event: string;
678
+ timestamp: number;
679
+ data: T;
680
+ }
681
+ interface VideoReadyEvent {
682
+ video_id: string;
683
+ application_id: string;
684
+ duration_seconds?: number;
685
+ width?: number;
686
+ height?: number;
687
+ thumbnail_url?: string;
688
+ playlist_url?: string;
689
+ }
690
+ interface VideoFailedEvent {
691
+ video_id: string;
692
+ application_id: string;
693
+ reason: string;
694
+ }
695
+ interface VideoUploadedEvent {
696
+ video_id: string;
697
+ application_id: string;
698
+ filename?: string;
699
+ size_bytes?: number;
700
+ }
701
+ interface VideoTranscodedEvent {
702
+ video_id: string;
703
+ application_id: string;
704
+ derivative_count: number;
705
+ }
706
+ interface WebhookRoutesConfig {
707
+ /** ScaleMule client configuration (optional, uses env vars by default) */
708
+ client?: Partial<ServerConfig>;
709
+ /** Webhook secret for signature verification (recommended for security) */
710
+ secret?: string;
711
+ /** Handler for video.ready events */
712
+ onVideoReady?: (event: VideoReadyEvent) => void | Promise<void>;
713
+ /** Handler for video.failed events */
714
+ onVideoFailed?: (event: VideoFailedEvent) => void | Promise<void>;
715
+ /** Handler for video.uploaded events */
716
+ onVideoUploaded?: (event: VideoUploadedEvent) => void | Promise<void>;
717
+ /** Handler for video.transcoded events */
718
+ onVideoTranscoded?: (event: VideoTranscodedEvent) => void | Promise<void>;
719
+ /** Generic handler for any webhook event */
720
+ onEvent?: (event: WebhookEvent) => void | Promise<void>;
721
+ }
722
+ /**
723
+ * Verify webhook signature using HMAC-SHA256
724
+ *
725
+ * ScaleMule webhooks include a signature header in the format: sha256=<hex_signature>
726
+ *
727
+ * @param payload - Raw request body as string
728
+ * @param signature - Value of X-Webhook-Signature header
729
+ * @param secret - Your webhook secret
730
+ * @returns true if signature is valid
731
+ *
732
+ * @example
733
+ * ```typescript
734
+ * const isValid = verifyWebhookSignature(body, signature, secret)
735
+ * if (!isValid) {
736
+ * return new Response('Invalid signature', { status: 401 })
737
+ * }
738
+ * ```
739
+ */
740
+ declare function verifyWebhookSignature(payload: string, signature: string, secret: string): boolean;
741
+ /**
742
+ * Parse a webhook event from the raw payload
743
+ *
744
+ * @param payload - Raw request body as string
745
+ * @returns Parsed webhook event
746
+ */
747
+ declare function parseWebhookEvent<T = Record<string, unknown>>(payload: string): WebhookEvent<T>;
748
+ /**
749
+ * Register a webhook for video events
750
+ *
751
+ * @param url - The URL to receive webhook notifications
752
+ * @param options - Registration options
753
+ * @returns The webhook ID and secret for signature verification
754
+ *
755
+ * @example
756
+ * ```typescript
757
+ * const { id, secret } = await registerVideoWebhook(
758
+ * 'https://myapp.com/api/webhooks/scalemule',
759
+ * { events: ['video.ready', 'video.failed'] }
760
+ * )
761
+ *
762
+ * // Store the secret securely for signature verification
763
+ * await saveToEnv('SCALEMULE_WEBHOOK_SECRET', secret)
764
+ * ```
765
+ */
766
+ declare function registerVideoWebhook(url: string, options?: {
767
+ /** Events to subscribe to (defaults to video.ready and video.failed) */
768
+ events?: ('video.ready' | 'video.failed' | 'video.uploaded' | 'video.transcoded')[];
769
+ /** Human-readable webhook name */
770
+ name?: string;
771
+ /** Client configuration */
772
+ clientConfig?: Partial<ServerConfig>;
773
+ }): Promise<{
774
+ id: string;
775
+ secret: string;
776
+ }>;
777
+ type RouteHandler$1 = (request: Request, context: {
778
+ params: Promise<{
779
+ scalemule?: string[];
780
+ }>;
781
+ }) => Promise<Response>;
782
+ /**
783
+ * Create Next.js App Router route handlers for ScaleMule webhooks
784
+ *
785
+ * Returns a POST handler that:
786
+ * - Verifies webhook signature (if secret provided)
787
+ * - Parses the event payload
788
+ * - Calls appropriate event handlers
789
+ * - Returns proper responses
790
+ *
791
+ * @param config - Webhook routes configuration
792
+ * @returns Object with POST handler for use in route.ts
793
+ *
794
+ * @example
795
+ * ```typescript
796
+ * // app/api/webhooks/scalemule/route.ts
797
+ * import { createWebhookRoutes } from '@scalemule/nextjs/server'
798
+ *
799
+ * export const { POST } = createWebhookRoutes({
800
+ * secret: process.env.SCALEMULE_WEBHOOK_SECRET,
801
+ * onVideoReady: async (event) => {
802
+ * // Update your database when video is ready
803
+ * await db.videos.update({
804
+ * where: { id: event.video_id },
805
+ * data: {
806
+ * status: 'ready',
807
+ * duration: event.duration_seconds,
808
+ * thumbnailUrl: event.thumbnail_url,
809
+ * }
810
+ * })
811
+ * },
812
+ * onVideoFailed: async (event) => {
813
+ * // Handle failed video processing
814
+ * await notifyUser(event.video_id, event.reason)
815
+ * }
816
+ * })
817
+ * ```
818
+ */
819
+ declare function createWebhookRoutes(config?: WebhookRoutesConfig): {
820
+ POST: RouteHandler$1;
821
+ };
822
+
823
+ /**
824
+ * Simplified webhook handler for 1-line setup.
825
+ *
826
+ * Usage in your Next.js app:
827
+ * ```ts
828
+ * // app/api/webhooks/scalemule/route.ts
829
+ * import { createWebhookHandler } from '@scalemule/nextjs/server/webhooks'
830
+ *
831
+ * export const POST = createWebhookHandler({
832
+ * secret: process.env.SCALEMULE_WEBHOOK_SECRET,
833
+ * onEvent: {
834
+ * 'video.transcoding.completed': async (event) => { ... },
835
+ * 'storage.file.uploaded': async (event) => { ... },
836
+ * }
837
+ * })
838
+ * ```
839
+ */
840
+
841
+ interface WebhookHandlerConfig {
842
+ /** Webhook secret for signature verification */
843
+ secret?: string;
844
+ /** Map of event name → handler function */
845
+ onEvent?: Record<string, (event: WebhookEvent) => void | Promise<void>>;
846
+ }
847
+ type RouteHandler = (request: Request) => Promise<Response>;
848
+ /**
849
+ * Create a webhook handler for ScaleMule events.
850
+ *
851
+ * Simpler alternative to createWebhookRoutes() — uses an event map
852
+ * instead of separate onVideoReady, onVideoFailed, etc. callbacks.
853
+ */
854
+ declare function createWebhookHandler(config?: WebhookHandlerConfig): RouteHandler;
855
+
856
+ export { type ServerConfig as S, type VideoFailedEvent as V, type WebhookEvent as W, ScaleMuleServer as a, type VideoReadyEvent as b, type VideoTranscodedEvent as c, type VideoUploadedEvent as d, type WebhookRoutesConfig as e, createServerClient as f, createWebhookHandler as g, createWebhookRoutes as h, resolveGatewayUrl as i, parseWebhookEvent as p, registerVideoWebhook as r, verifyWebhookSignature as v };