@clickup/rest-client 2.10.293 → 2.10.296

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 (92) hide show
  1. package/.eslintrc.base.js +20 -2
  2. package/README.md +3 -1
  3. package/SECURITY.md +39 -0
  4. package/dist/.eslintcache +1 -0
  5. package/dist/RestClient.js +1 -1
  6. package/dist/RestClient.js.map +1 -1
  7. package/dist/RestOptions.d.ts +5 -7
  8. package/dist/RestOptions.d.ts.map +1 -1
  9. package/dist/RestOptions.js +2 -2
  10. package/dist/RestOptions.js.map +1 -1
  11. package/dist/RestRequest.d.ts.map +1 -1
  12. package/dist/RestRequest.js +7 -13
  13. package/dist/RestRequest.js.map +1 -1
  14. package/dist/RestResponse.d.ts +4 -1
  15. package/dist/RestResponse.d.ts.map +1 -1
  16. package/dist/RestResponse.js +2 -1
  17. package/dist/RestResponse.js.map +1 -1
  18. package/dist/RestStream.js.map +1 -1
  19. package/dist/errors/RestRateLimitError.d.ts.map +1 -1
  20. package/dist/errors/RestRateLimitError.js.map +1 -1
  21. package/dist/errors/RestRetriableError.d.ts.map +1 -1
  22. package/dist/errors/RestRetriableError.js.map +1 -1
  23. package/dist/errors/RestTokenInvalidError.d.ts.map +1 -1
  24. package/dist/errors/RestTokenInvalidError.js.map +1 -1
  25. package/dist/helpers/depaginate.d.ts +1 -1
  26. package/dist/helpers/depaginate.d.ts.map +1 -1
  27. package/dist/helpers/depaginate.js.map +1 -1
  28. package/dist/internal/RestFetchReader.d.ts +9 -2
  29. package/dist/internal/RestFetchReader.d.ts.map +1 -1
  30. package/dist/internal/RestFetchReader.js +14 -3
  31. package/dist/internal/RestFetchReader.js.map +1 -1
  32. package/dist/internal/RestRangeUploader.js.map +1 -1
  33. package/dist/internal/calcRetryDelay.js.map +1 -1
  34. package/dist/internal/inferResBodyEncoding.js.map +1 -1
  35. package/dist/internal/inspectPossibleJSON.js.map +1 -1
  36. package/dist/internal/substituteParams.js.map +1 -1
  37. package/dist/internal/throwIfErrorResponse.js.map +1 -1
  38. package/dist/middlewares/paceRequests.js.map +1 -1
  39. package/dist/pacers/PacerQPS.js.map +1 -1
  40. package/docs/README.md +3 -1
  41. package/docs/classes/PacerComposite.md +7 -3
  42. package/docs/classes/PacerQPS.md +7 -3
  43. package/docs/classes/RestClient.md +32 -28
  44. package/docs/classes/RestContentSizeOverLimitError.md +5 -1
  45. package/docs/classes/RestError.md +5 -1
  46. package/docs/classes/RestRateLimitError.md +6 -2
  47. package/docs/classes/RestRequest.md +22 -18
  48. package/docs/classes/RestResponse.md +25 -10
  49. package/docs/classes/RestResponseError.md +5 -1
  50. package/docs/classes/RestRetriableError.md +6 -2
  51. package/docs/classes/RestStream.md +12 -8
  52. package/docs/classes/RestTimeoutError.md +5 -1
  53. package/docs/classes/RestTokenInvalidError.md +6 -2
  54. package/docs/interfaces/Middleware.md +4 -4
  55. package/docs/interfaces/Pacer.md +2 -2
  56. package/docs/interfaces/PacerQPSBackend.md +2 -2
  57. package/docs/interfaces/RestLogEvent.md +1 -1
  58. package/docs/interfaces/RestOptions.md +59 -23
  59. package/docs/interfaces/TokenGetter.md +3 -3
  60. package/docs/modules.md +4 -4
  61. package/jest.config.js +3 -0
  62. package/package.json +40 -8
  63. package/src/RestClient.ts +490 -0
  64. package/src/RestOptions.ts +186 -0
  65. package/src/RestRequest.ts +441 -0
  66. package/src/RestResponse.ts +49 -0
  67. package/src/RestStream.ts +89 -0
  68. package/src/errors/RestContentSizeOverLimitError.ts +3 -0
  69. package/src/errors/RestError.ts +6 -0
  70. package/src/errors/RestRateLimitError.ts +12 -0
  71. package/src/errors/RestResponseError.ts +46 -0
  72. package/src/errors/RestRetriableError.ts +12 -0
  73. package/src/errors/RestTimeoutError.ts +3 -0
  74. package/src/errors/RestTokenInvalidError.ts +11 -0
  75. package/src/helpers/depaginate.ts +37 -0
  76. package/src/index.ts +50 -0
  77. package/src/internal/RestFetchReader.ts +188 -0
  78. package/src/internal/RestRangeUploader.ts +61 -0
  79. package/src/internal/calcRetryDelay.ts +59 -0
  80. package/src/internal/inferResBodyEncoding.ts +33 -0
  81. package/src/internal/inspectPossibleJSON.ts +71 -0
  82. package/src/internal/prependNewlineIfMultiline.ts +3 -0
  83. package/src/internal/substituteParams.ts +25 -0
  84. package/src/internal/throwIfErrorResponse.ts +89 -0
  85. package/src/internal/toFloatMs.ts +3 -0
  86. package/src/middlewares/paceRequests.ts +42 -0
  87. package/src/pacers/Pacer.ts +22 -0
  88. package/src/pacers/PacerComposite.ts +29 -0
  89. package/src/pacers/PacerQPS.ts +147 -0
  90. package/tsconfig.json +5 -13
  91. package/typedoc.json +6 -1
  92. package/dist/tsconfig.tsbuildinfo +0 -1
