sendclap 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +84 -2
- package/dist/cjs/index.d.ts +271 -0
- package/dist/cjs/index.js +243 -0
- package/dist/cjs/package.json +1 -0
- package/dist/esm/index.d.ts +271 -0
- package/dist/esm/index.js +198 -0
- package/package.json +28 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sendclap
|
|
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,85 @@
|
|
|
1
|
-
#
|
|
1
|
+
# sendclap
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The official JavaScript and TypeScript client for [Sendclap](https://sendclap.com). It checks license keys from the app you ship and talks to the creator REST API from your server. It has no dependencies and uses the global `fetch`, so it runs in Node 18+, Bun, Deno, browsers and Electron, and it ships ESM, CommonJS and type definitions.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install sendclap
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## License checks
|
|
10
|
+
|
|
11
|
+
The license calls need no API key, so they are safe to make from the app your customers run.
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { LicenseClient, NetworkError, instanceName } from 'sendclap'
|
|
15
|
+
|
|
16
|
+
const licenses = new LicenseClient()
|
|
17
|
+
const key = settings.licenseKey
|
|
18
|
+
try {
|
|
19
|
+
settings.instanceId ??= (await licenses.activate(key, await instanceName())).instance_id // first run
|
|
20
|
+
const r = await licenses.validate(key, settings.instanceId)
|
|
21
|
+
if (r.valid) settings.lastValidated = Date.now()
|
|
22
|
+
else lockApp(r.status) // "invalid" (unknown key), "disabled" (refunded or disputed) or "not_activated"
|
|
23
|
+
} catch (e) {
|
|
24
|
+
// offline: keep working for 7 days after the last successful check
|
|
25
|
+
if (!(e instanceof NetworkError) || Date.now() - settings.lastValidated > 7 * 86400_000) lockApp('unverified')
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
- `activate(licenseKey, instanceName)` registers this device and returns `{ instance_id, license, product }`. Activating the same instance again counts once, and the instance id is simply the name you passed.
|
|
30
|
+
- `validate(licenseKey, instanceId?)` returns `{ valid, status, license?, product? }`. Its `status` is `active`, `not_activated` (the key exists but this device isn't activated), `invalid` (unknown key) or `disabled` (the payment was refunded or disputed). It throws only when no definite answer came back, which is how you tell "offline" from "invalid".
|
|
31
|
+
- `deactivate(licenseKey, instanceId)` frees one activation so the customer can move to another machine. It throws `InstanceNotFoundError` if that instance wasn't activated.
|
|
32
|
+
|
|
33
|
+
To tell a customer why a license doesn't work, branch on the status, or catch the typed error from `activate`:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
const r = await licenses.validate(key, instanceId)
|
|
37
|
+
if (r.status === 'disabled') showMessage('This license was refunded or disputed.')
|
|
38
|
+
else if (r.status === 'invalid') showMessage('That license key does not exist.')
|
|
39
|
+
|
|
40
|
+
try { await licenses.activate(key, name) } catch (e) {
|
|
41
|
+
if (e instanceof DisabledLicenseError) showMessage('This license was refunded or disputed.')
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`instanceName()` returns the hostname in Node, Bun, Deno and Electron's main process, and a random id kept in `localStorage` in browsers. The name is sent to Sendclap and shown to the creator in the activity log, and machines that share a hostname share an activation. If that matters, generate your own id (for example `crypto.randomUUID()` saved on first run) and pass it instead.
|
|
46
|
+
|
|
47
|
+
Cache the result of the last successful `validate` and validate again at startup or once a day. On a `NetworkError`, accept the cached result for a grace period. On `invalid` or `not_activated`, lock.
|
|
48
|
+
|
|
49
|
+
## Creator API
|
|
50
|
+
|
|
51
|
+
> **Never ship your `sc_` API key inside an app, a browser bundle or anything a customer can download.** Anyone who has it can read your payments and customers. Use `ApiClient` only on your own server.
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
import { ApiClient } from 'sendclap'
|
|
55
|
+
|
|
56
|
+
const sendclap = new ApiClient(process.env.SENDCLAP_API_KEY!)
|
|
57
|
+
const checkout = await sendclap.createCheckout({ type: 'product', product_id: 1, email: 'buyer@example.com' })
|
|
58
|
+
redirect(checkout.url) // then poll until it is paid
|
|
59
|
+
const { status } = await sendclap.getCheckout(checkout.id)
|
|
60
|
+
const page = await sendclap.listPayments({ status: 'paid', limit: 10 }) // { data, has_more, next }
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Lists come back as pages of `{ data, has_more, next }`, newest first. Pass `next` back as `after` for the following page, or use the auto-paging `all…` methods, which are async iterators:
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
if (page.has_more) await sendclap.listPayments({ status: 'paid', limit: 10, after: page.next! })
|
|
67
|
+
for await (const p of sendclap.allPayments({ status: 'paid' })) console.log(p.id, p.amount)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
The methods are `createCheckout`, `getCheckout` (both return the checkout `url`), `me`, `getPayment`, `listProducts`, `listMemberships`, `listPayments`, `listMembers`, `listLicenses` and `listDisputes` (pages), `allPayments`, `allMembers`, `allLicenses` and `allDisputes` (iterators), and `getCreator`. The last one is public and works with an empty key. Responses keep the API's own snake_case field names, as described in the [API docs](https://sendclap.com/docs).
|
|
71
|
+
|
|
72
|
+
Both clients take `{ baseUrl, timeout }` options. The defaults are `https://sendclap.com` and 15000 ms. Requests send `User-Agent: sendclap-js/<version>`, or `x-sendclap-client: sendclap-js/<version>` in a browser, where `User-Agent` can't be set.
|
|
73
|
+
|
|
74
|
+
## Errors
|
|
75
|
+
|
|
76
|
+
Every error is a `SendclapError` with `.status`, `.code` (the server's machine-readable code, such as `invalid_api_key` or `not_found`) and the server's message. The typed errors are chosen by `code`:
|
|
77
|
+
|
|
78
|
+
| Error | `code` | When |
|
|
79
|
+
| --- | --- | --- |
|
|
80
|
+
| `InvalidLicenseError` | `license_not_found` | The key doesn't exist (404) |
|
|
81
|
+
| `DisabledLicenseError` | `license_disabled` | The key was disabled after a refund or a dispute (403) |
|
|
82
|
+
| `InstanceNotFoundError` | `instance_not_found` | `deactivate` for an instance that isn't activated (404) |
|
|
83
|
+
| `ActivationLimitError` | `activation_limit` | Every activation is in use, and `.license` shows the counts (409) |
|
|
84
|
+
| `NetworkError` | `network_error` | No response arrived (offline, DNS, TLS or timeout), and `.status` is 0 |
|
|
85
|
+
| `SendclapError` | anything else | Such as `bad_request`, `invalid_api_key` or `not_found`. All of the errors above extend it. |
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
export declare const VERSION = "0.2.0";
|
|
2
|
+
export interface ClientOptions {
|
|
3
|
+
/** Defaults to https://sendclap.com. */
|
|
4
|
+
baseUrl?: string;
|
|
5
|
+
/** Request timeout in milliseconds. Defaults to 15000. */
|
|
6
|
+
timeout?: number;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Any failed request. `status` is the HTTP status (0 when no response arrived) and `code` the server's machine-readable
|
|
10
|
+
* code, such as `invalid_api_key` or `not_found` ('' when the reply wasn't a Sendclap error, 'network_error' with no reply).
|
|
11
|
+
*/
|
|
12
|
+
export declare class SendclapError extends Error {
|
|
13
|
+
readonly status: number;
|
|
14
|
+
readonly code: string;
|
|
15
|
+
readonly body?: unknown;
|
|
16
|
+
constructor(message: string, status: number, code: string, body?: unknown);
|
|
17
|
+
}
|
|
18
|
+
/** The license key doesn't exist (`license_not_found`). */
|
|
19
|
+
export declare class InvalidLicenseError extends SendclapError {
|
|
20
|
+
constructor(message: string, body?: unknown);
|
|
21
|
+
}
|
|
22
|
+
/** The key exists but was disabled after a refund or a dispute (`license_disabled`). */
|
|
23
|
+
export declare class DisabledLicenseError extends SendclapError {
|
|
24
|
+
constructor(message: string, body?: unknown);
|
|
25
|
+
}
|
|
26
|
+
/** Every activation of the key is in use; deactivate another instance first (`activation_limit`). */
|
|
27
|
+
export declare class ActivationLimitError extends SendclapError {
|
|
28
|
+
readonly license: LicenseInfo;
|
|
29
|
+
readonly product: ProductRef;
|
|
30
|
+
constructor(message: string, license: LicenseInfo, product: ProductRef, body?: unknown);
|
|
31
|
+
}
|
|
32
|
+
/** Deactivate was called for an instance that isn't activated (`instance_not_found`). */
|
|
33
|
+
export declare class InstanceNotFoundError extends SendclapError {
|
|
34
|
+
constructor(message: string, body?: unknown);
|
|
35
|
+
}
|
|
36
|
+
/** No response: offline, DNS, TLS or timeout. Fall back to your cached validation. */
|
|
37
|
+
export declare class NetworkError extends SendclapError {
|
|
38
|
+
readonly cause?: unknown;
|
|
39
|
+
constructor(message: string, cause?: unknown);
|
|
40
|
+
}
|
|
41
|
+
export interface LicenseInfo {
|
|
42
|
+
key: string;
|
|
43
|
+
activations: number;
|
|
44
|
+
max_activations: number;
|
|
45
|
+
}
|
|
46
|
+
export interface ProductRef {
|
|
47
|
+
id?: number;
|
|
48
|
+
name?: string;
|
|
49
|
+
}
|
|
50
|
+
export interface ActivateResult {
|
|
51
|
+
instance_id: string;
|
|
52
|
+
license: LicenseInfo;
|
|
53
|
+
product: ProductRef;
|
|
54
|
+
}
|
|
55
|
+
export interface DeactivateResult {
|
|
56
|
+
license: LicenseInfo;
|
|
57
|
+
product: ProductRef;
|
|
58
|
+
}
|
|
59
|
+
export interface ValidateResult {
|
|
60
|
+
valid: boolean;
|
|
61
|
+
/** `active`: valid. `not_activated`: the key exists but this instance isn't activated. `invalid`: unknown key. `disabled`: refunded or disputed. */
|
|
62
|
+
status: 'active' | 'not_activated' | 'invalid' | 'disabled';
|
|
63
|
+
license?: LicenseInfo;
|
|
64
|
+
product?: ProductRef;
|
|
65
|
+
}
|
|
66
|
+
export interface CheckoutParams {
|
|
67
|
+
type: 'tip' | 'product' | 'membership';
|
|
68
|
+
/** Tip amount in US dollars, 1 to 10000. */
|
|
69
|
+
amount?: number;
|
|
70
|
+
product_id?: number;
|
|
71
|
+
tier_id?: number;
|
|
72
|
+
/** Required for memberships. */
|
|
73
|
+
email?: string;
|
|
74
|
+
method?: 'card' | 'crypto';
|
|
75
|
+
message?: string;
|
|
76
|
+
}
|
|
77
|
+
export interface Checkout {
|
|
78
|
+
id: string;
|
|
79
|
+
status: string;
|
|
80
|
+
type: string;
|
|
81
|
+
amount: number;
|
|
82
|
+
currency: string;
|
|
83
|
+
method: string;
|
|
84
|
+
email: string | null;
|
|
85
|
+
/** Where to send the customer to pay. */
|
|
86
|
+
url: string;
|
|
87
|
+
}
|
|
88
|
+
export interface Totals {
|
|
89
|
+
payments: number;
|
|
90
|
+
gross: number;
|
|
91
|
+
fees: number;
|
|
92
|
+
net: number;
|
|
93
|
+
}
|
|
94
|
+
export interface Stats {
|
|
95
|
+
handle: string;
|
|
96
|
+
name: string;
|
|
97
|
+
url: string;
|
|
98
|
+
currency: string;
|
|
99
|
+
last_30_days: Totals;
|
|
100
|
+
all_time: Totals;
|
|
101
|
+
members: {
|
|
102
|
+
active: number;
|
|
103
|
+
monthly_recurring: number;
|
|
104
|
+
};
|
|
105
|
+
open_disputes: number;
|
|
106
|
+
}
|
|
107
|
+
/** `limit` is at most 500; `after` is the previous page's `next`. */
|
|
108
|
+
export interface PageParams {
|
|
109
|
+
limit?: number;
|
|
110
|
+
after?: number;
|
|
111
|
+
}
|
|
112
|
+
export interface PaymentFilter extends PageParams {
|
|
113
|
+
status?: string;
|
|
114
|
+
type?: string;
|
|
115
|
+
email?: string;
|
|
116
|
+
}
|
|
117
|
+
export interface LicenseFilter extends PageParams {
|
|
118
|
+
email?: string;
|
|
119
|
+
}
|
|
120
|
+
export interface Page<T> {
|
|
121
|
+
data: T[];
|
|
122
|
+
has_more: boolean;
|
|
123
|
+
next: number | null;
|
|
124
|
+
}
|
|
125
|
+
export interface Payment {
|
|
126
|
+
id: number;
|
|
127
|
+
type: string;
|
|
128
|
+
method: string;
|
|
129
|
+
status: string;
|
|
130
|
+
amount: number;
|
|
131
|
+
fee: number;
|
|
132
|
+
currency: string;
|
|
133
|
+
email: string | null;
|
|
134
|
+
message: string | null;
|
|
135
|
+
reference: string | null;
|
|
136
|
+
test: boolean;
|
|
137
|
+
created_at: string;
|
|
138
|
+
}
|
|
139
|
+
export interface PaymentDetail extends Payment {
|
|
140
|
+
item: string;
|
|
141
|
+
purchase_ip: string | null;
|
|
142
|
+
purchase_device: string | null;
|
|
143
|
+
dispute: {
|
|
144
|
+
id: string;
|
|
145
|
+
status: string;
|
|
146
|
+
reason: string | null;
|
|
147
|
+
respond_by: string | null;
|
|
148
|
+
} | null;
|
|
149
|
+
activity: {
|
|
150
|
+
at: string;
|
|
151
|
+
event: string;
|
|
152
|
+
detail: string | null;
|
|
153
|
+
ip: string | null;
|
|
154
|
+
}[];
|
|
155
|
+
evidence_pdf: string;
|
|
156
|
+
}
|
|
157
|
+
export interface Member {
|
|
158
|
+
email: string;
|
|
159
|
+
tier: string;
|
|
160
|
+
method: string;
|
|
161
|
+
status: string;
|
|
162
|
+
price: number;
|
|
163
|
+
interval: string;
|
|
164
|
+
current_period_ends: string;
|
|
165
|
+
joined_at: string;
|
|
166
|
+
}
|
|
167
|
+
export interface IssuedLicense {
|
|
168
|
+
key: string;
|
|
169
|
+
product: string;
|
|
170
|
+
email: string;
|
|
171
|
+
activations: number;
|
|
172
|
+
max_activations: number;
|
|
173
|
+
disabled: boolean;
|
|
174
|
+
issued_at: string;
|
|
175
|
+
}
|
|
176
|
+
export interface Dispute {
|
|
177
|
+
id: string;
|
|
178
|
+
payment_id: number;
|
|
179
|
+
email: string | null;
|
|
180
|
+
amount: number;
|
|
181
|
+
reason: string | null;
|
|
182
|
+
status: string;
|
|
183
|
+
respond_by: string | null;
|
|
184
|
+
opened_at: string;
|
|
185
|
+
}
|
|
186
|
+
export interface Product {
|
|
187
|
+
id: number;
|
|
188
|
+
name: string;
|
|
189
|
+
description: string;
|
|
190
|
+
price: number;
|
|
191
|
+
currency: string;
|
|
192
|
+
delivers_file: boolean;
|
|
193
|
+
issues_license_key: boolean;
|
|
194
|
+
page: string;
|
|
195
|
+
x402: string | null;
|
|
196
|
+
}
|
|
197
|
+
export interface Membership {
|
|
198
|
+
id: number;
|
|
199
|
+
name: string;
|
|
200
|
+
description: string;
|
|
201
|
+
price: number;
|
|
202
|
+
currency: string;
|
|
203
|
+
interval: string;
|
|
204
|
+
x402: string | null;
|
|
205
|
+
}
|
|
206
|
+
export interface Creator {
|
|
207
|
+
handle: string;
|
|
208
|
+
name: string;
|
|
209
|
+
bio: string;
|
|
210
|
+
url: string;
|
|
211
|
+
avatar: string | null;
|
|
212
|
+
links: {
|
|
213
|
+
label: string;
|
|
214
|
+
url: string;
|
|
215
|
+
}[];
|
|
216
|
+
payment_methods: {
|
|
217
|
+
card: boolean;
|
|
218
|
+
crypto: boolean;
|
|
219
|
+
x402: boolean;
|
|
220
|
+
};
|
|
221
|
+
tip: {
|
|
222
|
+
suggested: number;
|
|
223
|
+
currency: string;
|
|
224
|
+
page: string;
|
|
225
|
+
x402: string | null;
|
|
226
|
+
};
|
|
227
|
+
memberships: Membership[];
|
|
228
|
+
products: Product[];
|
|
229
|
+
}
|
|
230
|
+
/** License checks from the app you ship. Needs no API key. */
|
|
231
|
+
export declare class LicenseClient {
|
|
232
|
+
private options;
|
|
233
|
+
constructor(options?: ClientOptions);
|
|
234
|
+
private call;
|
|
235
|
+
/** Registers this device against the key. Throws InvalidLicenseError, DisabledLicenseError or ActivationLimitError. Activating the same instance twice counts once. The returned instance_id is the name you passed. */
|
|
236
|
+
activate(licenseKey: string, instanceName: string): Promise<ActivateResult>;
|
|
237
|
+
/** Checks the key (and, with an instance id, that this device is activated). Throws only when no definite answer came back. */
|
|
238
|
+
validate(licenseKey: string, instanceId?: string): Promise<ValidateResult>;
|
|
239
|
+
/** Releases a device, freeing one activation. Throws InstanceNotFoundError if it wasn't activated. */
|
|
240
|
+
deactivate(licenseKey: string, instanceId: string): Promise<DeactivateResult>;
|
|
241
|
+
}
|
|
242
|
+
/** The creator REST API. Server side only: never ship an sc_ key inside an app or a web page. */
|
|
243
|
+
export declare class ApiClient {
|
|
244
|
+
private apiKey;
|
|
245
|
+
private options;
|
|
246
|
+
/** `apiKey` may be empty if you only call getCreator. */
|
|
247
|
+
constructor(apiKey: string, options?: ClientOptions);
|
|
248
|
+
private get;
|
|
249
|
+
createCheckout(params: CheckoutParams): Promise<Checkout>;
|
|
250
|
+
getCheckout(id: string): Promise<Checkout>;
|
|
251
|
+
me(): Promise<Stats>;
|
|
252
|
+
listPayments(filter?: PaymentFilter): Promise<Page<Payment>>;
|
|
253
|
+
getPayment(id: number): Promise<PaymentDetail>;
|
|
254
|
+
listMembers(page?: PageParams): Promise<Page<Member>>;
|
|
255
|
+
listLicenses(filter?: LicenseFilter): Promise<Page<IssuedLicense>>;
|
|
256
|
+
listDisputes(page?: PageParams): Promise<Page<Dispute>>;
|
|
257
|
+
/** The auto-paging versions: `for await (const p of api.allPayments({ status: 'paid' }))` follows `next` until the end. */
|
|
258
|
+
allPayments(filter?: PaymentFilter): AsyncGenerator<Payment, any, any>;
|
|
259
|
+
allMembers(page?: PageParams): AsyncGenerator<Member, any, any>;
|
|
260
|
+
allLicenses(filter?: LicenseFilter): AsyncGenerator<IssuedLicense, any, any>;
|
|
261
|
+
allDisputes(page?: PageParams): AsyncGenerator<Dispute, any, any>;
|
|
262
|
+
listProducts(): Promise<Product[]>;
|
|
263
|
+
listMemberships(): Promise<Membership[]>;
|
|
264
|
+
/** Public: works without an API key. */
|
|
265
|
+
getCreator(handle: string): Promise<Creator>;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* A name for this installation: the hostname in Node, Bun, Deno and Electron's main process, and a random id kept in
|
|
269
|
+
* localStorage in browsers. It is sent to Sendclap and shown to the creator; machines sharing a hostname share an activation.
|
|
270
|
+
*/
|
|
271
|
+
export declare function instanceName(): Promise<string>;
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Sendclap client for JavaScript and TypeScript: license checks for the apps you ship, and the creator REST API for your server.
|
|
3
|
+
// Zero dependencies; uses the global fetch (Node 18+, Bun, Deno, browsers, Electron).
|
|
4
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
5
|
+
if (k2 === undefined) k2 = k;
|
|
6
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
7
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
8
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
9
|
+
}
|
|
10
|
+
Object.defineProperty(o, k2, desc);
|
|
11
|
+
}) : (function(o, m, k, k2) {
|
|
12
|
+
if (k2 === undefined) k2 = k;
|
|
13
|
+
o[k2] = m[k];
|
|
14
|
+
}));
|
|
15
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
16
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
17
|
+
}) : function(o, v) {
|
|
18
|
+
o["default"] = v;
|
|
19
|
+
});
|
|
20
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
21
|
+
var ownKeys = function(o) {
|
|
22
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
23
|
+
var ar = [];
|
|
24
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
25
|
+
return ar;
|
|
26
|
+
};
|
|
27
|
+
return ownKeys(o);
|
|
28
|
+
};
|
|
29
|
+
return function (mod) {
|
|
30
|
+
if (mod && mod.__esModule) return mod;
|
|
31
|
+
var result = {};
|
|
32
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
33
|
+
__setModuleDefault(result, mod);
|
|
34
|
+
return result;
|
|
35
|
+
};
|
|
36
|
+
})();
|
|
37
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
38
|
+
exports.ApiClient = exports.LicenseClient = exports.NetworkError = exports.InstanceNotFoundError = exports.ActivationLimitError = exports.DisabledLicenseError = exports.InvalidLicenseError = exports.SendclapError = exports.VERSION = void 0;
|
|
39
|
+
exports.instanceName = instanceName;
|
|
40
|
+
exports.VERSION = '0.2.0';
|
|
41
|
+
const DEFAULT_BASE_URL = 'https://sendclap.com';
|
|
42
|
+
const DEFAULT_TIMEOUT_MS = 15000;
|
|
43
|
+
// ---------- errors ----------
|
|
44
|
+
/**
|
|
45
|
+
* Any failed request. `status` is the HTTP status (0 when no response arrived) and `code` the server's machine-readable
|
|
46
|
+
* code, such as `invalid_api_key` or `not_found` ('' when the reply wasn't a Sendclap error, 'network_error' with no reply).
|
|
47
|
+
*/
|
|
48
|
+
class SendclapError extends Error {
|
|
49
|
+
constructor(message, status, code, body) {
|
|
50
|
+
super(message);
|
|
51
|
+
this.status = status;
|
|
52
|
+
this.code = code;
|
|
53
|
+
this.body = body;
|
|
54
|
+
this.name = 'SendclapError';
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
exports.SendclapError = SendclapError;
|
|
58
|
+
/** The license key doesn't exist (`license_not_found`). */
|
|
59
|
+
class InvalidLicenseError extends SendclapError {
|
|
60
|
+
constructor(message, body) {
|
|
61
|
+
super(message, 404, 'license_not_found', body);
|
|
62
|
+
this.name = 'InvalidLicenseError';
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
exports.InvalidLicenseError = InvalidLicenseError;
|
|
66
|
+
/** The key exists but was disabled after a refund or a dispute (`license_disabled`). */
|
|
67
|
+
class DisabledLicenseError extends SendclapError {
|
|
68
|
+
constructor(message, body) {
|
|
69
|
+
super(message, 403, 'license_disabled', body);
|
|
70
|
+
this.name = 'DisabledLicenseError';
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
exports.DisabledLicenseError = DisabledLicenseError;
|
|
74
|
+
/** Every activation of the key is in use; deactivate another instance first (`activation_limit`). */
|
|
75
|
+
class ActivationLimitError extends SendclapError {
|
|
76
|
+
constructor(message, license, product, body) {
|
|
77
|
+
super(message, 409, 'activation_limit', body);
|
|
78
|
+
this.license = license;
|
|
79
|
+
this.product = product;
|
|
80
|
+
this.name = 'ActivationLimitError';
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
exports.ActivationLimitError = ActivationLimitError;
|
|
84
|
+
/** Deactivate was called for an instance that isn't activated (`instance_not_found`). */
|
|
85
|
+
class InstanceNotFoundError extends SendclapError {
|
|
86
|
+
constructor(message, body) {
|
|
87
|
+
super(message, 404, 'instance_not_found', body);
|
|
88
|
+
this.name = 'InstanceNotFoundError';
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
exports.InstanceNotFoundError = InstanceNotFoundError;
|
|
92
|
+
/** No response: offline, DNS, TLS or timeout. Fall back to your cached validation. */
|
|
93
|
+
class NetworkError extends SendclapError {
|
|
94
|
+
constructor(message, cause) {
|
|
95
|
+
super(message, 0, 'network_error');
|
|
96
|
+
this.cause = cause;
|
|
97
|
+
this.name = 'NetworkError';
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
exports.NetworkError = NetworkError;
|
|
101
|
+
async function request(o, method, path, init = {}) {
|
|
102
|
+
const url = new URL(`${(o.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '')}/api/v1${path}`);
|
|
103
|
+
for (const [k, v] of Object.entries(init.query ?? {}))
|
|
104
|
+
if (v !== undefined && v !== '')
|
|
105
|
+
url.searchParams.set(k, String(v));
|
|
106
|
+
const headers = { accept: 'application/json' };
|
|
107
|
+
// browsers forbid setting User-Agent, so a web page identifies itself with x-sendclap-client instead
|
|
108
|
+
if (typeof globalThis.document === 'undefined')
|
|
109
|
+
headers['user-agent'] = `sendclap-js/${exports.VERSION}`;
|
|
110
|
+
else
|
|
111
|
+
headers['x-sendclap-client'] = `sendclap-js/${exports.VERSION}`;
|
|
112
|
+
if (init.body)
|
|
113
|
+
headers['content-type'] = 'application/json';
|
|
114
|
+
if (init.apiKey)
|
|
115
|
+
headers.authorization = `Bearer ${init.apiKey}`;
|
|
116
|
+
let res, text;
|
|
117
|
+
try {
|
|
118
|
+
res = await fetch(url, { method, headers, body: init.body && JSON.stringify(init.body), signal: AbortSignal.timeout(o.timeout ?? DEFAULT_TIMEOUT_MS) });
|
|
119
|
+
text = await res.text();
|
|
120
|
+
}
|
|
121
|
+
catch (e) {
|
|
122
|
+
throw new NetworkError(e instanceof Error ? e.message : String(e), e);
|
|
123
|
+
}
|
|
124
|
+
let data;
|
|
125
|
+
try {
|
|
126
|
+
data = JSON.parse(text);
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
data = undefined;
|
|
130
|
+
}
|
|
131
|
+
if (res.ok) {
|
|
132
|
+
if (data === undefined)
|
|
133
|
+
throw new SendclapError('invalid JSON response', res.status, text);
|
|
134
|
+
return data;
|
|
135
|
+
}
|
|
136
|
+
const message = typeof data?.error === 'string' ? data.error : `HTTP ${res.status}`;
|
|
137
|
+
const code = typeof data?.code === 'string' ? data.code : '';
|
|
138
|
+
if (code === 'license_not_found')
|
|
139
|
+
throw new InvalidLicenseError(message, data);
|
|
140
|
+
if (code === 'license_disabled')
|
|
141
|
+
throw new DisabledLicenseError(message, data);
|
|
142
|
+
if (code === 'instance_not_found')
|
|
143
|
+
throw new InstanceNotFoundError(message, data);
|
|
144
|
+
if (code === 'activation_limit')
|
|
145
|
+
throw new ActivationLimitError(message, data.license, data.product, data);
|
|
146
|
+
throw new SendclapError(message, res.status, code, data ?? text);
|
|
147
|
+
}
|
|
148
|
+
// ---------- clients ----------
|
|
149
|
+
/** License checks from the app you ship. Needs no API key. */
|
|
150
|
+
class LicenseClient {
|
|
151
|
+
constructor(options = {}) {
|
|
152
|
+
this.options = options;
|
|
153
|
+
}
|
|
154
|
+
call(action, licenseKey, instanceId) {
|
|
155
|
+
return request(this.options, 'POST', `/licenses/${action}`, { body: { license_key: licenseKey, ...(instanceId ? { instance_id: instanceId } : {}) } });
|
|
156
|
+
}
|
|
157
|
+
/** Registers this device against the key. Throws InvalidLicenseError, DisabledLicenseError or ActivationLimitError. Activating the same instance twice counts once. The returned instance_id is the name you passed. */
|
|
158
|
+
async activate(licenseKey, instanceName) {
|
|
159
|
+
const { instance_id, license, product } = await this.call('activate', licenseKey, instanceName);
|
|
160
|
+
return { instance_id, license, product };
|
|
161
|
+
}
|
|
162
|
+
/** Checks the key (and, with an instance id, that this device is activated). Throws only when no definite answer came back. */
|
|
163
|
+
async validate(licenseKey, instanceId) {
|
|
164
|
+
try {
|
|
165
|
+
const { valid, license, product } = await this.call('validate', licenseKey, instanceId);
|
|
166
|
+
return { valid, status: valid ? 'active' : 'not_activated', license, product };
|
|
167
|
+
}
|
|
168
|
+
catch (e) {
|
|
169
|
+
if (e instanceof InvalidLicenseError)
|
|
170
|
+
return { valid: false, status: 'invalid' };
|
|
171
|
+
if (e instanceof DisabledLicenseError)
|
|
172
|
+
return { valid: false, status: 'disabled' };
|
|
173
|
+
throw e;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
/** Releases a device, freeing one activation. Throws InstanceNotFoundError if it wasn't activated. */
|
|
177
|
+
async deactivate(licenseKey, instanceId) {
|
|
178
|
+
const { license, product } = await this.call('deactivate', licenseKey, instanceId);
|
|
179
|
+
return { license, product };
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
exports.LicenseClient = LicenseClient;
|
|
183
|
+
async function* paginate(fetchPage) {
|
|
184
|
+
let page = await fetchPage();
|
|
185
|
+
for (;;) {
|
|
186
|
+
yield* page.data;
|
|
187
|
+
if (!page.has_more || page.next === null)
|
|
188
|
+
return;
|
|
189
|
+
page = await fetchPage(page.next);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/** The creator REST API. Server side only: never ship an sc_ key inside an app or a web page. */
|
|
193
|
+
class ApiClient {
|
|
194
|
+
/** `apiKey` may be empty if you only call getCreator. */
|
|
195
|
+
constructor(apiKey, options = {}) {
|
|
196
|
+
this.apiKey = apiKey;
|
|
197
|
+
this.options = options;
|
|
198
|
+
}
|
|
199
|
+
get(path, query) {
|
|
200
|
+
return request(this.options, 'GET', path, { query, apiKey: this.apiKey });
|
|
201
|
+
}
|
|
202
|
+
createCheckout(params) {
|
|
203
|
+
return request(this.options, 'POST', '/checkouts', { body: params, apiKey: this.apiKey });
|
|
204
|
+
}
|
|
205
|
+
getCheckout(id) { return this.get(`/checkouts/${encodeURIComponent(id)}`); }
|
|
206
|
+
me() { return this.get('/me'); }
|
|
207
|
+
listPayments(filter = {}) { return this.get('/payments', { ...filter }); }
|
|
208
|
+
getPayment(id) { return this.get(`/payments/${encodeURIComponent(id)}`); }
|
|
209
|
+
listMembers(page = {}) { return this.get('/members', { ...page }); }
|
|
210
|
+
listLicenses(filter = {}) { return this.get('/licenses', { ...filter }); }
|
|
211
|
+
listDisputes(page = {}) { return this.get('/disputes', { ...page }); }
|
|
212
|
+
/** The auto-paging versions: `for await (const p of api.allPayments({ status: 'paid' }))` follows `next` until the end. */
|
|
213
|
+
allPayments(filter = {}) { return paginate(after => this.listPayments({ ...filter, after })); }
|
|
214
|
+
allMembers(page = {}) { return paginate(after => this.listMembers({ ...page, after })); }
|
|
215
|
+
allLicenses(filter = {}) { return paginate(after => this.listLicenses({ ...filter, after })); }
|
|
216
|
+
allDisputes(page = {}) { return paginate(after => this.listDisputes({ ...page, after })); }
|
|
217
|
+
listProducts() { return this.get('/products'); }
|
|
218
|
+
listMemberships() { return this.get('/memberships'); }
|
|
219
|
+
/** Public: works without an API key. */
|
|
220
|
+
getCreator(handle) { return this.get(`/creators/${encodeURIComponent(handle)}`); }
|
|
221
|
+
}
|
|
222
|
+
exports.ApiClient = ApiClient;
|
|
223
|
+
/**
|
|
224
|
+
* A name for this installation: the hostname in Node, Bun, Deno and Electron's main process, and a random id kept in
|
|
225
|
+
* localStorage in browsers. It is sent to Sendclap and shown to the creator; machines sharing a hostname share an activation.
|
|
226
|
+
*/
|
|
227
|
+
async function instanceName() {
|
|
228
|
+
var _a;
|
|
229
|
+
const g = globalThis;
|
|
230
|
+
if (g.Deno?.hostname)
|
|
231
|
+
return g.Deno.hostname();
|
|
232
|
+
if (g.process?.versions?.node) {
|
|
233
|
+
const id = 'node:os'; // a variable keeps browser bundlers from trying to resolve it
|
|
234
|
+
const os = g.process.getBuiltinModule?.(id) ?? await Promise.resolve(`${id}`).then(s => __importStar(require(s)));
|
|
235
|
+
return os.hostname();
|
|
236
|
+
}
|
|
237
|
+
try {
|
|
238
|
+
return ((_a = g.localStorage).sendclap_instance ?? (_a.sendclap_instance = g.crypto.randomUUID()));
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
return g.crypto.randomUUID();
|
|
242
|
+
}
|
|
243
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
export declare const VERSION = "0.2.0";
|
|
2
|
+
export interface ClientOptions {
|
|
3
|
+
/** Defaults to https://sendclap.com. */
|
|
4
|
+
baseUrl?: string;
|
|
5
|
+
/** Request timeout in milliseconds. Defaults to 15000. */
|
|
6
|
+
timeout?: number;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Any failed request. `status` is the HTTP status (0 when no response arrived) and `code` the server's machine-readable
|
|
10
|
+
* code, such as `invalid_api_key` or `not_found` ('' when the reply wasn't a Sendclap error, 'network_error' with no reply).
|
|
11
|
+
*/
|
|
12
|
+
export declare class SendclapError extends Error {
|
|
13
|
+
readonly status: number;
|
|
14
|
+
readonly code: string;
|
|
15
|
+
readonly body?: unknown;
|
|
16
|
+
constructor(message: string, status: number, code: string, body?: unknown);
|
|
17
|
+
}
|
|
18
|
+
/** The license key doesn't exist (`license_not_found`). */
|
|
19
|
+
export declare class InvalidLicenseError extends SendclapError {
|
|
20
|
+
constructor(message: string, body?: unknown);
|
|
21
|
+
}
|
|
22
|
+
/** The key exists but was disabled after a refund or a dispute (`license_disabled`). */
|
|
23
|
+
export declare class DisabledLicenseError extends SendclapError {
|
|
24
|
+
constructor(message: string, body?: unknown);
|
|
25
|
+
}
|
|
26
|
+
/** Every activation of the key is in use; deactivate another instance first (`activation_limit`). */
|
|
27
|
+
export declare class ActivationLimitError extends SendclapError {
|
|
28
|
+
readonly license: LicenseInfo;
|
|
29
|
+
readonly product: ProductRef;
|
|
30
|
+
constructor(message: string, license: LicenseInfo, product: ProductRef, body?: unknown);
|
|
31
|
+
}
|
|
32
|
+
/** Deactivate was called for an instance that isn't activated (`instance_not_found`). */
|
|
33
|
+
export declare class InstanceNotFoundError extends SendclapError {
|
|
34
|
+
constructor(message: string, body?: unknown);
|
|
35
|
+
}
|
|
36
|
+
/** No response: offline, DNS, TLS or timeout. Fall back to your cached validation. */
|
|
37
|
+
export declare class NetworkError extends SendclapError {
|
|
38
|
+
readonly cause?: unknown;
|
|
39
|
+
constructor(message: string, cause?: unknown);
|
|
40
|
+
}
|
|
41
|
+
export interface LicenseInfo {
|
|
42
|
+
key: string;
|
|
43
|
+
activations: number;
|
|
44
|
+
max_activations: number;
|
|
45
|
+
}
|
|
46
|
+
export interface ProductRef {
|
|
47
|
+
id?: number;
|
|
48
|
+
name?: string;
|
|
49
|
+
}
|
|
50
|
+
export interface ActivateResult {
|
|
51
|
+
instance_id: string;
|
|
52
|
+
license: LicenseInfo;
|
|
53
|
+
product: ProductRef;
|
|
54
|
+
}
|
|
55
|
+
export interface DeactivateResult {
|
|
56
|
+
license: LicenseInfo;
|
|
57
|
+
product: ProductRef;
|
|
58
|
+
}
|
|
59
|
+
export interface ValidateResult {
|
|
60
|
+
valid: boolean;
|
|
61
|
+
/** `active`: valid. `not_activated`: the key exists but this instance isn't activated. `invalid`: unknown key. `disabled`: refunded or disputed. */
|
|
62
|
+
status: 'active' | 'not_activated' | 'invalid' | 'disabled';
|
|
63
|
+
license?: LicenseInfo;
|
|
64
|
+
product?: ProductRef;
|
|
65
|
+
}
|
|
66
|
+
export interface CheckoutParams {
|
|
67
|
+
type: 'tip' | 'product' | 'membership';
|
|
68
|
+
/** Tip amount in US dollars, 1 to 10000. */
|
|
69
|
+
amount?: number;
|
|
70
|
+
product_id?: number;
|
|
71
|
+
tier_id?: number;
|
|
72
|
+
/** Required for memberships. */
|
|
73
|
+
email?: string;
|
|
74
|
+
method?: 'card' | 'crypto';
|
|
75
|
+
message?: string;
|
|
76
|
+
}
|
|
77
|
+
export interface Checkout {
|
|
78
|
+
id: string;
|
|
79
|
+
status: string;
|
|
80
|
+
type: string;
|
|
81
|
+
amount: number;
|
|
82
|
+
currency: string;
|
|
83
|
+
method: string;
|
|
84
|
+
email: string | null;
|
|
85
|
+
/** Where to send the customer to pay. */
|
|
86
|
+
url: string;
|
|
87
|
+
}
|
|
88
|
+
export interface Totals {
|
|
89
|
+
payments: number;
|
|
90
|
+
gross: number;
|
|
91
|
+
fees: number;
|
|
92
|
+
net: number;
|
|
93
|
+
}
|
|
94
|
+
export interface Stats {
|
|
95
|
+
handle: string;
|
|
96
|
+
name: string;
|
|
97
|
+
url: string;
|
|
98
|
+
currency: string;
|
|
99
|
+
last_30_days: Totals;
|
|
100
|
+
all_time: Totals;
|
|
101
|
+
members: {
|
|
102
|
+
active: number;
|
|
103
|
+
monthly_recurring: number;
|
|
104
|
+
};
|
|
105
|
+
open_disputes: number;
|
|
106
|
+
}
|
|
107
|
+
/** `limit` is at most 500; `after` is the previous page's `next`. */
|
|
108
|
+
export interface PageParams {
|
|
109
|
+
limit?: number;
|
|
110
|
+
after?: number;
|
|
111
|
+
}
|
|
112
|
+
export interface PaymentFilter extends PageParams {
|
|
113
|
+
status?: string;
|
|
114
|
+
type?: string;
|
|
115
|
+
email?: string;
|
|
116
|
+
}
|
|
117
|
+
export interface LicenseFilter extends PageParams {
|
|
118
|
+
email?: string;
|
|
119
|
+
}
|
|
120
|
+
export interface Page<T> {
|
|
121
|
+
data: T[];
|
|
122
|
+
has_more: boolean;
|
|
123
|
+
next: number | null;
|
|
124
|
+
}
|
|
125
|
+
export interface Payment {
|
|
126
|
+
id: number;
|
|
127
|
+
type: string;
|
|
128
|
+
method: string;
|
|
129
|
+
status: string;
|
|
130
|
+
amount: number;
|
|
131
|
+
fee: number;
|
|
132
|
+
currency: string;
|
|
133
|
+
email: string | null;
|
|
134
|
+
message: string | null;
|
|
135
|
+
reference: string | null;
|
|
136
|
+
test: boolean;
|
|
137
|
+
created_at: string;
|
|
138
|
+
}
|
|
139
|
+
export interface PaymentDetail extends Payment {
|
|
140
|
+
item: string;
|
|
141
|
+
purchase_ip: string | null;
|
|
142
|
+
purchase_device: string | null;
|
|
143
|
+
dispute: {
|
|
144
|
+
id: string;
|
|
145
|
+
status: string;
|
|
146
|
+
reason: string | null;
|
|
147
|
+
respond_by: string | null;
|
|
148
|
+
} | null;
|
|
149
|
+
activity: {
|
|
150
|
+
at: string;
|
|
151
|
+
event: string;
|
|
152
|
+
detail: string | null;
|
|
153
|
+
ip: string | null;
|
|
154
|
+
}[];
|
|
155
|
+
evidence_pdf: string;
|
|
156
|
+
}
|
|
157
|
+
export interface Member {
|
|
158
|
+
email: string;
|
|
159
|
+
tier: string;
|
|
160
|
+
method: string;
|
|
161
|
+
status: string;
|
|
162
|
+
price: number;
|
|
163
|
+
interval: string;
|
|
164
|
+
current_period_ends: string;
|
|
165
|
+
joined_at: string;
|
|
166
|
+
}
|
|
167
|
+
export interface IssuedLicense {
|
|
168
|
+
key: string;
|
|
169
|
+
product: string;
|
|
170
|
+
email: string;
|
|
171
|
+
activations: number;
|
|
172
|
+
max_activations: number;
|
|
173
|
+
disabled: boolean;
|
|
174
|
+
issued_at: string;
|
|
175
|
+
}
|
|
176
|
+
export interface Dispute {
|
|
177
|
+
id: string;
|
|
178
|
+
payment_id: number;
|
|
179
|
+
email: string | null;
|
|
180
|
+
amount: number;
|
|
181
|
+
reason: string | null;
|
|
182
|
+
status: string;
|
|
183
|
+
respond_by: string | null;
|
|
184
|
+
opened_at: string;
|
|
185
|
+
}
|
|
186
|
+
export interface Product {
|
|
187
|
+
id: number;
|
|
188
|
+
name: string;
|
|
189
|
+
description: string;
|
|
190
|
+
price: number;
|
|
191
|
+
currency: string;
|
|
192
|
+
delivers_file: boolean;
|
|
193
|
+
issues_license_key: boolean;
|
|
194
|
+
page: string;
|
|
195
|
+
x402: string | null;
|
|
196
|
+
}
|
|
197
|
+
export interface Membership {
|
|
198
|
+
id: number;
|
|
199
|
+
name: string;
|
|
200
|
+
description: string;
|
|
201
|
+
price: number;
|
|
202
|
+
currency: string;
|
|
203
|
+
interval: string;
|
|
204
|
+
x402: string | null;
|
|
205
|
+
}
|
|
206
|
+
export interface Creator {
|
|
207
|
+
handle: string;
|
|
208
|
+
name: string;
|
|
209
|
+
bio: string;
|
|
210
|
+
url: string;
|
|
211
|
+
avatar: string | null;
|
|
212
|
+
links: {
|
|
213
|
+
label: string;
|
|
214
|
+
url: string;
|
|
215
|
+
}[];
|
|
216
|
+
payment_methods: {
|
|
217
|
+
card: boolean;
|
|
218
|
+
crypto: boolean;
|
|
219
|
+
x402: boolean;
|
|
220
|
+
};
|
|
221
|
+
tip: {
|
|
222
|
+
suggested: number;
|
|
223
|
+
currency: string;
|
|
224
|
+
page: string;
|
|
225
|
+
x402: string | null;
|
|
226
|
+
};
|
|
227
|
+
memberships: Membership[];
|
|
228
|
+
products: Product[];
|
|
229
|
+
}
|
|
230
|
+
/** License checks from the app you ship. Needs no API key. */
|
|
231
|
+
export declare class LicenseClient {
|
|
232
|
+
private options;
|
|
233
|
+
constructor(options?: ClientOptions);
|
|
234
|
+
private call;
|
|
235
|
+
/** Registers this device against the key. Throws InvalidLicenseError, DisabledLicenseError or ActivationLimitError. Activating the same instance twice counts once. The returned instance_id is the name you passed. */
|
|
236
|
+
activate(licenseKey: string, instanceName: string): Promise<ActivateResult>;
|
|
237
|
+
/** Checks the key (and, with an instance id, that this device is activated). Throws only when no definite answer came back. */
|
|
238
|
+
validate(licenseKey: string, instanceId?: string): Promise<ValidateResult>;
|
|
239
|
+
/** Releases a device, freeing one activation. Throws InstanceNotFoundError if it wasn't activated. */
|
|
240
|
+
deactivate(licenseKey: string, instanceId: string): Promise<DeactivateResult>;
|
|
241
|
+
}
|
|
242
|
+
/** The creator REST API. Server side only: never ship an sc_ key inside an app or a web page. */
|
|
243
|
+
export declare class ApiClient {
|
|
244
|
+
private apiKey;
|
|
245
|
+
private options;
|
|
246
|
+
/** `apiKey` may be empty if you only call getCreator. */
|
|
247
|
+
constructor(apiKey: string, options?: ClientOptions);
|
|
248
|
+
private get;
|
|
249
|
+
createCheckout(params: CheckoutParams): Promise<Checkout>;
|
|
250
|
+
getCheckout(id: string): Promise<Checkout>;
|
|
251
|
+
me(): Promise<Stats>;
|
|
252
|
+
listPayments(filter?: PaymentFilter): Promise<Page<Payment>>;
|
|
253
|
+
getPayment(id: number): Promise<PaymentDetail>;
|
|
254
|
+
listMembers(page?: PageParams): Promise<Page<Member>>;
|
|
255
|
+
listLicenses(filter?: LicenseFilter): Promise<Page<IssuedLicense>>;
|
|
256
|
+
listDisputes(page?: PageParams): Promise<Page<Dispute>>;
|
|
257
|
+
/** The auto-paging versions: `for await (const p of api.allPayments({ status: 'paid' }))` follows `next` until the end. */
|
|
258
|
+
allPayments(filter?: PaymentFilter): AsyncGenerator<Payment, any, any>;
|
|
259
|
+
allMembers(page?: PageParams): AsyncGenerator<Member, any, any>;
|
|
260
|
+
allLicenses(filter?: LicenseFilter): AsyncGenerator<IssuedLicense, any, any>;
|
|
261
|
+
allDisputes(page?: PageParams): AsyncGenerator<Dispute, any, any>;
|
|
262
|
+
listProducts(): Promise<Product[]>;
|
|
263
|
+
listMemberships(): Promise<Membership[]>;
|
|
264
|
+
/** Public: works without an API key. */
|
|
265
|
+
getCreator(handle: string): Promise<Creator>;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* A name for this installation: the hostname in Node, Bun, Deno and Electron's main process, and a random id kept in
|
|
269
|
+
* localStorage in browsers. It is sent to Sendclap and shown to the creator; machines sharing a hostname share an activation.
|
|
270
|
+
*/
|
|
271
|
+
export declare function instanceName(): Promise<string>;
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// Sendclap client for JavaScript and TypeScript: license checks for the apps you ship, and the creator REST API for your server.
|
|
2
|
+
// Zero dependencies; uses the global fetch (Node 18+, Bun, Deno, browsers, Electron).
|
|
3
|
+
export const VERSION = '0.2.0';
|
|
4
|
+
const DEFAULT_BASE_URL = 'https://sendclap.com';
|
|
5
|
+
const DEFAULT_TIMEOUT_MS = 15000;
|
|
6
|
+
// ---------- errors ----------
|
|
7
|
+
/**
|
|
8
|
+
* Any failed request. `status` is the HTTP status (0 when no response arrived) and `code` the server's machine-readable
|
|
9
|
+
* code, such as `invalid_api_key` or `not_found` ('' when the reply wasn't a Sendclap error, 'network_error' with no reply).
|
|
10
|
+
*/
|
|
11
|
+
export class SendclapError extends Error {
|
|
12
|
+
constructor(message, status, code, body) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.status = status;
|
|
15
|
+
this.code = code;
|
|
16
|
+
this.body = body;
|
|
17
|
+
this.name = 'SendclapError';
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** The license key doesn't exist (`license_not_found`). */
|
|
21
|
+
export class InvalidLicenseError extends SendclapError {
|
|
22
|
+
constructor(message, body) {
|
|
23
|
+
super(message, 404, 'license_not_found', body);
|
|
24
|
+
this.name = 'InvalidLicenseError';
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** The key exists but was disabled after a refund or a dispute (`license_disabled`). */
|
|
28
|
+
export class DisabledLicenseError extends SendclapError {
|
|
29
|
+
constructor(message, body) {
|
|
30
|
+
super(message, 403, 'license_disabled', body);
|
|
31
|
+
this.name = 'DisabledLicenseError';
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Every activation of the key is in use; deactivate another instance first (`activation_limit`). */
|
|
35
|
+
export class ActivationLimitError extends SendclapError {
|
|
36
|
+
constructor(message, license, product, body) {
|
|
37
|
+
super(message, 409, 'activation_limit', body);
|
|
38
|
+
this.license = license;
|
|
39
|
+
this.product = product;
|
|
40
|
+
this.name = 'ActivationLimitError';
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Deactivate was called for an instance that isn't activated (`instance_not_found`). */
|
|
44
|
+
export class InstanceNotFoundError extends SendclapError {
|
|
45
|
+
constructor(message, body) {
|
|
46
|
+
super(message, 404, 'instance_not_found', body);
|
|
47
|
+
this.name = 'InstanceNotFoundError';
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** No response: offline, DNS, TLS or timeout. Fall back to your cached validation. */
|
|
51
|
+
export class NetworkError extends SendclapError {
|
|
52
|
+
constructor(message, cause) {
|
|
53
|
+
super(message, 0, 'network_error');
|
|
54
|
+
this.cause = cause;
|
|
55
|
+
this.name = 'NetworkError';
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async function request(o, method, path, init = {}) {
|
|
59
|
+
const url = new URL(`${(o.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '')}/api/v1${path}`);
|
|
60
|
+
for (const [k, v] of Object.entries(init.query ?? {}))
|
|
61
|
+
if (v !== undefined && v !== '')
|
|
62
|
+
url.searchParams.set(k, String(v));
|
|
63
|
+
const headers = { accept: 'application/json' };
|
|
64
|
+
// browsers forbid setting User-Agent, so a web page identifies itself with x-sendclap-client instead
|
|
65
|
+
if (typeof globalThis.document === 'undefined')
|
|
66
|
+
headers['user-agent'] = `sendclap-js/${VERSION}`;
|
|
67
|
+
else
|
|
68
|
+
headers['x-sendclap-client'] = `sendclap-js/${VERSION}`;
|
|
69
|
+
if (init.body)
|
|
70
|
+
headers['content-type'] = 'application/json';
|
|
71
|
+
if (init.apiKey)
|
|
72
|
+
headers.authorization = `Bearer ${init.apiKey}`;
|
|
73
|
+
let res, text;
|
|
74
|
+
try {
|
|
75
|
+
res = await fetch(url, { method, headers, body: init.body && JSON.stringify(init.body), signal: AbortSignal.timeout(o.timeout ?? DEFAULT_TIMEOUT_MS) });
|
|
76
|
+
text = await res.text();
|
|
77
|
+
}
|
|
78
|
+
catch (e) {
|
|
79
|
+
throw new NetworkError(e instanceof Error ? e.message : String(e), e);
|
|
80
|
+
}
|
|
81
|
+
let data;
|
|
82
|
+
try {
|
|
83
|
+
data = JSON.parse(text);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
data = undefined;
|
|
87
|
+
}
|
|
88
|
+
if (res.ok) {
|
|
89
|
+
if (data === undefined)
|
|
90
|
+
throw new SendclapError('invalid JSON response', res.status, text);
|
|
91
|
+
return data;
|
|
92
|
+
}
|
|
93
|
+
const message = typeof data?.error === 'string' ? data.error : `HTTP ${res.status}`;
|
|
94
|
+
const code = typeof data?.code === 'string' ? data.code : '';
|
|
95
|
+
if (code === 'license_not_found')
|
|
96
|
+
throw new InvalidLicenseError(message, data);
|
|
97
|
+
if (code === 'license_disabled')
|
|
98
|
+
throw new DisabledLicenseError(message, data);
|
|
99
|
+
if (code === 'instance_not_found')
|
|
100
|
+
throw new InstanceNotFoundError(message, data);
|
|
101
|
+
if (code === 'activation_limit')
|
|
102
|
+
throw new ActivationLimitError(message, data.license, data.product, data);
|
|
103
|
+
throw new SendclapError(message, res.status, code, data ?? text);
|
|
104
|
+
}
|
|
105
|
+
// ---------- clients ----------
|
|
106
|
+
/** License checks from the app you ship. Needs no API key. */
|
|
107
|
+
export class LicenseClient {
|
|
108
|
+
constructor(options = {}) {
|
|
109
|
+
this.options = options;
|
|
110
|
+
}
|
|
111
|
+
call(action, licenseKey, instanceId) {
|
|
112
|
+
return request(this.options, 'POST', `/licenses/${action}`, { body: { license_key: licenseKey, ...(instanceId ? { instance_id: instanceId } : {}) } });
|
|
113
|
+
}
|
|
114
|
+
/** Registers this device against the key. Throws InvalidLicenseError, DisabledLicenseError or ActivationLimitError. Activating the same instance twice counts once. The returned instance_id is the name you passed. */
|
|
115
|
+
async activate(licenseKey, instanceName) {
|
|
116
|
+
const { instance_id, license, product } = await this.call('activate', licenseKey, instanceName);
|
|
117
|
+
return { instance_id, license, product };
|
|
118
|
+
}
|
|
119
|
+
/** Checks the key (and, with an instance id, that this device is activated). Throws only when no definite answer came back. */
|
|
120
|
+
async validate(licenseKey, instanceId) {
|
|
121
|
+
try {
|
|
122
|
+
const { valid, license, product } = await this.call('validate', licenseKey, instanceId);
|
|
123
|
+
return { valid, status: valid ? 'active' : 'not_activated', license, product };
|
|
124
|
+
}
|
|
125
|
+
catch (e) {
|
|
126
|
+
if (e instanceof InvalidLicenseError)
|
|
127
|
+
return { valid: false, status: 'invalid' };
|
|
128
|
+
if (e instanceof DisabledLicenseError)
|
|
129
|
+
return { valid: false, status: 'disabled' };
|
|
130
|
+
throw e;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
/** Releases a device, freeing one activation. Throws InstanceNotFoundError if it wasn't activated. */
|
|
134
|
+
async deactivate(licenseKey, instanceId) {
|
|
135
|
+
const { license, product } = await this.call('deactivate', licenseKey, instanceId);
|
|
136
|
+
return { license, product };
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
async function* paginate(fetchPage) {
|
|
140
|
+
let page = await fetchPage();
|
|
141
|
+
for (;;) {
|
|
142
|
+
yield* page.data;
|
|
143
|
+
if (!page.has_more || page.next === null)
|
|
144
|
+
return;
|
|
145
|
+
page = await fetchPage(page.next);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/** The creator REST API. Server side only: never ship an sc_ key inside an app or a web page. */
|
|
149
|
+
export class ApiClient {
|
|
150
|
+
/** `apiKey` may be empty if you only call getCreator. */
|
|
151
|
+
constructor(apiKey, options = {}) {
|
|
152
|
+
this.apiKey = apiKey;
|
|
153
|
+
this.options = options;
|
|
154
|
+
}
|
|
155
|
+
get(path, query) {
|
|
156
|
+
return request(this.options, 'GET', path, { query, apiKey: this.apiKey });
|
|
157
|
+
}
|
|
158
|
+
createCheckout(params) {
|
|
159
|
+
return request(this.options, 'POST', '/checkouts', { body: params, apiKey: this.apiKey });
|
|
160
|
+
}
|
|
161
|
+
getCheckout(id) { return this.get(`/checkouts/${encodeURIComponent(id)}`); }
|
|
162
|
+
me() { return this.get('/me'); }
|
|
163
|
+
listPayments(filter = {}) { return this.get('/payments', { ...filter }); }
|
|
164
|
+
getPayment(id) { return this.get(`/payments/${encodeURIComponent(id)}`); }
|
|
165
|
+
listMembers(page = {}) { return this.get('/members', { ...page }); }
|
|
166
|
+
listLicenses(filter = {}) { return this.get('/licenses', { ...filter }); }
|
|
167
|
+
listDisputes(page = {}) { return this.get('/disputes', { ...page }); }
|
|
168
|
+
/** The auto-paging versions: `for await (const p of api.allPayments({ status: 'paid' }))` follows `next` until the end. */
|
|
169
|
+
allPayments(filter = {}) { return paginate(after => this.listPayments({ ...filter, after })); }
|
|
170
|
+
allMembers(page = {}) { return paginate(after => this.listMembers({ ...page, after })); }
|
|
171
|
+
allLicenses(filter = {}) { return paginate(after => this.listLicenses({ ...filter, after })); }
|
|
172
|
+
allDisputes(page = {}) { return paginate(after => this.listDisputes({ ...page, after })); }
|
|
173
|
+
listProducts() { return this.get('/products'); }
|
|
174
|
+
listMemberships() { return this.get('/memberships'); }
|
|
175
|
+
/** Public: works without an API key. */
|
|
176
|
+
getCreator(handle) { return this.get(`/creators/${encodeURIComponent(handle)}`); }
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* A name for this installation: the hostname in Node, Bun, Deno and Electron's main process, and a random id kept in
|
|
180
|
+
* localStorage in browsers. It is sent to Sendclap and shown to the creator; machines sharing a hostname share an activation.
|
|
181
|
+
*/
|
|
182
|
+
export async function instanceName() {
|
|
183
|
+
var _a;
|
|
184
|
+
const g = globalThis;
|
|
185
|
+
if (g.Deno?.hostname)
|
|
186
|
+
return g.Deno.hostname();
|
|
187
|
+
if (g.process?.versions?.node) {
|
|
188
|
+
const id = 'node:os'; // a variable keeps browser bundlers from trying to resolve it
|
|
189
|
+
const os = g.process.getBuiltinModule?.(id) ?? await import(/* webpackIgnore: true */ /* @vite-ignore */ id);
|
|
190
|
+
return os.hostname();
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
return ((_a = g.localStorage).sendclap_instance ?? (_a.sendclap_instance = g.crypto.randomUUID()));
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
return g.crypto.randomUUID();
|
|
197
|
+
}
|
|
198
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sendclap",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
}
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Official Sendclap client: license key checks for the apps you ship and the creator REST API.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": { "type": "git", "url": "git+https://github.com/backmeupplz/sendclap-sdk.git", "directory": "js" },
|
|
7
|
+
"homepage": "https://sendclap.com/docs",
|
|
8
|
+
"keywords": ["sendclap", "license", "license-key", "payments", "creators"],
|
|
9
|
+
"type": "module",
|
|
10
|
+
"main": "./dist/cjs/index.js",
|
|
11
|
+
"module": "./dist/esm/index.js",
|
|
12
|
+
"types": "./dist/esm/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"import": { "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" },
|
|
16
|
+
"require": { "types": "./dist/cjs/index.d.ts", "default": "./dist/cjs/index.js" }
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": ["dist"],
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"engines": { "node": ">=18" },
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build": "tsc -p tsconfig.json && tsc -p tsconfig.cjs.json && echo '{\"type\":\"commonjs\"}' > dist/cjs/package.json",
|
|
24
|
+
"test": "npm run build && node --test test/sendclap.test.mjs",
|
|
25
|
+
"prepublishOnly": "npm test"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"typescript": "^7.0.2"
|
|
29
|
+
}
|
|
30
|
+
}
|