@aloma.io/integration-sdk 3.8.69 → 3.8.71

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 (117) hide show
  1. package/README.md +15 -2
  2. package/build/internal/connector/server/on-connect/make-oauth.mjs +27 -6
  3. package/build/internal/fetcher/fetcher.d.mts +22 -1
  4. package/build/internal/fetcher/fetcher.mjs +99 -14
  5. package/build/internal/fetcher/oauth-fetcher.d.mts +15 -2
  6. package/build/internal/fetcher/oauth-fetcher.mjs +72 -27
  7. package/build/internal/util/index.d.mts +8 -0
  8. package/build/internal/util/index.mjs +13 -1
  9. package/build/internal/util/jwe/index.mjs +3 -1
  10. package/build/openapi-to-connector.mjs +5 -2
  11. package/package.json +9 -4
  12. package/.prettierrc.cjs +0 -8
  13. package/MULTI_RESOURCE_GUIDE.md +0 -220
  14. package/OPENAPI_TO_CONNECTOR.md +0 -346
  15. package/examples/hello-world/package.json +0 -25
  16. package/examples/hello-world/src/controller/index.mts +0 -12
  17. package/examples/hello-world/src/index.mts +0 -6
  18. package/examples/hello-world/tsconfig.json +0 -27
  19. package/examples/sample-api.json +0 -325
  20. package/examples/sample-api.yaml +0 -222
  21. package/examples/simple-api.json +0 -39
  22. package/index.js +0 -4
  23. package/src/builder/index.mts +0 -274
  24. package/src/builder/runtime-context.mts +0 -129
  25. package/src/cli.mts +0 -533
  26. package/src/controller/index.mts +0 -278
  27. package/src/index.mts +0 -2
  28. package/src/internal/connector/config.mts +0 -59
  29. package/src/internal/connector/index.mts +0 -53
  30. package/src/internal/connector/metrics.mts +0 -34
  31. package/src/internal/connector/server/index.mts +0 -51
  32. package/src/internal/connector/server/on-connect/decrypt-config.mts +0 -27
  33. package/src/internal/connector/server/on-connect/finish-oauth.mts +0 -109
  34. package/src/internal/connector/server/on-connect/index.mts +0 -162
  35. package/src/internal/connector/server/on-connect/make-oauth.mts +0 -97
  36. package/src/internal/connector/server/on-connect/start-oauth.mts +0 -24
  37. package/src/internal/connector/server/on-message.mts +0 -13
  38. package/src/internal/dispatcher/index.mts +0 -231
  39. package/src/internal/fetcher/fetcher.mts +0 -166
  40. package/src/internal/fetcher/oauth-fetcher.mts +0 -153
  41. package/src/internal/index.mts +0 -3
  42. package/src/internal/util/index.mts +0 -52
  43. package/src/internal/util/jwe/cli.mts +0 -12
  44. package/src/internal/util/jwe/index.mts +0 -72
  45. package/src/internal/websocket/config.mjs +0 -109
  46. package/src/internal/websocket/connection/constants.mjs +0 -25
  47. package/src/internal/websocket/connection/index.mjs +0 -71
  48. package/src/internal/websocket/connection/registration.mjs +0 -42
  49. package/src/internal/websocket/index.mjs +0 -46
  50. package/src/internal/websocket/transport/durable.mjs +0 -71
  51. package/src/internal/websocket/transport/index.mjs +0 -194
  52. package/src/internal/websocket/transport/packet.mjs +0 -54
  53. package/src/internal/websocket/transport/processor.mjs +0 -66
  54. package/src/openapi-to-connector.mts +0 -1644
  55. package/src/testing/fake-aloma.mts +0 -306
  56. package/src/testing/harness.mts +0 -172
  57. package/src/testing/index.mts +0 -15
  58. package/src/testing/keys.mts +0 -19
  59. package/src/testing/network-guard.mts +0 -57
  60. package/src/testing/runtime-connector.mts +0 -50
  61. package/src/testing/vendor-mock.mts +0 -166
  62. package/src/transform/index.mts +0 -544
  63. package/test/MUTATION-entry.md +0 -21
  64. package/test/MUTATION.md +0 -43
  65. package/test/dispatcher-ctx-forwarding.test.mjs +0 -161
  66. package/test/fixtures/transform/basic/expected.json +0 -9
  67. package/test/fixtures/transform/basic/src/controller/abstract.mts +0 -5
  68. package/test/fixtures/transform/basic/src/controller/index.mts +0 -30
  69. package/test/fixtures/transform/basic/tsconfig.json +0 -1
  70. package/test/fixtures/transform/interface-param/src/controller/abstract.mts +0 -5
  71. package/test/fixtures/transform/interface-param/src/controller/index.mts +0 -12
  72. package/test/fixtures/transform/interface-param/tsconfig.json +0 -1
  73. package/test/fixtures/transform/overloads/expected.json +0 -6
  74. package/test/fixtures/transform/overloads/src/controller/abstract.mts +0 -5
  75. package/test/fixtures/transform/overloads/src/controller/index.mts +0 -11
  76. package/test/fixtures/transform/overloads/tsconfig.json +0 -1
  77. package/test/fixtures/transform/tdd-stub/expected.json +0 -8
  78. package/test/fixtures/transform/tdd-stub/src/controller/abstract.mts +0 -6
  79. package/test/fixtures/transform/tdd-stub/src/controller/index.mts +0 -204
  80. package/test/fixtures/transform/tdd-stub/tsconfig.json +0 -1
  81. package/test/fixtures/transform/two-exports/src/controller/abstract.mts +0 -5
  82. package/test/fixtures/transform/two-exports/src/controller/index.mts +0 -9
  83. package/test/fixtures/transform/two-exports/tsconfig.json +0 -1
  84. package/test/fixtures/transform/type-error/src/controller/abstract.mts +0 -5
  85. package/test/fixtures/transform/type-error/src/controller/index.mts +0 -7
  86. package/test/fixtures/transform/type-error/tsconfig.json +0 -1
  87. package/test/fixtures/transform/typed/expected.json +0 -8
  88. package/test/fixtures/transform/typed/src/controller/abstract.mts +0 -5
  89. package/test/fixtures/transform/typed/src/controller/index.mts +0 -13
  90. package/test/fixtures/transform/typed/tsconfig.json +0 -1
  91. package/test/fixtures/transform/visibility/expected.json +0 -9
  92. package/test/fixtures/transform/visibility/src/controller/abstract.mts +0 -5
  93. package/test/fixtures/transform/visibility/src/controller/index.mts +0 -19
  94. package/test/fixtures/transform/visibility/tsconfig.json +0 -1
  95. package/test/harness-connector-smoke.test.mjs +0 -72
  96. package/test/harness.test.mjs +0 -375
  97. package/test/nested-resolver.test.mjs +0 -184
  98. package/test/openapi-generator-bugs.test.mjs +0 -248
  99. package/test/openapi-identifier-sanitise.test.mjs +0 -69
  100. package/test/openapi-nested-paths.test.mjs +0 -100
  101. package/test/openapi-to-connector.test.mts +0 -225
  102. package/test/openapi-ts-compilation.test.mjs +0 -178
  103. package/test/scenarios/README.md +0 -148
  104. package/test/scenarios/complex/expected/controller.mts +0 -271
  105. package/test/scenarios/complex/expected/orders-resource.mts +0 -262
  106. package/test/scenarios/complex/expected/products-resource.mts +0 -237
  107. package/test/scenarios/complex/specs/orders.json +0 -362
  108. package/test/scenarios/complex/specs/products.json +0 -308
  109. package/test/scenarios/simple/expected-controller.mts +0 -60
  110. package/test/scenarios/simple/simple-api.json +0 -39
  111. package/test/scenarios.test.mts +0 -294
  112. package/test/transform.test.mjs +0 -68
  113. package/test/verify-scenarios.mjs +0 -298
  114. package/tools/mutation-run-entry.mjs +0 -52
  115. package/tools/mutation-run.mjs +0 -120
  116. package/tools/run-tests.mjs +0 -64
  117. package/tsconfig.json +0 -27
