@ultimabase/stripe 0.0.0-first.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 (130) hide show
  1. package/README.md +7 -0
  2. package/dist/accounts.d.ts +9 -0
  3. package/dist/accounts.d.ts.map +1 -0
  4. package/dist/accounts.js +20 -0
  5. package/dist/apply.d.ts +26 -0
  6. package/dist/apply.d.ts.map +1 -0
  7. package/dist/apply.js +73 -0
  8. package/dist/audit.d.ts +3 -0
  9. package/dist/audit.d.ts.map +1 -0
  10. package/dist/audit.js +123 -0
  11. package/dist/billing-gateway.d.ts +158 -0
  12. package/dist/billing-gateway.d.ts.map +1 -0
  13. package/dist/billing-gateway.js +23 -0
  14. package/dist/billing.d.ts +130 -0
  15. package/dist/billing.d.ts.map +1 -0
  16. package/dist/billing.js +128 -0
  17. package/dist/calls.d.ts +61 -0
  18. package/dist/calls.d.ts.map +1 -0
  19. package/dist/calls.js +172 -0
  20. package/dist/catalog.d.ts +54 -0
  21. package/dist/catalog.d.ts.map +1 -0
  22. package/dist/catalog.js +182 -0
  23. package/dist/credit.d.ts +16 -0
  24. package/dist/credit.d.ts.map +1 -0
  25. package/dist/credit.js +18 -0
  26. package/dist/credits.d.ts +38 -0
  27. package/dist/credits.d.ts.map +1 -0
  28. package/dist/credits.js +138 -0
  29. package/dist/customer.d.ts +25 -0
  30. package/dist/customer.d.ts.map +1 -0
  31. package/dist/customer.js +88 -0
  32. package/dist/describe.d.ts +4 -0
  33. package/dist/describe.d.ts.map +1 -0
  34. package/dist/describe.js +56 -0
  35. package/dist/duplicates.d.ts +12 -0
  36. package/dist/duplicates.d.ts.map +1 -0
  37. package/dist/duplicates.js +24 -0
  38. package/dist/fake-billing.d.ts +72 -0
  39. package/dist/fake-billing.d.ts.map +1 -0
  40. package/dist/fake-billing.js +290 -0
  41. package/dist/gateway.d.ts +108 -0
  42. package/dist/gateway.d.ts.map +1 -0
  43. package/dist/gateway.js +196 -0
  44. package/dist/index.d.ts +15 -0
  45. package/dist/index.d.ts.map +1 -0
  46. package/dist/index.js +6 -0
  47. package/dist/job-input.d.ts +6 -0
  48. package/dist/job-input.d.ts.map +1 -0
  49. package/dist/job-input.js +20 -0
  50. package/dist/jobs.d.ts +16 -0
  51. package/dist/jobs.d.ts.map +1 -0
  52. package/dist/jobs.js +189 -0
  53. package/dist/keys.d.ts +10 -0
  54. package/dist/keys.d.ts.map +1 -0
  55. package/dist/keys.js +30 -0
  56. package/dist/kinds.d.ts +11 -0
  57. package/dist/kinds.d.ts.map +1 -0
  58. package/dist/kinds.js +4 -0
  59. package/dist/models.d.ts +71 -0
  60. package/dist/models.d.ts.map +1 -0
  61. package/dist/models.js +41 -0
  62. package/dist/plugin.d.ts +41 -0
  63. package/dist/plugin.d.ts.map +1 -0
  64. package/dist/plugin.js +229 -0
  65. package/dist/portal.d.ts +23 -0
  66. package/dist/portal.d.ts.map +1 -0
  67. package/dist/portal.js +66 -0
  68. package/dist/product.d.ts +57 -0
  69. package/dist/product.d.ts.map +1 -0
  70. package/dist/product.js +113 -0
  71. package/dist/running.d.ts +61 -0
  72. package/dist/running.d.ts.map +1 -0
  73. package/dist/running.js +35 -0
  74. package/dist/sdk-billing.d.ts +8 -0
  75. package/dist/sdk-billing.d.ts.map +1 -0
  76. package/dist/sdk-billing.js +200 -0
  77. package/dist/sdk-common.d.ts +13 -0
  78. package/dist/sdk-common.d.ts.map +1 -0
  79. package/dist/sdk-common.js +41 -0
  80. package/dist/sdk-customer.d.ts +9 -0
  81. package/dist/sdk-customer.d.ts.map +1 -0
  82. package/dist/sdk-customer.js +149 -0
  83. package/dist/sdk-invoices.d.ts +10 -0
  84. package/dist/sdk-invoices.d.ts.map +1 -0
  85. package/dist/sdk-invoices.js +53 -0
  86. package/dist/sdk-recovery.d.ts +5 -0
  87. package/dist/sdk-recovery.d.ts.map +1 -0
  88. package/dist/sdk-recovery.js +81 -0
  89. package/dist/sync.d.ts +8 -0
  90. package/dist/sync.d.ts.map +1 -0
  91. package/dist/sync.js +196 -0
  92. package/dist/testing.d.ts +24 -0
  93. package/dist/testing.d.ts.map +1 -0
  94. package/dist/testing.js +100 -0
  95. package/dist/webhook.d.ts +4 -0
  96. package/dist/webhook.d.ts.map +1 -0
  97. package/dist/webhook.js +73 -0
  98. package/package.json +51 -0
  99. package/src/accounts.ts +30 -0
  100. package/src/apply.ts +99 -0
  101. package/src/audit.ts +171 -0
  102. package/src/billing-gateway.ts +188 -0
  103. package/src/billing.ts +361 -0
  104. package/src/calls.ts +280 -0
  105. package/src/catalog.ts +327 -0
  106. package/src/credit.ts +36 -0
  107. package/src/credits.ts +206 -0
  108. package/src/customer.ts +113 -0
  109. package/src/describe.ts +76 -0
  110. package/src/duplicates.ts +45 -0
  111. package/src/fake-billing.ts +388 -0
  112. package/src/gateway.ts +333 -0
  113. package/src/index.ts +35 -0
  114. package/src/job-input.ts +24 -0
  115. package/src/jobs.ts +230 -0
  116. package/src/keys.ts +40 -0
  117. package/src/kinds.ts +15 -0
  118. package/src/models.ts +107 -0
  119. package/src/plugin.ts +307 -0
  120. package/src/portal.ts +95 -0
  121. package/src/product.ts +203 -0
  122. package/src/running.ts +104 -0
  123. package/src/sdk-billing.ts +220 -0
  124. package/src/sdk-common.ts +57 -0
  125. package/src/sdk-customer.ts +203 -0
  126. package/src/sdk-invoices.ts +81 -0
  127. package/src/sdk-recovery.ts +93 -0
  128. package/src/sync.ts +246 -0
  129. package/src/testing.ts +135 -0
  130. package/src/webhook.ts +100 -0
