@api-client/core 0.3.1 → 0.3.4

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 (183) hide show
  1. package/build/browser.d.ts +1 -1
  2. package/build/index.d.ts +2 -2
  3. package/build/index.js.map +1 -1
  4. package/build/src/models/Backend.d.ts +22 -0
  5. package/build/src/runtime/store/StoreSdk.d.ts +192 -12
  6. package/build/src/runtime/store/StoreSdk.js +592 -53
  7. package/build/src/runtime/store/StoreSdk.js.map +1 -1
  8. package/package.json +3 -1
  9. package/src/data/DataReader.ts +11 -0
  10. package/src/data/DataUtils.ts +108 -0
  11. package/src/data/JmesparthReader.ts +26 -0
  12. package/src/data/Json2Xml.ts +190 -0
  13. package/src/data/JsonReader.ts +41 -0
  14. package/src/data/PayloadPointer.ts +48 -0
  15. package/src/data/RequestDataExtractor.ts +133 -0
  16. package/src/data/UrlEncodedReader.ts +20 -0
  17. package/src/data/XmlReader.ts +103 -0
  18. package/src/events/BaseEvents.ts +259 -0
  19. package/src/events/CustomEvent.ts +27 -0
  20. package/src/events/EventTypes.ts +19 -0
  21. package/src/events/Events.ts +19 -0
  22. package/src/events/authorization/AuthorizationEventTypes.ts +22 -0
  23. package/src/events/authorization/AuthorizationEvents.ts +61 -0
  24. package/src/events/cookies/CookieEventTypes.ts +13 -0
  25. package/src/events/cookies/CookieEvents.ts +157 -0
  26. package/src/events/encryption/EncryptionEventTypes.ts +4 -0
  27. package/src/events/encryption/EncryptionEvents.ts +51 -0
  28. package/src/events/environment/EnvironmentEventTypes.ts +3 -0
  29. package/src/events/environment/EnvironmentEvents.ts +24 -0
  30. package/src/events/models/ClientCertificateEvents.ts +87 -0
  31. package/src/events/models/ModelEventTypes.ts +47 -0
  32. package/src/events/models/ModelEvents.ts +7 -0
  33. package/src/events/models/ProjectEvents.ts +331 -0
  34. package/src/events/process/ProcessEventTypes.ts +5 -0
  35. package/src/events/process/ProcessEvents.ts +76 -0
  36. package/src/events/readme.md +22 -0
  37. package/src/events/reporting/ReportingEventTypes.ts +3 -0
  38. package/src/events/reporting/ReportingEvents.ts +28 -0
  39. package/src/events/telemetry/TelemetryEventTypes.ts +10 -0
  40. package/src/events/telemetry/TelemetryEvents.ts +156 -0
  41. package/src/lib/cookies/Cookie.ts +312 -0
  42. package/src/lib/cookies/Cookies.ts +326 -0
  43. package/src/lib/cookies/Utils.ts +168 -0
  44. package/src/lib/headers/Headers.ts +219 -0
  45. package/src/lib/logging/DefaultLogger.ts +19 -0
  46. package/src/lib/logging/DummyLogger.ts +21 -0
  47. package/src/lib/logging/Logger.ts +16 -0
  48. package/src/lib/transformers/PayloadSerializer.ts +332 -0
  49. package/src/lib/transformers/Utils.ts +18 -0
  50. package/src/lib/uuid.ts +40 -0
  51. package/src/mocking/LegacyInterfaces.ts +52 -0
  52. package/src/mocking/LegacyMock.ts +37 -0
  53. package/src/mocking/legacy/Authorization.ts +39 -0
  54. package/src/mocking/legacy/Certificates.ts +145 -0
  55. package/src/mocking/legacy/Cookies.ts +51 -0
  56. package/src/mocking/legacy/HostRules.ts +43 -0
  57. package/src/mocking/legacy/Http.ts +236 -0
  58. package/src/mocking/legacy/HttpResponse.ts +106 -0
  59. package/src/mocking/legacy/RestApi.ts +68 -0
  60. package/src/mocking/legacy/Urls.ts +44 -0
  61. package/src/mocking/legacy/Variables.ts +53 -0
  62. package/src/models/ArcResponse.ts +166 -0
  63. package/src/models/Authorization.ts +481 -0
  64. package/src/models/AuthorizationData.ts +60 -0
  65. package/src/models/Backend.ts +107 -0
  66. package/src/models/ClientCertificate.ts +68 -0
  67. package/src/models/Environment.ts +279 -0
  68. package/src/models/ErrorResponse.ts +101 -0
  69. package/src/models/HistoryIndex.ts +76 -0
  70. package/src/models/HistoryRequest.ts +28 -0
  71. package/src/models/HostRule.ts +163 -0
  72. package/src/models/HttpCookie.ts +285 -0
  73. package/src/models/HttpProject.ts +1294 -0
  74. package/src/models/HttpProjectListItem.ts +23 -0
  75. package/src/models/HttpRequest.ts +124 -0
  76. package/src/models/HttpResponse.ts +143 -0
  77. package/src/models/License.ts +113 -0
  78. package/src/models/ProjectDefinitionProperty.ts +40 -0
  79. package/src/models/ProjectFolder.ts +439 -0
  80. package/src/models/ProjectItem.ts +135 -0
  81. package/src/models/ProjectParent.ts +113 -0
  82. package/src/models/ProjectRequest.ts +277 -0
  83. package/src/models/ProjectSchema.ts +202 -0
  84. package/src/models/Property.ts +423 -0
  85. package/src/models/Provider.ts +98 -0
  86. package/src/models/README.md +20 -0
  87. package/src/models/Request.ts +452 -0
  88. package/src/models/RequestActions.ts +163 -0
  89. package/src/models/RequestAuthorization.ts +115 -0
  90. package/src/models/RequestConfig.ts +317 -0
  91. package/src/models/RequestLog.ts +159 -0
  92. package/src/models/RequestTime.ts +108 -0
  93. package/src/models/RequestUiMeta.ts +258 -0
  94. package/src/models/RequestsSize.ts +65 -0
  95. package/src/models/ResponseAuthorization.ts +104 -0
  96. package/src/models/ResponseRedirect.ts +158 -0
  97. package/src/models/RevisionInfo.ts +37 -0
  98. package/src/models/SentRequest.ts +125 -0
  99. package/src/models/SerializablePayload.ts +68 -0
  100. package/src/models/Server.ts +153 -0
  101. package/src/models/Thing.ts +110 -0
  102. package/src/models/Url.ts +90 -0
  103. package/src/models/User.ts +120 -0
  104. package/src/models/WebApi.ts +234 -0
  105. package/src/models/WebApiIndex.ts +122 -0
  106. package/src/models/Workspace.ts +182 -0
  107. package/src/models/actions/Action.ts +213 -0
  108. package/src/models/actions/ActionView.ts +40 -0
  109. package/src/models/actions/Condition.ts +207 -0
  110. package/src/models/actions/ConditionView.ts +42 -0
  111. package/src/models/actions/Enums.ts +29 -0
  112. package/src/models/actions/RunnableAction.ts +144 -0
  113. package/src/models/actions/runnable/DeleteCookieAction.ts +113 -0
  114. package/src/models/actions/runnable/Runnable.ts +9 -0
  115. package/src/models/actions/runnable/SetCookieAction.ts +216 -0
  116. package/src/models/actions/runnable/SetVariableAction.ts +81 -0
  117. package/src/models/legacy/DataExport.ts +172 -0
  118. package/src/models/legacy/Normalizer.ts +110 -0
  119. package/src/models/legacy/actions/Actions.ts +269 -0
  120. package/src/models/legacy/authorization/Authorization.ts +572 -0
  121. package/src/models/legacy/models/ApiTypes.ts +202 -0
  122. package/src/models/legacy/models/ArcLegacyProject.ts +39 -0
  123. package/src/models/legacy/models/AuthData.ts +17 -0
  124. package/src/models/legacy/models/ClientCertificate.ts +95 -0
  125. package/src/models/legacy/models/Cookies.ts +52 -0
  126. package/src/models/legacy/models/HostRule.ts +35 -0
  127. package/src/models/legacy/models/RestApi.ts +49 -0
  128. package/src/models/legacy/models/UrlHistory.ts +37 -0
  129. package/src/models/legacy/models/Variable.ts +43 -0
  130. package/src/models/legacy/models/base.d.ts +95 -0
  131. package/src/models/legacy/request/ArcRequest.ts +405 -0
  132. package/src/models/legacy/request/ArcResponse.ts +177 -0
  133. package/src/models/legacy/request/HistoryData.ts +47 -0
  134. package/src/models/legacy/request/Legacy.ts +45 -0
  135. package/src/models/legacy/request/RequestBody.ts +87 -0
  136. package/src/models/transformers/ArcDexieTransformer.ts +323 -0
  137. package/src/models/transformers/ArcLegacyNormalizer.ts +85 -0
  138. package/src/models/transformers/ArcLegacyTransformer.ts +200 -0
  139. package/src/models/transformers/ArcPouchTransformer.ts +184 -0
  140. package/src/models/transformers/BaseTransformer.ts +116 -0
  141. package/src/models/transformers/ImportUtils.ts +141 -0
  142. package/src/models/transformers/LegacyDataExportToApiProject.ts +76 -0
  143. package/src/models/transformers/LegacyExportProcessor.ts +252 -0
  144. package/src/models/transformers/PostmanBackupTransformer.ts +306 -0
  145. package/src/models/transformers/PostmanDataTransformer.ts +50 -0
  146. package/src/models/transformers/PostmanTransformer.ts +106 -0
  147. package/src/models/transformers/PostmanV21Transformer.ts +311 -0
  148. package/src/models/transformers/PostmanV2Transformer.ts +308 -0
  149. package/src/models/transformers/har.ts +865 -0
  150. package/src/runtime/actions/ActionRunner.ts +83 -0
  151. package/src/runtime/actions/ConditionRunner.ts +194 -0
  152. package/src/runtime/actions/RunnableCondition.ts +57 -0
  153. package/src/runtime/actions/runnable/ActionRunnable.ts +19 -0
  154. package/src/runtime/actions/runnable/DeleteCookieRunnable.ts +39 -0
  155. package/src/runtime/actions/runnable/SetCookieRunnable.ts +92 -0
  156. package/src/runtime/actions/runnable/SetVariableRunnable.ts +53 -0
  157. package/src/runtime/http-engine/ArcEngine.ts +1064 -0
  158. package/src/runtime/http-engine/Errors.ts +13 -0
  159. package/src/runtime/http-engine/FormData.ts +85 -0
  160. package/src/runtime/http-engine/HttpEngine.ts +874 -0
  161. package/src/runtime/http-engine/HttpErrorCodes.ts +270 -0
  162. package/src/runtime/http-engine/NodeEngine.ts +787 -0
  163. package/src/runtime/http-engine/NodeEngineDirect.ts +476 -0
  164. package/src/runtime/http-engine/PayloadSupport.ts +84 -0
  165. package/src/runtime/http-engine/RequestUtils.ts +164 -0
  166. package/src/runtime/http-engine/ntlm/Des.ts +345 -0
  167. package/src/runtime/http-engine/ntlm/MD4.ts +135 -0
  168. package/src/runtime/http-engine/ntlm/NtlmAuth.ts +186 -0
  169. package/src/runtime/http-engine/ntlm/NtlmMessage.ts +57 -0
  170. package/src/runtime/modules/BasicAuthCache.ts +133 -0
  171. package/src/runtime/modules/ExecutionResponse.ts +4 -0
  172. package/src/runtime/modules/ModulesRegistry.ts +136 -0
  173. package/src/runtime/modules/RequestAuthorization.ts +110 -0
  174. package/src/runtime/modules/RequestCookies.ts +145 -0
  175. package/src/runtime/node/ProjectRunner.ts +275 -0
  176. package/src/runtime/node/RequestFactory.ts +422 -0
  177. package/src/runtime/node/VariablesStore.ts +25 -0
  178. package/src/runtime/store/StoreSdk.ts +838 -0
  179. package/src/runtime/variables/Cache.ts +53 -0
  180. package/src/runtime/variables/EvalFunctions.ts +132 -0
  181. package/src/runtime/variables/ProjectVariables.ts +6 -0
  182. package/src/runtime/variables/VariablesProcessor.ts +543 -0
  183. package/src/runtime/variables/VariablesTokenizer.ts +55 -0
