@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
package/dist/sync.js ADDED
@@ -0,0 +1,196 @@
1
+ // A payer's sync (D-371 point 4, D-375): what Stripe holds now is written
2
+ // to the application's subscription and purchase rows, so events out of
3
+ // order or lost leave nothing stale. Stripe is read outside any transaction;
4
+ // the write takes the customer's lock.
5
+ import { transaction } from 'ultimabase';
6
+ import { liveStatuses } from './billing-gateway.js';
7
+ import { lost, settleCredits, totals } from './credits.js';
8
+ import { duplicateJob, duplicatesOf } from './duplicates.js';
9
+ import { M, StripeCustomer } from './models.js';
10
+ import { runningOf, stripeOf } from './running.js';
11
+ /** The model when its payer is the customer's, else nothing to write. */
12
+ const ownModel = (model, row) => model?.payer.name === row.model ? model : undefined;
13
+ const connect = (id) => ({ connect: { id } });
14
+ /** Whether the row holds each value already. */
15
+ const holds = (row, values) => Object.entries(values).every(([field, value]) => {
16
+ const held = row[field];
17
+ return value instanceof Date && held instanceof Date
18
+ ? value.getTime() === held.getTime()
19
+ : held === value;
20
+ });
21
+ /**
22
+ * Creates the row of `stripeId`, or updates it when one of its values
23
+ * changed: a sync that finds it unchanged writes nothing, so the model's
24
+ * hooks run on a change only. The customer's lock is held.
25
+ */
26
+ async function save(model, stripeId, create, values) {
27
+ const row = await model.queries.findUnique({ where: { stripeId } }, M);
28
+ if (row === null) {
29
+ const data = { ...create, ...values, stripeId };
30
+ await model.queries.create({ data }, M);
31
+ }
32
+ else if (!holds(row, values)) {
33
+ await model.queries.update({ where: { id: row.id }, data: values }, M);
34
+ }
35
+ }
36
+ async function writeSubscription(model, row, one) {
37
+ if (one.product === null || one.price === null)
38
+ return;
39
+ const values = {
40
+ product: one.product,
41
+ price: one.price,
42
+ status: one.status,
43
+ quantity: one.quantity,
44
+ amount: one.amount,
45
+ every: one.every,
46
+ everyCount: one.everyCount,
47
+ currentPeriodEnd: one.currentPeriodEnd,
48
+ cancelAt: one.cancelAt,
49
+ canceledAt: one.canceledAt,
50
+ trialEnd: one.trialEnd,
51
+ startedAt: one.startedAt,
52
+ scheduledProduct: one.scheduled?.product ?? null,
53
+ scheduledPrice: one.scheduled?.price ?? null,
54
+ scheduledAt: one.scheduled?.at ?? null,
55
+ };
56
+ await save(model, one.id, { payer: connect(row.payer) }, values);
57
+ }
58
+ async function writePayment(running, row, payment) {
59
+ const product = payment.product === null ? undefined : running.products.get(payment.product);
60
+ if (product === undefined)
61
+ return;
62
+ const purchase = ownModel(running.purchase, row);
63
+ if (purchase !== undefined) {
64
+ const refunded = payment.disputeLost ? payment.amount : payment.refunded;
65
+ const values = {
66
+ amount: payment.amount,
67
+ refunded,
68
+ // A free purchase, after a full discount, is paid, not refunded.
69
+ status: lost(payment) ? 'refunded' : 'paid',
70
+ receiptUrl: payment.receiptUrl,
71
+ };
72
+ const create = {
73
+ product: product.key,
74
+ quantity: payment.quantity,
75
+ paidAt: payment.paidAt,
76
+ payer: connect(row.payer),
77
+ };
78
+ await save(purchase, payment.id, create, values);
79
+ }
80
+ if (!('prices' in product) && ownModel(running.balance, row) !== undefined) {
81
+ const sums = totals(product.gives, payment.quantity);
82
+ await settleCredits(row.payer, payment, sums, 'purchase');
83
+ }
84
+ }
85
+ /**
86
+ * Gives what the invoice's periods give, for the periods not ended yet: a
87
+ * `gives` added later pays nothing for the past (D-377 point 4).
88
+ */
89
+ async function writeInvoice(running, row, invoice, readAt) {
90
+ const sums = new Map();
91
+ for (const { product: key, price, quantity, end } of invoice.periods) {
92
+ const product = key === null ? undefined : running.products.get(key);
93
+ if (end <= readAt || price === null || !product || !('prices' in product)) {
94
+ continue;
95
+ }
96
+ totals(product.prices[price]?.gives ?? [], quantity, sums);
97
+ }
98
+ if (sums.size === 0 && !lost(invoice))
99
+ return;
100
+ await settleCredits(row.payer, invoice, sums, 'subscription');
101
+ }
102
+ /** Whether a recurring price gives credits: then the sync reads invoices. */
103
+ const readsInvoices = ({ products, balance }) => balance !== undefined &&
104
+ [...products.values()].some((product) => 'prices' in product &&
105
+ Object.values(product.prices).some(({ gives }) => gives !== undefined));
106
+ /** The next time one of the live subscriptions changes by itself. */
107
+ function renewsAt(state) {
108
+ const times = state.subscriptions
109
+ .filter(({ status }) => liveStatuses.includes(status))
110
+ .flatMap((one) => [
111
+ one.currentPeriodEnd,
112
+ one.cancelAt,
113
+ one.trialEnd,
114
+ one.scheduled?.at ?? null,
115
+ ])
116
+ .filter((time) => time !== null)
117
+ .map((time) => time.getTime());
118
+ return times.length === 0 ? null : new Date(Math.min(...times));
119
+ }
120
+ /** Ends the live rows of a customer Stripe deleted, and forgets it. */
121
+ async function forget(running, row) {
122
+ const subscription = ownModel(running.subscription, row);
123
+ if (subscription !== undefined) {
124
+ const where = {
125
+ payer: { is: { id: row.payer } },
126
+ status: { in: liveStatuses },
127
+ };
128
+ const data = { status: 'canceled', canceledAt: new Date() };
129
+ await subscription.queries.updateManyAndReturn({ where, data }, M);
130
+ }
131
+ await StripeCustomer.delete({ where: { id: row.id } }, M);
132
+ }
133
+ /** Writes what was read of the customer, under its lock. */
134
+ async function write(running, row, state, readAt) {
135
+ if (state.deleted) {
136
+ await forget(running, row);
137
+ return;
138
+ }
139
+ const subscription = ownModel(running.subscription, row);
140
+ if (subscription !== undefined) {
141
+ for (const one of state.subscriptions) {
142
+ await writeSubscription(subscription, row, one);
143
+ }
144
+ }
145
+ for (const payment of state.payments) {
146
+ await writePayment(running, row, payment);
147
+ }
148
+ if (ownModel(running.balance, row) !== undefined) {
149
+ for (const invoice of state.invoices) {
150
+ await writeInvoice(running, row, invoice, readAt);
151
+ }
152
+ }
153
+ // Enqueued with the write: a sync that writes nothing read older.
154
+ if (running.oneSubscription) {
155
+ for (const { id } of duplicatesOf(state.subscriptions)) {
156
+ await duplicateJob.enqueue({ subscription: id });
157
+ }
158
+ }
159
+ }
160
+ /**
161
+ * Writes what Stripe holds of the customer of row `id`. The sync takes the
162
+ * next number of the customer's syncs, reads Stripe, then writes only when
163
+ * no sync begun after it wrote first. A change at Stripe sends an event
164
+ * whose sync begins after it, so no sync begun before overwrites it.
165
+ */
166
+ export async function syncCustomer(id) {
167
+ const running = runningOf('stripe.sync');
168
+ const { gateway } = stripeOf('stripe.sync');
169
+ const [begun] = await StripeCustomer.updateManyAndReturn({ where: { id }, data: { syncsBegun: { increment: 1 } } }, M);
170
+ const stripeId = begun?.stripeId ?? null;
171
+ if (begun === undefined || stripeId === null)
172
+ return;
173
+ const readAt = new Date();
174
+ const invoices = readsInvoices(running);
175
+ // Only a catalog that sells once has Checkouts a discount made free.
176
+ const free = [...running.products.values()].some((one) => !('prices' in one));
177
+ const state = await gateway.readCustomer(stripeId, { invoices, free });
178
+ await transaction(async () => {
179
+ const number = begun.syncsBegun;
180
+ const data = {
181
+ syncWritten: number,
182
+ syncedAt: readAt,
183
+ renewsAt: renewsAt(state),
184
+ };
185
+ // The customer's lock, taken by the write.
186
+ const [row] = await StripeCustomer.updateManyAndReturn({ where: { id, stripeId, syncWritten: { lt: number } }, data }, M);
187
+ if (row !== undefined)
188
+ await write(running, row, state, readAt);
189
+ });
190
+ // Outside the lock, as any call to Stripe (D-380).
191
+ for (const one of state.subscriptions) {
192
+ if (one.card !== null && liveStatuses.includes(one.status)) {
193
+ await gateway.moveCard({ ...one, card: one.card });
194
+ }
195
+ }
196
+ }
@@ -0,0 +1,24 @@
1
+ import type { FakeBilling } from './fake-billing.ts';
2
+ import type { PortalSettings, StripePrice, StripeProduct } from './gateway.ts';
3
+ export type { CheckoutWrite, CustomerProfile, PortalFlow, PortalWrite, StripePayment, StripeSubscription, } from './billing-gateway.ts';
4
+ export type { FakeBilling, FakeCheckout, FakeCustomer } from './fake-billing.ts';
5
+ export { postEvent, thinEvent } from './fake-billing.ts';
6
+ export type { PortalSettings, StripePrice, StripeProduct } from './gateway.ts';
7
+ /**
8
+ * A Stripe account in memory: what the catalog wrote to it, its payers, and
9
+ * what a test does at Stripe. Hand `secret` and `webhookSecret` to
10
+ * `stripePlugin`'s keys.
11
+ */
12
+ export interface FakeStripe extends FakeBilling {
13
+ /** Its secret key: hand it to the code under test. */
14
+ readonly secret: string;
15
+ /** The products the catalog manages, by id. */
16
+ readonly products: Map<string, StripeProduct>;
17
+ /** The prices, by id. */
18
+ readonly prices: Map<string, StripePrice>;
19
+ /** The customer portal configurations, by id. */
20
+ readonly portals: Map<string, PortalSettings>;
21
+ }
22
+ /** A new Stripe account in memory; `secret` reaches it. */
23
+ export declare const fakeStripe: () => FakeStripe;
24
+ //# sourceMappingURL=testing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAEpD,OAAO,KAAK,EACX,cAAc,EAEd,WAAW,EACX,aAAa,EACb,MAAM,cAAc,CAAA;AAErB,YAAY,EACX,aAAa,EACb,eAAe,EACf,UAAU,EACV,WAAW,EACX,aAAa,EACb,kBAAkB,GAClB,MAAM,sBAAsB,CAAA;AAC7B,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAChF,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAA;AACxD,YAAY,EAAE,cAAc,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AAE9E;;;;GAIG;AACH,MAAM,WAAW,UAAW,SAAQ,WAAW;IAC9C,sDAAsD;IACtD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,+CAA+C;IAC/C,QAAQ,CAAC,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAA;IAC7C,yBAAyB;IACzB,QAAQ,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;IACzC,iDAAiD;IACjD,QAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAAA;CAC7C;AASD,2DAA2D;AAC3D,eAAO,MAAM,UAAU,QAAO,UAqF7B,CAAA"}
@@ -0,0 +1,100 @@
1
+ // @ultimabase/stripe/testing (D-371 point 8): a Stripe account in memory.
2
+ // Its secret key reaches it wherever a real key reaches Stripe, so a test
3
+ // runs the application's own calls, and no test reaches Stripe.
4
+ import { addFake } from './accounts.js';
5
+ import { fakeBilling } from './fake-billing.js';
6
+ export { postEvent, thinEvent } from './fake-billing.js';
7
+ /** The record of `map` at `id`, or Stripe's answer to an unknown id. */
8
+ const found = (map, id) => {
9
+ const record = map.get(id);
10
+ if (record === undefined)
11
+ throw new Error(`No such object: '${id}'.`);
12
+ return record;
13
+ };
14
+ /** A new Stripe account in memory; `secret` reaches it. */
15
+ export const fakeStripe = () => {
16
+ const products = new Map();
17
+ const prices = new Map();
18
+ const portals = new Map();
19
+ let created = 0;
20
+ const newId = (prefix) => {
21
+ created += 1;
22
+ return `${prefix}_${String(created)}`;
23
+ };
24
+ const billing = fakeBilling(prices, newId);
25
+ const fake = {
26
+ ...billing.fake,
27
+ secret: `sk_test_fake_${crypto.randomUUID()}`,
28
+ products,
29
+ prices,
30
+ portals,
31
+ };
32
+ const gateway = {
33
+ readCatalog: async () => {
34
+ const [portal] = portals;
35
+ return {
36
+ products: [...products.values()],
37
+ prices: [...prices.values()],
38
+ portal: portal === undefined ? null : { id: portal[0], settings: portal[1] },
39
+ };
40
+ },
41
+ createProduct: async ({ key, name, taxCode }) => {
42
+ const id = newId('prod');
43
+ products.set(id, { id, key, name, active: true, taxCode });
44
+ return id;
45
+ },
46
+ updateProduct: async (id, { key, name, taxCode }) => {
47
+ products.set(id, {
48
+ ...found(products, id),
49
+ key,
50
+ name,
51
+ taxCode,
52
+ active: true,
53
+ });
54
+ },
55
+ archiveProduct: async (id) => {
56
+ products.set(id, { ...found(products, id), active: false });
57
+ },
58
+ createPrice: async (price) => {
59
+ found(products, price.productId);
60
+ // `transfer_lookup_key`: the key leaves the price that held it.
61
+ for (const held of prices.values()) {
62
+ if (held.lookupKey === price.lookupKey) {
63
+ prices.set(held.id, { ...held, lookupKey: null });
64
+ }
65
+ }
66
+ const id = newId('price');
67
+ prices.set(id, {
68
+ id,
69
+ productId: price.productId,
70
+ lookupKey: price.lookupKey,
71
+ amount: price.amount,
72
+ currency: price.currency,
73
+ recurring: price.recurring,
74
+ taxBehavior: price.taxBehavior,
75
+ nickname: price.nickname,
76
+ active: true,
77
+ metadata: { ...price.metadata },
78
+ });
79
+ return id;
80
+ },
81
+ updatePrice: async (id, { nickname, metadata }) => {
82
+ const held = found(prices, id);
83
+ // Stripe merges the metadata it is sent.
84
+ const merged = { ...held.metadata, ...metadata };
85
+ prices.set(id, { ...held, nickname, metadata: merged });
86
+ },
87
+ archivePrice: async (id) => {
88
+ prices.set(id, { ...found(prices, id), active: false });
89
+ },
90
+ savePortal: async (id, settings) => {
91
+ if (id !== null)
92
+ found(portals, id);
93
+ const saved = id ?? newId('bpc');
94
+ portals.set(saved, settings);
95
+ return saved;
96
+ },
97
+ };
98
+ addFake(fake.secret, { ...gateway, ...billing.gateway });
99
+ return fake;
100
+ };
@@ -0,0 +1,4 @@
1
+ import type { Routes } from '@ultimabase/http';
2
+ /** The webhook's route, at `path`. */
3
+ export declare const webhookRoutes: (path: string) => Routes;
4
+ //# sourceMappingURL=webhook.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webhook.d.ts","sourceRoot":"","sources":["../src/webhook.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AAoE9C,sCAAsC;AACtC,eAAO,MAAM,aAAa,SAAU,MAAM,KAAG,MA2B1C,CAAA"}
@@ -0,0 +1,73 @@
1
+ import { routes } from '@ultimabase/http';
2
+ import { PublicError, transaction } from 'ultimabase';
3
+ import { eventJob } from './jobs.js';
4
+ import { M, StripeEvent } from './models.js';
5
+ import { runningOf } from './running.js';
6
+ const text = (from, key) => {
7
+ const value = typeof from === 'object' && from !== null
8
+ ? Reflect.get(from, key)
9
+ : undefined;
10
+ return typeof value === 'string' ? value : '';
11
+ };
12
+ /** The verified event, or `undefined` for a wrong or stale signature. */
13
+ function verified(client, payload, signature, secret) {
14
+ let event;
15
+ try {
16
+ event = client.parseEventNotification(payload, signature, secret);
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
21
+ const related = Reflect.get(Object(event), 'related_object');
22
+ return {
23
+ id: text(event, 'id'),
24
+ // `v1.customer.subscription.updated`: the v1 type it stands for.
25
+ type: text(event, 'type').replace(/^v1\./u, ''),
26
+ livemode: Reflect.get(Object(event), 'livemode') === true,
27
+ objectType: text(related, 'type'),
28
+ objectId: text(related, 'id'),
29
+ };
30
+ }
31
+ /** Stores the event and enqueues its job; one received twice is stored once. */
32
+ async function store(event) {
33
+ try {
34
+ await transaction(async () => {
35
+ const { livemode: _, id: stripeId, ...data } = event;
36
+ const { id } = await StripeEvent.create({ data: { ...data, stripeId } }, M);
37
+ await eventJob.enqueue({ event: id });
38
+ });
39
+ }
40
+ catch (error) {
41
+ if (error instanceof PublicError && error.code === 'UNIQUE_VIOLATION') {
42
+ return;
43
+ }
44
+ throw error;
45
+ }
46
+ }
47
+ /** The webhook's route, at `path`. */
48
+ export const webhookRoutes = (path) => routes().post(path, async (c) => {
49
+ const { stripe, logger } = runningOf('The Stripe webhook');
50
+ if (stripe === undefined) {
51
+ const message = 'Payments are unavailable.';
52
+ return c.json({ code: 'PAYMENT_UNAVAILABLE', message }, 503);
53
+ }
54
+ const signature = c.req.header('stripe-signature');
55
+ // The raw body: the signature covers its exact bytes.
56
+ const payload = await c.req.text();
57
+ const event = signature === undefined
58
+ ? undefined
59
+ : verified(stripe.client, payload, signature, stripe.webhook);
60
+ if (event === undefined) {
61
+ const message = 'The Stripe signature does not match.';
62
+ return c.json({ code: 'UNAUTHENTICATED', message }, 401);
63
+ }
64
+ // Another mode's event: acknowledged, so that Stripe stops sending
65
+ // it, and dropped.
66
+ if (event.livemode !== stripe.live) {
67
+ const details = { event: event.id, livemode: event.livemode };
68
+ logger.warn(details, 'A Stripe event of the other mode was dropped.');
69
+ return c.json({ received: false });
70
+ }
71
+ await store(event);
72
+ return c.json({ received: true });
73
+ });
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@ultimabase/stripe",
3
+ "version": "0.0.0-first.0",
4
+ "description": "Stripe for UltimaBase: a catalog declared in code, sold on Stripe's Checkout, with subscriptions, purchases and credits kept in the application's models.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "homepage": "https://ultimabase.dev/docs/stripe",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/MrEkinox/ultimabase.git",
11
+ "directory": "packages/stripe"
12
+ },
13
+ "engines": {
14
+ "node": ">=24.7.0"
15
+ },
16
+ "exports": {
17
+ ".": "./dist/index.js",
18
+ "./testing": "./dist/testing.js"
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "src",
23
+ "!src/**/*.test.ts",
24
+ "!src/test"
25
+ ],
26
+ "scripts": {
27
+ "prepack": "rm -rf dist && yarn run -T tsc --project tsconfig.build.json"
28
+ },
29
+ "publishConfig": {
30
+ "exports": {
31
+ ".": "./dist/index.js",
32
+ "./testing": "./dist/testing.js"
33
+ }
34
+ },
35
+ "peerDependencies": {
36
+ "@ultimabase/http": "^0.7.0",
37
+ "@ultimabase/jobs": "^0.7.0",
38
+ "ultimabase": "^0.7.0"
39
+ },
40
+ "devDependencies": {
41
+ "@ultimabase/http": "0.7.0",
42
+ "@ultimabase/jobs": "0.7.0",
43
+ "@ultimabase/testing": "0.7.0",
44
+ "ultimabase": "0.7.0",
45
+ "vite": "8.3.4",
46
+ "vitest": "5.0.5"
47
+ },
48
+ "dependencies": {
49
+ "stripe": "23.1.0"
50
+ }
51
+ }
@@ -0,0 +1,30 @@
1
+ // The Stripe account of a secret key. `fakeStripe()` of
2
+ // `@ultimabase/stripe/testing` registers its own key here, so a test hands
3
+ // that key to the code under test as it would hand a real one: no option
4
+ // of the public API exists for tests alone, and each fake is its own account.
5
+ import type { BillingGateway, RecoveryGateway } from './billing-gateway.ts'
6
+ import { sdkBilling } from './sdk-billing.ts'
7
+ import { sdkRecovery } from './sdk-recovery.ts'
8
+ import { type StripeGateway, sdkGateway, stripeClient } from './gateway.ts'
9
+
10
+ /** Everything the plugin asks a Stripe account. */
11
+ export type Gateway = StripeGateway & BillingGateway & RecoveryGateway
12
+
13
+ const fakes = new Map<string, Gateway>()
14
+
15
+ /** Makes `secret` reach `gateway` instead of Stripe. */
16
+ export const addFake = (secret: string, gateway: Gateway): void => {
17
+ fakes.set(secret, gateway)
18
+ }
19
+
20
+ /** The gateway of `secret`: a fake's, or Stripe's API. */
21
+ export const gatewayOf = (secret: string): Gateway => {
22
+ const fake = fakes.get(secret)
23
+ if (fake !== undefined) return fake
24
+ const client = stripeClient(secret)
25
+ return {
26
+ ...sdkGateway(client),
27
+ ...sdkBilling(client),
28
+ ...sdkRecovery(client),
29
+ }
30
+ }
package/src/apply.ts ADDED
@@ -0,0 +1,99 @@
1
+ // `applyStripeCatalog` (D-372 point 4): an application's deploy script
2
+ // brings its Stripe account to the catalog, with no running application.
3
+ // It prints the plan, a line a change, and applies it unless `dryRun`.
4
+ import { Refused } from 'ultimabase'
5
+ import { gatewayOf } from './accounts.ts'
6
+ import { type Catalog, applyCatalog, planCatalog } from './catalog.ts'
7
+ import { describeStep } from './describe.ts'
8
+ import { ownKeys } from './keys.ts'
9
+ import { type PortalOptions, checkPortal } from './portal.ts'
10
+ import type { Product } from './product.ts'
11
+
12
+ /** What `applyStripeCatalog` brings a Stripe account to. */
13
+ export interface StripeCatalogOptions {
14
+ /** The account's secret key; `undefined` is refused, as an unset variable. */
15
+ readonly secret: string | undefined
16
+ /** Every price's currency, in lowercase: `eur`. */
17
+ readonly currency: string
18
+ /** `'inclusive'`, by default, when the amounts include the taxes. */
19
+ readonly taxBehavior?: 'inclusive' | 'exclusive'
20
+ readonly products: readonly Product[]
21
+ readonly portal: PortalOptions
22
+ /** Prints the plan and changes nothing. */
23
+ readonly dryRun?: boolean
24
+ }
25
+
26
+ const entry = 'applyStripeCatalog'
27
+ const optionKeys = [
28
+ 'secret',
29
+ 'currency',
30
+ 'taxBehavior',
31
+ 'products',
32
+ 'portal',
33
+ 'dryRun',
34
+ ]
35
+
36
+ const print = (line: string): void => {
37
+ process.stdout.write(`${line}\n`)
38
+ }
39
+
40
+ type CatalogOptions = Pick<
41
+ StripeCatalogOptions,
42
+ 'currency' | 'taxBehavior' | 'products' | 'portal'
43
+ >
44
+
45
+ /**
46
+ * The catalog of `options`, shared with `stripePlugin`; refuses what Stripe
47
+ * would refuse, and a product named twice (D-372 point 5).
48
+ */
49
+ export function catalogOf(caller: string, options: CatalogOptions): Catalog {
50
+ const { currency, taxBehavior = 'inclusive', products, portal } = options
51
+ if (typeof currency !== 'string' || !/^[a-z]{3}$/u.test(currency)) {
52
+ throw new Refused(`${caller}: currency is a lowercase ISO code, as eur.`)
53
+ }
54
+ if (!['inclusive', 'exclusive'].includes(taxBehavior)) {
55
+ throw new Refused(`${caller}: taxBehavior is 'inclusive' or 'exclusive'.`)
56
+ }
57
+ // `Array.isArray` would type the products `any[]`.
58
+ const listed: unknown = products
59
+ if (!Array.isArray(listed)) {
60
+ throw new Refused(`${caller}: products lists what defineProduct returns.`)
61
+ }
62
+ const keys = new Set<string>()
63
+ for (const { key } of products) {
64
+ if (keys.has(key)) {
65
+ throw new Refused(`${caller}: two products have the key ${key}.`)
66
+ }
67
+ keys.add(key)
68
+ }
69
+ checkPortal(portal)
70
+ return { currency, taxBehavior, products, portal }
71
+ }
72
+
73
+ /** Brings the Stripe account of `secret` to the catalog, unless `dryRun`. */
74
+ export async function applyStripeCatalog(
75
+ options: StripeCatalogOptions,
76
+ ): Promise<void> {
77
+ ownKeys(entry, options, optionKeys)
78
+ const { secret, dryRun = false } = options
79
+ if (typeof secret !== 'string' || secret === '') {
80
+ throw new Refused(`${entry}: secret is the account's secret key, sk_….`)
81
+ }
82
+ const catalog = catalogOf(entry, options)
83
+ const { currency } = catalog
84
+ const gateway = gatewayOf(secret)
85
+ const state = await gateway.readCatalog()
86
+ const steps = planCatalog(catalog, state)
87
+ const mode = secret.includes('_live_') ? 'live' : 'test'
88
+ if (steps.length === 0) {
89
+ print(`Stripe catalog (${mode} mode): up to date.`)
90
+ return
91
+ }
92
+ print(
93
+ `Stripe catalog (${mode} mode): ${String(steps.length)} change${steps.length === 1 ? '' : 's'}${dryRun ? ', dry run' : ''}:`,
94
+ )
95
+ for (const step of steps) print(` ${describeStep(step, currency)}`)
96
+ if (dryRun) return
97
+ await applyCatalog(catalog, gateway, state, steps)
98
+ print('Stripe catalog: applied.')
99
+ }