@@ -0,0 +1,290 @@
1
+ // The fake account's payers (D-371 point 8): customers, Checkouts a test
2
+ // pays, subscriptions and payments, and the thin events each change sends
3
+ // to the webhook, signed as Stripe signs them.
4
+ import { Stripe } from 'stripe';
5
+ import { Missing } from './billing-gateway.js';
6
+ /** A thin event's body, as Stripe sends it to an event destination. */
7
+ export const thinEvent = (event) => JSON.stringify({
8
+ id: event.id ?? `evt_${crypto.randomUUID().replaceAll('-', '')}`,
9
+ object: 'v2.core.event',
10
+ type: `v1.${event.type}`,
11
+ livemode: event.livemode ?? false,
12
+ created: new Date().toISOString(),
13
+ related_object: { ...event.object, url: `/v1/${event.object.id}` },
14
+ });
15
+ /** Posts `payload` to the webhook of the application at `url`, signed. */
16
+ export const postEvent = async (url, payload, options) => fetch(`${url}${options.path ?? '/webhooks/stripe'}`, {
17
+ method: 'POST',
18
+ headers: {
19
+ 'content-type': 'application/json',
20
+ 'stripe-signature': Stripe.webhooks.generateTestHeaderString({
21
+ payload,
22
+ secret: options.secret,
23
+ }),
24
+ },
25
+ body: payload,
26
+ });
27
+ const found = (map, id) => {
28
+ const record = map.get(id);
29
+ if (record === undefined)
30
+ throw new Missing(id);
31
+ return record;
32
+ };
33
+ const day = 24 * 60 * 60 * 1000;
34
+ const days = {
35
+ day: 1,
36
+ week: 7,
37
+ month: 30,
38
+ year: 365,
39
+ };
40
+ const periodOf = ({ every, everyCount }) => (days[every] ?? 30) * everyCount * day;
41
+ /** The fake's billing, over its catalog's prices. */
42
+ export function fakeBilling(prices, newId) {
43
+ const customers = new Map();
44
+ const keys = new Map();
45
+ const checkouts = new Map();
46
+ const subscriptions = new Map();
47
+ const payments = new Map();
48
+ const invoices = new Map();
49
+ const portalSessions = [];
50
+ const subscriptionRefunds = new Set();
51
+ const sent = [];
52
+ /** Each event's object and time, which Stripe lists for 30 days. */
53
+ const listed = [];
54
+ const send = (type, id, object) => {
55
+ sent.push(thinEvent({ type, object: { id, type: object } }));
56
+ listed.push({ id, type: object, at: new Date() });
57
+ };
58
+ const ownerOf = (type, id) => {
59
+ const maps = {
60
+ 'checkout.session': checkouts,
61
+ subscription: subscriptions,
62
+ payment_intent: payments,
63
+ invoice: invoices,
64
+ };
65
+ if (type === 'customer')
66
+ return customers.has(id) ? id : null;
67
+ return maps[type]?.get(id)?.customerId ?? null;
68
+ };
69
+ const priceOf = (lookupKey) => {
70
+ const held = [...prices.values()].find((one) => one.active && one.lookupKey === lookupKey);
71
+ if (held === undefined)
72
+ throw new Error(`No price is ${lookupKey}.`);
73
+ return held;
74
+ };
75
+ const live = (id) => {
76
+ const customer = found(customers, id);
77
+ if (customer.deleted)
78
+ throw new Missing(id);
79
+ return customer;
80
+ };
81
+ /** Bills a subscription's period, which ends at `end`. */
82
+ const bill = (subscription, end) => {
83
+ const id = newId('in');
84
+ const { product, price, quantity, amount, customerId } = subscription;
85
+ const periods = [{ product, price, quantity, end }];
86
+ const refunds = { refunded: 0, disputeLost: false };
87
+ invoices.set(id, { id, customerId, periods, amount, ...refunds });
88
+ send('invoice.paid', id, 'invoice');
89
+ return id;
90
+ };
91
+ const subscribe = (checkout, price) => {
92
+ const id = newId('sub');
93
+ const now = Date.now();
94
+ const { every = 'month', count = 1 } = price.recurring ?? {};
95
+ const trialEnd = checkout.trialDays === null
96
+ ? null
97
+ : new Date(now + checkout.trialDays * day);
98
+ const [product = '', name = ''] = checkout.lookupKey.split('.');
99
+ subscriptions.set(id, {
100
+ id,
101
+ customerId: checkout.customerId,
102
+ product,
103
+ price: name,
104
+ status: trialEnd === null ? 'active' : 'trialing',
105
+ quantity: checkout.quantity,
106
+ amount: (price.amount ?? 0) * checkout.quantity,
107
+ every,
108
+ everyCount: count,
109
+ currentPeriodEnd: trialEnd ?? new Date(now + (days[every] ?? 30) * count * day),
110
+ cancelAt: null,
111
+ canceledAt: null,
112
+ trialEnd,
113
+ startedAt: new Date(now),
114
+ scheduled: null,
115
+ card: newId('pm'),
116
+ });
117
+ send('customer.subscription.created', id, 'subscription');
118
+ const created = found(subscriptions, id);
119
+ if (trialEnd === null)
120
+ bill(created, created.currentPeriodEnd);
121
+ return id;
122
+ };
123
+ const charge = (checkout, price, free) => {
124
+ // A free Checkout stands for its payment, which Stripe does not make.
125
+ const id = free ? checkout.id : newId('pi');
126
+ payments.set(id, {
127
+ id,
128
+ customerId: checkout.customerId,
129
+ product: checkout.product,
130
+ quantity: checkout.quantity,
131
+ amount: free ? 0 : (price.amount ?? 0) * checkout.quantity,
132
+ refunded: 0,
133
+ disputeLost: false,
134
+ paidAt: new Date(),
135
+ receiptUrl: free ? null : `https://pay.stripe.test/receipts/${id}`,
136
+ });
137
+ if (!free)
138
+ send('payment_intent.succeeded', id, 'payment_intent');
139
+ return id;
140
+ };
141
+ const gateway = {
142
+ createCustomer: async (profile, idempotencyKey) => {
143
+ const held = keys.get(idempotencyKey);
144
+ if (held !== undefined)
145
+ return held;
146
+ const id = newId('cus');
147
+ customers.set(id, { id, profile, deleted: false, card: null });
148
+ keys.set(idempotencyKey, id);
149
+ return id;
150
+ },
151
+ updateCustomer: async (id, profile) => {
152
+ customers.set(id, { ...live(id), profile });
153
+ },
154
+ deleteCustomer: async (id) => {
155
+ fake.deleteCustomer(id);
156
+ },
157
+ readCustomer: async (id, options) => {
158
+ const customer = customers.get(id);
159
+ if (customer === undefined || customer.deleted) {
160
+ return { deleted: true, subscriptions: [], payments: [], invoices: [] };
161
+ }
162
+ const own = (map) => [...map.values()].filter((one) => one.customerId === id);
163
+ return {
164
+ deleted: false,
165
+ subscriptions: own(subscriptions),
166
+ // Stripe lists a free Checkout only when asked to.
167
+ payments: own(payments).filter((one) => options?.free === true || !one.id.startsWith('cs_')),
168
+ invoices: options?.invoices === true ? own(invoices) : [],
169
+ };
170
+ },
171
+ customerOf: async (type, id) => ownerOf(type, id),
172
+ openCheckout: async (checkout) => {
173
+ live(checkout.customerId);
174
+ priceOf(checkout.lookupKey);
175
+ const id = newId('cs');
176
+ const url = `https://checkout.stripe.test/${id}`;
177
+ checkouts.set(id, { ...checkout, id, url, status: 'open' });
178
+ return url;
179
+ },
180
+ expireCheckouts: async (customerId) => {
181
+ live(customerId);
182
+ for (const checkout of checkouts.values()) {
183
+ if (checkout.customerId === customerId && checkout.status === 'open') {
184
+ checkouts.set(checkout.id, { ...checkout, status: 'expired' });
185
+ }
186
+ }
187
+ },
188
+ checkoutCustomer: async (id) => checkouts.get(id)?.customerId ?? null,
189
+ openPortal: async (portal) => {
190
+ live(portal.customerId);
191
+ portalSessions.push(portal);
192
+ return `https://billing.stripe.test/${newId('bps')}`;
193
+ },
194
+ moveCard: async ({ id, customerId, card }) => {
195
+ customers.set(customerId, { ...live(customerId), card });
196
+ fake.update(id, { card: null });
197
+ },
198
+ cancelAndRefund: async (id) => {
199
+ const held = found(subscriptions, id);
200
+ if (held.status !== 'canceled') {
201
+ const ended = { status: 'canceled', canceledAt: new Date() };
202
+ subscriptions.set(id, { ...held, ...ended });
203
+ send('customer.subscription.deleted', id, 'subscription');
204
+ }
205
+ subscriptionRefunds.add(id);
206
+ },
207
+ changedSince: async (since) => {
208
+ const changed = new Map();
209
+ for (const { id, type, at } of listed) {
210
+ const customer = ownerOf(type, id);
211
+ if (customer !== null && at > since)
212
+ changed.set(customer, at);
213
+ }
214
+ return changed;
215
+ },
216
+ };
217
+ const fake = {
218
+ webhookSecret: `whsec_fake_${crypto.randomUUID()}`,
219
+ customers,
220
+ checkouts,
221
+ subscriptions,
222
+ payments,
223
+ invoices,
224
+ portalSessions,
225
+ subscriptionRefunds,
226
+ pay: (url, options) => {
227
+ const checkout = [...checkouts.values()].find((one) => one.url === url);
228
+ if (checkout?.status !== 'open')
229
+ throw new Error(`${url} is not open.`);
230
+ const price = priceOf(checkout.lookupKey);
231
+ checkouts.set(checkout.id, { ...checkout, status: 'complete' });
232
+ const id = checkout.mode === 'subscription'
233
+ ? subscribe(checkout, price)
234
+ : charge(checkout, price, options?.free ?? false);
235
+ send('checkout.session.completed', checkout.id, 'checkout.session');
236
+ return id;
237
+ },
238
+ update: (id, changes) => {
239
+ subscriptions.set(id, { ...found(subscriptions, id), ...changes });
240
+ send('customer.subscription.updated', id, 'subscription');
241
+ },
242
+ renew: (id) => {
243
+ const held = found(subscriptions, id);
244
+ const start = Math.max(held.currentPeriodEnd.getTime(), Date.now());
245
+ const end = new Date(start + periodOf(held));
246
+ const renewed = { ...held, status: 'active', currentPeriodEnd: end };
247
+ subscriptions.set(id, renewed);
248
+ send('customer.subscription.updated', id, 'subscription');
249
+ return bill(renewed, end);
250
+ },
251
+ refund: (id, amount) => {
252
+ const map = invoices.has(id)
253
+ ? invoices
254
+ : payments;
255
+ const paid = found(map, id);
256
+ const refunded = paid.refunded + (amount ?? paid.amount);
257
+ map.set(id, { ...paid, refunded });
258
+ send('charge.refunded', id, invoices.has(id) ? 'invoice' : 'payment_intent');
259
+ },
260
+ loseDispute: (id) => {
261
+ const map = invoices.has(id)
262
+ ? invoices
263
+ : payments;
264
+ map.set(id, { ...found(map, id), disputeLost: true });
265
+ send('charge.dispute.closed', id, invoices.has(id) ? 'invoice' : 'payment_intent');
266
+ },
267
+ deleteCustomer: (id) => {
268
+ const customer = customers.get(id);
269
+ if (customer === undefined || customer.deleted)
270
+ return;
271
+ customers.set(id, { ...customer, deleted: true });
272
+ for (const one of subscriptions.values()) {
273
+ if (one.customerId === id && one.status !== 'canceled') {
274
+ subscriptions.set(one.id, { ...one, status: 'canceled' });
275
+ }
276
+ }
277
+ send('customer.deleted', id, 'customer');
278
+ },
279
+ deliver: async (url, path) => {
280
+ for (const payload of sent.splice(0)) {
281
+ const secret = fake.webhookSecret;
282
+ const response = await postEvent(url, payload, { secret, path });
283
+ if (!response.ok) {
284
+ throw new Error(`The webhook answered ${String(response.status)}.`);
285
+ }
286
+ }
287
+ },
288
+ };
289
+ return { gateway, fake };
290
+ }
@@ -0,0 +1,108 @@
1
+ import { Stripe } from 'stripe';
2
+ import type { Every } from './product.ts';
3
+ /** How often a price bills: Stripe's `interval` and `interval_count`. */
4
+ export interface Recurring<E extends string = string> {
5
+ readonly every: E;
6
+ readonly count: number;
7
+ }
8
+ /** A product the catalog manages, as Stripe holds it. */
9
+ export interface StripeProduct {
10
+ readonly id: string;
11
+ /** Its `metadata.key`. */
12
+ readonly key: string | null;
13
+ readonly name: string;
14
+ readonly active: boolean;
15
+ readonly taxCode: string | null;
16
+ }
17
+ /** A price, as Stripe holds it. */
18
+ export interface StripePrice {
19
+ readonly id: string;
20
+ readonly productId: string;
21
+ readonly lookupKey: string | null;
22
+ readonly amount: number | null;
23
+ readonly currency: string;
24
+ /** `null` for a one-time price. */
25
+ readonly recurring: Recurring | null;
26
+ readonly taxBehavior: string | null;
27
+ readonly nickname: string | null;
28
+ readonly active: boolean;
29
+ readonly metadata: Readonly<Record<string, string>>;
30
+ }
31
+ /** A product the portal lets a subscription move to, with its prices. */
32
+ export interface PortalProduct {
33
+ readonly productId: string;
34
+ readonly priceIds: readonly string[];
35
+ }
36
+ /** The customer portal's configuration, as the catalog writes it. */
37
+ export interface PortalSettings {
38
+ readonly returnUrl: string | null;
39
+ readonly termsUrl: string | null;
40
+ readonly privacyUrl: string | null;
41
+ /** `always_invoice` or `create_prorations`. */
42
+ readonly prorationBehavior: string;
43
+ /** Whether a downgrade waits for the period's end. */
44
+ readonly scheduleAtPeriodEnd: readonly string[];
45
+ /** `end_trial` or `continue_trial`. */
46
+ readonly trialUpdate: string;
47
+ /** `at_period_end` or `immediately`. */
48
+ readonly cancelMode: string;
49
+ /** `null` when Stripe did not list them. */
50
+ readonly products: readonly PortalProduct[] | null;
51
+ readonly active: boolean;
52
+ }
53
+ /** What Stripe holds of the catalog. */
54
+ export interface CatalogState {
55
+ /** The managed products, archived ones included. */
56
+ readonly products: readonly StripeProduct[];
57
+ /** Every price, archived ones included. */
58
+ readonly prices: readonly StripePrice[];
59
+ /** The managed portal configuration, if one was saved. */
60
+ readonly portal: {
61
+ readonly id: string;
62
+ readonly settings: PortalSettings;
63
+ } | null;
64
+ }
65
+ /** A product as the catalog writes it. */
66
+ export interface ProductWrite {
67
+ readonly key: string;
68
+ readonly name: string;
69
+ readonly taxCode: string | null;
70
+ }
71
+ /** A price as the catalog writes it: Stripe never changes its billing. */
72
+ export interface PriceWrite {
73
+ readonly productId: string;
74
+ readonly lookupKey: string;
75
+ readonly amount: number;
76
+ readonly currency: string;
77
+ /** `null` for a one-time price. */
78
+ readonly recurring: Recurring<Every> | null;
79
+ readonly taxBehavior: 'inclusive' | 'exclusive';
80
+ readonly nickname: string;
81
+ readonly metadata: Readonly<Record<string, string>>;
82
+ }
83
+ /** What the plugin asks Stripe. */
84
+ export interface StripeGateway {
85
+ /** The managed products, every price, and the managed portal. */
86
+ readonly readCatalog: () => Promise<CatalogState>;
87
+ /** Creates a managed product; returns its id. */
88
+ readonly createProduct: (product: ProductWrite) => Promise<string>;
89
+ /** Renames a product, sets its tax code, and makes it active. */
90
+ readonly updateProduct: (id: string, product: ProductWrite) => Promise<void>;
91
+ readonly archiveProduct: (id: string) => Promise<void>;
92
+ /** Creates a price, which takes its lookup key over; returns its id. */
93
+ readonly createPrice: (price: PriceWrite) => Promise<string>;
94
+ /** Sets a price's nickname and metadata. */
95
+ readonly updatePrice: (id: string, price: Pick<PriceWrite, 'nickname' | 'metadata'>) => Promise<void>;
96
+ readonly archivePrice: (id: string) => Promise<void>;
97
+ /** Creates the portal configuration, or updates `id`; returns its id. */
98
+ readonly savePortal: (id: string | null, settings: PortalSettings) => Promise<string>;
99
+ }
100
+ /** `metadata.managedBy` of what the catalog writes: nothing else is touched. */
101
+ export declare const managedBy = "ultimabase";
102
+ /** The Stripe client of a secret key. */
103
+ export declare const stripeClient: (secret: string) => Stripe;
104
+ /** The configuration's parameters, from `settings`. */
105
+ export declare const portalParams: (settings: PortalSettings) => Stripe.BillingPortal.ConfigurationCreateParams;
106
+ /** The gateway over Stripe's API. */
107
+ export declare const sdkGateway: (client: Stripe) => StripeGateway;
108
+ //# sourceMappingURL=gateway.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gateway.d.ts","sourceRoot":"","sources":["../src/gateway.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAC/B,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,cAAc,CAAA;AAGzC,yEAAyE;AACzE,MAAM,WAAW,SAAS,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM;IACnD,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAA;IACjB,QAAQ,CAAC,KAAK,E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AChF,eAAO,MAAM,SAAS,eAAe,CAAA;AAKrC,yCAAyC;AACzC,eAAO,MAAM,YAAY,WAAY,MAAM,KAAG,MAM3C,CAAA;AA+CH,uDAAuD;AACvD,eAAO,MAAM,YAAY,aACd,cAAc,KACtB,MAAM,CAAC,aAAa,CAAC,yBAsCvB,CAAA;AAED,qCAAqC;AACrC,eAAO,MAAM,UAAU,WAAY,MAAM,KAAG,aA6G1C,CAAA"}
@@ -0,0 +1,196 @@
1
+ // Stripe, behind the narrow gateway the plugin calls. `sdkGateway` reaches
2
+ // Stripe through its SDK; `@ultimabase/stripe/testing` holds a fake in
3
+ // memory, and no test of `yarn validate` reaches Stripe.
4
+ import { Stripe } from 'stripe';
5
+ import { all } from './sdk-common.js';
6
+ /** `metadata.managedBy` of what the catalog writes: nothing else is touched. */
7
+ export const managedBy = 'ultimabase';
8
+ /** The API version the plugin reads Stripe's objects with: the SDK's. */
9
+ const apiVersion = '2026-10-28.endive';
10
+ /** The Stripe client of a secret key. */
11
+ export const stripeClient = (secret) => new Stripe(secret, {
12
+ apiVersion,
13
+ maxNetworkRetries: 2,
14
+ // A request past 10 s fails, and its caller retries.
15
+ timeout: 10_000,
16
+ });
17
+ const idOf = (value) => typeof value === 'string' ? value : value.id;
18
+ const priceOf = (price) => ({
19
+ id: price.id,
20
+ productId: idOf(price.product),
21
+ lookupKey: price.lookup_key,
22
+ amount: price.unit_amount,
23
+ currency: price.currency,
24
+ recurring: price.recurring === null
25
+ ? null
26
+ : {
27
+ every: price.recurring.interval,
28
+ count: price.recurring.interval_count,
29
+ },
30
+ taxBehavior: price.tax_behavior,
31
+ nickname: price.nickname,
32
+ active: price.active,
33
+ metadata: price.metadata,
34
+ });
35
+ const portalOf = (portal) => {
36
+ const update = portal.features.subscription_update;
37
+ return {
38
+ returnUrl: portal.default_return_url,
39
+ termsUrl: portal.business_profile.terms_of_service_url,
40
+ privacyUrl: portal.business_profile.privacy_policy_url,
41
+ prorationBehavior: update.proration_behavior,
42
+ scheduleAtPeriodEnd: update.schedule_at_period_end.conditions.map(({ type }) => type),
43
+ trialUpdate: update.trial_update_behavior,
44
+ cancelMode: portal.features.subscription_cancel.mode,
45
+ products: update.products?.map(({ product, prices }) => ({
46
+ productId: product,
47
+ priceIds: prices,
48
+ })) ?? null,
49
+ active: portal.active,
50
+ };
51
+ };
52
+ /** The configuration's parameters, from `settings`. */
53
+ export const portalParams = (settings) => {
54
+ const products = settings.products ?? [];
55
+ return {
56
+ business_profile: {
57
+ ...(settings.termsUrl !== null && {
58
+ terms_of_service_url: settings.termsUrl,
59
+ }),
60
+ ...(settings.privacyUrl !== null && {
61
+ privacy_policy_url: settings.privacyUrl,
62
+ }),
63
+ },
64
+ ...(settings.returnUrl !== null && {
65
+ default_return_url: settings.returnUrl,
66
+ }),
67
+ features: {
68
+ subscription_update: {
69
+ // The portal refuses an update with no product to move to.
70
+ enabled: products.length > 0,
71
+ default_allowed_updates: ['price'],
72
+ products: products.map(({ productId, priceIds }) => ({
73
+ product: productId,
74
+ prices: [...priceIds],
75
+ })),
76
+ proration_behavior: settings.prorationBehavior,
77
+ trial_update_behavior: settings.trialUpdate,
78
+ schedule_at_period_end: {
79
+ conditions: settings.scheduleAtPeriodEnd.map((type) => ({ type })),
80
+ },
81
+ },
82
+ subscription_cancel: {
83
+ enabled: true,
84
+ mode: settings.cancelMode,
85
+ },
86
+ payment_method_update: { enabled: true },
87
+ invoice_history: { enabled: true },
88
+ },
89
+ metadata: { managedBy },
90
+ };
91
+ };
92
+ /** The gateway over Stripe's API. */
93
+ export const sdkGateway = (client) => ({
94
+ readCatalog: async () => {
95
+ // Three lists, whatever the catalog's size.
96
+ const [products, prices, portals] = await Promise.all([
97
+ all(client.products.list({ limit: 100 })),
98
+ all(client.prices.list({ limit: 100 })),
99
+ all(client.billingPortal.configurations.list({
100
+ limit: 100,
101
+ expand: ['data.features.subscription_update.products'],
102
+ })),
103
+ ]);
104
+ const portal = portals.find(({ metadata }) => metadata?.['managedBy'] === managedBy);
105
+ return {
106
+ products: products
107
+ .filter(({ metadata }) => metadata['managedBy'] === managedBy)
108
+ .map((product) => ({
109
+ id: product.id,
110
+ key: product.metadata['key'] ?? null,
111
+ name: product.name,
112
+ active: product.active,
113
+ taxCode: product.tax_code === null || product.tax_code === undefined
114
+ ? null
115
+ : idOf(product.tax_code),
116
+ })),
117
+ prices: prices.map(priceOf),
118
+ portal: portal === undefined
119
+ ? null
120
+ : { id: portal.id, settings: portalOf(portal) },
121
+ };
122
+ },
123
+ createProduct: async ({ key, name, taxCode }) => {
124
+ const created = await client.products.create({
125
+ name,
126
+ ...(taxCode !== null && { tax_code: taxCode }),
127
+ metadata: { managedBy, key },
128
+ });
129
+ return created.id;
130
+ },
131
+ updateProduct: async (id, { key, name, taxCode }) => {
132
+ await client.products.update(id, {
133
+ name,
134
+ active: true,
135
+ // An empty string unsets it.
136
+ tax_code: taxCode ?? '',
137
+ metadata: { managedBy, key },
138
+ });
139
+ },
140
+ archiveProduct: async (id) => {
141
+ await client.products.update(id, { active: false });
142
+ },
143
+ createPrice: async (price) => {
144
+ const created = await client.prices.create({
145
+ product: price.productId,
146
+ currency: price.currency,
147
+ unit_amount: price.amount,
148
+ ...(price.recurring !== null && {
149
+ recurring: {
150
+ interval: price.recurring.every,
151
+ interval_count: price.recurring.count,
152
+ },
153
+ }),
154
+ tax_behavior: price.taxBehavior,
155
+ lookup_key: price.lookupKey,
156
+ transfer_lookup_key: true,
157
+ nickname: price.nickname,
158
+ metadata: { ...price.metadata },
159
+ });
160
+ return created.id;
161
+ },
162
+ updatePrice: async (id, { nickname, metadata }) => {
163
+ await client.prices.update(id, { nickname, metadata: { ...metadata } });
164
+ },
165
+ archivePrice: async (id) => {
166
+ await client.prices.update(id, { active: false });
167
+ },
168
+ savePortal: async (id, settings) => {
169
+ const params = portalParams(settings);
170
+ if (id === null) {
171
+ return (await client.billingPortal.configurations.create(params)).id;
172
+ }
173
+ // Stripe drops an empty list or an absent key, keeping the old value:
174
+ // an update clears a setting with an empty string.
175
+ const { subscription_update: update } = params.features;
176
+ const conditions = update?.schedule_at_period_end?.conditions ?? [];
177
+ await client.billingPortal.configurations.update(id, {
178
+ ...params,
179
+ business_profile: {
180
+ terms_of_service_url: settings.termsUrl ?? '',
181
+ privacy_policy_url: settings.privacyUrl ?? '',
182
+ },
183
+ features: {
184
+ ...params.features,
185
+ subscription_update: {
186
+ ...update,
187
+ schedule_at_period_end: {
188
+ conditions: conditions.length > 0 ? conditions : '',
189
+ },
190
+ },
191
+ },
192
+ active: true,
193
+ });
194
+ return id;
195
+ },
196
+ });
@@ -0,0 +1,15 @@
1
+ export type { StripeCatalogOptions } from './apply.ts';
2
+ export { applyStripeCatalog } from './apply.ts';
3
+ export type { BalanceFields, CreditHistoryFields, PurchaseFields, SubscriptionFields, WithStripe, } from './billing.ts';
4
+ export { defineBalance, defineCreditHistory, definePurchase, defineSubscription, } from './billing.ts';
5
+ export type { CustomerProfile } from './billing-gateway.ts';
6
+ export type { CheckoutArgs, PortalArgs } from './calls.ts';
7
+ export { stripe } from './calls.ts';
8
+ export type { Credit, CreditAmount } from './credit.ts';
9
+ export { defineCredit } from './credit.ts';
10
+ export type { Stripe, StripeOptions } from './plugin.ts';
11
+ export { stripePlugin } from './plugin.ts';
12
+ export type { PortalOptions } from './portal.ts';
13
+ export type { Every, OneTimePrice, OneTimeProduct, Product, RecurringPrice, SubscriptionProduct, } from './product.ts';
14
+ export { defineProduct } from './product.ts';
15
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,YAAY,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAA;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAC/C,YAAY,EACX,aAAa,EACb,mBAAmB,EACnB,cAAc,EACd,kBAAkB,EAClB,UAAU,GACV,MAAM,cAAc,CAAA;AACrB,OAAO,EACN,aAAa,EACb,mBAAmB,EACnB,cAAc,EACd,kBAAkB,GAClB,MAAM,cAAc,CAAA;AACrB,YAAY,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAA;AAC3D,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAA;AACnC,YAAY,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC1C,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC1C,YAAY,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAChD,YAAY,EACX,KAAK,EACL,YAAY,EACZ,cAAc,EACd,OAAO,EACP,cAAc,EACd,mBAAmB,GACnB,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { applyStripeCatalog } from './apply.js';
2
+ export { defineBalance, defineCreditHistory, definePurchase, defineSubscription, } from './billing.js';
3
+ export { stripe } from './calls.js';
4
+ export { defineCredit } from './credit.js';
5
+ export { stripePlugin } from './plugin.js';
6
+ export { defineProduct } from './product.js';
@@ -0,0 +1,6 @@
1
+ import type { StandardSchema } from '@ultimabase/jobs';
2
+ /** A job's input: an object of the strings `keys` names. */
3
+ export declare function strings<const K extends string>(...keys: K[]): StandardSchema<{
4
+ readonly [P in K]: string;
5
+ }>;
6
+ //# sourceMappingURL=job-input.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"job-input.d.ts","sourceRoot":"","sources":["../src/job-input.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAA;AAEtD,4DAA4D;AAC5D,wBAAgB,OAAO,CAAC,KAAK,CAAC,CAAC,SAAS,MAAM,EAC7C,GAAG,IAAI,EAAE,CAAC,EAAE,GACV,cAAc,CAAC;IAAE,QAAQ,EAAE,CAAC,IAAI,CAAC,GAAG,MAAM;CAAE,CAAC,CAiB/C"}
@@ -0,0 +1,20 @@
1
+ /** A job's input: an object of the strings `keys` names. */
2
+ export function strings(...keys) {
3
+ const message = `An object of strings: ${keys.join(', ')}.`;
4
+ return {
5
+ '~standard': {
6
+ version: 1,
7
+ vendor: 'ultimabase-stripe',
8
+ validate: (value) => {
9
+ const read = {};
10
+ for (const key of keys) {
11
+ const field = Reflect.get(Object(value), key);
12
+ if (typeof field !== 'string')
13
+ return { issues: [{ message }] };
14
+ read[key] = field;
15
+ }
16
+ return { value: read };
17
+ },
18
+ },
19
+ };
20
+ }