modern-treasury 0.0.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.
Files changed (169) hide show
  1. package/.eslintrc.js +10 -0
  2. package/.prettierrc +6 -0
  3. package/LICENSE +7 -0
  4. package/README.md +198 -0
  5. package/build +10 -0
  6. package/core.ts +746 -0
  7. package/dist/cjs/core.d.ts +215 -0
  8. package/dist/cjs/core.js +815 -0
  9. package/dist/cjs/core.js.map +1 -0
  10. package/dist/cjs/index.d.ts +118 -0
  11. package/dist/cjs/index.js +128 -0
  12. package/dist/cjs/index.js.map +1 -0
  13. package/dist/cjs/pagination.d.ts +14 -0
  14. package/dist/cjs/pagination.js +22 -0
  15. package/dist/cjs/pagination.js.map +1 -0
  16. package/dist/cjs/resource.d.ts +11 -0
  17. package/dist/cjs/resource.js +16 -0
  18. package/dist/cjs/resource.js.map +1 -0
  19. package/dist/cjs/resources/counterparties.d.ts +500 -0
  20. package/dist/cjs/resources/counterparties.js +57 -0
  21. package/dist/cjs/resources/counterparties.js.map +1 -0
  22. package/dist/cjs/resources/documents.d.ts +66 -0
  23. package/dist/cjs/resources/documents.js +23 -0
  24. package/dist/cjs/resources/documents.js.map +1 -0
  25. package/dist/cjs/resources/events.d.ts +53 -0
  26. package/dist/cjs/resources/events.js +22 -0
  27. package/dist/cjs/resources/events.js.map +1 -0
  28. package/dist/cjs/resources/expected-payments.d.ts +928 -0
  29. package/dist/cjs/resources/expected-payments.js +31 -0
  30. package/dist/cjs/resources/expected-payments.js.map +1 -0
  31. package/dist/cjs/resources/external-accounts.d.ts +597 -0
  32. package/dist/cjs/resources/external-accounts.js +51 -0
  33. package/dist/cjs/resources/external-accounts.js.map +1 -0
  34. package/dist/cjs/resources/incoming-payment-details.d.ts +487 -0
  35. package/dist/cjs/resources/incoming-payment-details.js +35 -0
  36. package/dist/cjs/resources/incoming-payment-details.js.map +1 -0
  37. package/dist/cjs/resources/index.d.ts +15 -0
  38. package/dist/cjs/resources/index.js +46 -0
  39. package/dist/cjs/resources/index.js.map +1 -0
  40. package/dist/cjs/resources/internal-accounts.d.ts +666 -0
  41. package/dist/cjs/resources/internal-accounts.js +31 -0
  42. package/dist/cjs/resources/internal-accounts.js.map +1 -0
  43. package/dist/cjs/resources/line-items.d.ts +90 -0
  44. package/dist/cjs/resources/line-items.js +38 -0
  45. package/dist/cjs/resources/line-items.js.map +1 -0
  46. package/dist/cjs/resources/paper-items.d.ts +279 -0
  47. package/dist/cjs/resources/paper-items.js +25 -0
  48. package/dist/cjs/resources/paper-items.js.map +1 -0
  49. package/dist/cjs/resources/payment-orders/index.d.ts +2 -0
  50. package/dist/cjs/resources/payment-orders/index.js +33 -0
  51. package/dist/cjs/resources/payment-orders/index.js.map +1 -0
  52. package/dist/cjs/resources/payment-orders/payment-orders.d.ts +2180 -0
  53. package/dist/cjs/resources/payment-orders/payment-orders.js +56 -0
  54. package/dist/cjs/resources/payment-orders/payment-orders.js.map +1 -0
  55. package/dist/cjs/resources/payment-orders/reversals.d.ts +46 -0
  56. package/dist/cjs/resources/payment-orders/reversals.js +23 -0
  57. package/dist/cjs/resources/payment-orders/reversals.js.map +1 -0
  58. package/dist/cjs/resources/returns.d.ts +487 -0
  59. package/dist/cjs/resources/returns.js +31 -0
  60. package/dist/cjs/resources/returns.js.map +1 -0
  61. package/dist/cjs/resources/top-level.d.ts +3 -0
  62. package/dist/cjs/resources/top-level.js +4 -0
  63. package/dist/cjs/resources/top-level.js.map +1 -0
  64. package/dist/cjs/resources/transactions.d.ts +377 -0
  65. package/dist/cjs/resources/transactions.js +31 -0
  66. package/dist/cjs/resources/transactions.js.map +1 -0
  67. package/dist/cjs/resources/validations.d.ts +97 -0
  68. package/dist/cjs/resources/validations.js +16 -0
  69. package/dist/cjs/resources/validations.js.map +1 -0
  70. package/dist/cjs/resources/webhooks.d.ts +31 -0
  71. package/dist/cjs/resources/webhooks.js +44 -0
  72. package/dist/cjs/resources/webhooks.js.map +1 -0
  73. package/dist/cjs/tests/api-resources/counterparties.test.d.ts +1 -0
  74. package/dist/cjs/tests/api-resources/counterparties.test.js +275 -0
  75. package/dist/cjs/tests/api-resources/counterparties.test.js.map +1 -0
  76. package/dist/cjs/tests/api-resources/documents.test.d.ts +1 -0
  77. package/dist/cjs/tests/api-resources/documents.test.js +78 -0
  78. package/dist/cjs/tests/api-resources/documents.test.js.map +1 -0
  79. package/dist/cjs/tests/api-resources/events.test.d.ts +1 -0
  80. package/dist/cjs/tests/api-resources/events.test.js +100 -0
  81. package/dist/cjs/tests/api-resources/events.test.js.map +1 -0
  82. package/dist/cjs/tests/api-resources/expected-payments.test.d.ts +1 -0
  83. package/dist/cjs/tests/api-resources/expected-payments.test.js +176 -0
  84. package/dist/cjs/tests/api-resources/expected-payments.test.js.map +1 -0
  85. package/dist/cjs/tests/api-resources/external-accounts.test.d.ts +1 -0
  86. package/dist/cjs/tests/api-resources/external-accounts.test.js +248 -0
  87. package/dist/cjs/tests/api-resources/external-accounts.test.js.map +1 -0
  88. package/dist/cjs/tests/api-resources/incoming-payment-details.test.d.ts +1 -0
  89. package/dist/cjs/tests/api-resources/incoming-payment-details.test.js +130 -0
  90. package/dist/cjs/tests/api-resources/incoming-payment-details.test.js.map +1 -0
  91. package/dist/cjs/tests/api-resources/internal-accounts.test.d.ts +1 -0
  92. package/dist/cjs/tests/api-resources/internal-accounts.test.js +144 -0
  93. package/dist/cjs/tests/api-resources/internal-accounts.test.js.map +1 -0
  94. package/dist/cjs/tests/api-resources/line-items.test.d.ts +1 -0
  95. package/dist/cjs/tests/api-resources/line-items.test.js +123 -0
  96. package/dist/cjs/tests/api-resources/line-items.test.js.map +1 -0
  97. package/dist/cjs/tests/api-resources/paper-items.test.d.ts +1 -0
  98. package/dist/cjs/tests/api-resources/paper-items.test.js +96 -0
  99. package/dist/cjs/tests/api-resources/paper-items.test.js.map +1 -0
  100. package/dist/cjs/tests/api-resources/payment-orders/payment-orders.test.d.ts +1 -0
  101. package/dist/cjs/tests/api-resources/payment-orders/payment-orders.test.js +77 -0
  102. package/dist/cjs/tests/api-resources/payment-orders/payment-orders.test.js.map +1 -0
  103. package/dist/cjs/tests/api-resources/returns.test.d.ts +1 -0
  104. package/dist/cjs/tests/api-resources/returns.test.js +116 -0
  105. package/dist/cjs/tests/api-resources/returns.test.js.map +1 -0
  106. package/dist/cjs/tests/api-resources/top-level.test.d.ts +1 -0
  107. package/dist/cjs/tests/api-resources/top-level.test.js +59 -0
  108. package/dist/cjs/tests/api-resources/top-level.test.js.map +1 -0
  109. package/dist/cjs/tests/api-resources/transactions.test.d.ts +1 -0
  110. package/dist/cjs/tests/api-resources/transactions.test.js +134 -0
  111. package/dist/cjs/tests/api-resources/transactions.test.js.map +1 -0
  112. package/dist/cjs/tests/api-resources/validations.test.d.ts +1 -0
  113. package/dist/cjs/tests/api-resources/validations.test.js +62 -0
  114. package/dist/cjs/tests/api-resources/validations.test.js.map +1 -0
  115. package/dist/cjs/tests/api-resources/webhooks.test.d.ts +1 -0
  116. package/dist/cjs/tests/api-resources/webhooks.test.js +100 -0
  117. package/dist/cjs/tests/api-resources/webhooks.test.js.map +1 -0
  118. package/dist/cjs/tests/form.test.d.ts +1 -0
  119. package/dist/cjs/tests/form.test.js +61 -0
  120. package/dist/cjs/tests/form.test.js.map +1 -0
  121. package/dist/cjs/tests/index.test.d.ts +1 -0
  122. package/dist/cjs/tests/index.test.js +57 -0
  123. package/dist/cjs/tests/index.test.js.map +1 -0
  124. package/dist/cjs/tests/responses.test.d.ts +1 -0
  125. package/dist/cjs/tests/responses.test.js +60 -0
  126. package/dist/cjs/tests/responses.test.js.map +1 -0
  127. package/index.ts +175 -0
  128. package/jest.config.js +8 -0
  129. package/package.json +47 -0
  130. package/pagination.ts +36 -0
  131. package/resource.ts +22 -0
  132. package/resources/counterparties.ts +666 -0
  133. package/resources/documents.ts +97 -0
  134. package/resources/events.ts +86 -0
  135. package/resources/expected-payments.ts +1016 -0
  136. package/resources/external-accounts.ts +762 -0
  137. package/resources/incoming-payment-details.ts +592 -0
  138. package/resources/index.ts +16 -0
  139. package/resources/internal-accounts.ts +774 -0
  140. package/resources/line-items.ts +138 -0
  141. package/resources/paper-items.ts +317 -0
  142. package/resources/payment-orders/index.ts +3 -0
  143. package/resources/payment-orders/payment-orders.ts +2486 -0
  144. package/resources/payment-orders/reversals.ts +72 -0
  145. package/resources/returns.ts +545 -0
  146. package/resources/top-level.ts +5 -0
  147. package/resources/transactions.ts +441 -0
  148. package/resources/validations.ts +115 -0
  149. package/resources/webhooks.ts +48 -0
  150. package/tests/api-resources/counterparties.test.ts +237 -0
  151. package/tests/api-resources/documents.test.ts +40 -0
  152. package/tests/api-resources/events.test.ts +62 -0
  153. package/tests/api-resources/expected-payments.test.ts +138 -0
  154. package/tests/api-resources/external-accounts.test.ts +210 -0
  155. package/tests/api-resources/incoming-payment-details.test.ts +92 -0
  156. package/tests/api-resources/internal-accounts.test.ts +103 -0
  157. package/tests/api-resources/line-items.test.ts +85 -0
  158. package/tests/api-resources/paper-items.test.ts +58 -0
  159. package/tests/api-resources/payment-orders/payment-orders.test.ts +39 -0
  160. package/tests/api-resources/returns.test.ts +78 -0
  161. package/tests/api-resources/top-level.test.ts +21 -0
  162. package/tests/api-resources/transactions.test.ts +96 -0
  163. package/tests/api-resources/validations.test.ts +24 -0
  164. package/tests/api-resources/webhooks.test.ts +102 -0
  165. package/tests/form.test.ts +27 -0
  166. package/tests/index.test.ts +62 -0
  167. package/tests/responses.test.ts +25 -0
  168. package/tsconfig.cjs.json +8 -0
  169. package/tsconfig.json +36 -0
