@astrada.co/ts-astrada-sdk 1.0.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.
Files changed (200) hide show
  1. package/.editorconfig +10 -0
  2. package/.github/workflows/on-push.yml +65 -0
  3. package/.releaserc +21 -0
  4. package/CHANGELOG.md +13 -0
  5. package/README.md +1 -0
  6. package/dist/astrada.co-ts-astrada-sdk-1.0.0.tgz +0 -0
  7. package/lib/apis/CardApi.d.ts +57 -0
  8. package/lib/apis/CardApi.js +109 -0
  9. package/lib/apis/CardSubscriptionApi.d.ts +61 -0
  10. package/lib/apis/CardSubscriptionApi.js +133 -0
  11. package/lib/apis/CardholderApi.d.ts +31 -0
  12. package/lib/apis/CardholderApi.js +56 -0
  13. package/lib/apis/EnrollmentMethodsApi.d.ts +31 -0
  14. package/lib/apis/EnrollmentMethodsApi.js +57 -0
  15. package/lib/apis/NetworkBulkFeedsApi.d.ts +60 -0
  16. package/lib/apis/NetworkBulkFeedsApi.js +129 -0
  17. package/lib/apis/SubaccountsApi.d.ts +72 -0
  18. package/lib/apis/SubaccountsApi.js +157 -0
  19. package/lib/apis/TransactionMessagesApi.d.ts +31 -0
  20. package/lib/apis/TransactionMessagesApi.js +56 -0
  21. package/lib/apis/TransactionsApi.d.ts +56 -0
  22. package/lib/apis/TransactionsApi.js +106 -0
  23. package/lib/apis/WebhooksApi.d.ts +86 -0
  24. package/lib/apis/WebhooksApi.js +194 -0
  25. package/lib/apis/index.d.ts +9 -0
  26. package/lib/apis/index.js +27 -0
  27. package/lib/index.d.ts +3 -0
  28. package/lib/index.js +21 -0
  29. package/lib/models/Card.d.ts +112 -0
  30. package/lib/models/Card.js +109 -0
  31. package/lib/models/CardLinks.d.ts +39 -0
  32. package/lib/models/CardLinks.js +53 -0
  33. package/lib/models/CardSubscription.d.ts +118 -0
  34. package/lib/models/CardSubscription.js +109 -0
  35. package/lib/models/CardSubscriptionLinks.d.ts +45 -0
  36. package/lib/models/CardSubscriptionLinks.js +57 -0
  37. package/lib/models/Cardholder.d.ts +64 -0
  38. package/lib/models/Cardholder.js +68 -0
  39. package/lib/models/CardholderCorporate.d.ts +38 -0
  40. package/lib/models/CardholderCorporate.js +50 -0
  41. package/lib/models/CardholderLinks.d.ts +33 -0
  42. package/lib/models/CardholderLinks.js +51 -0
  43. package/lib/models/Conflict.d.ts +57 -0
  44. package/lib/models/Conflict.js +67 -0
  45. package/lib/models/CreateNetworkBulkFeedRequest.d.ts +52 -0
  46. package/lib/models/CreateNetworkBulkFeedRequest.js +66 -0
  47. package/lib/models/CreateSubaccountRequest.d.ts +39 -0
  48. package/lib/models/CreateSubaccountRequest.js +55 -0
  49. package/lib/models/CreateWebhook201Response.d.ts +98 -0
  50. package/lib/models/CreateWebhook201Response.js +96 -0
  51. package/lib/models/CreateWebhookRequest.d.ts +67 -0
  52. package/lib/models/CreateWebhookRequest.js +73 -0
  53. package/lib/models/EnrollmentMethods200Response.d.ts +40 -0
  54. package/lib/models/EnrollmentMethods200Response.js +58 -0
  55. package/lib/models/EnrollmentMethodsRequest.d.ts +32 -0
  56. package/lib/models/EnrollmentMethodsRequest.js +50 -0
  57. package/lib/models/GetSubaccounts200Response.d.ts +40 -0
  58. package/lib/models/GetSubaccounts200Response.js +56 -0
  59. package/lib/models/GetSubaccounts200ResponseEmbedded.d.ts +33 -0
  60. package/lib/models/GetSubaccounts200ResponseEmbedded.js +51 -0
  61. package/lib/models/GetSubaccounts200ResponseLinks.d.ts +39 -0
  62. package/lib/models/GetSubaccounts200ResponseLinks.js +53 -0
  63. package/lib/models/GetTransactions200Response.d.ts +40 -0
  64. package/lib/models/GetTransactions200Response.js +56 -0
  65. package/lib/models/GetTransactions200ResponseEmbedded.d.ts +33 -0
  66. package/lib/models/GetTransactions200ResponseEmbedded.js +51 -0
  67. package/lib/models/InlineObject.d.ts +52 -0
  68. package/lib/models/InlineObject.js +64 -0
  69. package/lib/models/InlineObject1.d.ts +45 -0
  70. package/lib/models/InlineObject1.js +61 -0
  71. package/lib/models/InlineObject2.d.ts +45 -0
  72. package/lib/models/InlineObject2.js +61 -0
  73. package/lib/models/InlineObject3.d.ts +45 -0
  74. package/lib/models/InlineObject3.js +61 -0
  75. package/lib/models/InlineObject4.d.ts +57 -0
  76. package/lib/models/InlineObject4.js +65 -0
  77. package/lib/models/InlineObject5.d.ts +45 -0
  78. package/lib/models/InlineObject5.js +61 -0
  79. package/lib/models/InlineObjectErrorsInner.d.ts +38 -0
  80. package/lib/models/InlineObjectErrorsInner.js +54 -0
  81. package/lib/models/Link.d.ts +74 -0
  82. package/lib/models/Link.js +64 -0
  83. package/lib/models/ListCardSubscriptions200Response.d.ts +46 -0
  84. package/lib/models/ListCardSubscriptions200Response.js +60 -0
  85. package/lib/models/ListCardSubscriptions200ResponseEmbedded.d.ts +33 -0
  86. package/lib/models/ListCardSubscriptions200ResponseEmbedded.js +51 -0
  87. package/lib/models/ListCardSubscriptions200ResponseLinks.d.ts +57 -0
  88. package/lib/models/ListCardSubscriptions200ResponseLinks.js +59 -0
  89. package/lib/models/ListCards200Response.d.ts +46 -0
  90. package/lib/models/ListCards200Response.js +60 -0
  91. package/lib/models/ListCards200ResponseEmbedded.d.ts +33 -0
  92. package/lib/models/ListCards200ResponseEmbedded.js +51 -0
  93. package/lib/models/ListNetworkBulkFeeds200Response.d.ts +46 -0
  94. package/lib/models/ListNetworkBulkFeeds200Response.js +60 -0
  95. package/lib/models/ListNetworkBulkFeeds200ResponseEmbedded.d.ts +33 -0
  96. package/lib/models/ListNetworkBulkFeeds200ResponseEmbedded.js +51 -0
  97. package/lib/models/ListWebhooks200Response.d.ts +40 -0
  98. package/lib/models/ListWebhooks200Response.js +56 -0
  99. package/lib/models/ListWebhooks200ResponseEmbedded.d.ts +33 -0
  100. package/lib/models/ListWebhooks200ResponseEmbedded.js +49 -0
  101. package/lib/models/ListWebhooks200ResponseLinks.d.ts +39 -0
  102. package/lib/models/ListWebhooks200ResponseLinks.js +51 -0
  103. package/lib/models/NetworkBulkFeeds.d.ts +81 -0
  104. package/lib/models/NetworkBulkFeeds.js +83 -0
  105. package/lib/models/Subaccount.d.ts +70 -0
  106. package/lib/models/Subaccount.js +76 -0
  107. package/lib/models/SubaccountConfiguration.d.ts +39 -0
  108. package/lib/models/SubaccountConfiguration.js +51 -0
  109. package/lib/models/SubaccountConfigurationVISA.d.ts +43 -0
  110. package/lib/models/SubaccountConfigurationVISA.js +61 -0
  111. package/lib/models/Transaction.d.ts +140 -0
  112. package/lib/models/Transaction.js +126 -0
  113. package/lib/models/TransactionAcceptor.d.ts +50 -0
  114. package/lib/models/TransactionAcceptor.js +62 -0
  115. package/lib/models/TransactionLinks.d.ts +51 -0
  116. package/lib/models/TransactionLinks.js +57 -0
  117. package/lib/models/TransactionMessage.d.ts +184 -0
  118. package/lib/models/TransactionMessage.js +159 -0
  119. package/lib/models/TransactionMessageAcceptor.d.ts +68 -0
  120. package/lib/models/TransactionMessageAcceptor.js +72 -0
  121. package/lib/models/UnprocessableEntity.d.ts +45 -0
  122. package/lib/models/UnprocessableEntity.js +61 -0
  123. package/lib/models/UpdateCardSubscriptionRequest.d.ts +39 -0
  124. package/lib/models/UpdateCardSubscriptionRequest.js +55 -0
  125. package/lib/models/UpdateSubaccountRequest.d.ts +39 -0
  126. package/lib/models/UpdateSubaccountRequest.js +51 -0
  127. package/lib/models/UpdateWebhookRequest.d.ts +61 -0
  128. package/lib/models/UpdateWebhookRequest.js +65 -0
  129. package/lib/models/Webhook.d.ts +92 -0
  130. package/lib/models/Webhook.js +92 -0
  131. package/lib/models/index.d.ts +51 -0
  132. package/lib/models/index.js +69 -0
  133. package/lib/runtime.d.ts +215 -0
  134. package/lib/runtime.js +394 -0
  135. package/package.json +21 -0
  136. package/src/apis/CardApi.ts +174 -0
  137. package/src/apis/CardSubscriptionApi.ts +223 -0
  138. package/src/apis/CardholderApi.ts +93 -0
  139. package/src/apis/EnrollmentMethodsApi.ts +98 -0
  140. package/src/apis/NetworkBulkFeedsApi.ts +211 -0
  141. package/src/apis/SubaccountsApi.ts +253 -0
  142. package/src/apis/TransactionMessagesApi.ts +93 -0
  143. package/src/apis/TransactionsApi.ts +169 -0
  144. package/src/apis/WebhooksApi.ts +315 -0
  145. package/src/apis/index.ts +11 -0
  146. package/src/index.ts +5 -0
  147. package/src/models/Card.ts +187 -0
  148. package/src/models/CardLinks.ts +82 -0
  149. package/src/models/CardSubscription.ts +194 -0
  150. package/src/models/CardSubscriptionLinks.ts +91 -0
  151. package/src/models/Cardholder.ts +124 -0
  152. package/src/models/CardholderCorporate.ts +73 -0
  153. package/src/models/CardholderLinks.ts +74 -0
  154. package/src/models/Conflict.ts +102 -0
  155. package/src/models/CreateNetworkBulkFeedRequest.ts +95 -0
  156. package/src/models/CreateSubaccountRequest.ts +83 -0
  157. package/src/models/CreateWebhook201Response.ts +168 -0
  158. package/src/models/CreateWebhookRequest.ts +114 -0
  159. package/src/models/EnrollmentMethods200Response.ts +77 -0
  160. package/src/models/EnrollmentMethodsRequest.ts +66 -0
  161. package/src/models/GetSubaccounts200Response.ts +90 -0
  162. package/src/models/GetSubaccounts200ResponseEmbedded.ts +74 -0
  163. package/src/models/GetSubaccounts200ResponseLinks.ts +82 -0
  164. package/src/models/GetTransactions200Response.ts +90 -0
  165. package/src/models/GetTransactions200ResponseEmbedded.ts +74 -0
  166. package/src/models/InlineObject.ts +101 -0
  167. package/src/models/InlineObject1.ts +85 -0
  168. package/src/models/InlineObject2.ts +85 -0
  169. package/src/models/InlineObject3.ts +85 -0
  170. package/src/models/InlineObject4.ts +101 -0
  171. package/src/models/InlineObject5.ts +85 -0
  172. package/src/models/InlineObjectErrorsInner.ts +75 -0
  173. package/src/models/Link.ts +122 -0
  174. package/src/models/ListCardSubscriptions200Response.ts +99 -0
  175. package/src/models/ListCardSubscriptions200ResponseEmbedded.ts +74 -0
  176. package/src/models/ListCardSubscriptions200ResponseLinks.ts +106 -0
  177. package/src/models/ListCards200Response.ts +99 -0
  178. package/src/models/ListCards200ResponseEmbedded.ts +74 -0
  179. package/src/models/ListNetworkBulkFeeds200Response.ts +99 -0
  180. package/src/models/ListNetworkBulkFeeds200ResponseEmbedded.ts +74 -0
  181. package/src/models/ListWebhooks200Response.ts +90 -0
  182. package/src/models/ListWebhooks200ResponseEmbedded.ts +73 -0
  183. package/src/models/ListWebhooks200ResponseLinks.ts +81 -0
  184. package/src/models/NetworkBulkFeeds.ts +143 -0
  185. package/src/models/Subaccount.ts +135 -0
  186. package/src/models/SubaccountConfiguration.ts +81 -0
  187. package/src/models/SubaccountConfigurationVISA.ts +80 -0
  188. package/src/models/Transaction.ts +238 -0
  189. package/src/models/TransactionAcceptor.ts +93 -0
  190. package/src/models/TransactionLinks.ts +98 -0
  191. package/src/models/TransactionMessage.ts +289 -0
  192. package/src/models/TransactionMessageAcceptor.ts +119 -0
  193. package/src/models/UnprocessableEntity.ts +85 -0
  194. package/src/models/UpdateCardSubscriptionRequest.ts +75 -0
  195. package/src/models/UpdateSubaccountRequest.ts +81 -0
  196. package/src/models/UpdateWebhookRequest.ts +103 -0
  197. package/src/models/Webhook.ts +159 -0
  198. package/src/models/index.ts +53 -0
  199. package/src/runtime.ts +524 -0
  200. package/tsconfig.json +13 -0
