@billionaire-sh/node-sdk 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 +21 -0
- package/README.md +254 -2
- package/dist/client.cjs +315 -0
- package/dist/client.d.cts +1190 -0
- package/dist/client.d.mts +1190 -0
- package/dist/client.mjs +313 -0
- package/dist/schemas.cjs +3800 -0
- package/dist/schemas.d.cts +3977 -0
- package/dist/schemas.d.mts +3977 -0
- package/dist/schemas.mjs +3798 -0
- package/package.json +62 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Kolaveri Labs
|
|
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,255 @@
|
|
|
1
|
-
#
|
|
1
|
+
# billionaire Node.js SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A TypeScript-first Node.js SDK for integrating with billionaire, the accounting and tax platform. This SDK provides a simple, type-safe interface to the billionaire API: the invoices an entity issues, its bookkeeping, and everything else billionaire keeps for it.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
billionaire keeps the books of an entity — its invoices, bookings, payments and tax returns. Other platforms do not invoice on their own: they hand what they charged to billionaire through this SDK, and the entity that owns the platform issues its invoice, books the revenue and settles the payment, all with billionaire's one invoicing engine. The platforms stay loosely coupled: they know billionaire only through its API and this SDK.
|
|
8
|
+
|
|
9
|
+
### Key Features
|
|
10
|
+
|
|
11
|
+
- 🔐 **OAuth2 Authentication** - Secure client credentials flow with automatic token management
|
|
12
|
+
- 🏢 **Multi-Tenant Support** - Every call acts for one entity; a robot account is granted the entities it may act for
|
|
13
|
+
- 📝 **TypeScript Support** - Full TypeScript support with auto-generated types from OpenAPI spec
|
|
14
|
+
- 🔄 **Auto Token Refresh** - Automatic token renewal with 5-minute buffer before expiration
|
|
15
|
+
- 🎯 **Type-Safe API** - OpenAPI-generated types ensure type safety across all operations
|
|
16
|
+
- ⚡ **Modern Architecture** - Built with ES modules and CommonJS dual support
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install @billionaire-sh/node-sdk
|
|
22
|
+
# or
|
|
23
|
+
yarn add @billionaire-sh/node-sdk
|
|
24
|
+
# or
|
|
25
|
+
pnpm add @billionaire-sh/node-sdk
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Quick Start
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
import { BLNRClient } from '@billionaire-sh/node-sdk'
|
|
32
|
+
|
|
33
|
+
// Initialize the client
|
|
34
|
+
const client = new BLNRClient({
|
|
35
|
+
clientId: 'your-client-id',
|
|
36
|
+
clientSecret: 'your-client-secret',
|
|
37
|
+
entityId: 'your-entity-id', // Optional - will use default from token if not provided
|
|
38
|
+
baseUrl: 'https://billionaire.sh/api', // Optional - defaults to production
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
// `platformInvoices` is the platform's own API (`/platform/invoices`): it
|
|
42
|
+
// acts for the entity that owns the platform, so the robot needs its grant
|
|
43
|
+
// there — `entityId` plays no part in it.
|
|
44
|
+
|
|
45
|
+
// Before charging: the invoice the entity would issue, nothing issued
|
|
46
|
+
const preview = await client.platformInvoices.preview({
|
|
47
|
+
currency: 'EUR',
|
|
48
|
+
issuedAt: new Date().toISOString(),
|
|
49
|
+
grossAmount: 11781,
|
|
50
|
+
lines: [/* … each line's net, tax and rate, as it will be charged */],
|
|
51
|
+
})
|
|
52
|
+
// preview.invoice?.netAmount, .taxAmount, .grossAmount, .byRate, .lines
|
|
53
|
+
|
|
54
|
+
// The platform charged a customer: the entity issues its invoice for it
|
|
55
|
+
const { outcome, invoiceId } = await client.platformInvoices.process({
|
|
56
|
+
platform: 'order3000',
|
|
57
|
+
stripeInvoiceId: 'in_1QxYz…',
|
|
58
|
+
// … the customer, the lines and the totals the platform charged
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
// Paid, voided and credited invoices follow the same way
|
|
62
|
+
await client.platformInvoices.processPayment('in_1QxYz…', { /* … */ })
|
|
63
|
+
await client.platformInvoices.processVoid('in_1QxYz…', { voidedAt })
|
|
64
|
+
await client.platformInvoices.processCredit('in_1QxYz…', {
|
|
65
|
+
stripeCreditNoteId: 'cn_1QxYz…',
|
|
66
|
+
creditedAt,
|
|
67
|
+
grossAmount: 11781,
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
// The platform's invoices the entity still shows as unpaid, for a
|
|
71
|
+
// follow-up that asks the payment provider about each
|
|
72
|
+
const open = await client.platformInvoices.listOpen({
|
|
73
|
+
filters: { platform: 'order3000' },
|
|
74
|
+
pagination: { page: 1, pageSize: 100 },
|
|
75
|
+
})
|
|
76
|
+
for (const invoice of open) console.log(invoice.stripeInvoiceId)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Type naming convention
|
|
80
|
+
|
|
81
|
+
Every exported name in this SDK carries a **`BLNR`** prefix
|
|
82
|
+
(`BLNRClient`, `BLNRProcessPlatformInvoiceRequest`, …). The prefix
|
|
83
|
+
namespaces the SDK surface so consumer code never has to alias imports to
|
|
84
|
+
disambiguate them from local domain types:
|
|
85
|
+
|
|
86
|
+
```typescript
|
|
87
|
+
// no `as SDKFoo` aliasing needed — the name is already namespaced
|
|
88
|
+
import type { BLNRProcessPlatformInvoiceRequest } from '@billionaire-sh/node-sdk'
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Architecture
|
|
92
|
+
|
|
93
|
+
### Authentication Flow
|
|
94
|
+
|
|
95
|
+
The SDK uses OAuth2 client credentials flow for authentication:
|
|
96
|
+
|
|
97
|
+
1. **Initial Authentication**: On first use, the SDK requests an access token using your client credentials
|
|
98
|
+
2. **Token Storage**: The access token is stored in memory with its expiration time
|
|
99
|
+
3. **Automatic Refresh**: Tokens are automatically refreshed 5 minutes before expiration
|
|
100
|
+
4. **Entity Resolution**: If no entity ID is provided, the SDK extracts the default entity from the JWT token
|
|
101
|
+
|
|
102
|
+
### Project Structure
|
|
103
|
+
|
|
104
|
+
```
|
|
105
|
+
billionaire-node-sdk/
|
|
106
|
+
├── src/
|
|
107
|
+
│ ├── client.ts # Main client class and initialization
|
|
108
|
+
│ ├── token-manager.ts # OAuth2 token management and refresh logic
|
|
109
|
+
│ ├── resources/
|
|
110
|
+
│ │ ├── index.ts # Base resource class for API calls
|
|
111
|
+
│ │ └── platformInvoices.ts # Platform invoices resource implementation
|
|
112
|
+
│ └── types/
|
|
113
|
+
│ ├── index.ts # Type exports
|
|
114
|
+
│ └── generated.d.ts # Auto-generated types from OpenAPI spec
|
|
115
|
+
├── scripts/
|
|
116
|
+
│ ├── dev.sh # Development script with Vault integration
|
|
117
|
+
│ └── vaultcar.sh # HashiCorp Vault integration for secrets
|
|
118
|
+
└── package.json
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Configuration
|
|
122
|
+
|
|
123
|
+
### Client Options
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
interface BLNRClientConfig {
|
|
127
|
+
clientId: string // OAuth2 client ID (required)
|
|
128
|
+
clientSecret: string // OAuth2 client secret (required)
|
|
129
|
+
entityId?: string // Specific entity ID (optional)
|
|
130
|
+
baseUrl?: string // Base URL for API requests (default: https://billionaire.sh/api)
|
|
131
|
+
tokenUrl?: string // OAuth2 token endpoint (default: ${baseUrl}/m2m/token)
|
|
132
|
+
}
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### Environment Variables
|
|
136
|
+
|
|
137
|
+
For development, you can use environment variables:
|
|
138
|
+
|
|
139
|
+
```bash
|
|
140
|
+
BILLIONAIRE_CLIENT_ID=your-client-id
|
|
141
|
+
BILLIONAIRE_CLIENT_SECRET=your-client-secret
|
|
142
|
+
BILLIONAIRE_BASE_URL=https://billionaire.sh/api
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## API Documentation
|
|
146
|
+
|
|
147
|
+
The OpenAPI document is served by billionaire itself:
|
|
148
|
+
|
|
149
|
+
- **Development**: http://localhost:8000/api/openapi
|
|
150
|
+
- **Staging**: https://staging.billionaire.sh/api/openapi
|
|
151
|
+
- **Production**: https://billionaire.sh/api/openapi
|
|
152
|
+
|
|
153
|
+
## SDK Development Workflow
|
|
154
|
+
|
|
155
|
+
### Adding New API Endpoints
|
|
156
|
+
|
|
157
|
+
When new endpoints are added or modified in billionaire, follow this workflow to update the SDK:
|
|
158
|
+
|
|
159
|
+
1. **Define API Contracts**: Create or update TypeScript contracts that define the API structure
|
|
160
|
+
- Add/modify contracts in `/apps/billionaire/billionaire/src/app/api/openapi/contracts/`
|
|
161
|
+
- Use `@ts-rest/core` to define type-safe contracts
|
|
162
|
+
- Export contracts from `/apps/billionaire/billionaire/src/app/api/openapi/contract.ts`
|
|
163
|
+
- Write the OpenAPI document: `npm run build:openapi-json` in `apps/billionaire/billionaire`
|
|
164
|
+
|
|
165
|
+
2. **Implement API Endpoints**: Create the actual endpoint logic in billionaire
|
|
166
|
+
- Implement handlers in `/apps/billionaire/billionaire/src/app/api/entities/[entityIdOrAccessor]/` following the contract definitions — or, for the platform's own API, in `/apps/billionaire/billionaire/src/app/api/platform/`, which acts for the entity that owns the platform (its resource overrides `rootPath()`)
|
|
167
|
+
- Each handler is a thin proxy over a server action declaring `permissions: ['iam:robot', …]`
|
|
168
|
+
- Ensure endpoints match the contracts exactly
|
|
169
|
+
|
|
170
|
+
3. **Update SDK Resources**: Integrate the new endpoints into the SDK
|
|
171
|
+
- Create or update resource classes in `/libs/billionaire/node-sdk/src/resources/`
|
|
172
|
+
- Follow the existing pattern extending from `BaseResource`
|
|
173
|
+
- Export new resources from the main `BLNRClient` class
|
|
174
|
+
- After the OpenAPI document changed, run `npm run generate` (types and zod schemas) and keep the result: the generated files are tracked
|
|
175
|
+
- `npm run build` only bundles — it never rewrites `src`, so a checkout that merely builds the SDK stays clean; publishing (`prepack`) generates first
|
|
176
|
+
|
|
177
|
+
4. **Create Changeset**: Document the changes
|
|
178
|
+
|
|
179
|
+
```bash
|
|
180
|
+
pnpm changeset
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
- Select `billionaire` package
|
|
184
|
+
- Choose version bump type (patch/minor/major)
|
|
185
|
+
- Describe the new endpoints or changes added
|
|
186
|
+
|
|
187
|
+
### Local Development
|
|
188
|
+
|
|
189
|
+
```bash
|
|
190
|
+
# Generate types and zod schemas from the OpenAPI spec (tracked files)
|
|
191
|
+
npm run generate
|
|
192
|
+
|
|
193
|
+
# Bundle the package locally (does not regenerate)
|
|
194
|
+
npm run build
|
|
195
|
+
|
|
196
|
+
# Test SDK in development mode
|
|
197
|
+
npm run dev
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### Development with Vault
|
|
201
|
+
|
|
202
|
+
The SDK includes HashiCorp Vault integration for secure credential management:
|
|
203
|
+
|
|
204
|
+
```bash
|
|
205
|
+
# Run with Vault integration
|
|
206
|
+
npm run dev
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
Credentials are fetched from:
|
|
210
|
+
|
|
211
|
+
- `secret/order3000/BILLIONAIRE_CLIENT_ID`
|
|
212
|
+
- `secret/order3000/BILLIONAIRE_CLIENT_SECRET`
|
|
213
|
+
- `secret/order3000/BILLIONAIRE_BASE_URL`
|
|
214
|
+
|
|
215
|
+
## Security Considerations
|
|
216
|
+
|
|
217
|
+
1. **Never commit credentials** - Always use environment variables or secret management systems
|
|
218
|
+
2. **Token Security** - Access tokens are stored in memory only, never persisted to disk
|
|
219
|
+
3. **HTTPS Only** - All API calls are made over HTTPS
|
|
220
|
+
4. **Automatic Token Rotation** - Tokens are refreshed automatically before expiration
|
|
221
|
+
|
|
222
|
+
## Error Handling
|
|
223
|
+
|
|
224
|
+
A failed call throws an `Error` whose message starts with the HTTP status and carries the response body:
|
|
225
|
+
|
|
226
|
+
```typescript
|
|
227
|
+
try {
|
|
228
|
+
await client.platformInvoices.process(request)
|
|
229
|
+
} catch (error) {
|
|
230
|
+
// "HTTP 400: Bad Request — {"error":"…"}"
|
|
231
|
+
console.error(error)
|
|
232
|
+
}
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
## Platform Integration
|
|
236
|
+
|
|
237
|
+
### Multi-Tenant Architecture
|
|
238
|
+
|
|
239
|
+
Every call acts for one entity:
|
|
240
|
+
|
|
241
|
+
- **Automatic Entity Resolution**: If no entity ID is provided, the SDK uses the default entity from the authentication token
|
|
242
|
+
- **Explicit Entity Selection**: You can specify an entity ID in the client configuration
|
|
243
|
+
- **Entity Isolation**: All operations are scoped to the specified entity, and a robot account acts only for the entities it is granted
|
|
244
|
+
|
|
245
|
+
## Contributing
|
|
246
|
+
|
|
247
|
+
This SDK is part of the Kolaveri monorepo. Development follows the monorepo conventions:
|
|
248
|
+
|
|
249
|
+
1. Follow TypeScript strict mode
|
|
250
|
+
2. Run linting before commits: `npx nx lint billionaire-node-sdk`
|
|
251
|
+
3. Generate types from OpenAPI spec when API changes
|
|
252
|
+
|
|
253
|
+
## License
|
|
254
|
+
|
|
255
|
+
Part of the Kolaveri platform - see root repository for license information.
|
package/dist/client.cjs
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var __defProp$1 = Object.defineProperty;
|
|
4
|
+
var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
5
|
+
var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
6
|
+
class TokenManager {
|
|
7
|
+
constructor(clientId, clientSecret, tokenEndpoint, userEntityId) {
|
|
8
|
+
this.clientId = clientId;
|
|
9
|
+
this.clientSecret = clientSecret;
|
|
10
|
+
this.tokenEndpoint = tokenEndpoint;
|
|
11
|
+
this.userEntityId = userEntityId;
|
|
12
|
+
__publicField$1(this, "accessToken", null);
|
|
13
|
+
__publicField$1(this, "tokenExpiresAt", 0);
|
|
14
|
+
__publicField$1(this, "refreshPromise", null);
|
|
15
|
+
__publicField$1(this, "defaultEntityId");
|
|
16
|
+
}
|
|
17
|
+
async initialize() {
|
|
18
|
+
await this.refreshToken();
|
|
19
|
+
}
|
|
20
|
+
async getToken() {
|
|
21
|
+
if (this.accessToken && Date.now() < this.tokenExpiresAt - 3e5) {
|
|
22
|
+
return this.accessToken;
|
|
23
|
+
}
|
|
24
|
+
return this.refreshToken();
|
|
25
|
+
}
|
|
26
|
+
getEntityId() {
|
|
27
|
+
if (this.userEntityId) {
|
|
28
|
+
return this.userEntityId;
|
|
29
|
+
}
|
|
30
|
+
if (!this.defaultEntityId) {
|
|
31
|
+
throw new Error(
|
|
32
|
+
"No entity ID available. The robot account may not be associated with any entities."
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
return this.defaultEntityId;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Async counterpart to {@link getEntityId}. Fetches the token if it
|
|
39
|
+
* hasn't been loaded yet (which is what populates `defaultEntityId` via
|
|
40
|
+
* `setDefaultEntityId`), then returns the entity id.
|
|
41
|
+
*
|
|
42
|
+
* Prefer this over `getEntityId()` from request paths — a cold SDK
|
|
43
|
+
* instance will otherwise synchronously throw "No entity ID available"
|
|
44
|
+
* before the token has had a chance to load.
|
|
45
|
+
*/
|
|
46
|
+
async getEntityIdAsync() {
|
|
47
|
+
if (this.userEntityId) {
|
|
48
|
+
return this.userEntityId;
|
|
49
|
+
}
|
|
50
|
+
if (!this.defaultEntityId) {
|
|
51
|
+
await this.getToken();
|
|
52
|
+
}
|
|
53
|
+
return this.getEntityId();
|
|
54
|
+
}
|
|
55
|
+
async refreshToken() {
|
|
56
|
+
if (this.refreshPromise) return this.refreshPromise;
|
|
57
|
+
this.refreshPromise = fetch(this.tokenEndpoint, {
|
|
58
|
+
method: "POST",
|
|
59
|
+
headers: { "Content-Type": "application/json" },
|
|
60
|
+
body: JSON.stringify({
|
|
61
|
+
clientId: this.clientId,
|
|
62
|
+
clientSecret: this.clientSecret
|
|
63
|
+
}),
|
|
64
|
+
signal: AbortSignal.timeout(36e4)
|
|
65
|
+
}).then(async (response) => {
|
|
66
|
+
if (!response.ok) {
|
|
67
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
68
|
+
}
|
|
69
|
+
return response.json();
|
|
70
|
+
}).then((data) => {
|
|
71
|
+
this.accessToken = data.accessToken;
|
|
72
|
+
this.tokenExpiresAt = Date.now() + data.expiresIn * 1e3;
|
|
73
|
+
this.setDefaultEntityId();
|
|
74
|
+
return this.accessToken;
|
|
75
|
+
}).catch((error) => {
|
|
76
|
+
throw error;
|
|
77
|
+
}).finally(() => {
|
|
78
|
+
this.refreshPromise = null;
|
|
79
|
+
});
|
|
80
|
+
return this.refreshPromise;
|
|
81
|
+
}
|
|
82
|
+
setDefaultEntityId() {
|
|
83
|
+
if (this.userEntityId || !this.accessToken) return;
|
|
84
|
+
try {
|
|
85
|
+
const [, payload] = this.accessToken.split(".");
|
|
86
|
+
const decoded = JSON.parse(
|
|
87
|
+
Buffer.from(payload, "base64").toString()
|
|
88
|
+
);
|
|
89
|
+
if (!decoded.entities || decoded.entities.length === 0) {
|
|
90
|
+
this.defaultEntityId = void 0;
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
this.defaultEntityId = decoded.entities[0];
|
|
94
|
+
} catch {
|
|
95
|
+
throw new Error("Failed to parse entity ID from token");
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
class BaseResource {
|
|
101
|
+
constructor(tokenManager, baseUrl, resourcePath) {
|
|
102
|
+
this.tokenManager = tokenManager;
|
|
103
|
+
this.baseUrl = baseUrl;
|
|
104
|
+
this.resourcePath = resourcePath;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* What the resource's path hangs below: the robot's entity
|
|
108
|
+
* (`/entities/{entityId}`). A resource of the platform's own API, which
|
|
109
|
+
* acts for the entity that owns the platform, overrides it (KLVR-2229).
|
|
110
|
+
* Read after the token is fetched — the entity id comes with it.
|
|
111
|
+
*/
|
|
112
|
+
rootPath() {
|
|
113
|
+
return `/entities/${this.tokenManager.getEntityId()}`;
|
|
114
|
+
}
|
|
115
|
+
async request(method, path, data, cacheOptions) {
|
|
116
|
+
const token = await this.tokenManager.getToken();
|
|
117
|
+
const url = `${this.baseUrl}${this.rootPath()}${this.resourcePath}${path}`;
|
|
118
|
+
const init = {
|
|
119
|
+
method,
|
|
120
|
+
headers: {
|
|
121
|
+
Authorization: `Bearer ${token}`,
|
|
122
|
+
"Content-Type": "application/json"
|
|
123
|
+
},
|
|
124
|
+
body: data ? JSON.stringify(data) : void 0,
|
|
125
|
+
signal: AbortSignal.timeout(36e4),
|
|
126
|
+
cache: cacheOptions?.cache ?? "no-store",
|
|
127
|
+
...cacheOptions?.next ? { next: cacheOptions.next } : {}
|
|
128
|
+
};
|
|
129
|
+
const response = await fetch(url, init);
|
|
130
|
+
if (!response.ok) {
|
|
131
|
+
let body = "";
|
|
132
|
+
try {
|
|
133
|
+
body = await response.text();
|
|
134
|
+
} catch {
|
|
135
|
+
}
|
|
136
|
+
throw new Error(
|
|
137
|
+
`HTTP ${response.status}: ${response.statusText}${body ? ` \u2014 ${body}` : ""}`
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
return response.json();
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Multipart counterpart to `request`. Skips the JSON Content-Type
|
|
144
|
+
* default — `fetch` sets `multipart/form-data; boundary=…`
|
|
145
|
+
* automatically when the body is a `FormData`. Use for binary uploads.
|
|
146
|
+
*/
|
|
147
|
+
async requestMultipart(method, path, formData) {
|
|
148
|
+
const token = await this.tokenManager.getToken();
|
|
149
|
+
const url = `${this.baseUrl}${this.rootPath()}${this.resourcePath}${path}`;
|
|
150
|
+
const response = await fetch(url, {
|
|
151
|
+
method,
|
|
152
|
+
headers: {
|
|
153
|
+
Authorization: `Bearer ${token}`
|
|
154
|
+
// Intentionally NO Content-Type — fetch sets the boundary.
|
|
155
|
+
},
|
|
156
|
+
body: formData,
|
|
157
|
+
cache: "no-store",
|
|
158
|
+
signal: AbortSignal.timeout(36e4)
|
|
159
|
+
});
|
|
160
|
+
if (!response.ok) {
|
|
161
|
+
let body = "";
|
|
162
|
+
try {
|
|
163
|
+
body = await response.text();
|
|
164
|
+
} catch {
|
|
165
|
+
}
|
|
166
|
+
throw new Error(
|
|
167
|
+
`HTTP ${response.status}: ${response.statusText}${body ? ` \u2014 ${body}` : ""}`
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
return response.json();
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
class PlatformInvoicesResource extends BaseResource {
|
|
175
|
+
constructor(tokenManager, baseUrl) {
|
|
176
|
+
super(tokenManager, baseUrl, "/invoices");
|
|
177
|
+
}
|
|
178
|
+
rootPath() {
|
|
179
|
+
return "/platform";
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Hand over what the platform invoiced one of its customers; the entity
|
|
183
|
+
* issues its own invoice for it. Idempotent on `stripeInvoiceId`.
|
|
184
|
+
* @param request - The platform's invoice, its lines and its customer
|
|
185
|
+
* @returns What became of it, and the entity's invoice once issued
|
|
186
|
+
*/
|
|
187
|
+
async process(request) {
|
|
188
|
+
return this.request("POST", "", request);
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* The tax the entity puts on what the platform charges each of these
|
|
192
|
+
* customers — by country and whether it is a consumer — so the payment
|
|
193
|
+
* provider charges exactly what the entity's invoice will say. The
|
|
194
|
+
* platform computes no tax of its own.
|
|
195
|
+
* @param request - The customers, each with the platform's own key
|
|
196
|
+
* @returns Each key's tax, null where the entity charges none
|
|
197
|
+
*/
|
|
198
|
+
async chargeTaxes(request) {
|
|
199
|
+
return this.request(
|
|
200
|
+
"POST",
|
|
201
|
+
"/charge-taxes",
|
|
202
|
+
request
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Preview the invoice the entity would issue for what the platform is
|
|
207
|
+
* about to charge — composed by billionaire's invoicing engine exactly as
|
|
208
|
+
* `process` issues it, nothing issued.
|
|
209
|
+
* @param request - The lines to charge, their currency, the day and the
|
|
210
|
+
* total the payment provider will charge
|
|
211
|
+
* @returns The invoice's net, VAT per rate, gross and lines — or why the
|
|
212
|
+
* entity would issue none
|
|
213
|
+
*/
|
|
214
|
+
async preview(request) {
|
|
215
|
+
return this.request(
|
|
216
|
+
"POST",
|
|
217
|
+
"/preview",
|
|
218
|
+
request
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* The platform's invoices the entity's books still show as unpaid, the
|
|
223
|
+
* oldest first, a page at a time — for a follow-up that asks the payment
|
|
224
|
+
* provider about each and hands a payment or void it missed back through
|
|
225
|
+
* `processPayment` / `processVoid`.
|
|
226
|
+
* @param request - The platform (`filters.platform`) and the page
|
|
227
|
+
* @returns Each invoice with the payment provider's id of the platform's
|
|
228
|
+
* invoice it documents
|
|
229
|
+
*/
|
|
230
|
+
async listOpen(request) {
|
|
231
|
+
return this.request(
|
|
232
|
+
"POST",
|
|
233
|
+
"/open",
|
|
234
|
+
request
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Get the entity's invoice for a platform invoice.
|
|
239
|
+
* @param stripeInvoiceId - The payment provider's id of the platform's invoice
|
|
240
|
+
* @returns The invoice's number, state and amounts
|
|
241
|
+
*/
|
|
242
|
+
async get(stripeInvoiceId) {
|
|
243
|
+
return this.request(
|
|
244
|
+
"GET",
|
|
245
|
+
`/${encodeURIComponent(stripeInvoiceId)}`
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Hand over that a platform invoice was paid; the entity records the
|
|
250
|
+
* money and settles its invoice. Idempotent on `stripeInvoiceId`.
|
|
251
|
+
* @param stripeInvoiceId - The payment provider's id of the paid invoice
|
|
252
|
+
* @param request - When it was paid, and how much
|
|
253
|
+
*/
|
|
254
|
+
async processPayment(stripeInvoiceId, request) {
|
|
255
|
+
return this.request(
|
|
256
|
+
"POST",
|
|
257
|
+
`/${encodeURIComponent(stripeInvoiceId)}/payments`,
|
|
258
|
+
request
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Hand over that the payment provider voided a platform invoice; the
|
|
263
|
+
* entity cancels its invoice for it.
|
|
264
|
+
* @param stripeInvoiceId - The payment provider's id of the voided invoice
|
|
265
|
+
* @param request - When it was voided
|
|
266
|
+
*/
|
|
267
|
+
async processVoid(stripeInvoiceId, request) {
|
|
268
|
+
return this.request(
|
|
269
|
+
"POST",
|
|
270
|
+
`/${encodeURIComponent(stripeInvoiceId)}/void`,
|
|
271
|
+
request
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Hand over a credit note the payment provider issued for a platform
|
|
276
|
+
* invoice — money back to the card, a credit on the customer's balance.
|
|
277
|
+
* One for all of it cancels the entity's invoice, and what the customer
|
|
278
|
+
* had paid becomes their credit; one for part of it is answered
|
|
279
|
+
* `partial_credit` and changes nothing.
|
|
280
|
+
* @param stripeInvoiceId - The payment provider's id of the credited invoice
|
|
281
|
+
* @param request - The credit note, when it was issued and what it takes back
|
|
282
|
+
*/
|
|
283
|
+
async processCredit(stripeInvoiceId, request) {
|
|
284
|
+
return this.request(
|
|
285
|
+
"POST",
|
|
286
|
+
`/${encodeURIComponent(stripeInvoiceId)}/credit`,
|
|
287
|
+
request
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
var __defProp = Object.defineProperty;
|
|
293
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
294
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
295
|
+
class BLNRClient {
|
|
296
|
+
constructor(config) {
|
|
297
|
+
__publicField(this, "platformInvoices");
|
|
298
|
+
__publicField(this, "baseUrl");
|
|
299
|
+
__publicField(this, "tokenManager");
|
|
300
|
+
this.baseUrl = config.baseUrl || "https://billionaire.sh/api";
|
|
301
|
+
const tokenUrl = config.tokenUrl || `${this.baseUrl}/m2m/token`;
|
|
302
|
+
this.tokenManager = new TokenManager(
|
|
303
|
+
config.clientId,
|
|
304
|
+
config.clientSecret,
|
|
305
|
+
tokenUrl,
|
|
306
|
+
config.entityId
|
|
307
|
+
);
|
|
308
|
+
this.platformInvoices = new PlatformInvoicesResource(
|
|
309
|
+
this.tokenManager,
|
|
310
|
+
this.baseUrl
|
|
311
|
+
);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
exports.BLNRClient = BLNRClient;
|