@vrplatform/hyperline-client 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/build/main/client.d.ts +812 -0
  2. package/build/main/client.js +187 -0
  3. package/build/main/client.js.map +1 -0
  4. package/build/main/const.d.ts +24 -0
  5. package/build/main/const.js +209 -1
  6. package/build/main/const.js.map +1 -1
  7. package/build/main/hooks.d.ts +10 -0
  8. package/build/main/hooks.js +13 -0
  9. package/build/main/hooks.js.map +1 -0
  10. package/build/main/index.d.ts +3 -867
  11. package/build/main/index.js +3 -217
  12. package/build/main/index.js.map +1 -1
  13. package/build/main/tsconfig.main.tsbuildinfo +1 -1
  14. package/build/main/types.d.ts +35 -0
  15. package/build/main/types.js +2 -0
  16. package/build/main/types.js.map +1 -0
  17. package/build/main/utils.d.ts +1 -0
  18. package/build/main/utils.js +6 -0
  19. package/build/main/utils.js.map +1 -0
  20. package/build/module/client.d.ts +812 -0
  21. package/build/module/client.js +189 -0
  22. package/build/module/client.js.map +1 -0
  23. package/build/module/const.d.ts +24 -0
  24. package/build/module/const.js +209 -1
  25. package/build/module/const.js.map +1 -1
  26. package/build/module/hooks.d.ts +10 -0
  27. package/build/module/hooks.js +13 -0
  28. package/build/module/hooks.js.map +1 -0
  29. package/build/module/index.d.ts +3 -867
  30. package/build/module/index.js +3 -219
  31. package/build/module/index.js.map +1 -1
  32. package/build/module/tsconfig.esm.tsbuildinfo +1 -1
  33. package/build/module/types.d.ts +35 -0
  34. package/build/module/types.js +2 -0
  35. package/build/module/types.js.map +1 -0
  36. package/build/module/utils.d.ts +1 -0
  37. package/build/module/utils.js +6 -0
  38. package/build/module/utils.js.map +1 -0
  39. package/package.json +1 -1
  40. package/src/client.ts +362 -0
  41. package/src/const.ts +225 -1
  42. package/src/hooks.ts +24 -0
  43. package/src/index.ts +3 -445
  44. package/src/types.ts +43 -0
  45. package/src/utils.ts +5 -0
package/src/index.ts CHANGED
@@ -1,446 +1,4 @@
1
- import { utc } from '@finalytic/utils';
2
- import type { TrackingEvent } from '@vrplatform/log';
3
- import type { components, operations, paths } from './_types.generated';
4
-
5
- export type HyperlineEntities = components['schemas'];
6
- export type HyperlineEndpoints = paths;
7
-
8
1
  export * from './const';