package/src/runtime.ts ADDED
@@ -0,0 +1,524 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ /**
4
+ * Astrada API
5
+ * Welcome to our API Reference. 👋
6
+ *
7
+ * The version of the OpenAPI document: 2024-02-28
8
+ * Contact: developer@astrada.co
9
+ *
10
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
11
+ * https://openapi-generator.tech
12
+ * Do not edit the class manually.
13
+ */
14
+
15
+
16
+
17
+ export const BASE_PATH = "https://api.astrada.co".replace(/\/+$/, "");
18
+
19
+ export interface ConfigurationParameters {
20
+ accountId: string; // parameter for authentication
21
+ clientId: string; // parameter for authentication
22
+ clientSecret: string; // parameter for authentication
23
+ // optional parameters
24
+ basePath?: string; // override base path
25
+ fetchApi?: FetchAPI; // override for fetch implementation
26
+ middleware?: Middleware[]; // middleware to apply before/after fetch requests
27
+ queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings
28
+ headers?: HTTPHeaders; //header params we want to use on every request
29
+ credentials?: RequestCredentials; //value for the credentials param we want to use on each request
30
+ }
31
+
32
+ export interface AccessToken {
33
+ access_token: string;
34
+ token_type: string;
35
+ expires_in: number;
36
+ scope?: string;
37
+ }
38
+
39
+ export interface AuthenticationParameter {
40
+ accountId: string;
41
+ clientId: string;
42
+ clientSecret: string;
43
+ fetchApi: FetchAPI;
44
+ basePath: string;
45
+ }
46
+
47
+ export interface AuthenticationError {
48
+ error: string;
49
+ error_description?: string;
50
+ status?: number;
51
+ }
52
+
53
+ export class Configuration {
54
+ private authClient: AuthenticationClient
55
+ constructor(private configuration: ConfigurationParameters) {
56
+ this.authClient = new AuthenticationClient({
57
+ basePath: this.basePath,
58
+ clientId: this.clientId,
59
+ clientSecret: this.clientSecret,
60
+ accountId: this.accountId,
61
+ fetchApi: this.fetchApi
62
+ });
63
+ }
64
+
65
+ set config(configuration: Configuration) {
66
+ this.configuration = configuration;
67
+ }
68
+
69
+ get accessToken(): (name?: string, scopes?: string[]) => Promise<string> {
70
+ return this.authClient.getAccessToken.bind(this.authClient);
71
+ }
72
+
73
+ get accountId(): string {
74
+ return this.configuration.accountId;
75
+ }
76
+
77
+ get clientId(): string {
78
+ return this.configuration.clientId;
79
+ }
80
+
81
+ get clientSecret(): string {
82
+ return this.configuration.clientSecret;
83
+ }
84
+
85
+ get basePath(): string {
86
+ return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
87
+ }
88
+
89
+ get fetchApi(): FetchAPI | undefined {
90
+ return this.configuration.fetchApi;
91
+ }
92
+
93
+ get middleware(): Middleware[] {
94
+ return this.configuration.middleware || [];
95
+ }
96
+
97
+ get queryParamsStringify(): (params: HTTPQuery) => string {
98
+ return this.configuration.queryParamsStringify || querystring;
99
+ }
100
+
101
+ get headers(): HTTPHeaders | undefined {
102
+ return this.configuration.headers;
103
+ }
104
+
105
+ get credentials(): RequestCredentials | undefined {
106
+ return this.configuration.credentials;
107
+ }
108
+ }
109
+
110
+ export class AuthenticationClient {
111
+ private cachedToken: AccessToken | null = null;
112
+ private tokenExpiry: number = 0;
113
+
114
+ constructor(private authConfig: AuthenticationParameter) { }
115
+
116
+ async getAccessToken(name?: string, scopes?: string[]): Promise<string> {
117
+ if (this.isTokenValid()) {
118
+ return 'Bearer ' + this.cachedToken!.access_token;
119
+ }
120
+
121
+ const tokenResponse = await this.requestNewToken();
122
+ this.cacheToken(tokenResponse);
123
+ return 'Bearer ' + tokenResponse.access_token;
124
+ }
125
+
126
+ private async requestNewToken(): Promise<AccessToken> {
127
+ const params = new URLSearchParams({
128
+ client_id: this.authConfig.clientId,
129
+ client_secret: this.authConfig.clientSecret,
130
+ grant_type: "client_credentials",
131
+ });
132
+ const url = `${this.authConfig.basePath}/auth/realms/${this.authConfig.accountId}/protocol/openid-connect/token`;
133
+
134
+ const response = await (this.authConfig.fetchApi || fetch)(url, {
135
+ method: 'POST',
136
+ headers: {
137
+ 'Content-Type': 'application/x-www-form-urlencoded',
138
+ },
139
+ body: params
140
+ });
141
+ const data = await response.json() as any;
142
+
143
+ if (response && (response.status >= 200 && response.status < 300)) {
144
+ return data as AccessToken;
145
+ }
146
+
147
+ if (data) {
148
+ const astradaError: AuthenticationError = {
149
+ error: data.error || "authentication_failed",
150
+ error_description:
151
+ data.error_description ||
152
+ "Failed to authenticate with Astrada API",
153
+ status: response.status,
154
+ };
155
+ throw new ResponseError(response, `Authentication failed: ${astradaError.error_description}`);
156
+ }
157
+
158
+ throw new ResponseError(response, 'Response returned an error code');
159
+ }
160
+
161
+ private cacheToken(token: AccessToken): void {
162
+ this.cachedToken = token;
163
+ this.tokenExpiry = Date.now() + token.expires_in * 1000 - 30000; // 30s buffer
164
+ }
165
+
166
+ private isTokenValid(): boolean {
167
+ return this.cachedToken !== null && Date.now() < this.tokenExpiry;
168
+ }
169
+
170
+ clearCache(): void {
171
+ this.cachedToken = null;
172
+ this.tokenExpiry = 0;
173
+ }
174
+ }
175
+
176
+
177
+ /**
178
+ * This is the base class for all generated API classes.
179
+ */
180
+ export class BaseAPI {
181
+
182
+ private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i');
183
+ private middleware: Middleware[];
184
+ private cachedToken: AccessToken | null = null;
185
+ private tokenExpiry: number = 0;
186
+
187
+ constructor(protected configuration: Configuration) {
188
+ this.middleware = configuration.middleware;
189
+ }
190
+
191
+ withMiddleware<T extends BaseAPI>(this: T, ...middlewares: Middleware[]) {
192
+ const next = this.clone<T>();
193
+ next.middleware = next.middleware.concat(...middlewares);
194
+ return next;
195
+ }
196
+
197
+ withPreMiddleware<T extends BaseAPI>(this: T, ...preMiddlewares: Array<Middleware['pre']>) {
198
+ const middlewares = preMiddlewares.map((pre) => ({ pre }));
199
+ return this.withMiddleware<T>(...middlewares);
200
+ }
201
+
202
+ withPostMiddleware<T extends BaseAPI>(this: T, ...postMiddlewares: Array<Middleware['post']>) {
203
+ const middlewares = postMiddlewares.map((post) => ({ post }));
204
+ return this.withMiddleware<T>(...middlewares);
205
+ }
206
+
207
+ /**
208
+ * Check if the given MIME is a JSON MIME.
209
+ * JSON MIME examples:
210
+ * application/json
211
+ * application/json; charset=UTF8
212
+ * APPLICATION/JSON
213
+ * application/vnd.company+json
214
+ * @param mime - MIME (Multipurpose Internet Mail Extensions)
215
+ * @return True if the given MIME is JSON, false otherwise.
216
+ */
217
+ protected isJsonMime(mime: string | null | undefined): boolean {
218
+ if (!mime) {
219
+ return false;
220
+ }
221
+ return BaseAPI.jsonRegex.test(mime);
222
+ }
223
+
224
+ protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise<Response> {
225
+ const { url, init } = await this.createFetchParams(context, initOverrides);
226
+
227
+ const response = await this.fetchApi(url, init);
228
+ if (response && (response.status >= 200 && response.status < 300)) {
229
+ return response;
230
+ }
231
+ throw new ResponseError(response, 'Response returned an error code');
232
+ }
233
+
234
+ private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction) {
235
+ let url = this.configuration.basePath + context.path;
236
+ if (context.query !== undefined && Object.keys(context.query).length !== 0) {
237
+ // only add the querystring to the URL if there are query parameters.
238
+ // this is done to avoid urls ending with a "?" character which buggy webservers
239
+ // do not handle correctly sometimes.
240
+ url += '?' + this.configuration.queryParamsStringify(context.query);
241
+ }
242
+
243
+ const headers = Object.assign({}, this.configuration.headers, context.headers);
244
+ Object.keys(headers).forEach(key => headers[key] === undefined ? delete headers[key] : {});
245
+
246
+ const initOverrideFn =
247
+ typeof initOverrides === "function"
248
+ ? initOverrides
249
+ : async () => initOverrides;
250
+
251
+ const initParams = {
252
+ method: context.method,
253
+ headers,
254
+ body: context.body,
255
+ credentials: this.configuration.credentials,
256
+ };
257
+
258
+ const overriddenInit: RequestInit = {
259
+ ...initParams,
260
+ ...(await initOverrideFn({
261
+ init: initParams,
262
+ context,
263
+ }))
264
+ };
265
+
266
+ let body: any;
267
+ if (isFormData(overriddenInit.body)
268
+ || (overriddenInit.body instanceof URLSearchParams)
269
+ || isBlob(overriddenInit.body)) {
270
+ body = overriddenInit.body;
271
+ } else if (this.isJsonMime(headers['Content-Type'])) {
272
+ body = JSON.stringify(overriddenInit.body);
273
+ } else {
274
+ body = overriddenInit.body;
275
+ }
276
+
277
+ const init: RequestInit = {
278
+ ...overriddenInit,
279
+ body
280
+ };
281
+
282
+ return { url, init };
283
+ }
284
+
285
+ private fetchApi = async (url: string, init: RequestInit) => {
286
+ let fetchParams = { url, init };
287
+ for (const middleware of this.middleware) {
288
+ if (middleware.pre) {
289
+ fetchParams = await middleware.pre({
290
+ fetch: this.fetchApi,
291
+ ...fetchParams,
292
+ }) || fetchParams;
293
+ }
294
+ }
295
+ let response: Response | undefined = undefined;
296
+ try {
297
+ response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init);
298
+ } catch (e) {
299
+ for (const middleware of this.middleware) {
300
+ if (middleware.onError) {
301
+ response = await middleware.onError({
302
+ fetch: this.fetchApi,
303
+ url: fetchParams.url,
304
+ init: fetchParams.init,
305
+ error: e,
306
+ response: response ? response.clone() : undefined,
307
+ }) || response;
308
+ }
309
+ }
310
+ if (response === undefined) {
311
+ if (e instanceof Error) {
312
+ throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response');
313
+ } else {
314
+ throw e;
315
+ }
316
+ }
317
+ }
318
+ for (const middleware of this.middleware) {
319
+ if (middleware.post) {
320
+ response = await middleware.post({
321
+ fetch: this.fetchApi,
322
+ url: fetchParams.url,
323
+ init: fetchParams.init,
324
+ response: response.clone(),
325
+ }) || response;
326
+ }
327
+ }
328
+ return response;
329
+ }
330
+
331
+ /**
332
+ * Create a shallow clone of `this` by constructing a new instance
333
+ * and then shallow cloning data members.
334
+ */
335
+ private clone<T extends BaseAPI>(this: T): T {
336
+ const constructor = this.constructor as any;
337
+ const next = new constructor(this.configuration);
338
+ next.middleware = this.middleware.slice();
339
+ return next;
340
+ }
341
+ };
342
+
343
+ function isBlob(value: any): value is Blob {
344
+ return typeof Blob !== 'undefined' && value instanceof Blob;
345
+ }
346
+
347
+ function isFormData(value: any): value is FormData {
348
+ return typeof FormData !== "undefined" && value instanceof FormData;
349
+ }
350
+
351
+ export class ResponseError extends Error {
352
+ override name: "ResponseError" = "ResponseError";
353
+ constructor(public response: Response, msg?: string) {
354
+ super(msg);
355
+ }
356
+ }
357
+
358
+ export class FetchError extends Error {
359
+ override name: "FetchError" = "FetchError";
360
+ constructor(public cause: Error, msg?: string) {
361
+ super(msg);
362
+ }
363
+ }
364
+
365
+ export class RequiredError extends Error {
366
+ override name: "RequiredError" = "RequiredError";
367
+ constructor(public field: string, msg?: string) {
368
+ super(msg);
369
+ }
370
+ }
371
+
372
+ export const COLLECTION_FORMATS = {
373
+ csv: ",",
374
+ ssv: " ",
375
+ tsv: "\t",
376
+ pipes: "|",
377
+ };
378
+
379
+ export type FetchAPI = typeof fetch;
380
+ export type RequestCredentials = 'omit' | 'same-origin' | 'include';
381
+
382
+ export type Json = any;
383
+ export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';
384
+ export type HTTPHeaders = { [key: string]: string };
385
+ export type HTTPQuery = { [key: string]: string | number | null | boolean | Array<string | number | null | boolean> | Set<string | number | null | boolean> | HTTPQuery };
386
+ export type HTTPBody = Json | FormData | URLSearchParams;
387
+ export type HTTPRequestInit = { headers?: HTTPHeaders; method: HTTPMethod; credentials?: RequestCredentials; body?: HTTPBody };
388
+ export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original';
389
+
390
+ export type InitOverrideFunction = (requestContext: { init: HTTPRequestInit, context: RequestOpts }) => Promise<RequestInit>
391
+
392
+ export interface FetchParams {
393
+ url: string;
394
+ init: RequestInit;
395
+ }
396
+
397
+ export interface RequestOpts {
398
+ path: string;
399
+ method: HTTPMethod;
400
+ headers: HTTPHeaders;
401
+ query?: HTTPQuery;
402
+ body?: HTTPBody;
403
+ }
404
+
405
+ export function querystring(params: HTTPQuery, prefix: string = ''): string {
406
+ return Object.keys(params)
407
+ .map(key => querystringSingleKey(key, params[key], prefix))
408
+ .filter(part => part.length > 0)
409
+ .join('&');
410
+ }
411
+
412
+ function querystringSingleKey(key: string, value: string | number | null | undefined | boolean | Array<string | number | null | boolean> | Set<string | number | null | boolean> | HTTPQuery, keyPrefix: string = ''): string {
413
+ const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key);
414
+ if (value instanceof Array) {
415
+ const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue)))
416
+ .join(`&${encodeURIComponent(fullKey)}=`);
417
+ return `${encodeURIComponent(fullKey)}=${multiValue}`;
418
+ }
419
+ if (value instanceof Set) {
420
+ const valueAsArray = Array.from(value);
421
+ return querystringSingleKey(key, valueAsArray, keyPrefix);
422
+ }
423
+ if (value instanceof Date) {
424
+ return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`;
425
+ }
426
+ if (value instanceof Object) {
427
+ return querystring(value as HTTPQuery, fullKey);
428
+ }
429
+ return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`;
430
+ }
431
+
432
+ export function exists(json: any, key: string) {
433
+ const value = json[key];
434
+ return value !== null && value !== undefined;
435
+ }
436
+
437
+ export function mapValues(data: any, fn: (item: any) => any) {
438
+ const result: { [key: string]: any } = {};
439
+ for (const key of Object.keys(data)) {
440
+ result[key] = fn(data[key]);
441
+ }
442
+ return result;
443
+ }
444
+
445
+ export function canConsumeForm(consumes: Consume[]): boolean {
446
+ for (const consume of consumes) {
447
+ if ('multipart/form-data' === consume.contentType) {
448
+ return true;
449
+ }
450
+ }
451
+ return false;
452
+ }
453
+
454
+ export interface Consume {
455
+ contentType: string;
456
+ }
457
+
458
+ export interface RequestContext {
459
+ fetch: FetchAPI;
460
+ url: string;
461
+ init: RequestInit;
462
+ }
463
+
464
+ export interface ResponseContext {
465
+ fetch: FetchAPI;
466
+ url: string;
467
+ init: RequestInit;
468
+ response: Response;
469
+ }
470
+
471
+ export interface ErrorContext {
472
+ fetch: FetchAPI;
473
+ url: string;
474
+ init: RequestInit;
475
+ error: unknown;
476
+ response?: Response;
477
+ }
478
+
479
+ export interface Middleware {
480
+ pre?(context: RequestContext): Promise<FetchParams | void>;
481
+ post?(context: ResponseContext): Promise<Response | void>;
482
+ onError?(context: ErrorContext): Promise<Response | void>;
483
+ }
484
+
485
+ export interface ApiResponse<T> {
486
+ raw: Response;
487
+ value(): Promise<T>;
488
+ }
489
+
490
+ export interface ResponseTransformer<T> {
491
+ (json: any): T;
492
+ }
493
+
494
+ export class JSONApiResponse<T> {
495
+ constructor(public raw: Response, private transformer: ResponseTransformer<T> = (jsonValue: any) => jsonValue) { }
496
+
497
+ async value(): Promise<T> {
498
+ return this.transformer(await this.raw.json());
499
+ }
500
+ }
501
+
502
+ export class VoidApiResponse {
503
+ constructor(public raw: Response) { }
504
+
505
+ async value(): Promise<void> {
506
+ return undefined;
507
+ }
508
+ }
509
+
510
+ export class BlobApiResponse {
511
+ constructor(public raw: Response) { }
512
+
513
+ async value(): Promise<Blob> {
514
+ return await this.raw.blob();
515
+ };
516
+ }
517
+
518
+ export class TextApiResponse {
519
+ constructor(public raw: Response) { }
520
+
521
+ async value(): Promise<string> {
522
+ return await this.raw.text();
523
+ };
524
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "outDir": "./lib",
4
+ "declaration": true,
5
+ "target": "ES2020",
6
+ "lib": ["ES2020"],
7
+ "moduleResolution": "node",
8
+ "module": "commonjs",
9
+ "types": ["node"]
10
+ },
11
+ "include": ["src"],
12
+ "exclude": ["node_modules"]
13
+ }