@tenthbilling/node 0.0.0-stage → 0.1.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shaw Apps LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,134 @@
1
- # Temporary Holding Version
1
+ # @tenthbilling/node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Tenth server SDK: entitlement checks, credits, grants, Stripe subscription management, the event feed, webhook verification and customer token minting. No runtime dependencies; Node 24 or later.
4
+
5
+ Use it only on your server. It takes a **secret key** (`tenth_test_sk_…` / `tenth_live_sk_…`), which can act for any customer of its app. Publishable keys belong in apps (`@tenthbilling/expo`) and are refused here.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @tenthbilling/node
11
+ ```
12
+
13
+ ```ts
14
+ import { Tenth } from '@tenthbilling/node';
15
+
16
+ const tenth = new Tenth({ secretKey: process.env.TENTH_SECRET_KEY! });
17
+ ```
18
+
19
+ Options: `baseUrl` (default `https://api.tenthbilling.com`), `timeoutMs` per attempt (default 10 000), `maxRetries` (default 2), `fetch`.
20
+
21
+ ## Common calls
22
+
23
+ ```ts
24
+ // 1. Gate a feature
25
+ if (await tenth.hasEntitlement(userId, 'pro')) {
26
+ /* … */
27
+ }
28
+
29
+ // 2. Full customer state: entitlements, credit balances, subscriptions
30
+ const state = await tenth.customers.get(userId);
31
+
32
+ // 3. Spend credits. Pass your own idempotency_key (a job id, say) so your retries can't double-debit.
33
+ const { balance } = await tenth.credits.debit(userId, 'ai_tokens', {
34
+ amount: 25,
35
+ idempotency_key: `job-${jobId}`,
36
+ });
37
+
38
+ // 4. Comp an entitlement
39
+ await tenth.grants.create(userId, {
40
+ entitlement: 'pro',
41
+ reason: 'Beta tester',
42
+ expires_at: '2027-01-01T00:00:00Z',
43
+ });
44
+
45
+ // 5. Read the event feed from where you left off
46
+ for await (const event of tenth.events.listAll({ after: lastProcessedId })) {
47
+ /* handle event.payload, then store event.id */
48
+ }
49
+ ```
50
+
51
+ Also: `customers.entitlements / alias / update / delete`, `credits.get / reserve / commit / release`, `grants.revoke`, `revenueTransactions.list / listAll`, `subscriptions.change / cancel / resume / anchor`, `purchases.refund`, `checkoutSessions.create`, `paymentIntents.create`, `receipts.submit`. Request bodies use the API's field names (`app_user_id`, `success_url`, …).
52
+
53
+ Every mutating call sends an `Idempotency-Key` (yours via `{ idempotencyKey }` as the last argument, or a random one) and reuses it when retrying. Network errors, 429 and 5xx are retried with exponential backoff, honoring `Retry-After`; other 4xx are not.
54
+
55
+ Failures throw `TenthError` with `status`, `code` (Tenth's stable error code, e.g. `insufficient_credits`), `detail` and `requestId`. Errors never contain your key.
56
+
57
+ ```ts
58
+ try {
59
+ await tenth.credits.debit(userId, 'ai_tokens', { amount: 25 });
60
+ } catch (err) {
61
+ if (err instanceof TenthError && err.code === 'insufficient_credits') {
62
+ /* … */
63
+ }
64
+ }
65
+ ```
66
+
67
+ ## Webhooks
68
+
69
+ Verify against the **raw** body: a parsed and re-serialized object won't match the signature. `verifyWebhook` checks the `Tenth-Signature` header in constant time, rejects timestamps more than 5 minutes off, and only then parses the event.
70
+
71
+ Express:
72
+
73
+ ```ts
74
+ import express from 'express';
75
+ import { verifyWebhook, TenthWebhookError } from '@tenthbilling/node';
76
+
77
+ app.post('/webhooks/tenth', express.raw({ type: 'application/json' }), (req, res) => {
78
+ let event;
79
+ try {
80
+ event = verifyWebhook({
81
+ payload: req.body, // Buffer
82
+ header: req.headers['tenth-signature'],
83
+ secret: process.env.TENTH_WEBHOOK_SECRET!,
84
+ });
85
+ } catch (err) {
86
+ if (err instanceof TenthWebhookError) return res.sendStatus(400);
87
+ throw err;
88
+ }
89
+ // Deliveries are at-least-once: dedupe on event.id.
90
+ handle(event); // event.type, event.data, event.customer (full customer state)
91
+ res.sendStatus(200);
92
+ });
93
+ ```
94
+
95
+ Fastify:
96
+
97
+ ```ts
98
+ fastify.register(async (scope) => {
99
+ scope.addContentTypeParser('application/json', { parseAs: 'buffer' }, (_req, body, done) =>
100
+ done(null, body),
101
+ );
102
+ scope.post('/webhooks/tenth', async (request, reply) => {
103
+ const event = verifyWebhook({
104
+ payload: request.body as Buffer,
105
+ header: request.headers['tenth-signature'],
106
+ secret: process.env.TENTH_WEBHOOK_SECRET!,
107
+ });
108
+ handle(event);
109
+ return reply.code(200).send();
110
+ });
111
+ });
112
+ ```
113
+
114
+ While rotating an endpoint's secret, pass both: `secret: [newSecret, oldSecret]`.
115
+
116
+ ## Customer tokens
117
+
118
+ For apps without Clerk or another identity provider, your server mints a short-lived token for the signed-in user; the app sends it with its publishable key.
119
+
120
+ ```ts
121
+ import { mintCustomerToken } from '@tenthbilling/node';
122
+
123
+ const token = mintCustomerToken({
124
+ tokenSecret: process.env.TENTH_CUSTOMER_TOKEN_SECRET!, // per app and environment, from the dashboard
125
+ appId: 'your-app-id',
126
+ environment: 'live',
127
+ appUserId: user.id,
128
+ ttlSeconds: 3600, // 1 to 86 400
129
+ });
130
+ ```
131
+
132
+ Only mint for the user your server has authenticated: whoever holds the token can read and buy as that customer.
133
+
134
+ Full reference: https://tenthbilling.com/docs/node
@@ -0,0 +1,115 @@
1
+ import { Transport, type FetchLike, type RequestOptions } from './http.js';
2
+ import type { AliasResult, BodyOf, CheckoutSession, CreditDebitResult, CreditHold, CustomerCredits, CustomerEntitlements, CustomerState, CustomerUpdate, EventsPage, FeedEvent, Grant, GrantCreate, PaymentIntent, QueryOf, ReceiptResult, RevenueTransaction, RevenueTransactionsPage, SubscriptionAnchor, SubscriptionChange } from './types.js';
3
+ export interface TenthOptions {
4
+ /** `tenth_test_sk_…` or `tenth_live_sk_…`. Load it from your secret store, never from source. */
5
+ secretKey: string;
6
+ /** API origin. Defaults to https://api.tenthbilling.com. */
7
+ baseUrl?: string;
8
+ /** Per-attempt timeout. Defaults to 10 000 ms. */
9
+ timeoutMs?: number;
10
+ /** Retries after the first attempt, on network errors, 429 and 5xx. Defaults to 2. */
11
+ maxRetries?: number;
12
+ /** A fetch implementation; defaults to the global one. */
13
+ fetch?: FetchLike;
14
+ }
15
+ /** Secret-key bodies name the customer explicitly; `me` only means something with a customer token. */
16
+ type ForCustomer<B> = B extends unknown ? Omit<B, 'app_user_id'> & {
17
+ app_user_id: string;
18
+ } : never;
19
+ /** Credit spends: `idempotency_key` defaults to the request's Idempotency-Key. */
20
+ type Spend<B> = Omit<B, 'idempotency_key'> & {
21
+ idempotency_key?: string;
22
+ };
23
+ export declare class Tenth {
24
+ #private;
25
+ readonly customers: Customers;
26
+ readonly credits: Credits;
27
+ readonly grants: Grants;
28
+ readonly events: Events;
29
+ readonly revenueTransactions: RevenueTransactions;
30
+ readonly subscriptions: Subscriptions;
31
+ readonly purchases: Purchases;
32
+ readonly checkoutSessions: CheckoutSessions;
33
+ readonly paymentIntents: PaymentIntents;
34
+ readonly receipts: Receipts;
35
+ constructor(options: TenthOptions);
36
+ /**
37
+ * True when the customer has the entitlement active now. An unknown customer has nothing, so a
38
+ * 404 is false rather than an error.
39
+ */
40
+ hasEntitlement(appUserId: string, entitlement: string, options?: RequestOptions): Promise<boolean>;
41
+ }
42
+ declare abstract class Resource {
43
+ protected readonly http: Transport;
44
+ constructor(http: Transport);
45
+ }
46
+ declare class Customers extends Resource {
47
+ /** Entitlements, credit balances and subscriptions. */
48
+ get(appUserId: string, options?: RequestOptions): Promise<CustomerState>;
49
+ /** The hot path: just the entitlements. */
50
+ entitlements(appUserId: string, options?: RequestOptions): Promise<CustomerEntitlements>;
51
+ /** Makes `body.alias` resolve to this customer (identify, or merge). */
52
+ alias(appUserId: string, body: BodyOf<'/v1/customers/{id}/alias', 'post'>, options?: RequestOptions): Promise<AliasResult>;
53
+ /** Sets email and merges attributes; a null attribute removes it. */
54
+ update(appUserId: string, body: CustomerUpdate, options?: RequestOptions): Promise<CustomerState>;
55
+ /** Privacy delete: personal data goes, financial records stay. */
56
+ delete(appUserId: string, options?: RequestOptions): Promise<void>;
57
+ }
58
+ declare class Credits extends Resource {
59
+ /** Balances and recent transactions; page back with `before`. */
60
+ get(appUserId: string, query?: QueryOf<'/v1/customers/{id}/credits', 'get'>, options?: RequestOptions): Promise<CustomerCredits>;
61
+ /** Spends credits. The same idempotency key never debits twice. */
62
+ debit(appUserId: string, creditType: string, body: Spend<BodyOf<'/v1/customers/{id}/credits/{type}/debit', 'post'>>, options?: RequestOptions): Promise<CreditDebitResult>;
63
+ /** Holds credits for long-running work; commit or release the hold later. */
64
+ reserve(appUserId: string, creditType: string, body: Spend<BodyOf<'/v1/customers/{id}/credits/{type}/reserve', 'post'>>, options?: RequestOptions): Promise<CreditHold>;
65
+ /** Spends a hold; committing less than it releases the rest. */
66
+ commit(appUserId: string, creditType: string, holdId: string, body?: BodyOf<'/v1/customers/{id}/credits/{type}/holds/{holdId}/commit', 'post'>, options?: RequestOptions): Promise<CreditDebitResult>;
67
+ /** Releases a hold without spending. */
68
+ release(appUserId: string, creditType: string, holdId: string, options?: RequestOptions): Promise<CreditHold>;
69
+ }
70
+ declare class Grants extends Resource {
71
+ /** Gives an entitlement or credits without payment; creates the customer if new. */
72
+ create(appUserId: string, body: GrantCreate, options?: RequestOptions): Promise<Grant>;
73
+ /** Revokes a grant; unspent granted credits are removed. */
74
+ revoke(grantId: string, options?: RequestOptions): Promise<Grant>;
75
+ }
76
+ type EventsQuery = QueryOf<'/v1/events', 'get'>;
77
+ type RevenueQuery = QueryOf<'/v1/revenue/transactions', 'get'>;
78
+ declare class Events extends Resource {
79
+ /** One page of the event feed, oldest first. Pass the last id you processed as `after`. */
80
+ list(query?: EventsQuery, options?: RequestOptions): Promise<EventsPage>;
81
+ /** Every event after `query.after`: `for await (const event of tenth.events.listAll())`. */
82
+ listAll(query?: EventsQuery, options?: RequestOptions): AsyncGenerator<FeedEvent>;
83
+ }
84
+ declare class RevenueTransactions extends Resource {
85
+ /** One page of revenue rows (the data behind the transactions export). */
86
+ list(query?: RevenueQuery, options?: RequestOptions): Promise<RevenueTransactionsPage>;
87
+ /** Every revenue row matching `query`. */
88
+ listAll(query?: RevenueQuery, options?: RequestOptions): AsyncGenerator<RevenueTransaction>;
89
+ }
90
+ /** Stripe subscriptions only; store subscriptions are managed in the store. */
91
+ declare class Subscriptions extends Resource {
92
+ change(id: string, body: SubscriptionChange, options?: RequestOptions): Promise<CustomerState>;
93
+ /** At period end by default. */
94
+ cancel(id: string, body?: BodyOf<'/v1/subscriptions/{id}/cancel', 'post'>, options?: RequestOptions): Promise<CustomerState>;
95
+ resume(id: string, options?: RequestOptions): Promise<CustomerState>;
96
+ /** Moves to a fixed billing day. */
97
+ anchor(id: string, body: SubscriptionAnchor, options?: RequestOptions): Promise<CustomerState>;
98
+ }
99
+ declare class Purchases extends Resource {
100
+ /** Refunds a Stripe one-time purchase; leave out `amount` for the full amount. */
101
+ refund(id: string, body?: BodyOf<'/v1/purchases/{id}/refund', 'post'>, options?: RequestOptions): Promise<CustomerState>;
102
+ }
103
+ declare class CheckoutSessions extends Resource {
104
+ /** Starts a hosted Stripe Checkout for a customer. */
105
+ create(body: ForCustomer<BodyOf<'/v1/checkout-sessions', 'post'>>, options?: RequestOptions): Promise<CheckoutSession>;
106
+ }
107
+ declare class PaymentIntents extends Resource {
108
+ /** Starts an embedded Stripe payment for a customer. */
109
+ create(body: ForCustomer<BodyOf<'/v1/payment-intents', 'post'>>, options?: RequestOptions): Promise<PaymentIntent>;
110
+ }
111
+ declare class Receipts extends Resource {
112
+ /** Submits an App Store or Google Play purchase for a customer. */
113
+ submit(body: ForCustomer<BodyOf<'/v1/receipts', 'post'>>, options?: RequestOptions): Promise<ReceiptResult>;
114
+ }
115
+ export type { Customers, Credits, Grants, Events, RevenueTransactions, Subscriptions, Purchases, CheckoutSessions, PaymentIntents, Receipts, };
package/dist/client.js ADDED
@@ -0,0 +1,220 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { TenthError } from './errors.js';
3
+ import { Transport, path } from './http.js';
4
+ const KEY_RE = /^tenth_(test|live)_(pk|sk)_[0-9A-Za-z]{32}$/;
5
+ const DEFAULT_BASE_URL = 'https://api.tenthbilling.com';
6
+ export class Tenth {
7
+ #http;
8
+ customers;
9
+ credits;
10
+ grants;
11
+ events;
12
+ revenueTransactions;
13
+ subscriptions;
14
+ purchases;
15
+ checkoutSessions;
16
+ paymentIntents;
17
+ receipts;
18
+ constructor(options) {
19
+ const { secretKey } = options ?? {};
20
+ const parsed = typeof secretKey === 'string' ? KEY_RE.exec(secretKey) : null;
21
+ if (!parsed) {
22
+ throw new TenthError('invalid_config', 'secretKey must be a Tenth secret key (tenth_test_sk_… or tenth_live_sk_…).');
23
+ }
24
+ if (parsed[2] === 'pk') {
25
+ throw new TenthError('publishable_key_not_allowed', 'This is a publishable key: publishable keys belong in apps (@tenthbilling/expo). The server SDK needs a secret key (tenth_…_sk_…).');
26
+ }
27
+ const fetchImpl = options.fetch ?? globalThis.fetch;
28
+ if (typeof fetchImpl !== 'function') {
29
+ throw new TenthError('invalid_config', 'No fetch implementation is available (Node 24+).');
30
+ }
31
+ this.#http = new Transport({
32
+ secretKey,
33
+ baseUrl: checkBaseUrl(options.baseUrl ?? DEFAULT_BASE_URL),
34
+ timeoutMs: checkPositiveInt('timeoutMs', options.timeoutMs ?? 10_000, 1),
35
+ maxRetries: checkPositiveInt('maxRetries', options.maxRetries ?? 2, 0),
36
+ fetch: fetchImpl,
37
+ });
38
+ this.customers = new Customers(this.#http);
39
+ this.credits = new Credits(this.#http);
40
+ this.grants = new Grants(this.#http);
41
+ this.events = new Events(this.#http);
42
+ this.revenueTransactions = new RevenueTransactions(this.#http);
43
+ this.subscriptions = new Subscriptions(this.#http);
44
+ this.purchases = new Purchases(this.#http);
45
+ this.checkoutSessions = new CheckoutSessions(this.#http);
46
+ this.paymentIntents = new PaymentIntents(this.#http);
47
+ this.receipts = new Receipts(this.#http);
48
+ }
49
+ async hasEntitlement(appUserId, entitlement, options) {
50
+ try {
51
+ const { entitlements } = await this.customers.entitlements(appUserId, options);
52
+ return entitlements[entitlement]?.active === true;
53
+ }
54
+ catch (err) {
55
+ if (err instanceof TenthError && err.status === 404 && err.code === 'not_found')
56
+ return false;
57
+ throw err;
58
+ }
59
+ }
60
+ [Symbol.for('nodejs.util.inspect.custom')]() {
61
+ return 'Tenth {}';
62
+ }
63
+ }
64
+ function checkBaseUrl(value) {
65
+ let url;
66
+ try {
67
+ url = new URL(value);
68
+ }
69
+ catch {
70
+ throw new TenthError('invalid_config', 'baseUrl must be an absolute URL.');
71
+ }
72
+ const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
73
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) {
74
+ throw new TenthError('invalid_config', 'baseUrl must use https.');
75
+ }
76
+ if (url.username || url.password || url.search || url.hash || url.pathname !== '/') {
77
+ throw new TenthError('invalid_config', 'baseUrl must be an origin, such as https://api.tenthbilling.com.');
78
+ }
79
+ return url.origin;
80
+ }
81
+ function checkPositiveInt(name, value, min) {
82
+ if (!Number.isInteger(value) || value < min) {
83
+ throw new TenthError('invalid_config', `${name} must be an integer ≥ ${min}.`);
84
+ }
85
+ return value;
86
+ }
87
+ class Resource {
88
+ http;
89
+ constructor(http) {
90
+ this.http = http;
91
+ }
92
+ }
93
+ class Customers extends Resource {
94
+ get(appUserId, options) {
95
+ return this.http.request({ method: 'GET', path: path `/v1/customers/${appUserId}` }, options);
96
+ }
97
+ entitlements(appUserId, options) {
98
+ return this.http.request({ method: 'GET', path: path `/v1/customers/${appUserId}/entitlements` }, options);
99
+ }
100
+ alias(appUserId, body, options) {
101
+ return this.http.request({ method: 'POST', path: path `/v1/customers/${appUserId}/alias`, body }, options);
102
+ }
103
+ update(appUserId, body, options) {
104
+ return this.http.request({ method: 'PATCH', path: path `/v1/customers/${appUserId}`, body }, options);
105
+ }
106
+ async delete(appUserId, options) {
107
+ await this.http.request({ method: 'DELETE', path: path `/v1/customers/${appUserId}` }, options);
108
+ }
109
+ }
110
+ class Credits extends Resource {
111
+ get(appUserId, query = {}, options) {
112
+ return this.http.request({ method: 'GET', path: path `/v1/customers/${appUserId}/credits`, query }, options);
113
+ }
114
+ debit(appUserId, creditType, body, options) {
115
+ const [payload, opts] = spend(body, options);
116
+ return this.http.request({
117
+ method: 'POST',
118
+ path: path `/v1/customers/${appUserId}/credits/${creditType}/debit`,
119
+ body: payload,
120
+ }, opts);
121
+ }
122
+ reserve(appUserId, creditType, body, options) {
123
+ const [payload, opts] = spend(body, options);
124
+ return this.http.request({
125
+ method: 'POST',
126
+ path: path `/v1/customers/${appUserId}/credits/${creditType}/reserve`,
127
+ body: payload,
128
+ }, opts);
129
+ }
130
+ commit(appUserId, creditType, holdId, body = {}, options) {
131
+ return this.http.request({
132
+ method: 'POST',
133
+ path: path `/v1/customers/${appUserId}/credits/${creditType}/holds/${holdId}/commit`,
134
+ body,
135
+ }, options);
136
+ }
137
+ release(appUserId, creditType, holdId, options) {
138
+ return this.http.request({
139
+ method: 'POST',
140
+ path: path `/v1/customers/${appUserId}/credits/${creditType}/holds/${holdId}/release`,
141
+ }, options);
142
+ }
143
+ }
144
+ function spend(body, options) {
145
+ const key = body.idempotency_key ?? options?.idempotencyKey ?? randomUUID();
146
+ return [
147
+ { ...body, idempotency_key: key },
148
+ { ...options, idempotencyKey: options?.idempotencyKey ?? key },
149
+ ];
150
+ }
151
+ class Grants extends Resource {
152
+ create(appUserId, body, options) {
153
+ return this.http.request({ method: 'POST', path: path `/v1/customers/${appUserId}/grants`, body }, options);
154
+ }
155
+ revoke(grantId, options) {
156
+ return this.http.request({ method: 'DELETE', path: path `/v1/grants/${grantId}` }, options);
157
+ }
158
+ }
159
+ async function* paginate(fetchPage, query) {
160
+ let after = query.after;
161
+ for (;;) {
162
+ const page = await fetchPage({ ...query, after });
163
+ for (const item of page.data)
164
+ yield item;
165
+ const last = page.data.at(-1);
166
+ if (!page.has_more || !last)
167
+ return;
168
+ after = last.id;
169
+ }
170
+ }
171
+ class Events extends Resource {
172
+ list(query = {}, options) {
173
+ return this.http.request({ method: 'GET', path: '/v1/events', query }, options);
174
+ }
175
+ listAll(query = {}, options) {
176
+ return paginate((q) => this.list(q, options), query);
177
+ }
178
+ }
179
+ class RevenueTransactions extends Resource {
180
+ list(query = {}, options) {
181
+ return this.http.request({ method: 'GET', path: '/v1/revenue/transactions', query }, options);
182
+ }
183
+ listAll(query = {}, options) {
184
+ return paginate((q) => this.list(q, options), query);
185
+ }
186
+ }
187
+ class Subscriptions extends Resource {
188
+ change(id, body, options) {
189
+ return this.http.request({ method: 'POST', path: path `/v1/subscriptions/${id}/change`, body }, options);
190
+ }
191
+ cancel(id, body = {}, options) {
192
+ return this.http.request({ method: 'POST', path: path `/v1/subscriptions/${id}/cancel`, body }, options);
193
+ }
194
+ resume(id, options) {
195
+ return this.http.request({ method: 'POST', path: path `/v1/subscriptions/${id}/resume` }, options);
196
+ }
197
+ anchor(id, body, options) {
198
+ return this.http.request({ method: 'POST', path: path `/v1/subscriptions/${id}/anchor`, body }, options);
199
+ }
200
+ }
201
+ class Purchases extends Resource {
202
+ refund(id, body = {}, options) {
203
+ return this.http.request({ method: 'POST', path: path `/v1/purchases/${id}/refund`, body }, options);
204
+ }
205
+ }
206
+ class CheckoutSessions extends Resource {
207
+ create(body, options) {
208
+ return this.http.request({ method: 'POST', path: '/v1/checkout-sessions', body }, options);
209
+ }
210
+ }
211
+ class PaymentIntents extends Resource {
212
+ create(body, options) {
213
+ return this.http.request({ method: 'POST', path: '/v1/payment-intents', body }, options);
214
+ }
215
+ }
216
+ class Receipts extends Resource {
217
+ submit(body, options) {
218
+ return this.http.request({ method: 'POST', path: '/v1/receipts', body }, options);
219
+ }
220
+ }
@@ -0,0 +1,32 @@
1
+ /** Codes the SDK raises itself, before or instead of a response from Tenth. */
2
+ export type ClientErrorCode = 'invalid_config' | 'publishable_key_not_allowed' | 'invalid_argument' | 'network_error' | 'timeout' | 'aborted' | 'invalid_response';
3
+ export interface TenthErrorInit {
4
+ /** HTTP status, or null when no response arrived (network error, timeout) or none was sent. */
5
+ status?: number | null;
6
+ detail?: string;
7
+ requestId?: string;
8
+ /** Field-level validation issues from a 422 problem. */
9
+ errors?: unknown;
10
+ /** Seconds from a 429/503 Retry-After header. */
11
+ retryAfterSeconds?: number;
12
+ }
13
+ export declare class TenthError extends Error {
14
+ readonly name: string;
15
+ readonly status: number | null;
16
+ /** Tenth's stable error code (e.g. `insufficient_credits`), or a {@link ClientErrorCode}. */
17
+ readonly code: string;
18
+ readonly detail: string | undefined;
19
+ /** The API's x-request-id, for support. */
20
+ readonly requestId: string | undefined;
21
+ readonly errors: unknown;
22
+ readonly retryAfterSeconds: number | undefined;
23
+ constructor(code: string, message: string, init?: TenthErrorInit);
24
+ toJSON(): Record<string, unknown>;
25
+ }
26
+ /** Why {@link verifyWebhook} refused a delivery. */
27
+ export type WebhookErrorReason = 'missing_header' | 'malformed_header' | 'timestamp_too_old' | 'timestamp_in_future' | 'signature_mismatch' | 'payload_not_raw' | 'invalid_payload';
28
+ export declare class TenthWebhookError extends TenthError {
29
+ readonly name: string;
30
+ readonly reason: WebhookErrorReason;
31
+ constructor(reason: WebhookErrorReason, message: string);
32
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,37 @@
1
+ export class TenthError extends Error {
2
+ name = 'TenthError';
3
+ status;
4
+ code;
5
+ detail;
6
+ requestId;
7
+ errors;
8
+ retryAfterSeconds;
9
+ constructor(code, message, init = {}) {
10
+ super(message);
11
+ this.code = code;
12
+ this.status = init.status ?? null;
13
+ this.detail = init.detail;
14
+ this.requestId = init.requestId;
15
+ this.errors = init.errors;
16
+ this.retryAfterSeconds = init.retryAfterSeconds;
17
+ }
18
+ toJSON() {
19
+ return {
20
+ name: this.name,
21
+ code: this.code,
22
+ status: this.status,
23
+ message: this.message,
24
+ detail: this.detail,
25
+ requestId: this.requestId,
26
+ errors: this.errors,
27
+ };
28
+ }
29
+ }
30
+ export class TenthWebhookError extends TenthError {
31
+ name = 'TenthWebhookError';
32
+ reason;
33
+ constructor(reason, message) {
34
+ super(reason, message);
35
+ this.reason = reason;
36
+ }
37
+ }