@@ -1,162 +0,0 @@
1
- import {init} from '@paralleldrive/cuid2';
2
- import {AbstractController} from '../../../../index.mjs';
3
- import Dispatcher from '../../../dispatcher/index.mjs';
4
- import Fetcher from '../../../fetcher/fetcher.mjs';
5
- import {Config} from '../../../websocket/config.mjs';
6
- import {decryptConfig} from './decrypt-config.mjs';
7
- import {patchFinishOAuth} from './finish-oauth.mjs';
8
- import {makeOAuth} from './make-oauth.mjs';
9
- import {patchStartOAuth} from './start-oauth.mjs';
10
-
11
- const cuid = init({length: 32});
12
-
13
- export const onConnect = ({
14
- dispatcher,
15
- configSchema,
16
- config,
17
- start,
18
- }: {
19
- config: Config;
20
- configSchema: any;
21
- start: any;
22
- dispatcher: Dispatcher;
23
- }) => {
24
- return async (transport) => {
25
- dispatcher.onConfig = async function (secrets) {
26
- const decrypted: any = await decryptConfig({
27
- configSchema,
28
- secrets,
29
- config,
30
- });
31
-
32
- if (decrypted?.oauthResult?.scope) {
33
- console.log(`Scope: ${decrypted.oauthResult.scope}`);
34
- }
35
-
36
- await patchStartOAuth({dispatcher, decrypted});
37
- await patchFinishOAuth({dispatcher, decrypted, config, transport});
38
-
39
- const theOAuth = await makeOAuth({
40
- config,
41
- transport,
42
- decrypted,
43
- dispatcher,
44
- });
45
-
46
- const getBlob = (id) => {
47
- return new Promise((resolve, reject) => {
48
- const packet = transport.newPacket(
49
- {},
50
- (ret) => (ret?.error ? reject(ret.error) : resolve(ret)),
51
- `_req-${cuid()}`
52
- );
53
-
54
- packet.method('connector.blob.get');
55
- packet.args({
56
- id,
57
- });
58
-
59
- transport.send(packet);
60
- });
61
- };
62
-
63
- const getBlobContent = (id) => {
64
- return new Promise((resolve, reject) => {
65
- const packet = transport.newPacket(
66
- {},
67
- (ret) => (ret?.error ? reject(ret.error) : resolve(ret?.content)),
68
- `_req-${cuid()}`
69
- );
70
-
71
- packet.method('connector.blob.get-content');
72
- packet.args({
73
- id,
74
- });
75
-
76
- transport.send(packet);
77
- });
78
- };
79
-
80
- const createBlob = (args = {}) => {
81
- return new Promise((resolve, reject) => {
82
- const packet = transport.newPacket(
83
- {},
84
- (ret) => (ret?.error ? reject(ret.error) : resolve(ret?.id)),
85
- `_req-${cuid()}`
86
- );
87
-
88
- packet.method('connector.blob.create');
89
- packet.args(args);
90
-
91
- transport.send(packet);
92
- });
93
- };
94
-
95
- let oauthClient;
96
-
97
- start({
98
- config: decrypted,
99
- oauth: theOAuth,
100
- getBlob,
101
- getBlobContent,
102
- createBlob,
103
- healthCheck: async (controller: AbstractController) => {
104
- let result: any = {ok: true, error: null};
105
-
106
- try {
107
- if (oauthClient) {
108
- await oauthClient.__healthCheck();
109
- }
110
-
111
- await controller.__healthCheck(configSchema);
112
- } catch (e: any) {
113
- result.ok = false;
114
- result.error = e.message;
115
- }
116
-
117
- const packet = transport.newPacket({});
118
-
119
- packet.method('connector.health.check');
120
- packet.args(result);
121
-
122
- transport.send(packet);
123
- },
124
- getClient: (arg) => (theOAuth ? (oauthClient = theOAuth.getClient(arg)) : new Fetcher(arg)),
125
- newTask: (name, data) => {
126
- return new Promise((resolve, reject) => {
127
- const packet = transport.newPacket(
128
- {},
129
- (ret) => (ret?.error ? reject(ret.error) : resolve(ret)),
130
- `_req-${cuid()}`
131
- );
132
-
133
- packet.method('connector.task.new');
134
- packet.args({
135
- name,
136
- a: data,
137
- });
138
-
139
- transport.send(packet);
140
- });
141
- },
142
- updateTask: (id, data) => {
143
- return new Promise((resolve, reject) => {
144
- const packet = transport.newPacket(
145
- {},
146
- (ret) => (ret?.error ? reject(ret.error) : resolve(ret)),
147
- `_req-${cuid()}`
148
- );
149
-
150
- packet.method('connector.task.update');
151
- packet.args({
152
- id,
153
- a: data,
154
- });
155
-
156
- transport.send(packet);
157
- });
158
- },
159
- });
160
- };
161
- };
162
- };
@@ -1,97 +0,0 @@
1
- import Dispatcher from '../../../dispatcher/index.mjs';
2
- import {OAuth} from '../../../fetcher/oauth-fetcher.mjs';
3
- import {Config} from '../../../websocket/config.mjs';
4
-
5
- export const makeOAuth = async ({
6
- config,
7
- transport,
8
- decrypted,
9
- dispatcher,
10
- }: {
11
- config: Config;
12
- transport: any;
13
- decrypted: any;
14
- dispatcher: Dispatcher;
15
- }) => {
16
- const saveOAuthResult = async (what) => {
17
- const jwe = await config.validateKeys('RSA-OAEP-256');
18
- const value = await jwe.encrypt(what, 'none', config.id());
19
-
20
- const packet = transport.newPacket({});
21
-
22
- packet.method('connector.config-update');
23
- packet.args({
24
- value,
25
- });
26
-
27
- transport.send(packet);
28
- };
29
-
30
- const getRefreshToken = async (refreshToken) => {
31
- const tokenURL = process.env.OAUTH_TOKEN_URL || decrypted.tokenURL || dispatcher._oauth.tokenURL;
32
-
33
- const clientId = decrypted.clientId || process.env.OAUTH_CLIENT_ID || dispatcher._oauth.clientId;
34
- if (!clientId) throw new Error('clientId not configured');
35
-
36
- const clientSecret = decrypted.clientSecret || process.env.OAUTH_CLIENT_SECRET || dispatcher._oauth.clientSecret;
37
- if (!clientSecret) throw new Error('clientSecret not configured');
38
-
39
- const useAuthHeader = !!dispatcher._oauth.useAuthHeader;
40
-
41
- let headers = {};
42
-
43
- if (useAuthHeader) {
44
- headers = {
45
- ...headers,
46
- Authorization: `Basic ${btoa(`${clientId}:${clientSecret}`)}`,
47
- };
48
- }
49
-
50
- const response = await fetch(tokenURL, {
51
- method: 'POST',
52
- body: new URLSearchParams({
53
- grant_type: 'refresh_token',
54
- refresh_token: refreshToken,
55
- client_id: clientId,
56
- client_secret: clientSecret,
57
- }),
58
- headers: {
59
- 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
60
- Accept: 'application/json',
61
- ...headers,
62
- },
63
- signal: AbortSignal.timeout(60 * 1000),
64
- });
65
-
66
- const status = await response.status;
67
- const text = await response.text();
68
-
69
- if (status === 200) {
70
- return JSON.parse(text);
71
- } else {
72
- throw new Error('could not get refresh token ' + status + ' ' + text);
73
- }
74
- };
75
-
76
- const theOAuth = dispatcher._oauth ? new OAuth(decrypted.oauthResult, saveOAuthResult, getRefreshToken) : null;
77
-
78
- if (theOAuth) {
79
- clearInterval(dispatcher._refreshOAuthToken);
80
-
81
- if (!(dispatcher._oauth.noPeriodicTokenRefresh === false)) {
82
- dispatcher._refreshOAuthToken = setInterval(
83
- async () => {
84
- try {
85
- console.log('refreshing oauth token');
86
- await theOAuth.periodicRefresh();
87
- } catch (e) {
88
- console.log('periodic refresh', e);
89
- }
90
- },
91
- dispatcher._oauth.tokenRefreshPeriod || 4 * 60 * 60 * 15000
92
- );
93
- }
94
- }
95
-
96
- return theOAuth;
97
- };
@@ -1,24 +0,0 @@
1
- export const patchStartOAuth = async ({dispatcher, decrypted}) => {
2
- dispatcher.startOAuth = async function () {
3
- if (!dispatcher._oauth) throw new Error('oauth not configured');
4
-
5
- const authorizationURL =
6
- process.env.OAUTH_AUTHORIZATION_URL || decrypted.authorizationURL || dispatcher._oauth.authorizationURL;
7
-
8
- if (!authorizationURL) throw new Error('authorizationURL not configured');
9
-
10
- const clientId = decrypted.clientId || process.env.OAUTH_CLIENT_ID || dispatcher._oauth.clientId;
11
-
12
- if (!clientId) throw new Error('clientId not configured');
13
-
14
- const scopes = process.env.OAUTH_SCOPE || decrypted.scope || dispatcher._oauth.scope || '';
15
- const useCodeChallenge = !!dispatcher._oauth.useCodeChallenge;
16
-
17
- return {
18
- url: authorizationURL
19
- .replace(/\{\{clientId\}\}/gi, encodeURIComponent(clientId))
20
- .replace(/\{\{scope\}\}/gi, encodeURIComponent(scopes)),
21
- useCodeChallenge,
22
- };
23
- };
24
- };
@@ -1,13 +0,0 @@
1
- import {handlePacketError, reply} from '../../util/index.mjs';
2
-
3
- export const onMessage = (processPacket: any) => {
4
- return async (packet, transport) => {
5
- try {
6
- const ret = await processPacket(packet);
7
- if (ret) reply(ret, packet, transport);
8
- } catch (e) {
9
- console.log(e);
10
- handlePacketError(packet, e, transport);
11
- }
12
- };
13
- };
@@ -1,231 +0,0 @@
1
- export default class Dispatcher {
2
- private _config: any;
3
- private _main: any;
4
- _oauth: any;
5
- private _types: any;
6
- private _resolvers: any;
7
- _refreshOAuthToken?: any;
8
-
9
- constructor() {
10
- this._config = {fields: {}};
11
- }
12
-
13
- main(what) {
14
- this._main = what;
15
-
16
- return this;
17
- }
18
-
19
- oauth(arg) {
20
- if (arg.platformOAuth) {
21
- this.config({
22
- oauth: true,
23
- fields: {
24
- oauthResult: {
25
- name: 'OAuth Result',
26
- placeholder: 'will be set by finishing the oauth flow',
27
- type: 'managed',
28
- },
29
- },
30
- });
31
-
32
- return this;
33
- }
34
-
35
- if (!arg.authorizationURL) throw new Error('need a authorizationURL');
36
- if (!arg.tokenURL && !arg.finishOAuth) throw new Error('need a tokenURL or finishOAuth()');
37
-
38
- this._oauth = {...arg};
39
-
40
- this.config({
41
- oauth: true,
42
- fields: {
43
- oauthResult: {
44
- name: 'OAuth Result',
45
- placeholder: 'will be set by finishing the oauth flow',
46
- type: 'managed',
47
- optional: !!arg.connectionOptional,
48
- },
49
- },
50
- });
51
-
52
- if (arg.configurableClient) {
53
- this.config({
54
- fields: {
55
- clientId: {
56
- name: 'OAuth Client ID',
57
- placeholder: 'e.g. 1234',
58
- type: 'line',
59
- optional: !!arg.configurableClientOptional,
60
- plain: true,
61
- },
62
- clientSecret: {
63
- name: 'OAuth Client Secret',
64
- placeholder: 'e.g. axd5xde',
65
- optional: !!arg.configurableClientOptional,
66
- type: 'line',
67
- },
68
- },
69
- });
70
- }
71
-
72
- if (arg.configurableClientScope) {
73
- this.config({
74
- fields: {
75
- scope: {
76
- name: 'OAuth Scope',
77
- placeholder: 'e.g. x y z',
78
- type: 'line',
79
- description: `Default Scope:
80
-
81
- ${arg.configurableClientScope}
82
- `,
83
- optional: true,
84
- plain: true,
85
- },
86
- },
87
- });
88
- }
89
-
90
- return this;
91
- }
92
-
93
- types(what) {
94
- this._types = what;
95
-
96
- return this;
97
- }
98
-
99
- config({fields, oauth, description, summary}: any) {
100
- this._config.oauth = this._config.oauth || oauth;
101
- this._config.description = this._config.description || description;
102
- this._config.summary = this._config.summary || summary;
103
- this._config.fields = {...fields, ...this._config.fields};
104
-
105
- return this;
106
- }
107
-
108
- resolvers(what) {
109
- this._resolvers = {...this._resolvers, ...what};
110
-
111
- return this;
112
- }
113
-
114
- endpoint(what, notOptional) {
115
- this.config({
116
- fields: {
117
- _endpointToken: {
118
- name: 'Endpoint Token',
119
- placeholder: 'e.g. 1234',
120
- type: !!notOptional ? 'managed' : 'line',
121
- plain: true,
122
- optional: !notOptional,
123
- },
124
- },
125
- });
126
-
127
- this.resolvers({_endpoint: what});
128
-
129
- return this;
130
- }
131
-
132
- async startOAuth(): Promise<{
133
- url: string;
134
- useCodeChallenge: boolean;
135
- }> {
136
- throw new Error('oauth not configured');
137
- }
138
-
139
- async finishOAuth(arg: {code: string; redirectURI: string; codeVerifier?: string}): Promise<{value: string}> {
140
- throw new Error('oauth not configured');
141
- }
142
-
143
- build() {
144
- if (!this._types || !this._resolvers) throw new Error('missing types or resolvers');
145
- var local = this;
146
-
147
- const _resolvers = {...this._resolvers};
148
-
149
- const main = this._main || (() => {});
150
-
151
- const start = async (arg) => {
152
- console.log('starting ...');
153
- await main(arg);
154
- };
155
-
156
- const resolveMethod = (query) => {
157
- let current = _resolvers;
158
-
159
- while (query.length && current) {
160
- current = current[query.shift()];
161
- }
162
-
163
- return current;
164
- };
165
-
166
- const execute = async ({query, variables, taskId, namespace, sticky}: any) => {
167
- const ctx = {taskId, namespace, sticky};
168
- if (!Array.isArray(query)) query = [query];
169
-
170
- query = query
171
- .filter(
172
- (what) => !!what?.trim() && !['constructor', '__proto__', 'toString', 'toSource', 'prototype'].includes(what)
173
- )
174
- .slice(0, 20);
175
-
176
- const originalQuery = [...query];
177
-
178
- const method = resolveMethod(query);
179
- if (!method && !_resolvers.__default) throw new Error(`${originalQuery} not found`);
180
-
181
- return method ? method(variables, ctx) : _resolvers.__default(variables ? {...variables, __method: originalQuery} : variables, ctx);
182
- };
183
-
184
- const introspect = () => local._types;
185
- const configSchema = () => local._config;
186
-
187
- const processPacket = async (packet) => {
188
- switch (packet.method()) {
189
- case 'connector.introspect':
190
- // @ts-ignore
191
- const intro = await introspect({});
192
-
193
- return {configSchema: local._config, introspect: intro};
194
-
195
- case 'connector.start-oauth':
196
- // @ts-ignore
197
- return await local.startOAuth(packet.args());
198
-
199
- case 'connector.finish-oauth':
200
- // @ts-ignore
201
- return await local.finishOAuth(packet.args());
202
-
203
- case 'connector.query':
204
- const ret = await execute(packet.args());
205
-
206
- return typeof ret === 'object' && !Array.isArray(ret) ? ret : {[packet.args().query]: ret};
207
-
208
- case 'connector.set-config':
209
- await local.onConfig({...packet.args().secrets});
210
-
211
- return;
212
- }
213
-
214
- console.dir(packet, {depth: null});
215
- throw new Error('cannot handle packet');
216
- };
217
-
218
- return {
219
- introspect,
220
- configSchema,
221
- execute,
222
- processPacket,
223
- start,
224
- };
225
- }
226
- onConfig(arg0: any) {
227
- throw new Error('Method not implemented.');
228
- }
229
- }
230
-
231
- export {Dispatcher};
@@ -1,166 +0,0 @@
1
- import {unwrap} from '../util/index.mjs';
2
-
3
- /**
4
- * http request fetcher
5
- */
6
- export default class Fetcher {
7
- protected retry: number;
8
- protected baseUrl: any;
9
- protected onResponse: any;
10
- protected customize0: any;
11
- constructor({
12
- retry = 5,
13
- baseUrl,
14
- onResponse,
15
- customize,
16
- }: {
17
- retry?: number;
18
- baseUrl?: string;
19
- onResponse?: (response: Response) => void;
20
- customize?: (request: {[key: string]: any}) => void;
21
- } = {}) {
22
- this.retry = retry;
23
- this.baseUrl = baseUrl;
24
- this.onResponse = onResponse;
25
- if (customize) this.customize0 = customize;
26
- }
27
-
28
- async getToken(force: boolean): Promise<string> {
29
- throw new Error('not implemented');
30
- }
31
-
32
- protected async customize(options = {}, args = {}) {
33
- if (this.customize0) await this.customize0(options, args);
34
- }
35
-
36
- protected async onError(e: any, url: string, options: any, retries: number, args: any, rateLimit?) {
37
- var local = this;
38
-
39
- return new Promise((resolve, reject) => {
40
- setTimeout(
41
- async () => {
42
- try {
43
- resolve(await local.fetch(url, options, retries, args));
44
- } catch (e) {
45
- reject(e);
46
- }
47
- },
48
- rateLimit ? 10000 : 500
49
- );
50
- });
51
- }
52
-
53
- /**
54
- * fetch data from a url
55
- * @param url url to fetch
56
- * @param options request options
57
- * @param retries retries left for the request
58
- * @param args optional args for customize()
59
- * @returns
60
- */
61
- async fetch(
62
- url: string,
63
- options?: {
64
- /**
65
- * request method like GET, POST, PUT, DELETE
66
- */
67
- method?: string;
68
- /**
69
- * request headers like Accept, Content-type
70
- */
71
- headers?: {[key: string]: any};
72
- /**
73
- * request body like "hello world" or {hello: "world"}
74
- */
75
- body?: any;
76
- },
77
- retries?: number,
78
- args: any = {}
79
- ) {
80
- var local = this,
81
- baseUrl = local.baseUrl;
82
- options ||= {};
83
-
84
- const options0: any = {...options};
85
-
86
- if (retries == null) retries = local.retry;
87
-
88
- let theURL = !baseUrl ? url : `${baseUrl?.endsWith('/') ? baseUrl : baseUrl + '/'}${url}`.replace(/\/\/+/gi, '/');
89
-
90
- try {
91
- options0.url = url;
92
- await local.customize(options0, args);
93
-
94
- url = options0.url;
95
- delete options0.url;
96
-
97
- theURL = !baseUrl ? url : `${baseUrl?.endsWith('/') ? baseUrl : baseUrl + '/'}${url}`.replace(/\/\/+/gi, '/');
98
-
99
- if (!options0?.headers || !options0?.headers?.Accept) {
100
- options0.headers = {
101
- ...options0.headers,
102
- Accept: 'application/json',
103
- };
104
- }
105
-
106
- if ((!options0?.headers || !options0?.headers?.['Content-type']) && !(options0?.body instanceof FormData)) {
107
- options0.headers = {
108
- ...options0.headers,
109
- 'Content-type': 'application/json',
110
- };
111
- }
112
-
113
- if (
114
- !(options0?.method === 'GET' || options0?.method === 'HEAD') &&
115
- options0?.body &&
116
- !(typeof options0.body === 'string') &&
117
- options0?.headers?.['Content-type'] === 'application/json'
118
- ) {
119
- options0.body = JSON.stringify(options0.body);
120
- }
121
-
122
- const timeout = Math.min(options0?.timeout || 30 * 60 * 1000, 30 * 60 * 1000);
123
- const ret = await fetch(theURL, {
124
- ...options0,
125
- signal: AbortSignal.timeout(timeout),
126
- });
127
- const status = await ret.status;
128
-
129
- if (status > 399) {
130
- const text = await ret.text();
131
- const e: any = new Error(status + ' ' + text);
132
-
133
- e.status = status;
134
- throw e;
135
- }
136
-
137
- if (local.onResponse) {
138
- await local.onResponse(ret);
139
- }
140
-
141
- if (status === 204) {
142
- return {ok: true};
143
- }
144
-
145
- return unwrap(ret, options0);
146
- } catch (e: any) {
147
- // too many requests
148
- if (e.status === 429) {
149
- return local.onError(e, url, options0, retries, args, true);
150
- }
151
-
152
- // bad request
153
- if (e.status === 400 || e.status === 422) {
154
- throw e;
155
- }
156
-
157
- --retries;
158
-
159
- console.log(theURL, e);
160
-
161
- if (retries <= 0) throw e;
162
-
163
- return local.onError(e, url, options0, retries, args);
164
- }
165
- }
166
- }