package/package.json CHANGED
@@ -1,19 +1,36 @@
1
1
  {
2
2
  "name": "@clickup/rest-client",
3
3
  "description": "A syntax sugar tool around Node fetch() API, tailored to work with TypeScript and response validators",
4
- "version": "2.10.293",
4
+ "version": "2.10.296",
5
5
  "license": "MIT",
6
- "main": "dist/index.js",
7
- "types": "dist/index.d.ts",
6
+ "keywords": [
7
+ "rest-client",
8
+ "rest",
9
+ "request",
10
+ "response",
11
+ "fetch",
12
+ "typescript",
13
+ "nodejs",
14
+ "superstruct",
15
+ "typescript-is",
16
+ "validation",
17
+ "json validation",
18
+ "strong typing",
19
+ "node-fetch"
20
+ ],
21
+ "main": "./dist/index.js",
22
+ "types": "./dist/index.d.ts",
23
+ "exports": "./dist/index.js",
8
24
  "scripts": {
9
25
  "build": "tsc",
10
- "dev": "tsc --watch",
26
+ "dev": "tsc --watch --preserveWatchOutput",
11
27
  "lint": "eslint . --ext .ts --cache --cache-location dist/.eslintcache",
12
28
  "test": "jest",
13
29
  "docs": "rm -rf docs && typedoc --plugin typedoc-plugin-markdown --plugin typedoc-plugin-merge-modules && sed -i '' -E 's#packages/[^/]+/##g' $(find docs -type f -name '*.md')",
14
- "clean": "rm -rf dist node_modules yarn.lock package-lock.json",
30
+ "clean": "rm -rf dist node_modules yarn.lock package-lock.json pnpm-lock.yaml *.log",
15
31
  "copy-package-to-public-dir": "copy-package-to-public-dir.sh",
16
- "deploy": "npm run build && npm test && npm publish --access=public"
32
+ "backport-package-from-public-dir": "backport-package-from-public-dir.sh",
33
+ "deploy": "npm run build && npm run lint && npm run test && npm publish --access=public"
17
34
  },
18
35
  "dependencies": {
19
36
  "abort-controller": "^3.0.0",
@@ -28,11 +45,26 @@
28
45
  "@types/jest": "^29.5.5",
29
46
  "@types/lodash": "^4.14.175",
30
47
  "@types/node-fetch": "^2.6.4",
31
- "superstruct": "^0.15.3",
48
+ "@types/node": "^20.4.1",
49
+ "@typescript-eslint/eslint-plugin": "^5.59.6",
50
+ "@typescript-eslint/parser": "^5.59.6",
51
+ "eslint-import-resolver-typescript": "^3.5.5",
52
+ "eslint-plugin-import": "^2.27.5",
53
+ "eslint-plugin-lodash": "^7.4.0",
54
+ "eslint-plugin-node": "^11.1.0",
55
+ "eslint-plugin-react-hooks": "^4.6.0",
56
+ "eslint-plugin-react": "^7.32.2",
57
+ "eslint-plugin-typescript-enum": "^2.1.0",
58
+ "eslint-plugin-typescript-sort-keys": "^2.3.0",
59
+ "eslint-plugin-unused-imports": "^2.0.0",
60
+ "eslint": "^8.40.0",
61
+ "jest": "^29.7.0",
62
+ "prettier": "3.2.1",
63
+ "superstruct": "^1.0.3",
32
64
  "ts-jest": "^29.1.1",
33
- "typedoc": "^0.25.2",
34
65
  "typedoc-plugin-markdown": "^3.16.0",
35
66
  "typedoc-plugin-merge-modules": "^5.1.0",
67
+ "typedoc": "^0.25.2",
36
68
  "typescript": "^5.2.2"
37
69
  },
38
70
  "repository": {
@@ -0,0 +1,490 @@
1
+ import crypto from "crypto";
2
+ import isUndefined from "lodash/isUndefined";
3
+ import omitBy from "lodash/omitBy";
4
+ import { Headers } from "node-fetch";
5
+ import OAuth1 from "oauth-1.0a";
6
+ import RestTokenInvalidError from "./errors/RestTokenInvalidError";
7
+ import RestRangeUploader from "./internal/RestRangeUploader";
8
+ import substituteParams from "./internal/substituteParams";
9
+ import type RestOptions from "./RestOptions";
10
+ import { DEFAULT_OPTIONS } from "./RestOptions";
11
+ import RestRequest from "./RestRequest";
12
+ import type RestResponse from "./RestResponse";
13
+
14
+ /**
15
+ * A callback which returns access token, possibly after refreshing it, and also
16
+ * possibly before a retry on "invalid token" condition. I.e. it can be called
17
+ * once or twice (the 2nd time after the previous request error, and that error
18
+ * will be passed as a parameter).
19
+ */
20
+ export interface TokenGetter<TData = string> {
21
+ (prevError: Error | null): Promise<TData>;
22
+ }
23
+
24
+ /**
25
+ * RestClient is an immutable object which allows to:
26
+ * 1. Send remote requests in different formats, in a caller-friendly manner.
27
+ * 2. Create a new RestClient objects deriving the current set of options and
28
+ * adding new ones.
29
+ */
30
+ export default class RestClient {
31
+ private readonly _options: RestOptions;
32
+
33
+ constructor(options: Partial<RestOptions> = {}) {
34
+ this._options = {
35
+ ...DEFAULT_OPTIONS,
36
+ ...omitBy(options, isUndefined), // undefined === "fallback to default"
37
+ ...(options.keepAlive ? { keepAlive: { ...options.keepAlive } } : {}),
38
+ ...(options.middlewares ? { middlewares: [...options.middlewares] } : {}),
39
+ };
40
+ }
41
+
42
+ /**
43
+ * Returns a new RestClient with some options updated with the passed ones.
44
+ */
45
+ withOptions(options: Partial<RestOptions>) {
46
+ return new RestClient({
47
+ ...this._options,
48
+ ...omitBy(options, isUndefined),
49
+ });
50
+ }
51
+
52
+ /**
53
+ * Returns a new RestClient with added middleware.
54
+ */
55
+ withMiddleware(
56
+ middleware: RestOptions["middlewares"][0],
57
+ method: "unshift" | "push" = "push",
58
+ ) {
59
+ const clone = new RestClient(this._options);
60
+ clone._options.middlewares[method](middleware);
61
+ return clone;
62
+ }
63
+
64
+ /**
65
+ * Returns a new RestClient with the base URL which will be prepended to all
66
+ * relative paths in get(), writeForm() etc. Allows to defer resolution of
67
+ * this base URL to the very late per-request moment. The complicated piece
68
+ * here is that, if we want base URL to be resolved asynchronously, we often
69
+ * times want to reuse the same RestClient object (to e.g. fetch some part of
70
+ * the base URL using already authenticated client). And a re-enterable call
71
+ * appears here which we must protect against in the code below.
72
+ */
73
+ withBase(base: string | (() => Promise<string>)) {
74
+ return this.withMiddleware(async function withBaseMiddleware(req, next) {
75
+ // If URL is already absolute, we don't even need to call base() lambda
76
+ // to resolve it. Return early.
77
+ if (req.url.match(/^\w+:\/\//)) {
78
+ return next(req);
79
+ }
80
+
81
+ // Re-enterable call detected, e.g. base() lambda issued a request
82
+ // through the same RestClient. We must just skip setting the base.
83
+ if (base === "") {
84
+ return next(req);
85
+ }
86
+
87
+ if (typeof base !== "string") {
88
+ const baseGetter = base;
89
+ base = ""; // disable re-enterable calls
90
+ try {
91
+ base = await baseGetter();
92
+ } catch (e: any) {
93
+ base = baseGetter;
94
+ throw e;
95
+ }
96
+ }
97
+
98
+ req.url = new URL(req.url, base).toString();
99
+ return next(req);
100
+ });
101
+ }
102
+
103
+ /**
104
+ * Returns a new RestClient with a custom header.
105
+ */
106
+ withHeader(name: string, value: string | (() => Promise<string>)) {
107
+ return this.withMiddleware(async function withHeaderMiddleware(req, next) {
108
+ req.headers.set(name, typeof value === "string" ? value : await value());
109
+ return next(req);
110
+ });
111
+ }
112
+
113
+ /**
114
+ * Returns a new RestClient with a bearer token authentication workflow.
115
+ * - RestClient supports interception of options.isTokenInvalid() signal and
116
+ * conversion it into RestTokenInvalidError exception.
117
+ * - If a token() is a lambda with 1 argument, it may be called the 2nd time
118
+ * when we get an isTokenInvalid() signal. In this case, the request is
119
+ * retried.
120
+ * - If token() is a lambda with 0 arguments, that means it doesn't want to
121
+ * watch for the isTokenInvalid() signal, so there is no sense in retrying
122
+ * the request either.
123
+ *
124
+ * From the first sight, it looks like options.isTokenInvalid() signal is
125
+ * coupled to setBearer() auth method only. But it's not true:
126
+ * isTokenInvalid() makes sense for ALL authentication methods actually (even
127
+ * for basic auth), and setBearer() is just one of "clients" which implements
128
+ * refreshing/retries on top of isTokenInvalid().
129
+ *
130
+ * Passing the token as lambda allows the caller to implement some complex
131
+ * logic, e.g.:
132
+ * - oauth2 tokens refreshing
133
+ * - marking the token as "revoked" in the database in case the refresh fails
134
+ * - marking the token as "revoked" after a failed request if refresh-token is
135
+ * not supported
136
+ */
137
+ withBearer(token: TokenGetter, bearerPrefix = "Bearer ") {
138
+ return this.withMiddleware(async function withBearerMiddleware(req, next) {
139
+ return tokenRetryStrategy(token, async (tokenData) => {
140
+ req.headers.set("Authorization", bearerPrefix + tokenData);
141
+ return next(req);
142
+ });
143
+ });
144
+ }
145
+
146
+ /**
147
+ * Returns a new RestClient with oauth1 authentication workflow.
148
+ * - In case we get an options.isTokenInvalid() signal, the token() lambda is
149
+ * called the 2nd time with the error object, then the request is retries.
150
+ * This gives the lambda a chance to recover or update something in the
151
+ * database.
152
+ *
153
+ * We use a separate and small oauth-1.0a node library here, because the more
154
+ * popular one (https://www.npmjs.com/package/oauth) doesn't support signing
155
+ * of arbitrary requests, it can only send its own requests.
156
+ */
157
+ withOAuth1(
158
+ consumer: { consumerKey: string; consumerSecret: string },
159
+ token: TokenGetter<{ token: string; tokenSecret: string }>,
160
+ ) {
161
+ const oauth = new OAuth1({
162
+ consumer: { key: consumer.consumerKey, secret: consumer.consumerSecret },
163
+ signature_method: "HMAC-SHA1",
164
+ hash_function: (baseString, key) =>
165
+ crypto.createHmac("sha1", key).update(baseString).digest("base64"),
166
+ });
167
+
168
+ return this.withMiddleware(async function withOAuth1Middleware(req, next) {
169
+ return tokenRetryStrategy(token, async (tokenData) => {
170
+ const requestData: OAuth1.RequestOptions = {
171
+ url: req.url,
172
+ method: req.method,
173
+ data: req.body,
174
+ };
175
+ const addHeaders = oauth.toHeader(
176
+ oauth.authorize(requestData, {
177
+ key: tokenData.token,
178
+ secret: tokenData.tokenSecret,
179
+ }),
180
+ );
181
+ for (const [name, value] of Object.entries(addHeaders)) {
182
+ req.headers.set(name, value);
183
+ }
184
+
185
+ return next(req);
186
+ });
187
+ });
188
+ }
189
+
190
+ /**
191
+ * Returns a new RestClient with basic authorization workflow.
192
+ */
193
+ withBasic(token: TokenGetter<{ name: string; password: string }>) {
194
+ return this.withMiddleware(async function withBasicMiddleware(req, next) {
195
+ return tokenRetryStrategy(token, async ({ name, password }) => {
196
+ const unencodedHeader = name + ":" + password;
197
+ req.headers.set(
198
+ "Authorization",
199
+ "Basic " + Buffer.from(unencodedHeader).toString("base64"),
200
+ );
201
+ return next(req);
202
+ });
203
+ });
204
+ }
205
+
206
+ /**
207
+ * Sends a plain GET request without body.
208
+ *
209
+ * NOTE, all args will be passed through `encodeURIComponent`.
210
+ */
211
+ get(
212
+ path: string,
213
+ args: Partial<Record<string, string | number | string[]>> = {},
214
+ accept: string = "application/json",
215
+ ) {
216
+ return this._noBodyRequest(path, args, "GET", accept);
217
+ }
218
+
219
+ /**
220
+ * Writes some raw string, buffer or a stream.
221
+ */
222
+ writeRaw(
223
+ path: string,
224
+ body: string | Buffer | NodeJS.ReadableStream,
225
+ contentType: string,
226
+ method: "POST" | "PUT" | "PATCH" = "POST",
227
+ accept?: string,
228
+ ) {
229
+ const origShape = simpleShape(path);
230
+ return new RestRequest(
231
+ this._options,
232
+ method,
233
+ path,
234
+ new Headers({
235
+ Accept: accept || contentType,
236
+ "Content-Type": contentType,
237
+ }),
238
+ body,
239
+ origShape,
240
+ );
241
+ }
242
+
243
+ /**
244
+ * A shortcut method to write JSON body.
245
+ */
246
+ writeJson(
247
+ path: string,
248
+ body: any,
249
+ method: "POST" | "PUT" | "PATCH" | "DELETE" = "POST",
250
+ accept: string = "application/json",
251
+ ) {
252
+ const origShape = simpleShape(path, body);
253
+ [path, body] = substituteParams(path, body);
254
+ return new RestRequest(
255
+ this._options,
256
+ method,
257
+ path,
258
+ new Headers({
259
+ Accept: accept || "application/json",
260
+ "Content-Type": "application/json",
261
+ }),
262
+ JSON.stringify(body),
263
+ origShape,
264
+ );
265
+ }
266
+
267
+ /**
268
+ * A shortcut method to write "application/x-www-form-urlencoded" data.
269
+ */
270
+ writeForm(
271
+ path: string,
272
+ body: Partial<Record<string, string>> | string,
273
+ method: "POST" | "PUT" | "PATCH" = "POST",
274
+ accept: string = "application/json",
275
+ ) {
276
+ const origShape = simpleShape(path, body);
277
+ [path, body] = substituteParams(path, body);
278
+ return new RestRequest(
279
+ this._options,
280
+ method,
281
+ path,
282
+ new Headers({
283
+ Accept: accept,
284
+ "Content-Type": "application/x-www-form-urlencoded",
285
+ }),
286
+ typeof body === "string"
287
+ ? body
288
+ : new URLSearchParams(
289
+ omitBy(body, isUndefined) as Record<string, string>,
290
+ ).toString(),
291
+ origShape,
292
+ );
293
+ }
294
+
295
+ /**
296
+ * A shortcut method to write DELETE request.
297
+ */
298
+ writeDelete(
299
+ path: string,
300
+ args: Partial<Record<string, string>> = {},
301
+ accept: string = "application/json",
302
+ ) {
303
+ return this._noBodyRequest(path, args, "DELETE", accept);
304
+ }
305
+
306
+ /**
307
+ * Returns a RestRequest prepared for sending GraphQL operation.
308
+ * - Expects the response to contain no errors; throws otherwise.
309
+ * - In case of success, returns just the content of `data` field (this is
310
+ * different with writeGraphQLNullable() which returns `data` as a separate
311
+ * fields along with `error` and `errors`).
312
+ */
313
+ writeGraphQLX(query: string, variables: any = {}) {
314
+ const oldIsSuccessResponse = this._options.isSuccessResponse;
315
+ return this.withOptions({
316
+ isSuccessResponse: (res) => {
317
+ const oldIsSuccess = oldIsSuccessResponse?.(res);
318
+ const json: any = res.json;
319
+ return oldIsSuccess === "THROW" ||
320
+ !json?.data ||
321
+ json.error ||
322
+ (json.errors instanceof Array && json.errors.length > 0)
323
+ ? "THROW"
324
+ : "BEST_EFFORT";
325
+ },
326
+ })
327
+ .withMiddleware(async function writeGraphQLXMiddleware(req, next) {
328
+ const res = await next(req);
329
+ const json: any = res.json;
330
+ // Substitute the response json object with just its data field.
331
+ Object.defineProperty(res, "json", { value: json.data });
332
+ return res;
333
+ })
334
+
335
+ ._writeGraphQLImpl<any>(query, variables);
336
+ }
337
+
338
+ /**
339
+ * Same as writeGraphQLX(), but doesn't throw if GraphQL response contains
340
+ * non-empty `error` or `errors` fields and instead returns the full response.
341
+ * I.e. allows the caller to process these errors.
342
+ */
343
+ writeGraphQLNullable(query: string, variables: any = {}) {
344
+ return this._writeGraphQLImpl<
345
+ { data?: any; error?: any; errors?: any[] } | null | undefined
346
+ >(query, variables);
347
+ }
348
+
349
+ /**
350
+ * Performs a series of Content-Range requests with content from a sequence of
351
+ * Buffers.
352
+ */
353
+ async rangeUpload(
354
+ path: string,
355
+ mimeType: string,
356
+ stream: AsyncIterable<Buffer>,
357
+ method: "POST" | "PUT" = "POST",
358
+ chunkSize: number,
359
+ ) {
360
+ return new RestRangeUploader(
361
+ this,
362
+ chunkSize,
363
+ method,
364
+ path,
365
+ mimeType,
366
+ ).upload(stream);
367
+ }
368
+
369
+ private _writeGraphQLImpl<TAssertShape>(query: string, variables: any = {}) {
370
+ const origShape = query;
371
+ // To beautify the query, we remove leading spaces (extracted from the last line).
372
+ query = query.trimEnd();
373
+ if (query.match(/\n([ \t]+)[^\n]+$/)) {
374
+ const prefix = RegExp.$1;
375
+ query = query.replace(new RegExp("^" + prefix, "gm"), "").trimEnd();
376
+ }
377
+
378
+ return new RestRequest<TAssertShape>(
379
+ this._options,
380
+ "POST",
381
+ "",
382
+ new Headers({ "Content-Type": "application/json" }),
383
+ JSON.stringify({ variables, query }), // variables first - for truncation in logs,
384
+ origShape,
385
+ );
386
+ }
387
+
388
+ /**
389
+ * Sends a plain request (with no body, like GET or DELETE).
390
+ */
391
+ private _noBodyRequest(
392
+ path: string,
393
+ args: Partial<Record<string, string | number | string[]>> = {},
394
+ method: "GET" | "DELETE",
395
+ accept: string = "application/json",
396
+ ) {
397
+ const origShape = simpleShape(path, args);
398
+ [path, args] = substituteParams(path, args);
399
+ const searchParams = new URLSearchParams();
400
+ for (const [k, v] of Object.entries(args)) {
401
+ if (Array.isArray(v)) {
402
+ for (const element of v) {
403
+ searchParams.append(k, element.toString());
404
+ }
405
+ } else if (v !== undefined) {
406
+ searchParams.append(k, v.toString());
407
+ }
408
+ }
409
+
410
+ const suffix = searchParams.toString();
411
+ if (suffix !== "") {
412
+ path += (path.includes("?") ? "&" : "?") + suffix;
413
+ }
414
+
415
+ return new RestRequest(
416
+ this._options,
417
+ method,
418
+ path,
419
+ new Headers({ Accept: accept }),
420
+ "",
421
+ origShape,
422
+ );
423
+ }
424
+ }
425
+
426
+ /**
427
+ * @ignore
428
+ * Calls token(null), then runs body() passing the result there. If we get a
429
+ * RestTokenInvalidError exception, call token() with this error as a parameter
430
+ * and then passes the response to body() again (kinda retry with a new token).
431
+ */
432
+ export async function tokenRetryStrategy<TData>(
433
+ token: TokenGetter<TData>,
434
+ body: (tokenData: TData) => Promise<RestResponse>,
435
+ ) {
436
+ let tokenData = await token(null);
437
+ try {
438
+ return await body(tokenData);
439
+ } catch (e: any) {
440
+ const supportsRetry = token.length > 0; // args count
441
+ if (e instanceof RestTokenInvalidError && supportsRetry) {
442
+ tokenData = await token(e);
443
+ try {
444
+ return await body(tokenData);
445
+ } catch (e: any) {
446
+ if (e instanceof RestTokenInvalidError) {
447
+ e.message = `(still failed, even with updated token) ${e.message}`;
448
+ }
449
+
450
+ throw e;
451
+ }
452
+ }
453
+
454
+ throw e;
455
+ }
456
+ }
457
+
458
+ /**
459
+ * Returns a simple "shape" of a request useful for e.g. grouping by in logger
460
+ * to figure out, which requests are more frequent.
461
+ * - reflects args names and not values
462
+ * - wipes the domain
463
+ * - removes query string parameter values
464
+ */
465
+ function simpleShape(path: string, args?: any) {
466
+ path = path.replace(/^\w+:\/\/[^/]+/, "").replace(/=[^&]+/g, "=");
467
+
468
+ const argsInPath: string[] = [];
469
+ const regex = /:([a-z0-9_]+)/gi;
470
+ while (true) {
471
+ const match = regex.exec(path);
472
+ if (!match) {
473
+ break;
474
+ } else {
475
+ argsInPath.push(match[1]);
476
+ }
477
+ }
478
+
479
+ const keys =
480
+ args && typeof args === "object"
481
+ ? Object.keys(args)
482
+ // Filter out args that are already mentioned in the path, e.g.
483
+ // /pages/:pageID/blocks.
484
+ .filter((arg) => !argsInPath.includes(arg))
485
+ .sort()
486
+ .join(",")
487
+ : "";
488
+
489
+ return path + (keys !== "" ? `:${keys}` : "");
490
+ }