@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/plugin.js ADDED
@@ -0,0 +1,229 @@
1
+ import { httpPlugin } from '@ultimabase/http';
2
+ import { jobsPlugin } from '@ultimabase/jobs';
3
+ import { definePlugin, isMaster, PublicError, Refused } from 'ultimabase';
4
+ import manifest from '../package.json' with { type: 'json' };
5
+ import { gatewayOf } from './accounts.js';
6
+ import { catalogOf } from './apply.js';
7
+ import { applyCatalog, planCatalog } from './catalog.js';
8
+ import { describeStep } from './describe.js';
9
+ import { stripeClient } from './gateway.js';
10
+ import { closeJob, stripeJobs } from './jobs.js';
11
+ import { ownKeys } from './keys.js';
12
+ import { billingModels } from './kinds.js';
13
+ import { M, StripeCustomer, StripeEvent, StripeScan } from './models.js';
14
+ import { rowsOf, runningOf, useRunning } from './running.js';
15
+ import { webhookRoutes } from './webhook.js';
16
+ const entry = 'stripePlugin';
17
+ const optionKeys = [
18
+ 'keys',
19
+ 'currency',
20
+ 'taxBehavior',
21
+ 'products',
22
+ 'portal',
23
+ 'customer',
24
+ 'webhookPath',
25
+ 'oneSubscription',
26
+ ];
27
+ const names = {
28
+ subscription: 'defineSubscription',
29
+ purchase: 'definePurchase',
30
+ balance: 'defineBalance',
31
+ history: 'defineCreditHistory',
32
+ };
33
+ /** The keys, refused when one of them is unset. */
34
+ function keysOf(keys) {
35
+ if (keys === undefined)
36
+ return undefined;
37
+ ownKeys(`${entry}'s keys`, keys, ['secret', 'webhook']);
38
+ const secret = Reflect.get(keys, 'secret');
39
+ const webhook = Reflect.get(keys, 'webhook');
40
+ if (typeof secret !== 'string' || !secret.startsWith('sk_')) {
41
+ throw new Refused(`${entry}: keys.secret is the secret key, sk_….`);
42
+ }
43
+ if (typeof webhook !== 'string' || !webhook.startsWith('whsec_')) {
44
+ throw new Refused(`${entry}: keys.webhook is the signing secret, whsec_….`);
45
+ }
46
+ return { secret, webhook };
47
+ }
48
+ /** The one model of `kind` among the application's, with its payer's. */
49
+ function billingOf(models, kind) {
50
+ const own = models.flatMap((model) => {
51
+ const declared = billingModels.get(model.queries);
52
+ return declared?.kind === kind ? [{ model, declared }] : [];
53
+ });
54
+ const [first, second] = own;
55
+ if (second !== undefined) {
56
+ throw new Refused(`models lists two models ${names[kind]} returned: an application has one.`);
57
+ }
58
+ if (first === undefined)
59
+ return undefined;
60
+ const target = first.declared.payer();
61
+ const payer = models.find(({ queries }) => queries === target);
62
+ const name = first.model.schema.name;
63
+ // The kernel refuses a relation to a model the application lacks.
64
+ if (payer === undefined)
65
+ throw new TypeError(`${name}'s payer is unknown.`);
66
+ return {
67
+ name,
68
+ queries: rowsOf(first.model.queries),
69
+ payer: { name: payer.schema.name, queries: rowsOf(payer.queries) },
70
+ };
71
+ }
72
+ /** Whether a product gives credits, by its price or with each of its prices. */
73
+ const givesCredits = (product) => 'prices' in product
74
+ ? Object.values(product.prices).some(({ gives = [] }) => gives.length > 0)
75
+ : product.gives.length > 0;
76
+ /**
77
+ * Refuses a product no model records, and credits without their history
78
+ * (D-372 point 5, D-374 point 1, D-377 point 2).
79
+ */
80
+ function checkModels(products, models) {
81
+ const { subscription, purchase, balance, history } = models;
82
+ for (const other of [purchase, history]) {
83
+ if (other && balance && other.payer.name !== balance.payer.name) {
84
+ throw new Refused(`${balance.name}'s owner and ${other.name}'s ${other === purchase ? 'payer' : 'owner'} are one model.`);
85
+ }
86
+ }
87
+ if (balance && !history) {
88
+ throw new Refused(`${balance.name} needs its history: declare it with defineCreditHistory.`);
89
+ }
90
+ for (const product of products) {
91
+ if ('prices' in product && subscription === undefined) {
92
+ throw new Refused(`${product.key} is a subscription: declare its model with defineSubscription.`);
93
+ }
94
+ if (givesCredits(product) && !balance) {
95
+ throw new Refused(`${product.key} gives credits: declare their model with defineBalance.`);
96
+ }
97
+ }
98
+ }
99
+ /**
100
+ * Compares the catalog with Stripe: applied with `NODE_ENV=development` and
101
+ * a test key, otherwise each difference is logged (D-372 point 4).
102
+ */
103
+ async function compare(running, logger) {
104
+ const { stripe, catalog } = running;
105
+ if (stripe === undefined)
106
+ return;
107
+ const { gateway, live } = stripe;
108
+ try {
109
+ const state = await gateway.readCatalog();
110
+ const steps = planCatalog(catalog, state);
111
+ if (steps.length === 0)
112
+ return;
113
+ const changes = steps.map((step) => describeStep(step, catalog.currency));
114
+ if (process.env['NODE_ENV'] !== 'development' || live) {
115
+ logger.warn({ changes }, 'The Stripe catalog differs from the code: apply it with applyStripeCatalog.');
116
+ return;
117
+ }
118
+ for (const change of changes)
119
+ logger.info(`Stripe catalog: ${change}`);
120
+ await applyCatalog(catalog, gateway, state, steps);
121
+ }
122
+ catch (error) {
123
+ logger.warn({ err: error }, 'The Stripe catalog could not be compared.');
124
+ }
125
+ }
126
+ /** Refuses a write to a billing model, and logs it (D-373 point 4). */
127
+ function refuse(caller, name, operation) {
128
+ const details = { model: name, operation };
129
+ const callerId = caller.kind === 'user' ? caller.user.id : null;
130
+ const message = `${name} ${operation} refused.`;
131
+ runningOf(entry).logger.warn({ ...details, callerId }, message);
132
+ throw new PublicError('ACCESS_DENIED', message, { details });
133
+ }
134
+ /** Only Master, so the plugin, creates or updates a billing model. */
135
+ const masterOnly = (operation) => ({ caller, name }) => {
136
+ if (!isMaster(caller))
137
+ refuse(caller, name, operation);
138
+ };
139
+ /**
140
+ * A billing row goes with its payer, whoever deletes the payer (D-373 point
141
+ * 3), and alone only by Master; then its customer is closed. The hook runs
142
+ * in the delete's transaction after its one write: a payer still stored
143
+ * means the row went alone, and the refusal rolls the delete back.
144
+ */
145
+ async function deleted(facts) {
146
+ const { caller, name, record } = facts;
147
+ const running = runningOf(entry);
148
+ const { subscription, purchase, balance, history } = running;
149
+ const billing = [subscription, purchase, balance, history];
150
+ const model = billing.find((one) => one?.name === name);
151
+ // The row holds its payer as `{ id }`.
152
+ const ref = Reflect.get(record, 'payer') ?? Reflect.get(record, 'owner');
153
+ const payer = Reflect.get(Object(ref), 'id');
154
+ if (model === undefined || typeof payer !== 'string')
155
+ return;
156
+ if (!isMaster(caller)) {
157
+ const where = { id: payer };
158
+ const kept = await model.payer.queries.findUnique({ where }, M);
159
+ if (kept !== null)
160
+ refuse(caller, name, 'delete');
161
+ }
162
+ if (running.stripe === undefined)
163
+ return;
164
+ await closeJob.enqueue({ model: model.payer.name, payer });
165
+ }
166
+ const definition = definePlugin({
167
+ name: 'stripe',
168
+ manifest,
169
+ requires: { http: httpPlugin, jobs: jobsPlugin },
170
+ models: [StripeCustomer, StripeEvent, StripeScan],
171
+ api: ({ plugins, options }) => {
172
+ const { webhookPath = '/webhooks/stripe' } = options;
173
+ if (typeof webhookPath !== 'string' || !webhookPath.startsWith('/')) {
174
+ throw new Refused(`${entry}: webhookPath is a path, as /webhooks/stripe.`);
175
+ }
176
+ plugins.http.mount(webhookRoutes(webhookPath));
177
+ plugins.jobs.add(stripeJobs);
178
+ },
179
+ hooks: {
180
+ beforeCreate: masterOnly('create'),
181
+ beforeUpdate: masterOnly('update'),
182
+ afterDelete: deleted,
183
+ },
184
+ start: async ({ options, models, logger }) => {
185
+ ownKeys(entry, options, optionKeys);
186
+ const keys = keysOf(options.keys);
187
+ const catalog = catalogOf(entry, options);
188
+ const { customer, oneSubscription = false } = options;
189
+ if (customer !== undefined && typeof customer !== 'function') {
190
+ throw new Refused(`${entry}: customer is (payer) => its profile.`);
191
+ }
192
+ if (typeof oneSubscription !== 'boolean') {
193
+ throw new Refused(`${entry}: oneSubscription is true or false.`);
194
+ }
195
+ const billing = {
196
+ subscription: billingOf(models, 'subscription'),
197
+ purchase: billingOf(models, 'purchase'),
198
+ balance: billingOf(models, 'balance'),
199
+ history: billingOf(models, 'history'),
200
+ };
201
+ checkModels(catalog.products, billing);
202
+ const running = {
203
+ stripe: keys === undefined
204
+ ? undefined
205
+ : {
206
+ gateway: gatewayOf(keys.secret),
207
+ client: stripeClient(keys.secret),
208
+ webhook: keys.webhook,
209
+ live: keys.secret.includes('_live_'),
210
+ },
211
+ catalog,
212
+ products: new Map(catalog.products.map((one) => [one.key, one])),
213
+ customer,
214
+ oneSubscription,
215
+ ...billing,
216
+ logger,
217
+ portal: undefined,
218
+ };
219
+ useRunning(running);
220
+ await compare(running, logger);
221
+ },
222
+ stop: () => {
223
+ useRunning(undefined);
224
+ },
225
+ });
226
+ /** Payments on Stripe's hosted pages; it requires `httpPlugin` and `jobsPlugin`. */
227
+ export const stripePlugin = definition.plugin;
228
+ /** The plugin's entry in a billing model's `use`, which `define*` adds. */
229
+ export const stripeUse = definition.use;
@@ -0,0 +1,23 @@
1
+ import type { PortalProduct, PortalSettings } from './gateway.ts';
2
+ /** How the customer portal lets a payer change plan and cancel. */
3
+ export interface PortalOptions {
4
+ /** Where the portal's return link leads. */
5
+ readonly returnUrl: string;
6
+ readonly termsUrl?: string;
7
+ readonly privacyUrl?: string;
8
+ /** `'invoiceNow'` charges a dearer plan's difference at once. */
9
+ readonly upgrades?: 'invoiceNow' | 'nextInvoice';
10
+ /** `'atPeriodEnd'` starts a cheaper or shorter plan at the period's end. */
11
+ readonly downgrades?: 'atPeriodEnd' | 'now';
12
+ /** `'endTrial'` ends a trial on a change, and charges the new plan. */
13
+ readonly trialChange?: 'endTrial' | 'keepTrial';
14
+ /** `'atPeriodEnd'` ends a canceled subscription at its period's end. */
15
+ readonly cancel?: 'atPeriodEnd' | 'now';
16
+ }
17
+ /** Refuses portal options Stripe would refuse, naming the option. */
18
+ export declare function checkPortal(portal: unknown): asserts portal is PortalOptions;
19
+ /** The portal's settings, letting a subscription move to `products`. */
20
+ export declare const portalSettings: (portal: PortalOptions, products: readonly PortalProduct[] | null) => PortalSettings;
21
+ /** Whether two settings are the same, whatever the order of their lists. */
22
+ export declare const samePortal: (one: PortalSettings, other: PortalSettings) => boolean;
23
+ //# sourceMappingURL=portal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"portal.d.ts","sourceRoot":"","sources":["../src/portal.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAGjE,mEAAmE;AACnE,MAAM,WAAW,aAAa;IAC7B,4CAA4C;IAC5C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;IAC5B,iEAAiE;IACjE,QAAQ,CAAC,QAAQ,CAAC,EAAE,YAAY,GAAG,aAAa,CAAA;IAChD,4EAA4E;IAC5E,QAAQ,CAAC,UAAU,CAAC,EAAE,aAAa,GAAG,KAAK,CAAA;IAC3C,uEAAuE;IACvE,QAAQ,CAAC,WAAW,CAAC,EAAE,UAAU,GAAG,WAAW,CAAA;IAC/C,wEAAwE;IACxE,QAAQ,CAAC,MAAM,CAAC,EAAE,aAAa,GAAG,KAAK,CAAA;CACvC;AAWD,qEAAqE;AACrE,wBAAgB,WAAW,CAAC,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,MAAM,IAAI,aAAa,CAoB5E;AAED,wEAAwE;AACxE,eAAO,MAAM,cAAc,WAClB,aAAa,YACX,SAAS,aAAa,EAAE,GAAG,IAAI,KACvC,cAaD,CAAA;AAkBF,4EAA4E;AAC5E,eAAO,MAAM,UAAU,QACjB,cAAc,SACZ,cAAc,KACnB,OAAwC,CAAA"}
package/dist/portal.js ADDED
@@ -0,0 +1,66 @@
1
+ // The customer portal's options (D-373 point 8), in Stripe's words: how a
2
+ // change of plan bills, which changes wait for the period's end, what a
3
+ // change during a trial does, and how a cancellation ends.
4
+ import { Refused } from 'ultimabase';
5
+ import { ownKeys } from './keys.js';
6
+ /** Each option's values, in Stripe's words; the first is the default. */
7
+ const choices = {
8
+ upgrades: { invoiceNow: 'always_invoice', nextInvoice: 'create_prorations' },
9
+ downgrades: { atPeriodEnd: true, now: false },
10
+ trialChange: { endTrial: 'end_trial', keepTrial: 'continue_trial' },
11
+ cancel: { atPeriodEnd: 'at_period_end', now: 'immediately' },
12
+ };
13
+ const urls = ['returnUrl', 'termsUrl', 'privacyUrl'];
14
+ /** Refuses portal options Stripe would refuse, naming the option. */
15
+ export function checkPortal(portal) {
16
+ ownKeys('portal', portal, [...urls, ...Object.keys(choices)]);
17
+ for (const name of urls) {
18
+ const url = Reflect.get(portal, name);
19
+ if (url === undefined && name !== 'returnUrl')
20
+ continue;
21
+ if (typeof url !== 'string' || !URL.canParse(url)) {
22
+ throw new Refused(`portal: ${name} is an absolute URL.`);
23
+ }
24
+ }
25
+ for (const [name, values] of Object.entries(choices)) {
26
+ const value = Reflect.get(portal, name);
27
+ if (value === undefined)
28
+ continue;
29
+ if (typeof value !== 'string' || !Object.hasOwn(values, value)) {
30
+ throw new Refused(`portal: ${name} is ${Object.keys(values)
31
+ .map((one) => `'${one}'`)
32
+ .join(' or ')}.`);
33
+ }
34
+ }
35
+ }
36
+ /** The portal's settings, letting a subscription move to `products`. */
37
+ export const portalSettings = (portal, products) => ({
38
+ returnUrl: portal.returnUrl,
39
+ termsUrl: portal.termsUrl ?? null,
40
+ privacyUrl: portal.privacyUrl ?? null,
41
+ prorationBehavior: choices.upgrades[portal.upgrades ?? 'invoiceNow'],
42
+ // A cheaper plan, or a shorter interval, waits for the period's end.
43
+ scheduleAtPeriodEnd: choices.downgrades[portal.downgrades ?? 'atPeriodEnd']
44
+ ? ['decreasing_item_amount', 'shortening_interval']
45
+ : [],
46
+ trialUpdate: choices.trialChange[portal.trialChange ?? 'endTrial'],
47
+ cancelMode: choices.cancel[portal.cancel ?? 'atPeriodEnd'],
48
+ products,
49
+ active: true,
50
+ });
51
+ /** The settings in a string, whatever the order of their lists. */
52
+ const sorted = (settings) => JSON.stringify([
53
+ settings.returnUrl,
54
+ settings.termsUrl,
55
+ settings.privacyUrl,
56
+ settings.prorationBehavior,
57
+ settings.scheduleAtPeriodEnd.toSorted(),
58
+ settings.trialUpdate,
59
+ settings.cancelMode,
60
+ settings.active,
61
+ settings.products
62
+ ?.map(({ productId, priceIds }) => [productId, priceIds.toSorted()])
63
+ .toSorted(([a], [b]) => String(a).localeCompare(String(b))),
64
+ ]);
65
+ /** Whether two settings are the same, whatever the order of their lists. */
66
+ export const samePortal = (one, other) => sorted(one) === sorted(other);
@@ -0,0 +1,57 @@
1
+ import type { CreditAmount } from './credit.ts';
2
+ /** How often a recurring price bills. */
3
+ export type Every = 'day' | 'week' | 'month' | 'year';
4
+ /** A subscription's price, billed every `everyCount` (1 by default) `every`. */
5
+ export interface RecurringPrice {
6
+ /** In the currency's smallest unit: `9_90` is 9.90 €. */
7
+ readonly amount: number;
8
+ readonly every: Every;
9
+ readonly everyCount?: number;
10
+ /** The credits each paid period gives (D-377 point 4). */
11
+ readonly gives?: readonly CreditAmount[];
12
+ }
13
+ /** A one-time product's price. */
14
+ export interface OneTimePrice {
15
+ /** In the currency's smallest unit. */
16
+ readonly amount: number;
17
+ }
18
+ /** A subscription, with its recurring prices by name. */
19
+ export interface SubscriptionProduct<K extends string = string, P extends string = string> {
20
+ /** The product's name in the application, never changed. */
21
+ readonly key: K;
22
+ /** What Checkout and the invoices show. */
23
+ readonly name: string;
24
+ /** Its Stripe Tax code, `txcd_…`. */
25
+ readonly taxCode?: string;
26
+ readonly prices: {
27
+ readonly [N in P]: RecurringPrice;
28
+ };
29
+ }
30
+ /** A product paid once, and the credits it gives. */
31
+ export interface OneTimeProduct<K extends string = string> {
32
+ readonly key: K;
33
+ readonly name: string;
34
+ readonly taxCode?: string;
35
+ readonly price: OneTimePrice;
36
+ readonly gives: readonly CreditAmount[];
37
+ }
38
+ /** A product of the catalog. */
39
+ export type Product = SubscriptionProduct | OneTimeProduct;
40
+ /** A subscription and its recurring prices (D-372). */
41
+ export declare function defineProduct<const K extends string, const P extends string>(definition: {
42
+ readonly key: K;
43
+ readonly name: string;
44
+ readonly taxCode?: string;
45
+ readonly prices: {
46
+ readonly [N in P]: RecurringPrice;
47
+ };
48
+ }): SubscriptionProduct<K, P>;
49
+ /** A product paid once, and the credits it gives (D-372). */
50
+ export declare function defineProduct<const K extends string>(definition: {
51
+ readonly key: K;
52
+ readonly name: string;
53
+ readonly taxCode?: string;
54
+ readonly price: OneTimePrice;
55
+ readonly gives?: readonly CreditAmount[];
56
+ }): OneTimeProduct<K>;
57
+ //# sourceMappingURL=product.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"product.d.ts","sourceRoot":"","sources":["../src/product.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAG/C,yCAAyC;AACzC,MAAM,MAAM,KAAK,GAAG,KAAK,GAAG,MA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AAK,CAAC,CAAC,SAAS,MAAM,EACtB,KAAK,CAAC,CAAC,SAAS,MAAM,EACrB,UAAU,EAAE;IACb,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAA;IACf,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,MAAM,EAAE;QAAE,QAAQ,EAAE,CAAC,IAAI,CAAC,GAAG,cAAc;KAAE,CAAA;CACtD,GAAG,mBAAmB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;AAC7B,6DAA6D;AAC7D,wBAAgB,aAAa,CAAC,KAAK,CAAC,CAAC,SAAS,MAAM,EAAE,UAAU,EAAE;IACjE,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAA;IACf,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAA;IAC5B,QAAQ,CAAC,KAAK,CAAC,EAAE,SAAS,YAAY,EAAE,CAAA;CACxC,GAAG,cAAc,CAAC,CAAC,CAAC,CAAA"}
@@ -0,0 +1,113 @@
1
+ // `defineProduct` (D-372): what an application sells, either a subscription
2
+ // with its recurring prices or a one-time product with the credits it gives.
3
+ // The catalog writes it to Stripe; the product's key never changes.
4
+ import { Refused } from 'ultimabase';
5
+ import { checkKey, ownKeys, whereOf } from './keys.js';
6
+ /** Stripe bills at most every three years. */
7
+ const longest = {
8
+ day: 1095,
9
+ week: 156,
10
+ month: 36,
11
+ year: 3,
12
+ };
13
+ const productKeys = ['key', 'name', 'taxCode', 'prices', 'price', 'gives'];
14
+ /** Refuses an amount that is not a positive integer. */
15
+ function checkAmount(where, amount) {
16
+ if (!Number.isSafeInteger(amount) || Number(amount) <= 0) {
17
+ throw new Refused(`${where}: the amount ${String(amount)} is not a positive integer, in the currency's smallest unit.`);
18
+ }
19
+ }
20
+ /** Refuses a recurring price Stripe would refuse; returns its interval. */
21
+ function checkRecurring(where, price) {
22
+ ownKeys(where, price, ['amount', 'every', 'everyCount', 'gives']);
23
+ checkAmount(where, Reflect.get(price, 'amount'));
24
+ checkGives(where, Reflect.get(price, 'gives') ?? []);
25
+ const every = Reflect.get(price, 'every');
26
+ const most = Object.entries(longest).find(([name]) => name === every)?.[1];
27
+ if (most === undefined) {
28
+ throw new Refused(`${where}: every is 'day', 'week', 'month' or 'year'.`);
29
+ }
30
+ const count = Reflect.get(price, 'everyCount') ?? 1;
31
+ if (!Number.isSafeInteger(count) ||
32
+ Number(count) < 1 ||
33
+ Number(count) > most) {
34
+ throw new Refused(`${where}: everyCount is an integer from 1 to ${String(most)}.`);
35
+ }
36
+ return `${String(count)} ${String(every)}`;
37
+ }
38
+ /** Refuses a subscription's prices: none, a bad one, or two of one interval. */
39
+ function checkPrices(where, prices) {
40
+ if (typeof prices !== 'object' || prices === null) {
41
+ throw new Refused(`${where}: prices holds the recurring prices by name.`);
42
+ }
43
+ const names = Object.keys(prices);
44
+ if (names.length === 0) {
45
+ throw new Refused(`${where}: prices holds at least one price.`);
46
+ }
47
+ // The customer portal takes one price per interval of a product.
48
+ const intervals = new Map();
49
+ for (const name of names) {
50
+ checkKey(where, name);
51
+ const price = Reflect.get(prices, name);
52
+ const interval = checkRecurring(`${where}.${name}`, price);
53
+ const other = intervals.get(interval);
54
+ if (other !== undefined) {
55
+ throw new Refused(`${where}: ${other} and ${name} both bill every ${interval}; a product has one price per interval.`);
56
+ }
57
+ intervals.set(interval, name);
58
+ }
59
+ }
60
+ /** Refuses what a one-time product gives: one credit twice, or a bad one. */
61
+ function checkGives(where, gives) {
62
+ if (!Array.isArray(gives)) {
63
+ throw new Refused(`${where}: gives lists credits, as [blueGems(500)].`);
64
+ }
65
+ const given = new Set();
66
+ for (const item of gives) {
67
+ const credit = typeof item === 'object' && item !== null
68
+ ? Reflect.get(item, 'credit')
69
+ : undefined;
70
+ if (typeof credit !== 'string') {
71
+ throw new Refused(`${where}: gives lists credits, as [blueGems(500)].`);
72
+ }
73
+ checkAmount(`${where} gives ${credit}`, Reflect.get(Object(item), 'amount'));
74
+ if (given.has(credit)) {
75
+ throw new Refused(`${where}: gives ${credit} twice.`);
76
+ }
77
+ given.add(credit);
78
+ }
79
+ }
80
+ export function defineProduct(definition) {
81
+ ownKeys('defineProduct', definition, productKeys);
82
+ checkKey('defineProduct', definition.key);
83
+ const where = whereOf('defineProduct', definition);
84
+ const { key, name, taxCode, prices, price } = definition;
85
+ if (typeof name !== 'string' || name.trim() === '') {
86
+ throw new Refused(`${where}: name is what Checkout and the invoices show.`);
87
+ }
88
+ if (taxCode !== undefined && typeof taxCode !== 'string') {
89
+ throw new Refused(`${where}: taxCode is a Stripe Tax code, as txcd_10000000.`);
90
+ }
91
+ const tax = taxCode === undefined ? {} : { taxCode };
92
+ if ((prices === undefined) === (price === undefined)) {
93
+ throw new Refused(`${where}: a product has either prices, recurring, or one price, paid once.`);
94
+ }
95
+ if (price === undefined) {
96
+ if (definition.gives !== undefined) {
97
+ throw new Refused(`${where}: gives goes with a one-time price.`);
98
+ }
99
+ checkPrices(where, prices);
100
+ return Object.freeze({ key, name, ...tax, prices: { ...prices } });
101
+ }
102
+ ownKeys(where, price, ['amount']);
103
+ checkAmount(where, price.amount);
104
+ const gives = definition.gives ?? [];
105
+ checkGives(where, gives);
106
+ return Object.freeze({
107
+ key,
108
+ name,
109
+ ...tax,
110
+ price: { amount: price.amount },
111
+ gives: [...gives],
112
+ });
113
+ }
@@ -0,0 +1,61 @@
1
+ import type { Stripe } from 'stripe';
2
+ import type { Logger, QueryOptions } from 'ultimabase';
3
+ import type { Gateway } from './accounts.ts';
4
+ import type { CustomerProfile } from './billing-gateway.ts';
5
+ import type { Catalog } from './catalog.ts';
6
+ import type { Product } from './product.ts';
7
+ /** A row as the plugin reads it, from a model it does not type. */
8
+ export type Row = {
9
+ readonly id: string;
10
+ readonly [field: string]: unknown;
11
+ };
12
+ /** The queries the plugin sends to the application's models. */
13
+ export interface Rows {
14
+ findUnique(args: object, options: QueryOptions): Promise<Row | null>;
15
+ findMany(args: object, options: QueryOptions): Promise<readonly Row[]>;
16
+ create(args: object, options: QueryOptions): Promise<Row>;
17
+ update(args: object, options: QueryOptions): Promise<Row>;
18
+ upsert(args: object, options: QueryOptions): Promise<Row>;
19
+ updateManyAndReturn(args: object, options: QueryOptions): Promise<readonly Row[]>;
20
+ groupBy(args: object, options: QueryOptions): Promise<readonly Readonly<Record<string, unknown>>[]>;
21
+ }
22
+ /** A model's queries, as the plugin sends them. */
23
+ export declare function rowsOf(queries: object): Rows;
24
+ /** A model the plugin writes, with its payer's model. */
25
+ export interface Billing {
26
+ readonly name: string;
27
+ readonly queries: Rows;
28
+ /** The payer's or owner's model: its name and queries. */
29
+ readonly payer: {
30
+ readonly name: string;
31
+ readonly queries: Rows;
32
+ };
33
+ }
34
+ /** What the plugin holds while the application runs. */
35
+ export interface Running {
36
+ /** `undefined` without keys: every call throws `PAYMENT_UNAVAILABLE`. */
37
+ readonly stripe: {
38
+ readonly gateway: Gateway;
39
+ /** Verifies the webhook's events; it reaches no network. */
40
+ readonly client: Stripe;
41
+ readonly webhook: string;
42
+ readonly live: boolean;
43
+ } | undefined;
44
+ readonly catalog: Catalog;
45
+ readonly products: ReadonlyMap<string, Product>;
46
+ readonly customer: ((payer: never) => CustomerProfile) | undefined;
47
+ readonly oneSubscription: boolean;
48
+ readonly subscription: Billing | undefined;
49
+ readonly purchase: Billing | undefined;
50
+ readonly balance: Billing | undefined;
51
+ readonly history: Billing | undefined;
52
+ readonly logger: Logger;
53
+ /** The managed portal configuration's id, once read. */
54
+ portal: string | null | undefined;
55
+ }
56
+ export declare const useRunning: (state: Running | undefined) => void;
57
+ /** The running plugin; a call before the application starts is a bug. */
58
+ export declare function runningOf(entry: string): Running;
59
+ /** The gateway, or `PAYMENT_UNAVAILABLE` without keys (D-371). */
60
+ export declare function stripeOf(entry: string): NonNullable<Running['stripe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QAAQ,CAAC,OAAO,EAAE,OAAO,GAAG,SAAS,CAAA;IACrC,QAAQ,CAAC,OAAO,EAAE,OAAO,GAAG,SAAS,CAAA;IACrC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,wDAAwD;IACxD,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAA;CACjC;AAID,eAAO,MAAM,UAAU,UAAW,OAAO,GAAG,SAAS,KAAG,IAEvD,CAAA;AAED,yEAAyE;AACzE,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAOhD;AAED,kEAAkE;AAClE,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,WAAW,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAItE"}
@@ -0,0 +1,35 @@
1
+ import { unavailable } from './billing-gateway.js';
2
+ const methods = [
3
+ 'findUnique',
4
+ 'findMany',
5
+ 'create',
6
+ 'update',
7
+ 'upsert',
8
+ 'updateManyAndReturn',
9
+ 'groupBy',
10
+ ];
11
+ const isRows = (queries) => methods.every((name) => typeof Reflect.get(queries, name) === 'function');
12
+ /** A model's queries, as the plugin sends them. */
13
+ export function rowsOf(queries) {
14
+ if (isRows(queries))
15
+ return queries;
16
+ throw new TypeError('A model’s queries were expected.');
17
+ }
18
+ let running;
19
+ export const useRunning = (state) => {
20
+ running = state;
21
+ };
22
+ /** The running plugin; a call before the application starts is a bug. */
23
+ export function runningOf(entry) {
24
+ if (running === undefined) {
25
+ throw new Error(`${entry} runs while an application with stripePlugin() runs.`);
26
+ }
27
+ return running;
28
+ }
29
+ /** The gateway, or `PAYMENT_UNAVAILABLE` without keys (D-371). */
30
+ export function stripeOf(entry) {
31
+ const { stripe } = runningOf(entry);
32
+ if (stripe === undefined)
33
+ throw unavailable();
34
+ return stripe;
35
+ }
@@ -0,0 +1,8 @@
1
+ import type { Stripe } from 'stripe';
2
+ import type { BillingGateway } from './billing-gateway.ts';
3
+ import type { Ref } from './sdk-common.ts';
4
+ /** The customer an object belongs to, read from Stripe. */
5
+ export declare function ownerOf(client: Stripe, type: string, id: string): Promise<Ref>;
6
+ /** The billing gateway over Stripe's API. */
7
+ export declare const sdkBilling: (client: Stripe) => BillingGateway;
8
+ //# sourceMappingURL=sdk-billing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sdk-billing.d.ts","sourceRoot":"","sources":["../src/sdk-billing.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AACpC,OAAO,KAAK,EACX,cAAc,EAGd,MAAM,sBAAsB,CAAA;AAG7B,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAA;AAQ1C,2DAA2D;AAC3D,wBAAsB,OAAO,CAC5B,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,GACR,OAAO,CAAC,GAAG,CAAC,CA0Bd;AAiDD,6CAA6C;AAC7C,eAAO,MAAM,UAAU,WAAY,MAAM,KAAG,cAuH1C,CAAA"}