@dream-api/sdk 0.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.
@@ -0,0 +1,520 @@
1
+ /**
2
+ * Dream API SDK - Type Definitions
3
+ */
4
+ interface DreamAPIConfig {
5
+ /** Your secret key (sk_test_xxx or sk_live_xxx) */
6
+ secretKey: string;
7
+ /** Your publishable key (pk_test_xxx or pk_live_xxx) - used for auth URL helpers */
8
+ publishableKey?: string;
9
+ /** Base URL override (for testing) */
10
+ baseUrl?: string;
11
+ /** Sign-up worker URL override */
12
+ signupUrl?: string;
13
+ /** Clerk base URL override (for production) */
14
+ clerkBaseUrl?: string;
15
+ }
16
+ interface Customer {
17
+ id: string;
18
+ email: string;
19
+ firstName?: string;
20
+ lastName?: string;
21
+ plan: string;
22
+ publishableKey: string;
23
+ createdAt: number;
24
+ }
25
+ interface CreateCustomerParams {
26
+ email: string;
27
+ password?: string;
28
+ firstName?: string;
29
+ lastName?: string;
30
+ plan?: string;
31
+ }
32
+ interface Usage {
33
+ userId: string;
34
+ plan: string;
35
+ usageCount: number;
36
+ limit: number | 'unlimited';
37
+ remaining: number | 'unlimited';
38
+ periodStart: string;
39
+ periodEnd: string;
40
+ }
41
+ interface UsageTrackResult {
42
+ success: boolean;
43
+ usage: Usage;
44
+ }
45
+ interface Tier {
46
+ name: string;
47
+ displayName: string;
48
+ price: number;
49
+ limit: number;
50
+ priceId: string;
51
+ productId: string;
52
+ features?: string;
53
+ popular?: boolean;
54
+ }
55
+ interface Product {
56
+ name: string;
57
+ price: number;
58
+ priceId: string;
59
+ productId: string;
60
+ description?: string;
61
+ imageUrl?: string;
62
+ inventory?: number;
63
+ }
64
+ interface CheckoutResult {
65
+ url: string;
66
+ sessionId?: string;
67
+ }
68
+ interface PortalResult {
69
+ url: string;
70
+ }
71
+ interface DashboardMetrics {
72
+ activeSubscriptions: number;
73
+ cancelingSubscriptions: number;
74
+ mrr: number;
75
+ totalRevenue?: number;
76
+ totalSales?: number;
77
+ avgOrderValue?: number;
78
+ usageThisPeriod: number;
79
+ customers: DashboardCustomer[];
80
+ tiers: Tier[];
81
+ products?: Product[];
82
+ orders?: Order[];
83
+ webhookStatus: WebhookStatus;
84
+ }
85
+ interface DashboardCustomer {
86
+ id: string;
87
+ email: string;
88
+ plan: string;
89
+ usage: number;
90
+ limit: number;
91
+ status: string;
92
+ renewsAt?: string;
93
+ }
94
+ interface Order {
95
+ customer: string;
96
+ email: string;
97
+ amount: number;
98
+ paymentId: string;
99
+ date: string;
100
+ }
101
+ interface WebhookStatus {
102
+ url: string;
103
+ lastEvent?: string;
104
+ recentEvents: Array<{
105
+ type: string;
106
+ timestamp: string;
107
+ }>;
108
+ }
109
+ interface DreamAPIError {
110
+ error: string;
111
+ message: string;
112
+ status?: number;
113
+ }
114
+ declare class DreamAPIException extends Error {
115
+ readonly status: number;
116
+ readonly code: string;
117
+ constructor(error: DreamAPIError, status?: number);
118
+ }
119
+
120
+ /**
121
+ * Dream API SDK - HTTP Client
122
+ *
123
+ * Handles all HTTP communication with the Dream API.
124
+ * Automatically injects authentication headers.
125
+ */
126
+
127
+ declare class DreamClient {
128
+ private secretKey;
129
+ private publishableKey;
130
+ private baseUrl;
131
+ private signupUrl;
132
+ private clerkUrl;
133
+ private userToken;
134
+ private tokenRefresher;
135
+ constructor(config: DreamAPIConfig);
136
+ /**
137
+ * Set the end-user JWT token for user-specific operations.
138
+ * Call this after the user signs in via Clerk.
139
+ */
140
+ setUserToken(token: string): void;
141
+ /**
142
+ * Clear the current user token (on sign out)
143
+ */
144
+ clearUserToken(): void;
145
+ /**
146
+ * Set a function to refresh the token before API calls
147
+ */
148
+ setTokenRefresher(refresher: () => Promise<string | null>): void;
149
+ /**
150
+ * Refresh token if we have a refresher set
151
+ */
152
+ private ensureFreshToken;
153
+ /**
154
+ * Get the publishable key
155
+ */
156
+ getPublishableKey(): string | undefined;
157
+ /**
158
+ * Get the sign-up URL base
159
+ */
160
+ getSignupBaseUrl(): string;
161
+ /**
162
+ * Get the Clerk base URL for hosted auth pages
163
+ */
164
+ getClerkBaseUrl(): string;
165
+ /**
166
+ * Make an authenticated request to the API
167
+ */
168
+ request<T>(method: 'GET' | 'POST' | 'PATCH' | 'DELETE', endpoint: string, options?: {
169
+ body?: unknown;
170
+ requiresUserToken?: boolean;
171
+ }): Promise<T>;
172
+ /**
173
+ * GET request
174
+ */
175
+ get<T>(endpoint: string, requiresUserToken?: boolean): Promise<T>;
176
+ /**
177
+ * POST request
178
+ */
179
+ post<T>(endpoint: string, body?: unknown, requiresUserToken?: boolean): Promise<T>;
180
+ /**
181
+ * PATCH request
182
+ */
183
+ patch<T>(endpoint: string, body?: unknown, requiresUserToken?: boolean): Promise<T>;
184
+ /**
185
+ * DELETE request
186
+ */
187
+ delete<T>(endpoint: string, requiresUserToken?: boolean): Promise<T>;
188
+ }
189
+
190
+ /**
191
+ * Dream API SDK - Clerk Integration
192
+ *
193
+ * Handles loading Clerk internally so devs never touch it.
194
+ * Uses the shared end-user-api Clerk app.
195
+ */
196
+ interface ClerkUser {
197
+ id: string;
198
+ email: string;
199
+ plan: string;
200
+ publishableKey: string;
201
+ }
202
+
203
+ /**
204
+ * Dream API SDK - Auth Helpers
205
+ *
206
+ * URL builders for sign-up, sign-in, and account management flows.
207
+ * All URLs point to dream-api's shared Clerk app (end-user-api).
208
+ *
209
+ * Also handles loading Clerk internally so devs never touch it.
210
+ */
211
+
212
+ interface AuthUrlOptions {
213
+ /** URL to redirect to after auth completes */
214
+ redirect: string;
215
+ }
216
+ declare class AuthHelpers {
217
+ private client;
218
+ private clerk;
219
+ private initialized;
220
+ constructor(client: DreamClient);
221
+ /**
222
+ * Initialize auth (loads Clerk internally).
223
+ * Call this on page load to detect existing sessions.
224
+ *
225
+ * @example
226
+ * ```typescript
227
+ * await api.auth.init();
228
+ * if (api.auth.isSignedIn()) {
229
+ * // User is signed in, token already set
230
+ * await api.usage.track();
231
+ * }
232
+ * ```
233
+ */
234
+ init(): Promise<void>;
235
+ /**
236
+ * Check if user is signed in
237
+ */
238
+ isSignedIn(): boolean;
239
+ /**
240
+ * Get current user info
241
+ */
242
+ getUser(): ClerkUser | null;
243
+ /**
244
+ * Sign out the current user
245
+ */
246
+ signOut(): Promise<void>;
247
+ /**
248
+ * Refresh the auth token (call before long sessions)
249
+ */
250
+ refreshToken(): Promise<void>;
251
+ /**
252
+ * Check if returning from auth redirect
253
+ */
254
+ static hasAuthParams(): boolean;
255
+ /**
256
+ * Get the sign-up URL for new users.
257
+ *
258
+ * Redirects to the sign-up worker which handles user creation
259
+ * and sets the required metadata (publishableKey, plan).
260
+ *
261
+ * @example
262
+ * ```typescript
263
+ * const signupUrl = api.auth.getSignUpUrl({ redirect: '/dashboard' });
264
+ * // Returns: https://sign-up.../signup?pk=pk_xxx&redirect=...
265
+ * window.location.href = signupUrl;
266
+ * ```
267
+ */
268
+ getSignUpUrl(options: AuthUrlOptions): string;
269
+ /**
270
+ * Get the sign-in URL for returning users.
271
+ *
272
+ * Redirects to Clerk's hosted sign-in page. After sign-in,
273
+ * users are redirected to your specified URL.
274
+ *
275
+ * @example
276
+ * ```typescript
277
+ * const signinUrl = api.auth.getSignInUrl({ redirect: '/dashboard' });
278
+ * window.location.href = signinUrl;
279
+ * ```
280
+ */
281
+ getSignInUrl(options: AuthUrlOptions): string;
282
+ /**
283
+ * Get the customer portal URL for account management.
284
+ *
285
+ * Redirects to Clerk's hosted account page where users can
286
+ * manage their profile, password, and security settings.
287
+ *
288
+ * Note: This is separate from billing management.
289
+ * For billing, use api.billing.openPortal().
290
+ *
291
+ * @example
292
+ * ```typescript
293
+ * const portalUrl = api.auth.getCustomerPortalUrl();
294
+ * window.location.href = portalUrl;
295
+ * ```
296
+ */
297
+ getCustomerPortalUrl(): string;
298
+ }
299
+
300
+ /**
301
+ * Dream API SDK
302
+ *
303
+ * Official SDK for Dream API - Auth, billing, and usage tracking in one API.
304
+ *
305
+ * @example
306
+ * ```typescript
307
+ * import { DreamAPI } from '@dream-api/sdk';
308
+ *
309
+ * const api = new DreamAPI({
310
+ * secretKey: 'sk_test_xxx',
311
+ * publishableKey: 'pk_test_xxx',
312
+ * });
313
+ *
314
+ * // Backend operations (SK only)
315
+ * await api.customers.create({ email: 'user@example.com' });
316
+ * const { tiers } = await api.products.listTiers();
317
+ * const dashboard = await api.dashboard.get();
318
+ *
319
+ * // Frontend operations (needs user token)
320
+ * api.setUserToken(clerkJWT);
321
+ * await api.usage.track();
322
+ * const usage = await api.usage.check();
323
+ * const { url } = await api.billing.createCheckout({ tier: 'pro' });
324
+ * ```
325
+ */
326
+
327
+ /**
328
+ * Dream API SDK Client
329
+ */
330
+ declare class DreamAPI {
331
+ private client;
332
+ /** Auth URL helpers */
333
+ readonly auth: AuthHelpers;
334
+ /** Customer management */
335
+ readonly customers: CustomerAPI;
336
+ /** Usage tracking */
337
+ readonly usage: UsageAPI;
338
+ /** Billing operations */
339
+ readonly billing: BillingAPI;
340
+ /** Product catalog */
341
+ readonly products: ProductAPI;
342
+ /** Dashboard metrics */
343
+ readonly dashboard: DashboardAPI;
344
+ constructor(config: DreamAPIConfig);
345
+ /**
346
+ * Set the end-user JWT token.
347
+ * Required for user-specific operations (usage, billing).
348
+ *
349
+ * @example
350
+ * ```typescript
351
+ * // After user signs in via Clerk
352
+ * const token = await clerk.session.getToken();
353
+ * api.setUserToken(token);
354
+ * ```
355
+ */
356
+ setUserToken(token: string): void;
357
+ /**
358
+ * Clear the user token (on sign out)
359
+ */
360
+ clearUserToken(): void;
361
+ }
362
+ declare class CustomerAPI {
363
+ private client;
364
+ constructor(client: DreamClient);
365
+ /**
366
+ * Create a new customer
367
+ *
368
+ * @example
369
+ * ```typescript
370
+ * const { customer } = await api.customers.create({
371
+ * email: 'user@example.com',
372
+ * firstName: 'John',
373
+ * plan: 'free',
374
+ * });
375
+ * ```
376
+ */
377
+ create(params: CreateCustomerParams): Promise<{
378
+ customer: Customer;
379
+ }>;
380
+ /**
381
+ * Get a customer by ID
382
+ */
383
+ get(customerId: string): Promise<{
384
+ customer: Customer;
385
+ }>;
386
+ /**
387
+ * Update a customer's plan
388
+ */
389
+ update(customerId: string, params: {
390
+ plan: string;
391
+ }): Promise<{
392
+ customer: Customer;
393
+ }>;
394
+ /**
395
+ * Delete a customer
396
+ */
397
+ delete(customerId: string): Promise<{
398
+ success: boolean;
399
+ deleted: {
400
+ id: string;
401
+ email: string;
402
+ };
403
+ }>;
404
+ }
405
+ declare class UsageAPI {
406
+ private client;
407
+ constructor(client: DreamClient);
408
+ /**
409
+ * Track a usage event.
410
+ * Increments the user's usage counter for the current period.
411
+ *
412
+ * @example
413
+ * ```typescript
414
+ * const { usage } = await api.usage.track();
415
+ * console.log(`Used ${usage.usageCount} of ${usage.limit}`);
416
+ * ```
417
+ */
418
+ track(): Promise<UsageTrackResult>;
419
+ /**
420
+ * Check current usage without incrementing.
421
+ *
422
+ * @example
423
+ * ```typescript
424
+ * const usage = await api.usage.check();
425
+ * if (usage.remaining <= 0) {
426
+ * // Show upgrade prompt
427
+ * }
428
+ * ```
429
+ */
430
+ check(): Promise<Usage>;
431
+ }
432
+ declare class BillingAPI {
433
+ private client;
434
+ constructor(client: DreamClient);
435
+ /**
436
+ * Create a checkout session for subscription upgrade.
437
+ *
438
+ * @example
439
+ * ```typescript
440
+ * const { url } = await api.billing.createCheckout({
441
+ * tier: 'pro',
442
+ * successUrl: '/success',
443
+ * cancelUrl: '/pricing',
444
+ * });
445
+ * window.location.href = url;
446
+ * ```
447
+ */
448
+ createCheckout(params: {
449
+ tier?: string;
450
+ priceId?: string;
451
+ successUrl?: string;
452
+ cancelUrl?: string;
453
+ }): Promise<CheckoutResult>;
454
+ /**
455
+ * Open the Stripe customer portal for billing management.
456
+ *
457
+ * @example
458
+ * ```typescript
459
+ * const { url } = await api.billing.openPortal({ returnUrl: '/dashboard' });
460
+ * window.location.href = url;
461
+ * ```
462
+ */
463
+ openPortal(params?: {
464
+ returnUrl?: string;
465
+ }): Promise<PortalResult>;
466
+ }
467
+ declare class ProductAPI {
468
+ private client;
469
+ constructor(client: DreamClient);
470
+ /**
471
+ * List subscription tiers
472
+ */
473
+ listTiers(): Promise<{
474
+ tiers: Tier[];
475
+ }>;
476
+ /**
477
+ * List products (for store projects)
478
+ */
479
+ list(): Promise<{
480
+ products: Product[];
481
+ }>;
482
+ /**
483
+ * Create a cart checkout (guest checkout for store)
484
+ */
485
+ cartCheckout(params: {
486
+ items: Array<{
487
+ priceId: string;
488
+ quantity: number;
489
+ }>;
490
+ customerEmail: string;
491
+ customerName?: string;
492
+ successUrl?: string;
493
+ cancelUrl?: string;
494
+ }): Promise<CheckoutResult>;
495
+ }
496
+ declare class DashboardAPI {
497
+ private client;
498
+ constructor(client: DreamClient);
499
+ /**
500
+ * Get dashboard metrics
501
+ *
502
+ * @example
503
+ * ```typescript
504
+ * const dashboard = await api.dashboard.get();
505
+ * console.log(`MRR: $${dashboard.mrr}`);
506
+ * console.log(`Active subs: ${dashboard.activeSubscriptions}`);
507
+ * ```
508
+ */
509
+ get(): Promise<DashboardMetrics>;
510
+ /**
511
+ * Get aggregate totals across all projects
512
+ */
513
+ getTotals(): Promise<{
514
+ totalRevenue: number;
515
+ totalCustomers: number;
516
+ totalMRR: number;
517
+ }>;
518
+ }
519
+
520
+ export { type CheckoutResult, type ClerkUser, type CreateCustomerParams, type Customer, type DashboardCustomer, type DashboardMetrics, DreamAPI, type DreamAPIConfig, type DreamAPIError, DreamAPIException, type Order, type PortalResult, type Product, type Tier, type Usage, type UsageTrackResult, type WebhookStatus, DreamAPI as default };