@@ -1,54 +1,196 @@
1
1
  import http from 'http';
2
2
  import https from 'https';
3
3
  import WebSocket from 'ws';
4
+ import { URL } from 'url';
5
+ const E_INVALID_JSON = 'The response is not a valid JSON.';
6
+ const E_RESPONSE_NO_VALUE = 'The response has no value.';
7
+ const E_RESPONSE_STATUS = 'Invalid response status: ';
8
+ const E_RESPONSE_UNKNOWN = 'The response has unknown format.';
9
+ const E_RESPONSE_LOCATION = 'The response has no "location" header.';
10
+ const baseUriSymbol = Symbol('baseUri');
4
11
  /**
5
12
  * NodeJS API for API Client's net-store module.
6
13
  */
7
14
  export class StoreSdk {
8
- baseUri;
9
15
  basePath;
10
16
  /**
11
17
  * The token to use with requests. Can be overwritten with each API call.
12
18
  */
13
19
  token;
20
+ /**
21
+ * The user authentication features.
22
+ */
23
+ auth = new AuthSdk(this);
24
+ /**
25
+ * The store information features
26
+ */
27
+ store = new BackendSdk(this);
28
+ /**
29
+ * The user spaces features.
30
+ */
31
+ space = new SpacesSdk(this);
32
+ /**
33
+ * The user projects features.
34
+ */
35
+ project = new ProjectsSdk(this);
36
+ /**
37
+ * Reads user information.
38
+ */
39
+ user = new UsersSdk(this);
40
+ /**
41
+ * The HTTP(S) requests.
42
+ */
43
+ http = new HttpClient(this);
44
+ /**
45
+ * The web socket requests.
46
+ */
47
+ ws = new WsClient(this);
48
+ [baseUriSymbol] = '';
49
+ /**
50
+ * @returns The base URI to the store.
51
+ */
52
+ get baseUri() {
53
+ return this[baseUriSymbol];
54
+ }
55
+ /**
56
+ * @param value The base URI to the store.
57
+ */
58
+ set baseUri(value) {
59
+ if (!value) {
60
+ throw new Error(`Invalid value for the baseUri`);
61
+ }
62
+ let url;
63
+ try {
64
+ url = new URL(value);
65
+ }
66
+ catch (e) {
67
+ throw new Error(`Invalid baseUri: Not an URL`);
68
+ }
69
+ this[baseUriSymbol] = url.origin;
70
+ const { pathname } = url;
71
+ if (pathname && pathname !== '/') {
72
+ this.basePath = pathname;
73
+ }
74
+ else {
75
+ this.basePath = undefined;
76
+ }
77
+ }
14
78
  /**
15
79
  * @param baseUri The base URI to the store.
16
80
  * @param basePath The base path (the router prefix) for the server.
17
81
  */
18
82
  constructor(baseUri, basePath) {
19
- this.baseUri = baseUri;
20
83
  this.basePath = basePath;
84
+ this.baseUri = baseUri;
21
85
  }
22
86
  /**
23
- * @returns Client information about the store configuration.
87
+ * Creates a full URL for a path.
88
+ * This adds the server's base path and the passed path to the configured base URL.
89
+ * @param path The path to the endpoint, without the base path.
24
90
  */
25
- async getInfo() {
26
- const { baseUri } = this;
27
- const url = `${baseUri}/store`;
28
- const result = await this.get(url);
29
- if (result.status !== 200) {
30
- throw new Error(`Invalid store response. Expected 200 status and ${result.status} received.`);
91
+ getUrl(path = '/') {
92
+ const { baseUri, basePath = '' } = this;
93
+ let userPath = path;
94
+ if (basePath && userPath.startsWith(basePath)) {
95
+ userPath = userPath.substring(basePath.length);
31
96
  }
32
- const body = result.body;
33
- let data;
34
- try {
35
- data = JSON.parse(body);
97
+ return new URL(`${basePath}${userPath}`, baseUri);
98
+ }
99
+ /**
100
+ * Appends list options to the query parameters.
101
+ * @param url The URL object to the API endpoint
102
+ * @param options The list options, if any
103
+ */
104
+ appendListOptions(url, options = {}) {
105
+ const { searchParams } = url;
106
+ if (options.cursor) {
107
+ searchParams.set('cursor', options.cursor);
36
108
  }
37
- catch (e) {
38
- throw new Error(`The server returned invalid response. Unable to read store status.`);
109
+ else {
110
+ if (typeof options.limit === 'number') {
111
+ searchParams.set('limit', String(options.limit));
112
+ }
113
+ if (options.query) {
114
+ searchParams.set('query', options.query);
115
+ }
116
+ if (Array.isArray(options.queryField)) {
117
+ options.queryField.forEach((field) => {
118
+ searchParams.append('queryField', field);
119
+ });
120
+ }
121
+ }
122
+ }
123
+ }
124
+ class SdkBase {
125
+ sdk;
126
+ constructor(sdk) {
127
+ this.sdk = sdk;
128
+ }
129
+ logInvalidResponse(response) {
130
+ if (response.body) {
131
+ try {
132
+ const data = JSON.parse(response.body);
133
+ if (data.message) {
134
+ console.warn(`[Store message]: ${data.message}`);
135
+ }
136
+ }
137
+ catch (e) {
138
+ // .
139
+ }
39
140
  }
40
- return data;
141
+ }
142
+ /**
143
+ * Throws unified message for a common error status codes.
144
+ * It handles 404, 403, and 401 status codes.
145
+ */
146
+ inspectCommonStatusCodes(status) {
147
+ if (status === 404) {
148
+ throw new Error(`Not found.`);
149
+ }
150
+ if (status === 403) {
151
+ throw new Error(`You have no access to this resource.`);
152
+ }
153
+ if (status === 401) {
154
+ throw new Error(`Not authorized.`);
155
+ }
156
+ }
157
+ }
158
+ class AuthSdk extends SdkBase {
159
+ getExpires(headers) {
160
+ if (!headers.expires) {
161
+ return undefined;
162
+ }
163
+ const d = new Date(headers.expires);
164
+ const time = d.getTime();
165
+ if (Number.isNaN(time)) {
166
+ console.warn(`Invalid session response: the expires header cannot be parsed.`);
167
+ return undefined;
168
+ }
169
+ return time;
41
170
  }
42
171
  /**
43
172
  * Creates unauthenticated session in the backend.
44
173
  * @returns The JWT for unauthenticated user.
45
174
  */
46
175
  async createSession() {
47
- const { baseUri } = this;
48
- const url = `${baseUri}/sessions`;
176
+ const url = this.sdk.getUrl('/sessions');
49
177
  // console.log('Create session: ', url);
50
- const result = await this.post(url);
51
- return result.body;
178
+ const result = await this.sdk.http.post(url.toString());
179
+ this.inspectCommonStatusCodes(result.status);
180
+ if (result.status !== 200) {
181
+ throw new Error(`Unable to create the session. Invalid response status: ${result.status}`);
182
+ }
183
+ if (!result.body) {
184
+ throw new Error(`Unable to create the session. Response has no token.`);
185
+ }
186
+ const info = {
187
+ token: result.body,
188
+ };
189
+ const expires = this.getExpires(result.headers);
190
+ if (expires) {
191
+ info.expires = expires;
192
+ }
193
+ return info;
52
194
  }
53
195
  /**
54
196
  * Initializes the authentication session.
@@ -56,17 +198,238 @@ export class StoreSdk {
56
198
  * @returns The location of the authorization endpoint.
57
199
  */
58
200
  async createAuthSession(token, loginPath = '/auth/login') {
59
- const { baseUri } = this;
60
- const url = `${baseUri}${loginPath}`;
61
- const result = await this.post(url, {
62
- token,
63
- });
201
+ const url = this.sdk.getUrl(loginPath);
202
+ const result = await this.sdk.http.post(url.toString(), { token });
203
+ this.inspectCommonStatusCodes(result.status);
64
204
  const loc = result.headers.location;
65
205
  if (!loc) {
66
206
  throw new Error(`The location header not returned by the server.`);
67
207
  }
68
208
  return loc;
69
209
  }
210
+ /**
211
+ * Listens to the first message coming to the client from the auth endpoint.
212
+ * @param authPath The authorization path returned by the server info or 401 response.
213
+ * @param token Optional token to use.
214
+ */
215
+ async listenAuth(authPath, token) {
216
+ const url = this.sdk.getUrl(authPath);
217
+ const client = await this.sdk.ws.createAndConnect(url.toString(), token);
218
+ return new Promise((resolve, reject) => {
219
+ client.on('message', (data) => {
220
+ const message = JSON.parse(data.toString());
221
+ this.sdk.ws.disconnect(client)
222
+ .then(() => {
223
+ if (message.status === 'OK') {
224
+ resolve();
225
+ }
226
+ else {
227
+ reject(new Error(message.message || 'Unknown error'));
228
+ }
229
+ }).catch(cause => reject(cause));
230
+ });
231
+ });
232
+ }
233
+ /**
234
+ * Renews authenticated token to a new one when the token expires.
235
+ * @param token Optional token to use.
236
+ * @returns
237
+ */
238
+ async renewToken(token = this.sdk.token) {
239
+ const authPath = '/sessions/renew';
240
+ const url = this.sdk.getUrl(authPath);
241
+ const result = await this.sdk.http.post(url.toString(), { token });
242
+ this.inspectCommonStatusCodes(result.status);
243
+ if (result.status !== 200) {
244
+ throw new Error(`Unable to renew the token. Invalid response status: ${result.status}`);
245
+ }
246
+ if (!result.body) {
247
+ throw new Error(`Unable to create the session. Response has no token.`);
248
+ }
249
+ const info = {
250
+ token: result.body,
251
+ };
252
+ const expires = this.getExpires(result.headers);
253
+ if (expires) {
254
+ info.expires = expires;
255
+ }
256
+ return info;
257
+ }
258
+ }
259
+ class BackendSdk extends SdkBase {
260
+ /**
261
+ * @returns Client information about the store configuration.
262
+ */
263
+ async getInfo() {
264
+ const url = this.sdk.getUrl('/store');
265
+ const result = await this.sdk.http.get(url.toString());
266
+ this.inspectCommonStatusCodes(result.status);
267
+ if (result.status !== 200) {
268
+ throw new Error(`Invalid store response. Expected 200 status and ${result.status} received.`);
269
+ }
270
+ const body = result.body;
271
+ let data;
272
+ try {
273
+ data = JSON.parse(body);
274
+ }
275
+ catch (e) {
276
+ throw new Error(`The server returned invalid response. Unable to read store status.`);
277
+ }
278
+ return data;
279
+ }
280
+ }
281
+ class SpacesSdk extends SdkBase {
282
+ /**
283
+ * Lists spaces in the store.
284
+ * @param options Optional query options.
285
+ */
286
+ async list(options) {
287
+ const { token } = this.sdk;
288
+ const url = this.sdk.getUrl('/spaces');
289
+ this.sdk.appendListOptions(url, options);
290
+ const result = await this.sdk.http.get(url.toString(), { token });
291
+ this.inspectCommonStatusCodes(result.status);
292
+ const E_PREFIX = 'Unable to list spaces. ';
293
+ if (result.status !== 200) {
294
+ this.logInvalidResponse(result);
295
+ throw new Error(`${E_PREFIX}${E_RESPONSE_STATUS}${result.status}`);
296
+ }
297
+ if (!result.body) {
298
+ throw new Error(`${E_PREFIX}${E_RESPONSE_NO_VALUE}`);
299
+ }
300
+ let data;
301
+ try {
302
+ data = JSON.parse(result.body);
303
+ }
304
+ catch (e) {
305
+ throw new Error(`${E_PREFIX}${E_INVALID_JSON}.`);
306
+ }
307
+ if (!Array.isArray(data.data)) {
308
+ throw new Error(`${E_PREFIX}${E_RESPONSE_UNKNOWN}.`);
309
+ }
310
+ return data;
311
+ }
312
+ /**
313
+ * Creates a workspace in the store.
314
+ * @param space The workspace definition.
315
+ * @returns The key of the creates space.
316
+ */
317
+ async create(space) {
318
+ const { token } = this.sdk;
319
+ const url = this.sdk.getUrl('/spaces');
320
+ const body = JSON.stringify(space);
321
+ const result = await this.sdk.http.post(url.toString(), { token, body });
322
+ this.inspectCommonStatusCodes(result.status);
323
+ const E_PREFIX = 'Unable to create a user space. ';
324
+ if (result.status !== 204) {
325
+ this.logInvalidResponse(result);
326
+ throw new Error(`${E_PREFIX}${E_RESPONSE_STATUS}${result.status}`);
327
+ }
328
+ const { location } = result.headers;
329
+ if (!location) {
330
+ throw new Error(`${E_PREFIX}${E_RESPONSE_LOCATION}`);
331
+ }
332
+ const id = location.split('/').pop();
333
+ return id;
334
+ }
335
+ /**
336
+ * Reads a user space definition from the store.
337
+ * @param key The user space key
338
+ * @returns The definition of the user space.
339
+ */
340
+ async read(key) {
341
+ const { token } = this.sdk;
342
+ const url = this.sdk.getUrl(`/spaces/${key}`);
343
+ const result = await this.sdk.http.get(url.toString(), { token });
344
+ this.inspectCommonStatusCodes(result.status);
345
+ const E_PREFIX = 'Unable to read a user space. ';
346
+ if (result.status !== 200) {
347
+ this.logInvalidResponse(result);
348
+ throw new Error(`${E_PREFIX}${E_RESPONSE_STATUS}${result.status}`);
349
+ }
350
+ if (!result.body) {
351
+ throw new Error(`${E_PREFIX}${E_RESPONSE_NO_VALUE}`);
352
+ }
353
+ let data;
354
+ try {
355
+ data = JSON.parse(result.body);
356
+ }
357
+ catch (e) {
358
+ throw new Error(`${E_PREFIX}${E_INVALID_JSON}.`);
359
+ }
360
+ if (data.kind !== 'ARC#Space') {
361
+ throw new Error(`${E_PREFIX}${E_RESPONSE_UNKNOWN}.`);
362
+ }
363
+ return data;
364
+ }
365
+ /**
366
+ * Patches a user space in the store.
367
+ * @param key The key of the user space to patch
368
+ * @param value The JSON patch to be processed.
369
+ * @returns The JSON patch to revert the change using the `json8-patch` library
370
+ */
371
+ async patch(key, value) {
372
+ const { token } = this.sdk;
373
+ const url = this.sdk.getUrl(`/spaces/${key}`);
374
+ const body = JSON.stringify(value);
375
+ const result = await this.sdk.http.patch(url.toString(), { token, body });
376
+ this.inspectCommonStatusCodes(result.status);
377
+ const E_PREFIX = 'Unable to patch a user space. ';
378
+ if (result.status !== 200) {
379
+ this.logInvalidResponse(result);
380
+ throw new Error(`${E_PREFIX}${E_RESPONSE_STATUS}${result.status}`);
381
+ }
382
+ if (!result.body) {
383
+ throw new Error(`${E_PREFIX}${E_RESPONSE_NO_VALUE}`);
384
+ }
385
+ let data;
386
+ try {
387
+ data = JSON.parse(result.body);
388
+ }
389
+ catch (e) {
390
+ throw new Error(`${E_PREFIX}${E_INVALID_JSON}.`);
391
+ }
392
+ if (!data.revert) {
393
+ throw new Error(`${E_PREFIX}${E_RESPONSE_UNKNOWN}.`);
394
+ }
395
+ return data.revert;
396
+ }
397
+ /**
398
+ * Deletes the space in the store.
399
+ *
400
+ * @param key The key of the space to delete.
401
+ */
402
+ async delete(key) {
403
+ const { token } = this.sdk;
404
+ const url = this.sdk.getUrl(`/spaces/${key}`);
405
+ const result = await this.sdk.http.delete(url.toString(), { token });
406
+ this.inspectCommonStatusCodes(result.status);
407
+ const E_PREFIX = 'Unable to delete a user space. ';
408
+ if (result.status !== 204) {
409
+ this.logInvalidResponse(result);
410
+ throw new Error(`${E_PREFIX}${E_RESPONSE_STATUS}${result.status}`);
411
+ }
412
+ }
413
+ /**
414
+ * Updates the sharing options of the space.
415
+ *
416
+ * @param key The user space key
417
+ * @param value The patch operation on the space's ACL
418
+ */
419
+ async patchUsers(key, value) {
420
+ const { token } = this.sdk;
421
+ const url = this.sdk.getUrl(`/spaces/${key}/users`);
422
+ const body = JSON.stringify(value);
423
+ const result = await this.sdk.http.patch(url.toString(), { token, body });
424
+ this.inspectCommonStatusCodes(result.status);
425
+ const E_PREFIX = 'Unable to patch a user space. ';
426
+ if (result.status !== 204) {
427
+ this.logInvalidResponse(result);
428
+ throw new Error(`${E_PREFIX}${E_RESPONSE_STATUS}${result.status}`);
429
+ }
430
+ }
431
+ }
432
+ class HttpClient extends SdkBase {
70
433
  /**
71
434
  * Performs the GET request.
72
435
  *
@@ -88,7 +451,7 @@ export class StoreSdk {
88
451
  }
89
452
  _get(url, opts = {}) {
90
453
  return new Promise((resolve, reject) => {
91
- const { method = 'GET', headers = {}, token = this.token } = opts;
454
+ const { method = 'GET', headers = {}, token = this.sdk.token } = opts;
92
455
  if (token) {
93
456
  headers.authorization = `Bearer ${token}`;
94
457
  }
@@ -117,7 +480,7 @@ export class StoreSdk {
117
480
  }
118
481
  post(url, opts = {}) {
119
482
  return new Promise((resolve, reject) => {
120
- const { method = 'POST', headers = {}, token = this.token } = opts;
483
+ const { method = 'POST', headers = {}, token = this.sdk.token } = opts;
121
484
  if (token) {
122
485
  headers.authorization = `Bearer ${token}`;
123
486
  }
@@ -155,36 +518,14 @@ export class StoreSdk {
155
518
  options.method = 'DELETE';
156
519
  return this.post(url, options);
157
520
  }
158
- /**
159
- * Listens to the first message coming to the client from the auth endpoint.
160
- * @param authPath The authorization path returned by the server info or 401 response.
161
- * @param token Optional token to use.
162
- */
163
- async listenAuth(authPath, token) {
164
- const { baseUri, basePath = '' } = this;
165
- const authUrl = new URL(`${basePath}${authPath}`, baseUri);
166
- const client = await this.createAndConnect(authUrl.toString(), token);
167
- return new Promise((resolve, reject) => {
168
- client.on('message', (data) => {
169
- const message = JSON.parse(data.toString());
170
- this.disconnect(client)
171
- .then(() => {
172
- if (message.status === 'OK') {
173
- resolve();
174
- }
175
- else {
176
- reject(new Error(message.message || 'Unknown error'));
177
- }
178
- }).catch(cause => reject(cause));
179
- });
180
- });
181
- }
521
+ }
522
+ class WsClient extends SdkBase {
182
523
  /**
183
524
  * Creates a WS client with optional token
184
525
  * @param addr The ws:// address
185
526
  * @param token Optional token to add.
186
527
  */
187
- getWsClient(addr, token = this.token) {
528
+ getClient(addr, token = this.sdk.token) {
188
529
  let url = addr;
189
530
  if (token) {
190
531
  url += url.includes('?') ? '&' : '?';
@@ -236,9 +577,207 @@ export class StoreSdk {
236
577
  * The combination of `getClient()` and `connect()`.
237
578
  */
238
579
  async createAndConnect(addr, token) {
239
- const client = this.getWsClient(addr, token);
580
+ const client = this.getClient(addr, token);
240
581
  await this.connect(client);
241
582
  return client;
242
583
  }
243
584
  }
585
+ class ProjectsSdk extends SdkBase {
586
+ /**
587
+ * Creates a project in a user space.
588
+ *
589
+ * @param key The user space key
590
+ * @param project THe project to create
591
+ * @returns The key of the created project.
592
+ */
593
+ async create(key, project) {
594
+ const { token } = this.sdk;
595
+ const url = this.sdk.getUrl(`/spaces/${key}/projects`);
596
+ const body = JSON.stringify(project);
597
+ const result = await this.sdk.http.post(url.toString(), { token, body });
598
+ this.inspectCommonStatusCodes(result.status);
599
+ const E_PREFIX = 'Unable to create a project. ';
600
+ if (result.status !== 204) {
601
+ this.logInvalidResponse(result);
602
+ throw new Error(`${E_PREFIX}${E_RESPONSE_STATUS}${result.status}`);
603
+ }
604
+ const { location } = result.headers;
605
+ if (!location) {
606
+ throw new Error(`${E_PREFIX}${E_RESPONSE_LOCATION}`);
607
+ }
608
+ const id = location.split('/').pop();
609
+ return id;
610
+ }
611
+ /**
612
+ * Reads a project definition from the store.
613
+ * @param space The user space key
614
+ * @param project The project key
615
+ * @returns The definition of the project.
616
+ */
617
+ async read(space, project) {
618
+ const { token } = this.sdk;
619
+ const url = this.sdk.getUrl(`/spaces/${space}/projects/${project}`);
620
+ const result = await this.sdk.http.get(url.toString(), { token });
621
+ this.inspectCommonStatusCodes(result.status);
622
+ const E_PREFIX = 'Unable to read a project. ';
623
+ if (result.status !== 200) {
624
+ this.logInvalidResponse(result);
625
+ throw new Error(`${E_PREFIX}${E_RESPONSE_STATUS}${result.status}`);
626
+ }
627
+ if (!result.body) {
628
+ throw new Error(`${E_PREFIX}${E_RESPONSE_NO_VALUE}`);
629
+ }
630
+ let data;
631
+ try {
632
+ data = JSON.parse(result.body);
633
+ }
634
+ catch (e) {
635
+ throw new Error(`${E_PREFIX}${E_INVALID_JSON}.`);
636
+ }
637
+ if (data.kind !== 'ARC#HttpProject') {
638
+ throw new Error(`${E_PREFIX}${E_RESPONSE_UNKNOWN}.`);
639
+ }
640
+ return data;
641
+ }
642
+ /**
643
+ * Lists projects in the space
644
+ *
645
+ * @param space The user space key
646
+ * @param options Optional query options.
647
+ */
648
+ async list(space, options) {
649
+ const { token } = this.sdk;
650
+ const url = this.sdk.getUrl(`/spaces/${space}/projects`);
651
+ this.sdk.appendListOptions(url, options);
652
+ const result = await this.sdk.http.get(url.toString(), { token });
653
+ this.inspectCommonStatusCodes(result.status);
654
+ const E_PREFIX = 'Unable to list projects. ';
655
+ if (result.status !== 200) {
656
+ this.logInvalidResponse(result);
657
+ throw new Error(`${E_PREFIX}${E_RESPONSE_STATUS}${result.status}`);
658
+ }
659
+ if (!result.body) {
660
+ throw new Error(`${E_PREFIX}${E_RESPONSE_NO_VALUE}`);
661
+ }
662
+ let data;
663
+ try {
664
+ data = JSON.parse(result.body);
665
+ }
666
+ catch (e) {
667
+ throw new Error(`${E_PREFIX}${E_INVALID_JSON}.`);
668
+ }
669
+ if (!Array.isArray(data.data)) {
670
+ throw new Error(`${E_PREFIX}${E_RESPONSE_UNKNOWN}.`);
671
+ }
672
+ return data;
673
+ }
674
+ /**
675
+ * Deletes a project form the store.
676
+ *
677
+ * @param space The key of the parent space.
678
+ * @param project The key of the project to delete.
679
+ */
680
+ async delete(space, project) {
681
+ const { token } = this.sdk;
682
+ const url = this.sdk.getUrl(`/spaces/${space}/projects/${project}`);
683
+ const result = await this.sdk.http.delete(url.toString(), { token });
684
+ this.inspectCommonStatusCodes(result.status);
685
+ const E_PREFIX = 'Unable to delete a project. ';
686
+ if (result.status !== 204) {
687
+ this.logInvalidResponse(result);
688
+ throw new Error(`${E_PREFIX}${E_RESPONSE_STATUS}${result.status}`);
689
+ }
690
+ }
691
+ /**
692
+ * Patches a project in the store.
693
+ * @param space The key of the parent user space
694
+ * @param project The key of project to patch.
695
+ * @param value The JSON patch to be processed.
696
+ * @returns The JSON patch to revert the change using the `json8-patch` library
697
+ */
698
+ async patch(space, project, value) {
699
+ const { token } = this.sdk;
700
+ const url = this.sdk.getUrl(`/spaces/${space}/projects/${project}`);
701
+ const body = JSON.stringify(value);
702
+ const result = await this.sdk.http.patch(url.toString(), { token, body });
703
+ this.inspectCommonStatusCodes(result.status);
704
+ const E_PREFIX = 'Unable to patch a project. ';
705
+ if (result.status !== 200) {
706
+ this.logInvalidResponse(result);
707
+ throw new Error(`${E_PREFIX}${E_RESPONSE_STATUS}${result.status}`);
708
+ }
709
+ if (!result.body) {
710
+ throw new Error(`${E_PREFIX}${E_RESPONSE_NO_VALUE}`);
711
+ }
712
+ let data;
713
+ try {
714
+ data = JSON.parse(result.body);
715
+ }
716
+ catch (e) {
717
+ throw new Error(`${E_PREFIX}${E_INVALID_JSON}.`);
718
+ }
719
+ if (!data.revert) {
720
+ throw new Error(`${E_PREFIX}${E_RESPONSE_UNKNOWN}.`);
721
+ }
722
+ return data.revert;
723
+ }
724
+ }
725
+ class UsersSdk extends SdkBase {
726
+ async me() {
727
+ const { token } = this.sdk;
728
+ const url = this.sdk.getUrl(`/users/me`);
729
+ const result = await this.sdk.http.get(url.toString(), { token });
730
+ this.inspectCommonStatusCodes(result.status);
731
+ const E_PREFIX = 'Unable to read a user. ';
732
+ if (result.status !== 200) {
733
+ this.logInvalidResponse(result);
734
+ throw new Error(`${E_PREFIX}${E_RESPONSE_STATUS}${result.status}`);
735
+ }
736
+ if (!result.body) {
737
+ throw new Error(`${E_PREFIX}${E_RESPONSE_NO_VALUE}`);
738
+ }
739
+ let data;
740
+ try {
741
+ data = JSON.parse(result.body);
742
+ }
743
+ catch (e) {
744
+ throw new Error(`${E_PREFIX}${E_INVALID_JSON}.`);
745
+ }
746
+ if (!data.key) {
747
+ throw new Error(`${E_PREFIX}${E_RESPONSE_UNKNOWN}.`);
748
+ }
749
+ return data;
750
+ }
751
+ /**
752
+ * Lists users in the store
753
+ *
754
+ * @param options Optional query options.
755
+ */
756
+ async list(options) {
757
+ const { token } = this.sdk;
758
+ const url = this.sdk.getUrl(`/users`);
759
+ this.sdk.appendListOptions(url, options);
760
+ const result = await this.sdk.http.get(url.toString(), { token });
761
+ this.inspectCommonStatusCodes(result.status);
762
+ const E_PREFIX = 'Unable to list projects. ';
763
+ if (result.status !== 200) {
764
+ this.logInvalidResponse(result);
765
+ throw new Error(`${E_PREFIX}${E_RESPONSE_STATUS}${result.status}`);
766
+ }
767
+ if (!result.body) {
768
+ throw new Error(`${E_PREFIX}${E_RESPONSE_NO_VALUE}`);
769
+ }
770
+ let data;
771
+ try {
772
+ data = JSON.parse(result.body);
773
+ }
774
+ catch (e) {
775
+ throw new Error(`${E_PREFIX}${E_INVALID_JSON}.`);
776
+ }
777
+ if (!Array.isArray(data.data)) {
778
+ throw new Error(`${E_PREFIX}${E_RESPONSE_UNKNOWN}.`);
779
+ }
780
+ return data;
781
+ }
782
+ }
244
783
  //# sourceMappingURL=StoreSdk.js.map