9
-
10
- export const webhooks = {
11
- 'payment_method.created': 'hyperline_payment_method_created',
12
- 'payment_method.errored': 'hyperline_payment_method_errored',
13
- 'payment_method.deleted': 'hyperline_payment_method_deleted',
14
- 'subscription.activated': 'hyperline_subscription_status_changed',
15
- 'subscription.reactivated': 'hyperline_subscription_status_changed',
16
- 'subscription.cancelled': 'hyperline_subscription_status_changed',
17
- 'subscription.cancellation_scheduled':
18
- 'hyperline_subscription_cancellation_scheduled',
19
- // 'subscription.created': 'hyperline_subscription_created',
20
- 'subscription.errored': 'hyperline_subscription_status_changed',
21
- 'subscription.paused': 'hyperline_subscription_status_changed',
22
- 'subscription.voided': 'hyperline_subscription_status_changed',
23
- // 'subscription.charged': 'hyperline_subscription_charged',
24
- 'customer.created': 'hyperline_customer_created',
25
- 'customer.updated': 'hyperline_customer_updated',
26
- } satisfies Record<string, TrackingEvent>;
27
-
28
- export type HyperlineWebhook = keyof typeof webhooks;
29
- export type HyperlineEvent<T extends HyperlineWebhook> = (typeof webhooks)[T];
30
- export type HyperlinePayload<T extends HyperlineWebhook> = {
31
- event_type: T;
32
- data: Record<string, any>;
33
- };
34
-
35
- export type BillableEvent = {
36
- record: {
37
- id: '202408_cus_w_Q7M9bXcHMKB6';
38
- amount: 26;
39
- };
40
- timestamp: '2024-08-07T07:35:20.307Z';
41
- event_type: 'api_call';
42
- customer_id: 'cus_w_Q7M9bXcHMKB6';
43
- };
44
- export type BillableEvents = {
45
- events_created: BillableEvent[];
46
- };
47
- export type CreateBillableEvent = {
48
- customer_id: string;
49
- event_type: 'api_call';
50
- timestamp: string;
51
- record: {
52
- id?: string;
53
- durationInMs?: number;
54
- isVerified?: true;
55
- amount?: number;
56
- amountGl?: number;
57
- amountNonGl?: number;
58
- };
59
- };
60
-
61
- type Logger = { error(message?: any, ...optionalParams: any[]): void };
62
-
63
- function arrayBufferToBase64(arrayBuffer: ArrayBuffer) {
64
- const uint8Array = new Uint8Array(arrayBuffer);
65
- const binaryString = String.fromCharCode.apply(null, uint8Array as any);
66
- return btoa(binaryString);
67
- }
68
-
69
- export class HyperlineAPI {
70
- constructor(token: string, logger: Logger = console) {
71
- this.headers = {
72
- 'Content-Type': 'application/json',
73
- Authorization: `Bearer ${token}`,
74
- };
75
- this.logger = logger;
76
- }
77
-
78
- private headers: Record<string, string>;
79
-
80
- private logger: Logger;
81
-
82
- private async fetchBasic<T>(
83
- path: string,
84
- options?: RequestInit,
85
- data?: Record<string, any>
86
- ): Promise<T | null> {
87
- if (data) options = { body: JSON.stringify(data), ...(options || {}) };
88
-
89
- const sandbox = this.headers.Authorization.includes('test')
90
- ? 'sandbox.'
91
- : '';
92
-
93
- const result = await fetch(`https://${sandbox}${path}`, {
94
- method: 'GET',
95
- ...options,
96
- headers: { ...this.headers, ...options?.headers },
97
- });
98
-
99
- if (!result || !result?.ok) {
100
- const status = result?.status;
101
- const statusText = result?.statusText;
102
-
103
- if (status === 429) {
104
- // get difference between rate limit reset and now
105
- const rateLimitReset = utc(result?.headers.get('x-ratelimit-reset'));
106
- const diff = rateLimitReset.diff(utc(), 'milliseconds');
107
-
108
- // wait until rate limit resets
109
- await new Promise((resolve) => setTimeout(resolve, diff));
110
-
111
- return await this.fetchBasic<T>(path, options, data);
112
- } else if (status === 404) {
113
- return null;
114
- } else {
115
- const content: any = await result.json();
116
- throw new Error(
117
- `Hyperline Error ${status} (${statusText}) in ${path} for ${options?.method || 'GET'}: ${content.message}`
118
- );
119
- }
120
- } else if (result.headers.get('content-type')?.includes('application/pdf'))
121
- return arrayBufferToBase64(await result.arrayBuffer()) as T;
122
-
123
- return (await result.json()) as T;
124
- }
125
-
126
- private async fetch<T>(
127
- path: string,
128
- options?: RequestInit,
129
- data?: Record<string, any>
130
- ): Promise<T | null> {
131
- return await this.fetchBasic(`api.hyperline.co${path}`, options, data);
132
- }
133
-
134
- private async fetchIngest<T>(
135
- path: string,
136
- options?: RequestInit,
137
- data?: Record<string, any>
138
- ): Promise<T | null> {
139
- return await this.fetchBasic(`ingest.hyperline.co${path}`, options, data);
140
- }
141
-
142
- // CUSTOMER
143
-
144
- async getCustomer(id?: string) {
145
- if (!id) {
146
- this.logger.error('Missing customer ID', { id });
147
- throw new Error('Missing customer ID');
148
- }
149
-
150
- return await this.fetch<
151
- paths['/v1/customers/{id}']['get']['responses'][200]['content']['application/json']
152
- >(`/v1/customers/${id}`);
153
- }
154
-
155
- async getCustomers(skip = 0, take = 100) {
156
- return await this.fetch<
157
- paths['/v1/customers']['get']['responses'][200]['content']['application/json']
158
- >(`/v1/customers?take=${take}&skip=${skip}`);
159
- }
160
-
161
- async getAllCustomers(
162
- items: paths['/v1/customers']['get']['responses'][200]['content']['application/json']['data'] = []
163
- ): Promise<
164
- paths['/v1/customers']['get']['responses'][200]['content']['application/json']['data']
165
- > {
166
- const { data } = (await this.getCustomers(items.length)) || { data: [] };
167
-
168
- return data.length
169
- ? this.getAllCustomers([...items, ...data])
170
- : [...items, ...data];
171
- }
172
-
173
- async createCustomer(
174
- data: NonNullable<
175
- paths['/v1/customers']['post']['requestBody']
176
- >['content']['application/json']
177
- ) {
178
- return await this.fetch<
179
- paths['/v1/customers']['post']['responses'][201]['content']['application/json']
180
- >(
181
- '/v1/customers',
182
- { method: 'POST' },
183
- { currency: 'USD', timezone: 'Etc/UTC', ...data }
184
- );
185
- }
186
-
187
- async updateCustomer(
188
- id: string,
189
- data: NonNullable<
190
- paths['/v1/customers/{id}']['put']['requestBody']
191
- >['content']['application/json']
192
- ) {
193
- if (!id) {
194
- this.logger.error('Missing customer ID', { id });
195
- throw new Error('Missing customer ID');
196
- }
197
-
198
- return await this.fetch<
199
- paths['/v1/customers/{id}']['put']['responses'][200]['content']['application/json']
200
- >(`/v1/customers/${id}`, { method: 'PUT' }, data);
201
- }
202
-
203
- async deleteCustomer(id: string) {
204
- return await this.fetch<
205
- paths['/v1/customers/{id}']['delete']['responses'][204]['content']
206
- >(`/v1/customers/${id}`, {
207
- method: 'DELETE',
208
- });
209
- }
210
-
211
- async archiveCustomer(id: string) {
212
- return await this.fetch<
213
- paths['/v1/customers/{id}/archive']['put']['responses'][200]['content']['application/json']
214
- >(`/v1/customers/${id}/archive`, {
215
- method: 'PUT',
216
- });
217
- }
218
-
219
- async unarchiveCustomer(id: string) {
220
- if (!id) {
221
- this.logger.error('Missing customer ID', { id });
222
- throw new Error('Missing customer ID');
223
- }
224
-
225
- return await this.fetch<
226
- paths['/v1/customers/{id}/unarchive']['put']['responses'][200]['content']['application/json']
227
- >(`/v1/customers/${id}/unarchive`, { method: 'PUT' });
228
- }
229
-
230
- async getCustomerPortal(id: string) {
231
- return await this.fetch<
232
- paths['/v1/customers/{id}/portal']['get']['responses'][200]['content']['application/json']
233
- >(`/v1/customers/${id}/portal`);
234
- }
235
-
236
- // SUBSCRIPTION
237
-
238
- async getSubscription(id: string) {
239
- if (!id) {
240
- this.logger.error('Missing subscription ID', { id });
241
- throw new Error('Missing subscription ID');
242
- }
243
-
244
- return await this.fetch<
245
- paths['/v2/subscriptions/{id}']['get']['responses'][200]['content']['application/json']
246
- >(`/v2/subscriptions/${id}?include_live_billing=true`);
247
- }
248
-
249
- async getSubscriptions(
250
- skip = 0,
251
- take = 100,
252
- query: operations['getSubscriptions']['parameters']['query'] = {
253
- status: 'all',
254
- }
255
- ) {
256
- return await this.fetch<
257
- paths['/v2/subscriptions']['get']['responses'][200]['content']['application/json']
258
- >(
259
- `/v2/subscriptions?take=${take}&skip=${skip}${Object.entries(query)
260
- .filter(([_, value]) => value !== undefined)
261
- .map(([key, value]) => `&${key}=${value}`)
262
- .join('')}`
263
- );
264
- }
265
-
266
- async getAllSubscriptions(
267
- items: paths['/v2/subscriptions']['get']['responses'][200]['content']['application/json']['data'] = [],
268
- query: operations['getSubscriptions']['parameters']['query'] = {}
269
- ): Promise<
270
- paths['/v2/subscriptions']['get']['responses'][200]['content']['application/json']['data']
271
- > {
272
- const { data } = (await this.getSubscriptions(
273
- items.length,
274
- 100,
275
- query
276
- )) || { data: [] };
277
-
278
- return data.length
279
- ? this.getAllSubscriptions([...items, ...data], query)
280
- : [...items, ...data];
281
- }
282
-
283
- async createSubscription(
284
- data: NonNullable<
285
- paths['/v2/subscriptions']['post']['requestBody']
286
- >['content']['application/json']
287
- ) {
288
- return await this.fetch<
289
- paths['/v2/subscriptions']['post']['responses'][201]['content']['application/json']
290
- >('/v2/subscriptions', { method: 'POST' }, data);
291
- }
292
-
293
- async updateSubscription(
294
- id: string,
295
- data: NonNullable<
296
- paths['/v1/subscriptions/{id}/update']['post']['requestBody']
297
- >['content']['application/json']
298
- ) {
299
- return await this.fetch<
300
- paths['/v1/subscriptions/{id}/update']['post']['responses'][201]['content']['application/json']
301
- >(`/v1/subscriptions/${id}/update`, { method: 'POST' }, data);
302
- }
303
-
304
- async cancelSubscription(
305
- id: string,
306
- data: NonNullable<
307
- paths['/v1/subscriptions/{id}/cancel']['post']['requestBody']
308
- >['content']['application/json']
309
- ) {
310
- return await this.fetch<
311
- paths['/v1/subscriptions/{id}/cancel']['post']['responses'][200]['content']['application/json']
312
- >(
313
- `/v1/subscriptions/${id}/cancel`,
314
- {
315
- method: 'POST',
316
- },
317
- data
318
- );
319
- }
320
-
321
- async reinstateSubscription(id: string) {
322
- return await this.fetch<
323
- paths['/v1/subscriptions/{id}/reinstate']['post']['responses'][200]['content']['application/json']
324
- >(`/v1/subscriptions/${id}/reinstate`, {
325
- method: 'POST',
326
- });
327
- }
328
-
329
- // PLAN
330
-
331
- async getPlan(id: string) {
332
- if (!id) {
333
- this.logger.error('Missing plan ID', { id });
334
- throw new Error('Missing plan ID');
335
- }
336
-
337
- return await this.fetch<
338
- paths['/v1/plans/{id}']['get']['responses'][200]['content']['application/json']
339
- >(`/v1/plans/${id}`);
340
- }
341
-
342
- async getPlans(skip = 0, take = 100) {
343
- return await this.fetch<
344
- paths['/v1/plans']['get']['responses'][200]['content']['application/json']
345
- >(`/v1/plans?take=${take}&skip=${skip}`);
346
- }
347
-
348
- // INVOICE
349
-
350
- async getInvoice(id: string) {
351
- if (!id) {
352
- this.logger.error('Missing invoice ID', { id });
353
- throw new Error('Missing invoice ID');
354
- }
355
-
356
- return await this.fetch<
357
- paths['/v1/invoices/{id}']['get']['responses'][200]['content']['application/json']
358
- >(`/v1/invoices/${id}`);
359
- }
360
-
361
- async getInvoices(
362
- skip = 0,
363
- take = 100,
364
- query: operations['getInvoices']['parameters']['query'] = { status: 'all' }
365
- ) {
366
- return await this.fetch<
367
- paths['/v1/invoices']['get']['responses'][200]['content']['application/json']
368
- >(
369
- `/v1/invoices?take=${take}&skip=${skip}&${Object.entries(query)
370
- .filter(([_, value]) => value !== undefined)
371
- .map(([key, value]) => `&${key}=${value}`)
372
- .join('')}`
373
- );
374
- }
375
-
376
- async getInvoicesByCustomerId(id: string) {
377
- return await this.fetch<
378
- paths['/v1/invoices']['get']['responses'][200]['content']['application/json']
379
- >(`/v1/invoices?customerId__equals=${id}`);
380
- }
381
-
382
- async getInvoiceDownload(id: string) {
383
- return await this.fetch<string>(
384
- // TODO: fix if type != unknown paths['/v1/invoices/{id}/download']['get']['responses'][200]['content']['application/pdf']
385
- `/v1/invoices/${id}/download`,
386
- {
387
- headers: { 'Content-type': 'application/pdf' },
388
- }
389
- );
390
- }
391
-
392
- async getAllInvoices(
393
- items: paths['/v1/invoices']['get']['responses'][200]['content']['application/json']['data'] = []
394
- ): Promise<
395
- paths['/v1/invoices']['get']['responses'][200]['content']['application/json']['data']
396
- > {
397
- const { data } = (await this.getInvoices(items.length)) || { data: [] };
398
-
399
- return data.length
400
- ? this.getAllInvoices([...items, ...data])
401
- : [...items, ...data];
402
- }
403
-
404
- // OTHERS
405
-
406
- async createBillableEvent(data: CreateBillableEvent[]) {
407
- if (!data.length) return { events_created: [] };
408
-
409
- return await this.fetchIngest<BillableEvents>(
410
- '/v1/events/batch',
411
- { method: 'POST' },
412
- data
413
- );
414
- }
415
-
416
- async getComponentToken(data: {
417
- customer_id: string;
418
- }) {
419
- return await this.fetch<
420
- paths['/v1/integrations/components/token']['post']['responses'][201]['content']['application/json']
421
- >('/v1/integrations/components/token', { method: 'POST' }, data);
422
- }
423
- }
424
-
425
- export function useHyperline(
426
- env: {
427
- PRODUCTION_HYPERLINE_API_KEY: string;
428
- DEV_HYPERLINE_API_KEY: string;
429
- },
430
- environment: 'production' | 'development',
431
- logger?: Logger
432
- ) {
433
- const isProduction = environment === 'production';
434
-
435
- const token = isProduction
436
- ? env.PRODUCTION_HYPERLINE_API_KEY
437
- : env.DEV_HYPERLINE_API_KEY;
438
-
439
- const hyperline = useHyperlineByToken(token, logger);
440
-
441
- return { hyperline, token, isProduction };
442
- }
443
-
444
- export function useHyperlineByToken(token: string, logger: Logger = console) {
445
- return new HyperlineAPI(token, logger);
446
- }
2
+ export * from './types';
3
+ export * from './client';
4
+ export * from './hooks';
package/src/types.ts ADDED
@@ -0,0 +1,43 @@
1
+ import type { components, paths } from './_types.generated';
2
+ import { WEBHOOKS } from './const';
3
+
4
+ export type HyperlineEntities = components['schemas'];
5
+
6
+ export type HyperlineEndpoints = paths;
7
+
8
+ export type HyperlineWebhook = keyof typeof WEBHOOKS;
9
+
10
+ export type HyperlineEvent<T extends HyperlineWebhook> = (typeof WEBHOOKS)[T];
11
+
12
+ export type HyperlinePayload<T extends HyperlineWebhook> = {
13
+ event_type: T;
14
+ data: Record<string, any>;
15
+ };
16
+
17
+ export type BillableEvent = {
18
+ record: {
19
+ id: '202408_cus_w_Q7M9bXcHMKB6';
20
+ amount: 26;
21
+ };
22
+ timestamp: '2024-08-07T07:35:20.307Z';
23
+ event_type: 'api_call';
24
+ customer_id: 'cus_w_Q7M9bXcHMKB6';
25
+ };
26
+
27
+ export type BillableEvents = {
28
+ events_created: BillableEvent[];
29
+ };
30
+
31
+ export type CreateBillableEvent = {
32
+ customer_id: string;
33
+ event_type: 'api_call';
34
+ timestamp: string;
35
+ record: {
36
+ id?: string;
37
+ durationInMs?: number;
38
+ isVerified?: true;
39
+ amount?: number;
40
+ amountGl?: number;
41
+ amountNonGl?: number;
42
+ };
43
+ };
package/src/utils.ts ADDED
@@ -0,0 +1,5 @@
1
+ export function arrayBufferToBase64(arrayBuffer: ArrayBuffer) {
2
+ const uint8Array = new Uint8Array(arrayBuffer);
3
+ const binaryString = String.fromCharCode.apply(null, uint8Array as any);
4
+ return btoa(binaryString);
5
+ }