usebecky 0.0.0-stage → 0.2.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.
Files changed (135) hide show
  1. package/README.md +701 -2
  2. package/dist/analytics/client.d.ts +219 -0
  3. package/dist/analytics/client.js +923 -0
  4. package/dist/analytics/cmp.d.ts +20 -0
  5. package/dist/analytics/cmp.js +166 -0
  6. package/dist/analytics/context.d.ts +29 -0
  7. package/dist/analytics/context.js +97 -0
  8. package/dist/auth/client.d.ts +401 -0
  9. package/dist/auth/client.js +1081 -0
  10. package/dist/auth/webauthn.d.ts +18 -0
  11. package/dist/auth/webauthn.js +138 -0
  12. package/dist/cli/ai.d.ts +54 -0
  13. package/dist/cli/ai.js +202 -0
  14. package/dist/cli/analytics.d.ts +53 -0
  15. package/dist/cli/analytics.js +357 -0
  16. package/dist/cli/config.d.ts +75 -0
  17. package/dist/cli/config.js +718 -0
  18. package/dist/cli/db.d.ts +48 -0
  19. package/dist/cli/db.js +215 -0
  20. package/dist/cli/deploy-api.d.ts +168 -0
  21. package/dist/cli/deploy-api.js +177 -0
  22. package/dist/cli/deploy-ci.d.ts +15 -0
  23. package/dist/cli/deploy-ci.js +54 -0
  24. package/dist/cli/deploy-detect.d.ts +64 -0
  25. package/dist/cli/deploy-detect.js +249 -0
  26. package/dist/cli/deploy-files.d.ts +112 -0
  27. package/dist/cli/deploy-files.js +778 -0
  28. package/dist/cli/deploy.d.ts +10 -0
  29. package/dist/cli/deploy.js +430 -0
  30. package/dist/cli/emails.d.ts +29 -0
  31. package/dist/cli/emails.js +122 -0
  32. package/dist/cli/framework.d.ts +135 -0
  33. package/dist/cli/framework.js +459 -0
  34. package/dist/cli/functions.d.ts +59 -0
  35. package/dist/cli/functions.js +426 -0
  36. package/dist/cli/hosting.d.ts +4 -0
  37. package/dist/cli/hosting.js +532 -0
  38. package/dist/cli/index.d.ts +2 -0
  39. package/dist/cli/index.js +9 -0
  40. package/dist/cli/payments.d.ts +35 -0
  41. package/dist/cli/payments.js +176 -0
  42. package/dist/cli/push.d.ts +36 -0
  43. package/dist/cli/push.js +172 -0
  44. package/dist/cli/run.d.ts +65 -0
  45. package/dist/cli/run.js +850 -0
  46. package/dist/cli/social.d.ts +52 -0
  47. package/dist/cli/social.js +532 -0
  48. package/dist/cli/tokens.d.ts +28 -0
  49. package/dist/cli/tokens.js +114 -0
  50. package/dist/cli/ui.d.ts +38 -0
  51. package/dist/cli/ui.js +140 -0
  52. package/dist/client.d.ts +94 -0
  53. package/dist/client.js +156 -0
  54. package/dist/db/query.d.ts +162 -0
  55. package/dist/db/query.js +336 -0
  56. package/dist/db/types.d.ts +93 -0
  57. package/dist/db/types.js +4 -0
  58. package/dist/forms/client.d.ts +65 -0
  59. package/dist/forms/client.js +106 -0
  60. package/dist/functions/client.d.ts +37 -0
  61. package/dist/functions/client.js +76 -0
  62. package/dist/index.d.ts +17 -0
  63. package/dist/index.js +16 -0
  64. package/dist/lib/dashboard-paths.d.ts +4 -0
  65. package/dist/lib/dashboard-paths.js +8 -0
  66. package/dist/lib/env.d.ts +9 -0
  67. package/dist/lib/env.js +55 -0
  68. package/dist/lib/errors.d.ts +22 -0
  69. package/dist/lib/errors.js +90 -0
  70. package/dist/lib/hosted.d.ts +2 -0
  71. package/dist/lib/hosted.js +7 -0
  72. package/dist/lib/http.d.ts +59 -0
  73. package/dist/lib/http.js +172 -0
  74. package/dist/lib/jwt.d.ts +1 -0
  75. package/dist/lib/jwt.js +31 -0
  76. package/dist/lib/locale.d.ts +12 -0
  77. package/dist/lib/locale.js +51 -0
  78. package/dist/lib/pkce.d.ts +20 -0
  79. package/dist/lib/pkce.js +124 -0
  80. package/dist/lib/storage-adapter.d.ts +15 -0
  81. package/dist/lib/storage-adapter.js +91 -0
  82. package/dist/lib/types.d.ts +339 -0
  83. package/dist/lib/types.js +1 -0
  84. package/dist/newsletter/client.d.ts +140 -0
  85. package/dist/newsletter/client.js +85 -0
  86. package/dist/payments/client.d.ts +352 -0
  87. package/dist/payments/client.js +323 -0
  88. package/dist/push/client.d.ts +110 -0
  89. package/dist/push/client.js +179 -0
  90. package/dist/realtime/client.d.ts +131 -0
  91. package/dist/realtime/client.js +513 -0
  92. package/dist/server/analytics.d.ts +176 -0
  93. package/dist/server/analytics.js +49 -0
  94. package/dist/server/cache.d.ts +74 -0
  95. package/dist/server/cache.js +154 -0
  96. package/dist/server/emails.d.ts +142 -0
  97. package/dist/server/emails.js +123 -0
  98. package/dist/server/events.d.ts +357 -0
  99. package/dist/server/events.js +219 -0
  100. package/dist/server/functions.d.ts +40 -0
  101. package/dist/server/functions.js +1 -0
  102. package/dist/server/http-utils.d.ts +10 -0
  103. package/dist/server/http-utils.js +115 -0
  104. package/dist/server/index.d.ts +195 -0
  105. package/dist/server/index.js +314 -0
  106. package/dist/server/payments.d.ts +218 -0
  107. package/dist/server/payments.js +150 -0
  108. package/dist/server/push.d.ts +85 -0
  109. package/dist/server/push.js +37 -0
  110. package/dist/server/usage.d.ts +43 -0
  111. package/dist/server/usage.js +8 -0
  112. package/dist/storage/client.d.ts +143 -0
  113. package/dist/storage/client.js +224 -0
  114. package/package.json +52 -4
  115. package/skill/usebecky/SKILL.md +339 -0
  116. package/skill/usebecky/references/access-rules.md +307 -0
  117. package/skill/usebecky/references/addons.md +68 -0
  118. package/skill/usebecky/references/analytics.md +166 -0
  119. package/skill/usebecky/references/android.md +434 -0
  120. package/skill/usebecky/references/auth.md +379 -0
  121. package/skill/usebecky/references/cache.md +51 -0
  122. package/skill/usebecky/references/components.md +127 -0
  123. package/skill/usebecky/references/emails.md +105 -0
  124. package/skill/usebecky/references/expo.md +147 -0
  125. package/skill/usebecky/references/functions.md +99 -0
  126. package/skill/usebecky/references/hosting.md +119 -0
  127. package/skill/usebecky/references/http-api.md +233 -0
  128. package/skill/usebecky/references/ios.md +355 -0
  129. package/skill/usebecky/references/payments.md +493 -0
  130. package/skill/usebecky/references/realtime.md +143 -0
  131. package/skill/usebecky/references/scheduled-jobs.md +82 -0
  132. package/skill/usebecky/references/sdk.md +838 -0
  133. package/skill/usebecky/references/storage.md +210 -0
  134. package/skill/usebecky/references/templates.md +191 -0
  135. package/skill/usebecky/references/wordpress.md +87 -0