@@ -0,0 +1,815 @@
1
+ 'use strict';
2
+ var __awaiter =
3
+ (this && this.__awaiter) ||
4
+ function (thisArg, _arguments, P, generator) {
5
+ function adopt(value) {
6
+ return value instanceof P
7
+ ? value
8
+ : new P(function (resolve) {
9
+ resolve(value);
10
+ });
11
+ }
12
+ return new (P || (P = Promise))(function (resolve, reject) {
13
+ function fulfilled(value) {
14
+ try {
15
+ step(generator.next(value));
16
+ } catch (e) {
17
+ reject(e);
18
+ }
19
+ }
20
+ function rejected(value) {
21
+ try {
22
+ step(generator['throw'](value));
23
+ } catch (e) {
24
+ reject(e);
25
+ }
26
+ }
27
+ function step(result) {
28
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
29
+ }
30
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
31
+ });
32
+ };
33
+ var __classPrivateFieldSet =
34
+ (this && this.__classPrivateFieldSet) ||
35
+ function (receiver, state, value, kind, f) {
36
+ if (kind === 'm') throw new TypeError('Private method is not writable');
37
+ if (kind === 'a' && !f) throw new TypeError('Private accessor was defined without a setter');
38
+ if (typeof state === 'function' ? receiver !== state || !f : !state.has(receiver))
39
+ throw new TypeError('Cannot write private member to an object whose class did not declare it');
40
+ return kind === 'a' ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value;
41
+ };
42
+ var __classPrivateFieldGet =
43
+ (this && this.__classPrivateFieldGet) ||
44
+ function (receiver, state, kind, f) {
45
+ if (kind === 'a' && !f) throw new TypeError('Private accessor was defined without a getter');
46
+ if (typeof state === 'function' ? receiver !== state || !f : !state.has(receiver))
47
+ throw new TypeError('Cannot read private member from an object whose class did not declare it');
48
+ return kind === 'm' ? f : kind === 'a' ? f.call(receiver) : f ? f.value : state.get(receiver);
49
+ };
50
+ var __rest =
51
+ (this && this.__rest) ||
52
+ function (s, e) {
53
+ var t = {};
54
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
55
+ if (s != null && typeof Object.getOwnPropertySymbols === 'function')
56
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
57
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
58
+ }
59
+ return t;
60
+ };
61
+ var __await =
62
+ (this && this.__await) ||
63
+ function (v) {
64
+ return this instanceof __await ? ((this.v = v), this) : new __await(v);
65
+ };
66
+ var __asyncGenerator =
67
+ (this && this.__asyncGenerator) ||
68
+ function (thisArg, _arguments, generator) {
69
+ if (!Symbol.asyncIterator) throw new TypeError('Symbol.asyncIterator is not defined.');
70
+ var g = generator.apply(thisArg, _arguments || []),
71
+ i,
72
+ q = [];
73
+ return (
74
+ (i = {}),
75
+ verb('next'),
76
+ verb('throw'),
77
+ verb('return'),
78
+ (i[Symbol.asyncIterator] = function () {
79
+ return this;
80
+ }),
81
+ i
82
+ );
83
+ function verb(n) {
84
+ if (g[n])
85
+ i[n] = function (v) {
86
+ return new Promise(function (a, b) {
87
+ q.push([n, v, a, b]) > 1 || resume(n, v);
88
+ });
89
+ };
90
+ }
91
+ function resume(n, v) {
92
+ try {
93
+ step(g[n](v));
94
+ } catch (e) {
95
+ settle(q[0][3], e);
96
+ }
97
+ }
98
+ function step(r) {
99
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
100
+ }
101
+ function fulfill(value) {
102
+ resume('next', value);
103
+ }
104
+ function reject(value) {
105
+ resume('throw', value);
106
+ }
107
+ function settle(f, v) {
108
+ if ((f(v), q.shift(), q.length)) resume(q[0][0], q[0][1]);
109
+ }
110
+ };
111
+ var __asyncValues =
112
+ (this && this.__asyncValues) ||
113
+ function (o) {
114
+ if (!Symbol.asyncIterator) throw new TypeError('Symbol.asyncIterator is not defined.');
115
+ var m = o[Symbol.asyncIterator],
116
+ i;
117
+ return m
118
+ ? m.call(o)
119
+ : ((o = typeof __values === 'function' ? __values(o) : o[Symbol.iterator]()),
120
+ (i = {}),
121
+ verb('next'),
122
+ verb('throw'),
123
+ verb('return'),
124
+ (i[Symbol.asyncIterator] = function () {
125
+ return this;
126
+ }),
127
+ i);
128
+ function verb(n) {
129
+ i[n] =
130
+ o[n] &&
131
+ function (v) {
132
+ return new Promise(function (resolve, reject) {
133
+ (v = o[n](v)), settle(resolve, reject, v.done, v.value);
134
+ });
135
+ };
136
+ }
137
+ function settle(resolve, reject, d, v) {
138
+ Promise.resolve(v).then(function (v) {
139
+ resolve({ value: v, done: d });
140
+ }, reject);
141
+ }
142
+ };
143
+ var __importDefault =
144
+ (this && this.__importDefault) ||
145
+ function (mod) {
146
+ return mod && mod.__esModule ? mod : { default: mod };
147
+ };
148
+ var _AbstractPage_client;
149
+ Object.defineProperty(exports, '__esModule', { value: true });
150
+ exports.getHeader =
151
+ exports.isHeadersProtocol =
152
+ exports.hasOwn =
153
+ exports.isEmptyObj =
154
+ exports.coerceInteger =
155
+ exports.multipartFormRequestOptions =
156
+ exports.APIConnectionTimeoutError =
157
+ exports.APIConnectionError =
158
+ exports.InternalServerError =
159
+ exports.RateLimitError =
160
+ exports.UnprocessableEntityError =
161
+ exports.ConflictError =
162
+ exports.NotFoundError =
163
+ exports.PermissionDeniedError =
164
+ exports.AuthenticationError =
165
+ exports.BadRequestError =
166
+ exports.APIError =
167
+ exports.isRequestOptions =
168
+ exports.createResponseHeaders =
169
+ exports.PagePromise =
170
+ exports.AbstractPage =
171
+ exports.APIResource =
172
+ exports.APIClient =
173
+ void 0;
174
+ const qs_1 = __importDefault(require('qs'));
175
+ const pkg_up_1 = __importDefault(require('pkg-up'));
176
+ const abort_controller_1 = require('abort-controller');
177
+ const formdata_node_1 = require('formdata-node');
178
+ const form_data_encoder_1 = require('form-data-encoder');
179
+ const stream_1 = require('stream');
180
+ const isNode = typeof process !== 'undefined';
181
+ let nodeFetch = undefined;
182
+ let getDefaultAgent = (_url) => undefined;
183
+ if (isNode) {
184
+ /* eslint-disable @typescript-eslint/no-var-requires */
185
+ nodeFetch = require('node-fetch');
186
+ const HttpAgent = require('agentkeepalive');
187
+ const HttpsAgent = HttpAgent.HttpsAgent;
188
+ /* eslint-enable @typescript-eslint/no-var-requires */
189
+ const defaultHttpAgent = new HttpAgent({ keepAlive: true });
190
+ const defaultHttpsAgent = new HttpsAgent({ keepAlive: true });
191
+ getDefaultAgent = (url) => (url.startsWith('https') ? defaultHttpsAgent : defaultHttpAgent);
192
+ }
193
+ const DEFAULT_MAX_RETRIES = 2;
194
+ const DEFAULT_TIMEOUT = 60 * 1000; // 60s
195
+ class APIClient {
196
+ constructor({ apiKey, baseURL, maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT, httpAgent }) {
197
+ this.apiKey = apiKey;
198
+ this.baseURL = baseURL;
199
+ this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);
200
+ this.timeout = validatePositiveInteger('timeout', timeout);
201
+ this.httpAgent = httpAgent;
202
+ if (isNode) {
203
+ this.fetch = nodeFetch;
204
+ } else {
205
+ // For other environments, use a global fetch function expected to already be present
206
+ if (typeof fetch === 'undefined' || typeof fetch !== 'function') {
207
+ throw new Error(
208
+ `Unexpected; running in a non-Node environment without a global "fetch" function defined.`,
209
+ );
210
+ }
211
+ // For now, we just pretend that Fetch is the same type as NodeFetch.
212
+ this.fetch = fetch;
213
+ }
214
+ }
215
+ authHeaders() {
216
+ return {};
217
+ }
218
+ /**
219
+ * Override this to add your own default headers, for example:
220
+ *
221
+ * {
222
+ * ...super.defaultHeaders(),
223
+ * Authorization: 'Bearer 123',
224
+ * }
225
+ */
226
+ defaultHeaders() {
227
+ return Object.assign(
228
+ {
229
+ Accept: 'application/json',
230
+ 'Content-Type': 'application/json',
231
+ 'User-Agent': this.getUserAgent(),
232
+ 'X-Stainless-Client-User-Agent': getPlatformPropertiesJSON(),
233
+ },
234
+ this.authHeaders(),
235
+ );
236
+ }
237
+ /**
238
+ * Override this to add your own qs.stringify options, for example:
239
+ *
240
+ * {
241
+ * ...super.qsOptions(),
242
+ * strictNullHandling: true,
243
+ * }
244
+ */
245
+ qsOptions() {
246
+ return {};
247
+ }
248
+ defaultIdempotencyKey() {
249
+ return `stainless-node-retry-${uuid4()}`;
250
+ }
251
+ get(path, opts) {
252
+ return this.request(Object.assign({ method: 'get', path }, opts));
253
+ }
254
+ post(path, opts) {
255
+ return this.request(Object.assign({ method: 'post', path }, opts));
256
+ }
257
+ patch(path, opts) {
258
+ return this.request(Object.assign({ method: 'patch', path }, opts));
259
+ }
260
+ put(path, opts) {
261
+ return this.request(Object.assign({ method: 'put', path }, opts));
262
+ }
263
+ delete(path, opts) {
264
+ return this.request(Object.assign({ method: 'delete', path }, opts));
265
+ }
266
+ getAPIList(path, Page, opts) {
267
+ return this.requestAPIList(Page, Object.assign({ method: 'get', path }, opts));
268
+ }
269
+ request(options, retriesRemaining) {
270
+ var _a, _b, _c, _d;
271
+ if (retriesRemaining === void 0) {
272
+ retriesRemaining = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries;
273
+ }
274
+ return __awaiter(this, void 0, void 0, function* () {
275
+ const { method, path, query, headers: headers = {} } = options;
276
+ const body =
277
+ options.body instanceof stream_1.Readable
278
+ ? options.body
279
+ : options.body
280
+ ? JSON.stringify(options.body, null, 2)
281
+ : null;
282
+ const contentLength = typeof body === 'string' ? body.length.toString() : null;
283
+ const url = this.buildURL(path, query);
284
+ const httpAgent =
285
+ (_c = (_b = options.httpAgent) !== null && _b !== void 0 ? _b : this.httpAgent) !== null &&
286
+ _c !== void 0
287
+ ? _c
288
+ : getDefaultAgent(url);
289
+ const timeout = (_d = options.timeout) !== null && _d !== void 0 ? _d : this.timeout;
290
+ validatePositiveInteger('timeout', timeout);
291
+ if (this.idempotencyHeader && method !== 'get') {
292
+ if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();
293
+ headers[this.idempotencyHeader] = options.idempotencyKey;
294
+ }
295
+ const req = Object.assign(
296
+ Object.assign(Object.assign({ method }, body && { body }), {
297
+ headers: Object.assign(
298
+ Object.assign(
299
+ Object.assign({}, contentLength && { 'Content-Length': contentLength }),
300
+ this.defaultHeaders(),
301
+ ),
302
+ headers,
303
+ ),
304
+ }),
305
+ httpAgent && { agent: httpAgent },
306
+ );
307
+ this.debug('request', url, options, req.headers);
308
+ const response = yield this.fetchWithTimeout(url, req, timeout).catch(castToError);
309
+ if (response instanceof Error) {
310
+ if (retriesRemaining) return this.retryRequest(options, retriesRemaining);
311
+ if (response.name === 'AbortError') throw new APIConnectionTimeoutError();
312
+ throw new APIConnectionError({ cause: response });
313
+ }
314
+ const responseHeaders = (0, exports.createResponseHeaders)(response.headers);
315
+ if (!response.ok) {
316
+ if (retriesRemaining && this.shouldRetry(response)) {
317
+ return this.retryRequest(options, retriesRemaining, responseHeaders);
318
+ }
319
+ const errText = yield response.text().catch(() => 'Unknown');
320
+ const errJSON = safeJSON(errText);
321
+ const errMessage = errJSON ? undefined : errText;
322
+ this.debug('response', response.status, url, responseHeaders, errMessage);
323
+ const err = APIError.generate(response.status, errJSON, errMessage, responseHeaders);
324
+ throw err;
325
+ }
326
+ const contentType = response.headers.get('content-type');
327
+ if (
328
+ contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')
329
+ ) {
330
+ const json = yield response.json();
331
+ Object.defineProperty(json, 'responseHeaders', {
332
+ enumerable: false,
333
+ writable: false,
334
+ value: responseHeaders,
335
+ });
336
+ this.debug('response', response.status, url, responseHeaders, json);
337
+ return json;
338
+ } else {
339
+ // TODO handle blob, arraybuffer, other content types, etc.
340
+ const text = response.text();
341
+ this.debug('response', response.status, url, responseHeaders, text);
342
+ return text;
343
+ }
344
+ });
345
+ }
346
+ requestAPIList(Page, options) {
347
+ const requestPromise = this.request(options);
348
+ return new PagePromise(this, requestPromise, options, Page);
349
+ }
350
+ buildURL(path, query) {
351
+ const url = isAbsoluteURL(path) ? new URL(path) : new URL(this.baseURL + path);
352
+ if (query) {
353
+ url.search = qs_1.default.stringify(query, this.qsOptions());
354
+ }
355
+ return url.toString();
356
+ }
357
+ fetchWithTimeout(url, _a = {}, ms) {
358
+ var { signal } = _a,
359
+ options = __rest(_a, ['signal']);
360
+ return __awaiter(this, void 0, void 0, function* () {
361
+ const controller = new abort_controller_1.AbortController();
362
+ if (signal) signal.addEventListener('abort', controller.abort);
363
+ const timeout = setTimeout(() => controller.abort(), ms);
364
+ return this.fetch(url, Object.assign({ signal: controller.signal }, options)).finally(() => {
365
+ clearTimeout(timeout);
366
+ });
367
+ });
368
+ }
369
+ shouldRetry(response) {
370
+ // Note this is not a standard header.
371
+ const shouldRetryHeader = response.headers.get('x-should-retry');
372
+ // If the server explicitly says whether or not to retry, obey.
373
+ if (shouldRetryHeader === 'true') return true;
374
+ if (shouldRetryHeader === 'false') return false;
375
+ // Retry on lock timeouts.
376
+ if (response.status === 409) return true;
377
+ // Retry on rate limits.
378
+ if (response.status === 429) return true;
379
+ // Retry internal errors.
380
+ if (response.status >= 500) return true;
381
+ return false;
382
+ }
383
+ retryRequest(options, retriesRemaining, responseHeaders) {
384
+ var _a;
385
+ return __awaiter(this, void 0, void 0, function* () {
386
+ retriesRemaining -= 1;
387
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
388
+ //
389
+ // TODO: we may want to handle the case where the header is using the http-date syntax: "Retry-After: <http-date>".
390
+ // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax for details.
391
+ const retryAfter = parseInt(
392
+ (responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders['retry-after']) ||
393
+ '',
394
+ );
395
+ const maxRetries = (_a = options.maxRetries) !== null && _a !== void 0 ? _a : this.maxRetries;
396
+ const timeout = this.calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) * 1000;
397
+ yield sleep(timeout);
398
+ return this.request(options, retriesRemaining);
399
+ });
400
+ }
401
+ calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) {
402
+ const initialRetryDelay = 0.5;
403
+ const maxRetryDelay = 2;
404
+ // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
405
+ // just do what it says.
406
+ if (Number.isInteger(retryAfter) && retryAfter <= 60) {
407
+ return retryAfter;
408
+ }
409
+ const numRetries = maxRetries - retriesRemaining;
410
+ // Apply exponential backoff, but not more than the max.
411
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(numRetries - 1, 2), maxRetryDelay);
412
+ // Apply some jitter, plus-or-minus half a second.
413
+ const jitter = Math.random() - 0.5;
414
+ return sleepSeconds + jitter;
415
+ }
416
+ getUserAgent() {
417
+ const packageVersion = getPackageVersion();
418
+ return `${this.constructor.name}/JS ${packageVersion}`;
419
+ }
420
+ debug(action, ...args) {
421
+ if (process.env['DEBUG'] === 'true') {
422
+ console.log(`${this.constructor.name}:DEBUG:${action}`, ...args);
423
+ }
424
+ }
425
+ }
426
+ exports.APIClient = APIClient;
427
+ class APIResource {
428
+ constructor(client) {
429
+ this.client = client;
430
+ this.get = client.get.bind(client);
431
+ this.post = client.post.bind(client);
432
+ this.patch = client.patch.bind(client);
433
+ this.put = client.put.bind(client);
434
+ this.delete = client.delete.bind(client);
435
+ this.getAPIList = client.getAPIList.bind(client);
436
+ }
437
+ }
438
+ exports.APIResource = APIResource;
439
+ class AbstractPage {
440
+ constructor(client, response, options) {
441
+ _AbstractPage_client.set(this, void 0);
442
+ __classPrivateFieldSet(this, _AbstractPage_client, client, 'f');
443
+ this.options = options;
444
+ }
445
+ hasNextPage() {
446
+ const items = this.getPaginatedItems();
447
+ if (!items.length) return false;
448
+ return this.nextPageParams() != null;
449
+ }
450
+ getNextPage() {
451
+ return __awaiter(this, void 0, void 0, function* () {
452
+ const nextQuery = this.nextPageParams();
453
+ if (!nextQuery) {
454
+ throw new Error(
455
+ 'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.',
456
+ );
457
+ }
458
+ const nextOptions = Object.assign(Object.assign({}, this.options), {
459
+ query: Object.assign(Object.assign({}, this.options.query), nextQuery),
460
+ });
461
+ return yield __classPrivateFieldGet(this, _AbstractPage_client, 'f').requestAPIList(
462
+ this.constructor,
463
+ nextOptions,
464
+ );
465
+ });
466
+ }
467
+ iterPages() {
468
+ return __asyncGenerator(this, arguments, function* iterPages_1() {
469
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
470
+ let page = this;
471
+ yield yield __await(page);
472
+ while (page.hasNextPage()) {
473
+ page = yield __await(page.getNextPage());
474
+ yield yield __await(page);
475
+ }
476
+ });
477
+ }
478
+ [((_AbstractPage_client = new WeakMap()), Symbol.asyncIterator)]() {
479
+ return __asyncGenerator(this, arguments, function* _a() {
480
+ var e_1, _b;
481
+ try {
482
+ for (var _c = __asyncValues(this.iterPages()), _d; (_d = yield __await(_c.next())), !_d.done; ) {
483
+ const page = _d.value;
484
+ for (const item of page.getPaginatedItems()) {
485
+ yield yield __await(item);
486
+ }
487
+ }
488
+ } catch (e_1_1) {
489
+ e_1 = { error: e_1_1 };
490
+ } finally {
491
+ try {
492
+ if (_d && !_d.done && (_b = _c.return)) yield __await(_b.call(_c));
493
+ } finally {
494
+ if (e_1) throw e_1.error;
495
+ }
496
+ }
497
+ });
498
+ }
499
+ }
500
+ exports.AbstractPage = AbstractPage;
501
+ class PagePromise extends Promise {
502
+ /**
503
+ * This subclass of Promise will resolve to an instantiated Page once the request completes.
504
+ */
505
+ constructor(client, requestPromise, options, Page) {
506
+ super((resolve, reject) =>
507
+ requestPromise.then((response) => resolve(new Page(client, response, options))).catch(reject),
508
+ );
509
+ }
510
+ /**
511
+ * Enable subclassing Promise.
512
+ * Ref: https://stackoverflow.com/a/60328122
513
+ */
514
+ static get [Symbol.species]() {
515
+ return Promise;
516
+ }
517
+ /**
518
+ * Allow auto-paginating iteration on an unawaited list call, eg:
519
+ *
520
+ * for await (const item of client.items.list()) {
521
+ * console.log(item)
522
+ * }
523
+ */
524
+ [Symbol.asyncIterator]() {
525
+ return __asyncGenerator(this, arguments, function* _a() {
526
+ var e_2, _b;
527
+ const page = yield __await(this);
528
+ try {
529
+ for (
530
+ var page_1 = __asyncValues(page), page_1_1;
531
+ (page_1_1 = yield __await(page_1.next())), !page_1_1.done;
532
+
533
+ ) {
534
+ const item = page_1_1.value;
535
+ yield yield __await(item);
536
+ }
537
+ } catch (e_2_1) {
538
+ e_2 = { error: e_2_1 };
539
+ } finally {
540
+ try {
541
+ if (page_1_1 && !page_1_1.done && (_b = page_1.return)) yield __await(_b.call(page_1));
542
+ } finally {
543
+ if (e_2) throw e_2.error;
544
+ }
545
+ }
546
+ });
547
+ }
548
+ }
549
+ exports.PagePromise = PagePromise;
550
+ const createResponseHeaders = (headers) => {
551
+ return new Proxy(Object.fromEntries(headers.entries()), {
552
+ get(target, name) {
553
+ const key = name.toString();
554
+ return target[key.toLowerCase()] || target[key];
555
+ },
556
+ });
557
+ };
558
+ exports.createResponseHeaders = createResponseHeaders;
559
+ // This is required so that we can determine if a given object matches the RequestOptions
560
+ // type at runtime. While this requires duplication, it is enforced by the TypeScript
561
+ // compiler such that any missing / extraneous keys will cause an error.
562
+ const requestOptionsKeys = {
563
+ method: true,
564
+ path: true,
565
+ query: true,
566
+ body: true,
567
+ headers: true,
568
+ maxRetries: true,
569
+ timeout: true,
570
+ httpAgent: true,
571
+ };
572
+ const isRequestOptions = (obj) => {
573
+ return (
574
+ typeof obj === 'object' &&
575
+ obj !== null &&
576
+ !isEmptyObj(obj) &&
577
+ Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))
578
+ );
579
+ };
580
+ exports.isRequestOptions = isRequestOptions;
581
+ class APIError extends Error {
582
+ constructor(status, error, message, headers) {
583
+ super(message || (error === null || error === void 0 ? void 0 : error.message));
584
+ this.status = status;
585
+ this.headers = headers;
586
+ this.error = error;
587
+ }
588
+ static generate(status, error, message, headers) {
589
+ if (!status) return new APIConnectionError({ cause: castToError(error) });
590
+ if (status === 400) return new BadRequestError(status, error, message, headers);
591
+ if (status === 401) return new AuthenticationError(status, error, message, headers);
592
+ if (status === 403) return new PermissionDeniedError(status, error, message, headers);
593
+ if (status === 404) return new NotFoundError(status, error, message, headers);
594
+ if (status === 409) return new ConflictError(status, error, message, headers);
595
+ if (status === 422) return new UnprocessableEntityError(status, error, message, headers);
596
+ if (status === 429) return new RateLimitError(status, error, message, headers);
597
+ if (status >= 500) return new InternalServerError(status, error, message, headers);
598
+ return new APIError(status, error, message, headers);
599
+ }
600
+ }
601
+ exports.APIError = APIError;
602
+ class BadRequestError extends APIError {
603
+ constructor() {
604
+ super(...arguments);
605
+ this.status = 400;
606
+ }
607
+ }
608
+ exports.BadRequestError = BadRequestError;
609
+ class AuthenticationError extends APIError {
610
+ constructor() {
611
+ super(...arguments);
612
+ this.status = 401;
613
+ }
614
+ }
615
+ exports.AuthenticationError = AuthenticationError;
616
+ class PermissionDeniedError extends APIError {
617
+ constructor() {
618
+ super(...arguments);
619
+ this.status = 403;
620
+ }
621
+ }
622
+ exports.PermissionDeniedError = PermissionDeniedError;
623
+ class NotFoundError extends APIError {
624
+ constructor() {
625
+ super(...arguments);
626
+ this.status = 404;
627
+ }
628
+ }
629
+ exports.NotFoundError = NotFoundError;
630
+ class ConflictError extends APIError {
631
+ constructor() {
632
+ super(...arguments);
633
+ this.status = 409;
634
+ }
635
+ }
636
+ exports.ConflictError = ConflictError;
637
+ class UnprocessableEntityError extends APIError {
638
+ constructor() {
639
+ super(...arguments);
640
+ this.status = 422;
641
+ }
642
+ }
643
+ exports.UnprocessableEntityError = UnprocessableEntityError;
644
+ class RateLimitError extends APIError {
645
+ constructor() {
646
+ super(...arguments);
647
+ this.status = 429;
648
+ }
649
+ }
650
+ exports.RateLimitError = RateLimitError;
651
+ class InternalServerError extends APIError {}
652
+ exports.InternalServerError = InternalServerError;
653
+ class APIConnectionError extends APIError {
654
+ constructor({ message, cause }) {
655
+ super(undefined, undefined, message || 'Connection error.', undefined);
656
+ this.status = undefined;
657
+ // eslint-disable-next-line
658
+ // @ts-ignore
659
+ if (cause) this.cause = cause;
660
+ }
661
+ }
662
+ exports.APIConnectionError = APIConnectionError;
663
+ class APIConnectionTimeoutError extends APIConnectionError {
664
+ constructor() {
665
+ super({ message: 'Request timed out.' });
666
+ }
667
+ }
668
+ exports.APIConnectionTimeoutError = APIConnectionTimeoutError;
669
+ let _packageVersion;
670
+ const getPackageVersion = () => {
671
+ try {
672
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
673
+ return _packageVersion !== null && _packageVersion !== void 0
674
+ ? _packageVersion
675
+ : (_packageVersion = require(pkg_up_1.default.sync()).version);
676
+ } catch (e) {
677
+ console.debug(`Ignoring error while determing package version ${e}`);
678
+ return (_packageVersion = 'unknown');
679
+ }
680
+ };
681
+ const getPlatformProperties = () => {
682
+ if (typeof process !== 'undefined') {
683
+ return {
684
+ lang: 'js',
685
+ packageVersion: getPackageVersion(),
686
+ os: process.platform,
687
+ arch: process.arch,
688
+ runtime: 'node',
689
+ runtimeVersion: process.version,
690
+ };
691
+ }
692
+ if (typeof Deno !== 'undefined') {
693
+ return {
694
+ lang: 'js',
695
+ packageVersion: getPackageVersion(),
696
+ os: Deno.build.os,
697
+ arch: Deno.build.arch,
698
+ runtime: 'deno',
699
+ runtimeVersion: Deno.version,
700
+ };
701
+ }
702
+ // TODO add support for Cloudflare workers, browsers, etc.
703
+ };
704
+ let _platformPropertiesJSON;
705
+ const getPlatformPropertiesJSON = () => {
706
+ return (
707
+ (_platformPropertiesJSON !== null && _platformPropertiesJSON !== void 0
708
+ ? _platformPropertiesJSON
709
+ : (_platformPropertiesJSON = JSON.stringify(getPlatformProperties()))) || ''
710
+ );
711
+ };
712
+ const safeJSON = (text) => {
713
+ try {
714
+ return JSON.parse(text);
715
+ } catch (err) {
716
+ return undefined;
717
+ }
718
+ };
719
+ // https://stackoverflow.com/a/19709846
720
+ const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i');
721
+ const isAbsoluteURL = (url) => {
722
+ return startsWithSchemeRegexp.test(url);
723
+ };
724
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
725
+ const validatePositiveInteger = (name, n) => {
726
+ if (!Number.isInteger(n)) {
727
+ throw new Error(`${name} must be an integer`);
728
+ }
729
+ if (n < 0) {
730
+ throw new Error(`${name} must be a positive integer`);
731
+ }
732
+ return n;
733
+ };
734
+ const castToError = (err) => {
735
+ if (err instanceof Error) return err;
736
+ return new Error(err);
737
+ };
738
+ const validateFormValue = (value) => {
739
+ if (
740
+ typeof value === 'string' ||
741
+ typeof value === 'number' ||
742
+ typeof value === 'boolean' ||
743
+ value instanceof formdata_node_1.File ||
744
+ value instanceof formdata_node_1.Blob
745
+ ) {
746
+ return value;
747
+ }
748
+ if (value == null) {
749
+ throw new TypeError(
750
+ `null is not a valid form data value, if you want to pass null then you need to use the string 'null'`,
751
+ );
752
+ }
753
+ throw new TypeError(
754
+ `Invalid value given to form, expected a string, number, boolean, File or Blob but got ${value} instead`,
755
+ );
756
+ };
757
+ const multipartFormRequestOptions = (opts) => {
758
+ const form = new formdata_node_1.FormData();
759
+ Object.entries(opts.body || {}).forEach(
760
+ ([key, value]) => value !== undefined && form.set(key, validateFormValue(value)),
761
+ );
762
+ const encoder = new form_data_encoder_1.FormDataEncoder(form);
763
+ return Object.assign(Object.assign({}, opts), {
764
+ headers: Object.assign(Object.assign(Object.assign({}, opts.headers), encoder.headers), {
765
+ 'Content-Length': encoder.contentLength,
766
+ }),
767
+ body: stream_1.Readable.from(encoder),
768
+ });
769
+ };
770
+ exports.multipartFormRequestOptions = multipartFormRequestOptions;
771
+ const coerceInteger = (value) => {
772
+ if (typeof value === 'number') return Math.round(value);
773
+ if (typeof value === 'string') return parseInt(value);
774
+ throw new Error(`Could not coerce ${value} (type: ${typeof value}) into a number`);
775
+ };
776
+ exports.coerceInteger = coerceInteger;
777
+ // https://stackoverflow.com/a/34491287
778
+ function isEmptyObj(obj) {
779
+ if (!obj) return true;
780
+ for (const _k in obj) return false;
781
+ return true;
782
+ }
783
+ exports.isEmptyObj = isEmptyObj;
784
+ // https://eslint.org/docs/latest/rules/no-prototype-builtins
785
+ function hasOwn(obj, key) {
786
+ return Object.prototype.hasOwnProperty.call(obj, key);
787
+ }
788
+ exports.hasOwn = hasOwn;
789
+ /**
790
+ * https://stackoverflow.com/a/2117523
791
+ */
792
+ const uuid4 = () => {
793
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
794
+ const r = (Math.random() * 16) | 0;
795
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
796
+ return v.toString(16);
797
+ });
798
+ };
799
+ const isHeadersProtocol = (headers) => {
800
+ return typeof (headers === null || headers === void 0 ? void 0 : headers.get) === 'function';
801
+ };
802
+ exports.isHeadersProtocol = isHeadersProtocol;
803
+ const getHeader = (headers, key) => {
804
+ const lowerKey = key.toLowerCase();
805
+ if ((0, exports.isHeadersProtocol)(headers)) return headers.get(key) || headers.get(lowerKey);
806
+ const value = headers[key] || headers[lowerKey];
807
+ if (Array.isArray(value)) {
808
+ if (value.length <= 1) return value[0];
809
+ console.warn(`Received ${value.length} entries for the ${key} header, using the first entry.`);
810
+ return value[0];
811
+ }
812
+ return value;
813
+ };
814
+ exports.getHeader = getHeader;
815
+ //# sourceMappingURL=core.js.map