@@ -0,0 +1,352 @@
1
+ import type { ConsentRef, VisitRef } from '../analytics/client.ts';
2
+ import type { HttpClient } from '../lib/http.ts';
3
+ import type { AccessInfo, BillingInfo, Order, OrderList, OrderStatus, PaymentsMode, Product, Result, Subscription } from '../lib/types.ts';
4
+ /**
5
+ * Everything Stripe.js needs to show an embedded payment form (`payments.createPayment()`).
6
+ *
7
+ * ```ts
8
+ * const stripe = await loadStripe(setup.publishable_key, { stripeAccount: setup.stripe_account })
9
+ * const elements = stripe.elements({ clientSecret: setup.client_secret })
10
+ * ```
11
+ */
12
+ export interface PaymentSetup {
13
+ /**
14
+ * `'payment'`: a one-time purchase, confirm with `stripe.confirmPayment()`.
15
+ * `'subscription'`: the first payment of a subscription, confirm with `stripe.confirmPayment()`.
16
+ * `'setup'`: a free trial (nothing to pay today), save the card with `stripe.confirmSetup()`.
17
+ */
18
+ mode: 'payment' | 'subscription' | 'setup';
19
+ /** `pi_..._secret_...` (payment, subscription) or `seti_..._secret_...` (setup). */
20
+ client_secret: string;
21
+ /** The platform's Stripe publishable key, for `loadStripe()`. */
22
+ publishable_key: string;
23
+ /** The developer's connected Stripe account, for `loadStripe(key, { stripeAccount })`. */
24
+ stripe_account: string;
25
+ /** Minor units (cents). Due now for payment/subscription; per period after the trial for setup. */
26
+ amount: number;
27
+ currency: string;
28
+ interval: 'month' | 'year' | null;
29
+ /** When the free trial ends (ISO date), or null. */
30
+ trial_end: string | null;
31
+ subscription_id: string | null;
32
+ product: {
33
+ key: string;
34
+ name: string;
35
+ };
36
+ price: {
37
+ key: string;
38
+ };
39
+ /** `false` in test mode: only Stripe's test cards work and nothing is charged. Older servers leave it out. */
40
+ livemode?: boolean;
41
+ }
42
+ /** How to load Stripe.js for this project (`payments.stripeConfig()`). */
43
+ export interface StripeConfig {
44
+ /** The platform's publishable key, or null when the server has no STRIPE_PUBLISHABLE_KEY. */
45
+ publishable_key: string | null;
46
+ /** The connected Stripe account, or null when the developer hasn't connected Stripe yet. */
47
+ stripe_account: string | null;
48
+ connected: boolean;
49
+ /** Currency used by most of the project's prices, e.g. `'usd'`. */
50
+ currency_default: string;
51
+ /** `'test'`: Stripe's test cards, nothing is charged (show a test-card hint); `'live'`: real payments.
52
+ * The publishable key and account above are this mode's. Older servers leave it out. */
53
+ mode?: PaymentsMode;
54
+ /** The shop's terms: a cart's payment form shows a checkbox and sends `acceptTerms: true`. */
55
+ terms_url?: string | null;
56
+ }
57
+ /** A shipping rate a cart can choose (`payments.quote()`); `amount` already counts free shipping. */
58
+ export interface ShippingRateOption {
59
+ id: string;
60
+ name: string;
61
+ amount: number;
62
+ min_days: number | null;
63
+ max_days: number | null;
64
+ }
65
+ /** What a cart costs before paying (`payments.quote(items)`). Amounts in minor units (cents). */
66
+ export interface CartQuote {
67
+ currency: string;
68
+ items: {
69
+ price: string;
70
+ product_key: string;
71
+ name: string;
72
+ variant: string | null;
73
+ unit_amount: number;
74
+ quantity: number;
75
+ amount: number;
76
+ shipping: boolean;
77
+ in_stock: boolean;
78
+ available: number | null;
79
+ }[];
80
+ subtotal: number;
81
+ discount: number;
82
+ /** The goods after the discount; shipping (and tax, in checkout) come on top. */
83
+ goods: number;
84
+ shipping: {
85
+ required: boolean;
86
+ countries: string[];
87
+ rates: ShippingRateOption[];
88
+ collect_phone: boolean;
89
+ };
90
+ /** Every line has enough left right now. */
91
+ in_stock: boolean;
92
+ /** Stripe Tax is on: pay with `checkout()` (the embedded form can't add tax). */
93
+ automatic_tax: boolean;
94
+ terms_url: string | null;
95
+ }
96
+ /** Where a cart goes, for `payments.createCartPayment()` (a cart with products that ship). */
97
+ export interface CartShipping {
98
+ /** The id of one of `quote().shipping.rates`. */
99
+ rate: string;
100
+ name: string;
101
+ address: {
102
+ line1: string;
103
+ line2?: string | null;
104
+ city: string;
105
+ state?: string | null;
106
+ postal_code?: string | null;
107
+ country: string;
108
+ };
109
+ /** Needed when the shop asks for it (`quote().shipping.collect_phone`). */
110
+ phone?: string;
111
+ }
112
+ /** An embedded payment form for a cart (`payments.createCartPayment()`): confirm with `stripe.confirmPayment()`. */
113
+ export interface CartPaymentSetup {
114
+ mode: 'payment';
115
+ client_secret: string;
116
+ publishable_key: string;
117
+ stripe_account: string;
118
+ livemode: boolean;
119
+ currency: string;
120
+ /** What the buyer pays now: `goods` after the discount plus `shipping`. */
121
+ amount: number;
122
+ goods: number;
123
+ shipping: number;
124
+ /** The order: read it with `payments.orders.get(order.id, order.token)` after paying. */
125
+ order: {
126
+ id: string;
127
+ token: string;
128
+ };
129
+ }
130
+ /** One line of a cart: a price key (`'mug'`, `'tshirt_m'`) and how many (default 1, at most 100). */
131
+ export interface CheckoutItem {
132
+ price: string;
133
+ quantity?: number;
134
+ }
135
+ /**
136
+ * A cart for `payments.checkout({ items })`: one-time prices in one currency, 1 to 50 lines. Signed-in users and
137
+ * guests can buy; guests only products without `features` (Stripe asks for their email).
138
+ */
139
+ export interface CheckoutCart {
140
+ items: CheckoutItem[];
141
+ /** Where to go after paying. `{ORDER_ID}` and `{ORDER_TOKEN}` are filled in, e.g.
142
+ * `'https://shop.com/thanks?order={ORDER_ID}&order_token={ORDER_TOKEN}'`. */
143
+ successUrl?: string;
144
+ cancelUrl?: string;
145
+ /** A discount code the customer typed, like `'SUMMER20'` (checked before Stripe opens). */
146
+ coupon?: string;
147
+ /** `false` hides Stripe's own code box (only shown on plans without a platform fee). */
148
+ promotionCodes?: boolean;
149
+ /** Fills in the email on Stripe's page for a guest (they can still change it). */
150
+ email?: string;
151
+ /** Up to 20 short text values kept on the order, e.g. `{ gift_note: 'Happy birthday!' }`. */
152
+ metadata?: Record<string, string | number | boolean>;
153
+ /** `false`: return the URL instead of opening Stripe (browsers redirect by default). */
154
+ redirect?: boolean;
155
+ }
156
+ /** What `checkout()` returns. `order` (one-time purchases): read it later with `payments.orders.get(order.id, order.token)`. */
157
+ export interface CheckoutResult {
158
+ url: string;
159
+ id: string;
160
+ livemode?: boolean;
161
+ order?: {
162
+ id: string;
163
+ token: string;
164
+ };
165
+ /** The goods after the discount, in minor units (carts always; a single price only with `coupon`). */
166
+ amount?: number;
167
+ currency?: string;
168
+ }
169
+ /**
170
+ * Shop orders: what a buyer bought (`payments.orders`). Signed-in users list their own; anyone with an order's token
171
+ * (a guest after checkout) can read that order.
172
+ */
173
+ export declare class OrdersClient {
174
+ private http;
175
+ private hasUser;
176
+ constructor(http: HttpClient, hasUser: () => Promise<boolean>);
177
+ /** The signed-in user's orders, newest first (completed checkouts only). Pass `next_cursor` back as `cursor`. */
178
+ list(options?: {
179
+ limit?: number;
180
+ cursor?: string;
181
+ status?: OrderStatus | OrderStatus[];
182
+ }): Promise<Result<OrderList>>;
183
+ /**
184
+ * One order with its lines and, once paid, links to its files. `token`: the order token from checkout (guests, or
185
+ * a link you emailed); without it the signed-in buyer reads their own order.
186
+ *
187
+ * ```ts
188
+ * const q = new URLSearchParams(location.search)
189
+ * const { data: order } = await baas.payments.orders.get(q.get('order')!, q.get('order_token'))
190
+ * ```
191
+ */
192
+ get(id: string, token?: string | null): Promise<Result<Order>>;
193
+ /**
194
+ * After returning from Stripe: wait until the order is no longer pending (Stripe confirms the payment with a webhook,
195
+ * usually within seconds). Resolves with the order (`status` `'paid'`, or still `'pending'` after `timeoutMs`,
196
+ * default 20 s), checking every `intervalMs` (default 1.5 s).
197
+ */
198
+ wait(id: string, token?: string | null, options?: {
199
+ timeoutMs?: number;
200
+ intervalMs?: number;
201
+ }): Promise<Result<Order>>;
202
+ }
203
+ export declare class PaymentsClient {
204
+ private http;
205
+ private hasUser;
206
+ private visit;
207
+ private consent;
208
+ /** Shop orders: `list()` (the signed-in user's), `get(id, token)`, `wait(id, token)`. */
209
+ readonly orders: OrdersClient;
210
+ /** `visit`: the analytics visit sent with checkout and payment forms (Revenue by source), see `analytics.visitRef()`.
211
+ * `consent`: the visitor's consent state for a server-side tagging extension, see `analytics.consentRef()`. */
212
+ constructor(http: HttpClient, hasUser: () => Promise<boolean>, visit?: () => VisitRef | undefined, consent?: () => Promise<ConsentRef | undefined>);
213
+ /** The consent state to send with a sale, never throwing. */
214
+ private currentConsent;
215
+ /** The visit to send with a sale, never throwing. */
216
+ private currentVisit;
217
+ /** Your public catalog: active products with their prices. */
218
+ products(): Promise<Result<Product[]>>;
219
+ /**
220
+ * Start Stripe Checkout for a price (e.g. `'pro_monthly'`). In a browser this redirects to
221
+ * Stripe; elsewhere (or with `redirect: false`) it returns the URL for you to open.
222
+ * The user must be signed in.
223
+ *
224
+ * Where Stripe sends the customer back: `successUrl` / `cancelUrl` when given, else the defaults
225
+ * from Dashboard → Payments → Checkout settings, else (in a browser) the current page, with
226
+ * `?checkout=success` added after paying.
227
+ *
228
+ * Discount codes: pass `coupon` (the code the customer typed in your app, like `'SUMMER20'`). It is checked
229
+ * before Stripe opens (errors: `invalid_coupon`, `coupon_expired`, `coupon_not_applicable`) and the result
230
+ * has the discounted `amount`. Without it, Stripe's checkout page shows its own code box, except for
231
+ * one-time products on the Free plan (usebecky's fee is set from the final price, so the code must be
232
+ * known first).
233
+ *
234
+ * A cart (a shop): `checkout({ items: [{ price: 'mug', quantity: 2 }, { price: 'stickers' }] })`. One-time prices
235
+ * in one currency, 1 to 50 lines; guests can buy products without `features` (no sign-in needed). The result has
236
+ * the `order` (`id`, `token`): after paying, `payments.orders.get(order.id, order.token)`. Without `successUrl`,
237
+ * the buyer comes back to this page with `?checkout=success&order=<id>&order_token=<token>`.
238
+ */
239
+ checkout(price: string, options?: {
240
+ successUrl?: string;
241
+ cancelUrl?: string;
242
+ quantity?: number;
243
+ promotionCodes?: boolean;
244
+ coupon?: string;
245
+ redirect?: boolean;
246
+ }): Promise<Result<CheckoutResult>>;
247
+ checkout(cart: CheckoutCart): Promise<Result<CheckoutResult>>;
248
+ /**
249
+ * Open the Stripe customer portal (change plan, cancel, update card). Redirects in a browser,
250
+ * otherwise returns the URL.
251
+ */
252
+ portal(options?: {
253
+ returnUrl?: string;
254
+ redirect?: boolean;
255
+ }): Promise<Result<{
256
+ url: string;
257
+ }>>;
258
+ /**
259
+ * Prepare an embedded payment form for a price (e.g. `'pro_monthly'`): a card form on your own page
260
+ * instead of Stripe's checkout page. Returns what Stripe.js needs (client secret, publishable key,
261
+ * connected account). The user must be signed in. Access is granted when Stripe confirms the
262
+ * payment: call `waitForAccess(feature)` after `stripe.confirmPayment()` / `stripe.confirmSetup()`.
263
+ */
264
+ createPayment(price: string, options?: {
265
+ quantity?: number;
266
+ coupon?: string;
267
+ }): Promise<Result<PaymentSetup>>;
268
+ /**
269
+ * What a cart costs before paying: its lines with their stock, the goods after a discount code, the shipping rates
270
+ * (and whether an address is needed), the shop's terms. Works for guests too.
271
+ *
272
+ * ```ts
273
+ * const { data: quote } = await baas.payments.quote([{ price: 'tshirt_m', quantity: 2 }, { price: 'mug' }])
274
+ * ```
275
+ */
276
+ quote(items: CheckoutItem[], options?: {
277
+ coupon?: string;
278
+ }): Promise<Result<CartQuote>>;
279
+ /**
280
+ * Prepare an embedded payment form for a cart: an order (its stock held for 31 minutes) and a payment for the goods
281
+ * plus the chosen shipping rate. Guests pass their `email`; carts that ship pass `shipping` (address and rate, e.g.
282
+ * from Stripe's Address Element); shops with terms need `acceptTerms: true`. Then `stripe.confirmPayment()`.
283
+ */
284
+ createCartPayment(cart: {
285
+ items: CheckoutItem[];
286
+ shipping?: CartShipping;
287
+ email?: string;
288
+ coupon?: string;
289
+ acceptTerms?: boolean;
290
+ metadata?: Record<string, string | number | boolean>;
291
+ locale?: string;
292
+ /** The order of an earlier try that wasn't paid (a declined card, another address): it is dropped and its stock freed. */
293
+ replaces?: {
294
+ id: string;
295
+ token: string;
296
+ };
297
+ }): Promise<Result<CartPaymentSetup>>;
298
+ /**
299
+ * After a successful payment: wait until the user has the feature (the payment is confirmed by a
300
+ * Stripe webhook, usually within a few seconds). Resolves `true` as soon as `hasAccess(feature)`
301
+ * is true, or `false` after `timeoutMs` (default 20 s), checking every `intervalMs` (default 1.5 s).
302
+ */
303
+ waitForAccess(feature: string, options?: {
304
+ timeoutMs?: number;
305
+ intervalMs?: number;
306
+ }): Promise<Result<boolean>>;
307
+ /** How to load Stripe.js for embedded payment forms: `{ publishable_key, stripe_account, connected, currency_default, mode }`. */
308
+ stripeConfig(): Promise<Result<StripeConfig>>;
309
+ /**
310
+ * Is your app taking real payments? `'test'` while you build (Stripe's test cards, nothing is charged),
311
+ * `'live'` after you switched to live (Dashboard → Payments → Go live). Use it to show a test-card hint
312
+ * only in test mode. `null` when the server is too old to say.
313
+ *
314
+ * ```ts
315
+ * const { data: mode } = await baas.payments.mode()
316
+ * if (mode === 'test') showHint('Test mode: pay with 4242 4242 4242 4242')
317
+ * ```
318
+ */
319
+ mode(): Promise<Result<PaymentsMode | null>>;
320
+ /** The signed-in user's subscriptions, purchases and entitlements. */
321
+ me(): Promise<Result<BillingInfo>>;
322
+ /** Does the signed-in user have this feature (from an active subscription, a purchase or a gift)? `false` when signed out. */
323
+ hasAccess(feature: string): Promise<Result<boolean>>;
324
+ /**
325
+ * Like `hasAccess`, and also says where the access comes from: `'subscription'` (paid or trial),
326
+ * `'purchase'`, `'gift'` (you gave it for free) or `null`. Handy for a "Gifted" badge.
327
+ * `{ access: false, source: null }` when signed out.
328
+ */
329
+ checkAccess(feature: string): Promise<Result<AccessInfo>>;
330
+ /**
331
+ * Cancel one of the signed-in user's subscriptions (an `id` from `me()`). By default at the end of the paid period:
332
+ * access stays until then and nothing more is charged. `atPeriodEnd: false` ends it now. Build your own cancel page
333
+ * with it (e.g. Germany's "Verträge hier kündigen" button), or send users to `portal()`.
334
+ *
335
+ * ```ts
336
+ * const { data: sub, error } = await baas.payments.cancelSubscription(sub.id)
337
+ * if (!error) show(`Canceled. Pro stays until ${new Date(sub.current_period_end!).toLocaleDateString()}.`)
338
+ * ```
339
+ * Errors: `not_signed_in`, `subscription_not_found` (not theirs either), `gift_subscription`.
340
+ */
341
+ cancelSubscription(id: string, options?: {
342
+ atPeriodEnd?: boolean;
343
+ }): Promise<Result<Subscription>>;
344
+ /** Take back the user's own cancellation at the period end (the subscription renews again). Errors: `subscription_ended`
345
+ * once it ended, `canceled_by_team` when your team canceled it (only your server can take that back). */
346
+ resumeSubscription(id: string): Promise<Result<Subscription>>;
347
+ /** A short-lived download link for a purchased product. */
348
+ download(productKey: string): Promise<Result<{
349
+ url: string;
350
+ expiresIn: number;
351
+ }>>;
352
+ }
@@ -0,0 +1,323 @@
1
+ import { notSignedIn } from "../auth/client.js";
2
+ import { UseBeckyError } from "../lib/errors.js";
3
+ const g = globalThis;
4
+ function canRedirect() {
5
+ return typeof g.window === 'object' && g.window !== null && typeof g.document === 'object' && typeof g.location?.assign === 'function';
6
+ }
7
+ /** The current page with `checkout=success` added to the query string (browsers only). */
8
+ function currentPage(extra) {
9
+ if (!canRedirect() || typeof g.location?.href !== 'string')
10
+ return undefined;
11
+ try {
12
+ const url = new URL(g.location.href);
13
+ for (const [k, v] of Object.entries(extra ?? {}))
14
+ url.searchParams.set(k, v);
15
+ return url.toString();
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ /**
22
+ * Shop orders: what a buyer bought (`payments.orders`). Signed-in users list their own; anyone with an order's token
23
+ * (a guest after checkout) can read that order.
24
+ */
25
+ export class OrdersClient {
26
+ http;
27
+ hasUser;
28
+ constructor(http, hasUser) {
29
+ this.http = http;
30
+ this.hasUser = hasUser;
31
+ }
32
+ /** The signed-in user's orders, newest first (completed checkouts only). Pass `next_cursor` back as `cursor`. */
33
+ async list(options = {}) {
34
+ if (!(await this.hasUser()))
35
+ return { data: null, error: withHint(notSignedIn(), 'Sign in to see your orders. A guest reads one order with payments.orders.get(id, token).') };
36
+ const status = Array.isArray(options.status) ? options.status.join(',') : options.status;
37
+ const res = await this.http.request('/payments/v1/orders', { query: { limit: options.limit, cursor: options.cursor, status } });
38
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
39
+ }
40
+ /**
41
+ * One order with its lines and, once paid, links to its files. `token`: the order token from checkout (guests, or
42
+ * a link you emailed); without it the signed-in buyer reads their own order.
43
+ *
44
+ * ```ts
45
+ * const q = new URLSearchParams(location.search)
46
+ * const { data: order } = await baas.payments.orders.get(q.get('order')!, q.get('order_token'))
47
+ * ```
48
+ */
49
+ async get(id, token) {
50
+ const res = await this.http.request(`/payments/v1/orders/${encodeURIComponent(id)}`, { query: token ? { token } : undefined });
51
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
52
+ }
53
+ /**
54
+ * After returning from Stripe: wait until the order is no longer pending (Stripe confirms the payment with a webhook,
55
+ * usually within seconds). Resolves with the order (`status` `'paid'`, or still `'pending'` after `timeoutMs`,
56
+ * default 20 s), checking every `intervalMs` (default 1.5 s).
57
+ */
58
+ async wait(id, token, options = {}) {
59
+ const timeoutMs = options.timeoutMs ?? 20_000;
60
+ const intervalMs = Math.max(50, options.intervalMs ?? 1_500);
61
+ const deadline = Date.now() + timeoutMs;
62
+ for (;;) {
63
+ const res = await this.get(id, token);
64
+ if (res.error && res.error.status > 0 && res.error.status < 500 && res.error.status !== 429)
65
+ return res; // won't fix itself
66
+ if (res.data && res.data.status !== 'pending')
67
+ return res;
68
+ const left = deadline - Date.now();
69
+ if (left <= 0)
70
+ return res;
71
+ await new Promise((r) => setTimeout(r, Math.min(intervalMs, left)));
72
+ }
73
+ }
74
+ }
75
+ export class PaymentsClient {
76
+ http;
77
+ hasUser;
78
+ visit;
79
+ consent;
80
+ /** Shop orders: `list()` (the signed-in user's), `get(id, token)`, `wait(id, token)`. */
81
+ orders;
82
+ /** `visit`: the analytics visit sent with checkout and payment forms (Revenue by source), see `analytics.visitRef()`.
83
+ * `consent`: the visitor's consent state for a server-side tagging extension, see `analytics.consentRef()`. */
84
+ constructor(http, hasUser, visit = () => undefined, consent = () => Promise.resolve(undefined)) {
85
+ this.http = http;
86
+ this.hasUser = hasUser;
87
+ this.visit = visit;
88
+ this.consent = consent;
89
+ this.orders = new OrdersClient(http, hasUser);
90
+ }
91
+ /** The consent state to send with a sale, never throwing. */
92
+ async currentConsent() {
93
+ try {
94
+ return await this.consent();
95
+ }
96
+ catch {
97
+ return undefined;
98
+ }
99
+ }
100
+ /** The visit to send with a sale, never throwing. */
101
+ currentVisit() {
102
+ try {
103
+ return this.visit();
104
+ }
105
+ catch {
106
+ return undefined;
107
+ }
108
+ }
109
+ /** Your public catalog: active products with their prices. */
110
+ async products() {
111
+ const res = await this.http.request('/payments/v1/products');
112
+ return res.error ? { data: null, error: res.error } : { data: res.data ?? [], error: null };
113
+ }
114
+ async checkout(what, single = {}) {
115
+ const cart = typeof what === 'string' ? null : what;
116
+ const options = cart ?? single;
117
+ // A single price needs an account (subscriptions and features belong to one); a cart may be bought as a guest.
118
+ if (!cart && !(await this.hasUser()))
119
+ return { data: null, error: withHint(notSignedIn(), 'Sign in before starting checkout, so the purchase is linked to the right account.') };
120
+ const back = cart ? { checkout: 'success', order: '{ORDER_ID}', order_token: '{ORDER_TOKEN}' } : { checkout: 'success' };
121
+ const res = await this.http.request('/payments/v1/checkout', {
122
+ method: 'POST',
123
+ body: {
124
+ ...(cart ? { items: cart.items.map((i) => ({ price: i.price, quantity: i.quantity })) } : { price: what, quantity: single.quantity }),
125
+ success_url: options.successUrl,
126
+ cancel_url: options.cancelUrl,
127
+ // Last resort (the dashboard's checkout settings come first): back to this page.
128
+ fallback_success_url: options.successUrl ? undefined : currentPage(back),
129
+ fallback_cancel_url: options.cancelUrl ? undefined : currentPage(),
130
+ promotion_codes: options.promotionCodes,
131
+ coupon: options.coupon || undefined,
132
+ email: cart?.email || undefined,
133
+ metadata: cart?.metadata,
134
+ // The analytics visit, so the sale can be credited to the source that brought the buyer.
135
+ visit: this.currentVisit(),
136
+ // The visitor's consent state, for a server-side tagging extension (purchase). Undefined: not sent.
137
+ consent: await this.currentConsent(),
138
+ },
139
+ });
140
+ if (res.error)
141
+ return { data: null, error: res.error };
142
+ if (options.redirect !== false && res.data?.url && canRedirect())
143
+ g.location.assign(res.data.url);
144
+ return { data: res.data, error: null };
145
+ }
146
+ /**
147
+ * Open the Stripe customer portal (change plan, cancel, update card). Redirects in a browser,
148
+ * otherwise returns the URL.
149
+ */
150
+ async portal(options = {}) {
151
+ if (!(await this.hasUser()))
152
+ return { data: null, error: notSignedIn() };
153
+ const res = await this.http.request('/payments/v1/portal', { method: 'POST', body: { return_url: options.returnUrl ?? (canRedirect() ? String(g.location.href) : undefined) } });
154
+ if (res.error)
155
+ return { data: null, error: res.error };
156
+ if (options.redirect !== false && res.data?.url && canRedirect())
157
+ g.location.assign(res.data.url);
158
+ return { data: res.data, error: null };
159
+ }
160
+ /**
161
+ * Prepare an embedded payment form for a price (e.g. `'pro_monthly'`): a card form on your own page
162
+ * instead of Stripe's checkout page. Returns what Stripe.js needs (client secret, publishable key,
163
+ * connected account). The user must be signed in. Access is granted when Stripe confirms the
164
+ * payment: call `waitForAccess(feature)` after `stripe.confirmPayment()` / `stripe.confirmSetup()`.
165
+ */
166
+ async createPayment(price, options = {}) {
167
+ if (!(await this.hasUser()))
168
+ return { data: null, error: withHint(notSignedIn(), 'Sign in before paying, so the purchase is linked to the right account.') };
169
+ const res = await this.http.request('/payments/v1/intent', {
170
+ method: 'POST',
171
+ body: { price, quantity: options.quantity, coupon: options.coupon || undefined, visit: this.currentVisit(), consent: await this.currentConsent() },
172
+ });
173
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
174
+ }
175
+ /**
176
+ * What a cart costs before paying: its lines with their stock, the goods after a discount code, the shipping rates
177
+ * (and whether an address is needed), the shop's terms. Works for guests too.
178
+ *
179
+ * ```ts
180
+ * const { data: quote } = await baas.payments.quote([{ price: 'tshirt_m', quantity: 2 }, { price: 'mug' }])
181
+ * ```
182
+ */
183
+ async quote(items, options = {}) {
184
+ if (!Array.isArray(items) || !items.length)
185
+ return { data: null, error: invalidInput('Pass the cart: [{ price: "tshirt_m", quantity: 2 }].') };
186
+ const res = await this.http.request('/payments/v1/quote', { method: 'POST', body: { items, coupon: options.coupon || undefined } });
187
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
188
+ }
189
+ /**
190
+ * Prepare an embedded payment form for a cart: an order (its stock held for 31 minutes) and a payment for the goods
191
+ * plus the chosen shipping rate. Guests pass their `email`; carts that ship pass `shipping` (address and rate, e.g.
192
+ * from Stripe's Address Element); shops with terms need `acceptTerms: true`. Then `stripe.confirmPayment()`.
193
+ */
194
+ async createCartPayment(cart) {
195
+ if (!cart || !Array.isArray(cart.items) || !cart.items.length)
196
+ return { data: null, error: invalidInput('Pass the cart: { items: [{ price: "tshirt_m", quantity: 2 }] }.') };
197
+ const res = await this.http.request('/payments/v1/intent', {
198
+ method: 'POST',
199
+ body: {
200
+ items: cart.items,
201
+ shipping: cart.shipping,
202
+ email: cart.email || undefined,
203
+ coupon: cart.coupon || undefined,
204
+ accept_terms: cart.acceptTerms || undefined,
205
+ metadata: cart.metadata,
206
+ locale: cart.locale,
207
+ replaces: cart.replaces,
208
+ consent: await this.currentConsent(),
209
+ },
210
+ });
211
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
212
+ }
213
+ /**
214
+ * After a successful payment: wait until the user has the feature (the payment is confirmed by a
215
+ * Stripe webhook, usually within a few seconds). Resolves `true` as soon as `hasAccess(feature)`
216
+ * is true, or `false` after `timeoutMs` (default 20 s), checking every `intervalMs` (default 1.5 s).
217
+ */
218
+ async waitForAccess(feature, options = {}) {
219
+ const timeoutMs = options.timeoutMs ?? 20_000;
220
+ const intervalMs = Math.max(50, options.intervalMs ?? 1_500);
221
+ if (!(await this.hasUser()))
222
+ return { data: null, error: withHint(notSignedIn(), 'Sign in first: access belongs to a signed-in user.') };
223
+ const deadline = Date.now() + timeoutMs;
224
+ for (;;) {
225
+ const res = await this.hasAccess(feature);
226
+ if (res.error && res.error.status > 0 && res.error.status < 500 && res.error.status !== 429)
227
+ return res; // won't fix itself
228
+ if (res.data === true)
229
+ return { data: true, error: null };
230
+ const left = deadline - Date.now();
231
+ if (left <= 0)
232
+ return res.error ? res : { data: false, error: null };
233
+ await new Promise((r) => setTimeout(r, Math.min(intervalMs, left)));
234
+ }
235
+ }
236
+ /** How to load Stripe.js for embedded payment forms: `{ publishable_key, stripe_account, connected, currency_default, mode }`. */
237
+ async stripeConfig() {
238
+ const res = await this.http.request('/payments/v1/config');
239
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
240
+ }
241
+ /**
242
+ * Is your app taking real payments? `'test'` while you build (Stripe's test cards, nothing is charged),
243
+ * `'live'` after you switched to live (Dashboard → Payments → Go live). Use it to show a test-card hint
244
+ * only in test mode. `null` when the server is too old to say.
245
+ *
246
+ * ```ts
247
+ * const { data: mode } = await baas.payments.mode()
248
+ * if (mode === 'test') showHint('Test mode: pay with 4242 4242 4242 4242')
249
+ * ```
250
+ */
251
+ async mode() {
252
+ const res = await this.stripeConfig();
253
+ return res.error ? { data: null, error: res.error } : { data: res.data?.mode ?? null, error: null };
254
+ }
255
+ /** The signed-in user's subscriptions, purchases and entitlements. */
256
+ async me() {
257
+ if (!(await this.hasUser()))
258
+ return { data: { customer_id: null, subscriptions: [], purchases: [], entitlements: [] }, error: null };
259
+ const res = await this.http.request('/payments/v1/me');
260
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
261
+ }
262
+ /** Does the signed-in user have this feature (from an active subscription, a purchase or a gift)? `false` when signed out. */
263
+ async hasAccess(feature) {
264
+ if (!(await this.hasUser()))
265
+ return { data: false, error: null };
266
+ const res = await this.http.request(`/payments/v1/access/${encodeURIComponent(feature)}`);
267
+ return res.error ? { data: null, error: res.error } : { data: !!res.data?.access, error: null };
268
+ }
269
+ /**
270
+ * Like `hasAccess`, and also says where the access comes from: `'subscription'` (paid or trial),
271
+ * `'purchase'`, `'gift'` (you gave it for free) or `null`. Handy for a "Gifted" badge.
272
+ * `{ access: false, source: null }` when signed out.
273
+ */
274
+ async checkAccess(feature) {
275
+ if (!(await this.hasUser()))
276
+ return { data: { access: false, source: null }, error: null };
277
+ const res = await this.http.request(`/payments/v1/access/${encodeURIComponent(feature)}`);
278
+ return res.error ? { data: null, error: res.error } : { data: { access: !!res.data?.access, source: res.data?.source ?? null }, error: null };
279
+ }
280
+ /**
281
+ * Cancel one of the signed-in user's subscriptions (an `id` from `me()`). By default at the end of the paid period:
282
+ * access stays until then and nothing more is charged. `atPeriodEnd: false` ends it now. Build your own cancel page
283
+ * with it (e.g. Germany's "Verträge hier kündigen" button), or send users to `portal()`.
284
+ *
285
+ * ```ts
286
+ * const { data: sub, error } = await baas.payments.cancelSubscription(sub.id)
287
+ * if (!error) show(`Canceled. Pro stays until ${new Date(sub.current_period_end!).toLocaleDateString()}.`)
288
+ * ```
289
+ * Errors: `not_signed_in`, `subscription_not_found` (not theirs either), `gift_subscription`.
290
+ */
291
+ async cancelSubscription(id, options = {}) {
292
+ if (!(await this.hasUser()))
293
+ return { data: null, error: notSignedIn() };
294
+ if (!id)
295
+ return { data: null, error: invalidInput('Pass the id of the subscription (from baas.payments.me()).') };
296
+ const res = await this.http.request(`/payments/v1/subscriptions/${encodeURIComponent(id)}/cancel`, { method: 'POST', body: { at_period_end: options.atPeriodEnd ?? true } });
297
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
298
+ }
299
+ /** Take back the user's own cancellation at the period end (the subscription renews again). Errors: `subscription_ended`
300
+ * once it ended, `canceled_by_team` when your team canceled it (only your server can take that back). */
301
+ async resumeSubscription(id) {
302
+ if (!(await this.hasUser()))
303
+ return { data: null, error: notSignedIn() };
304
+ if (!id)
305
+ return { data: null, error: invalidInput('Pass the id of the subscription (from baas.payments.me()).') };
306
+ const res = await this.http.request(`/payments/v1/subscriptions/${encodeURIComponent(id)}/resume`, { method: 'POST', body: {} });
307
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
308
+ }
309
+ /** A short-lived download link for a purchased product. */
310
+ async download(productKey) {
311
+ if (!(await this.hasUser()))
312
+ return { data: null, error: notSignedIn() };
313
+ const res = await this.http.request(`/payments/v1/downloads/${encodeURIComponent(productKey)}`);
314
+ return res.error ? { data: null, error: res.error } : { data: { url: res.data.url, expiresIn: res.data.expires_in }, error: null };
315
+ }
316
+ }
317
+ function withHint(err, hint) {
318
+ err.hint = hint;
319
+ return err;
320
+ }
321
+ function invalidInput(message) {
322
+ return new UseBeckyError({ code: 'invalid_input', message, status: 0 });
323
+ }