@scaleway/sdk-client 1.1.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 (149) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +36 -0
  3. package/dist/bridge.d.ts +12 -0
  4. package/dist/helpers/is-browser.cjs +4 -0
  5. package/dist/helpers/is-browser.d.ts +1 -0
  6. package/dist/helpers/is-browser.js +4 -0
  7. package/dist/helpers/is-response.cjs +4 -0
  8. package/dist/helpers/is-response.d.ts +8 -0
  9. package/dist/helpers/is-response.js +4 -0
  10. package/dist/helpers/json.cjs +7 -0
  11. package/dist/helpers/json.d.ts +13 -0
  12. package/dist/helpers/json.js +7 -0
  13. package/dist/helpers/marshalling.cjs +76 -0
  14. package/dist/helpers/marshalling.d.ts +60 -0
  15. package/dist/helpers/marshalling.js +76 -0
  16. package/dist/index.cjs +52 -0
  17. package/dist/index.d.ts +15 -0
  18. package/dist/index.js +52 -0
  19. package/dist/internal/async/interval-retrier.cjs +53 -0
  20. package/dist/internal/async/interval-retrier.d.ts +111 -0
  21. package/dist/internal/async/interval-retrier.js +53 -0
  22. package/dist/internal/async/sleep.cjs +6 -0
  23. package/dist/internal/async/sleep.d.ts +9 -0
  24. package/dist/internal/async/sleep.js +6 -0
  25. package/dist/internal/interceptors/composer.cjs +25 -0
  26. package/dist/internal/interceptors/composer.d.ts +25 -0
  27. package/dist/internal/interceptors/composer.js +25 -0
  28. package/dist/internal/interceptors/helpers.cjs +12 -0
  29. package/dist/internal/interceptors/helpers.d.ts +21 -0
  30. package/dist/internal/interceptors/helpers.js +12 -0
  31. package/dist/internal/interceptors/types.d.ts +89 -0
  32. package/dist/internal/logger/console-logger.cjs +24 -0
  33. package/dist/internal/logger/console-logger.d.ts +23 -0
  34. package/dist/internal/logger/console-logger.js +24 -0
  35. package/dist/internal/logger/index.cjs +12 -0
  36. package/dist/internal/logger/index.d.ts +25 -0
  37. package/dist/internal/logger/index.js +12 -0
  38. package/dist/internal/logger/level-resolver.cjs +13 -0
  39. package/dist/internal/logger/level-resolver.d.ts +9 -0
  40. package/dist/internal/logger/level-resolver.js +13 -0
  41. package/dist/internal/logger/logger.d.ts +13 -0
  42. package/dist/internal/validations/string-validation.cjs +30 -0
  43. package/dist/internal/validations/string-validation.d.ts +18 -0
  44. package/dist/internal/validations/string-validation.js +30 -0
  45. package/dist/internals.d.ts +10 -0
  46. package/dist/package.json.cjs +67 -0
  47. package/dist/package.json.js +67 -0
  48. package/dist/scw/api.cjs +8 -0
  49. package/dist/scw/api.d.ts +10 -0
  50. package/dist/scw/api.js +8 -0
  51. package/dist/scw/auth.cjs +26 -0
  52. package/dist/scw/auth.d.ts +57 -0
  53. package/dist/scw/auth.js +26 -0
  54. package/dist/scw/client-ini-factory.cjs +66 -0
  55. package/dist/scw/client-ini-factory.d.ts +111 -0
  56. package/dist/scw/client-ini-factory.js +66 -0
  57. package/dist/scw/client-ini-profile.cjs +23 -0
  58. package/dist/scw/client-ini-profile.d.ts +82 -0
  59. package/dist/scw/client-ini-profile.js +23 -0
  60. package/dist/scw/client-settings.cjs +51 -0
  61. package/dist/scw/client-settings.d.ts +59 -0
  62. package/dist/scw/client-settings.js +51 -0
  63. package/dist/scw/client.cjs +31 -0
  64. package/dist/scw/client.d.ts +71 -0
  65. package/dist/scw/client.js +31 -0
  66. package/dist/scw/constants.cjs +7 -0
  67. package/dist/scw/constants.d.ts +2 -0
  68. package/dist/scw/constants.js +7 -0
  69. package/dist/scw/custom-marshalling.cjs +126 -0
  70. package/dist/scw/custom-marshalling.d.ts +80 -0
  71. package/dist/scw/custom-marshalling.js +126 -0
  72. package/dist/scw/custom-types.cjs +11 -0
  73. package/dist/scw/custom-types.d.ts +74 -0
  74. package/dist/scw/custom-types.js +11 -0
  75. package/dist/scw/errors/error-parser.cjs +76 -0
  76. package/dist/scw/errors/error-parser.d.ts +12 -0
  77. package/dist/scw/errors/error-parser.js +76 -0
  78. package/dist/scw/errors/non-standard/invalid-request-mapper.cjs +36 -0
  79. package/dist/scw/errors/non-standard/invalid-request-mapper.d.ts +12 -0
  80. package/dist/scw/errors/non-standard/invalid-request-mapper.js +36 -0
  81. package/dist/scw/errors/non-standard/unknown-resource-mapper.cjs +23 -0
  82. package/dist/scw/errors/non-standard/unknown-resource-mapper.d.ts +11 -0
  83. package/dist/scw/errors/non-standard/unknown-resource-mapper.js +23 -0
  84. package/dist/scw/errors/scw-error-from-json.d.ts +10 -0
  85. package/dist/scw/errors/scw-error.cjs +43 -0
  86. package/dist/scw/errors/scw-error.d.ts +25 -0
  87. package/dist/scw/errors/scw-error.js +43 -0
  88. package/dist/scw/errors/standard/already-exists-error.cjs +31 -0
  89. package/dist/scw/errors/standard/already-exists-error.d.ts +16 -0
  90. package/dist/scw/errors/standard/already-exists-error.js +31 -0
  91. package/dist/scw/errors/standard/denied-authentication-error.cjs +37 -0
  92. package/dist/scw/errors/standard/denied-authentication-error.d.ts +15 -0
  93. package/dist/scw/errors/standard/denied-authentication-error.js +37 -0
  94. package/dist/scw/errors/standard/index.cjs +28 -0
  95. package/dist/scw/errors/standard/index.d.ts +17 -0
  96. package/dist/scw/errors/standard/index.js +28 -0
  97. package/dist/scw/errors/standard/invalid-arguments-error.cjs +54 -0
  98. package/dist/scw/errors/standard/invalid-arguments-error.d.ts +24 -0
  99. package/dist/scw/errors/standard/invalid-arguments-error.js +54 -0
  100. package/dist/scw/errors/standard/out-of-stock-error.cjs +17 -0
  101. package/dist/scw/errors/standard/out-of-stock-error.d.ts +14 -0
  102. package/dist/scw/errors/standard/out-of-stock-error.js +17 -0
  103. package/dist/scw/errors/standard/permissions-denied-error.cjs +29 -0
  104. package/dist/scw/errors/standard/permissions-denied-error.d.ts +23 -0
  105. package/dist/scw/errors/standard/permissions-denied-error.js +29 -0
  106. package/dist/scw/errors/standard/precondition-failed-error.cjs +32 -0
  107. package/dist/scw/errors/standard/precondition-failed-error.d.ts +15 -0
  108. package/dist/scw/errors/standard/precondition-failed-error.js +32 -0
  109. package/dist/scw/errors/standard/quotas-exceeded-error.cjs +43 -0
  110. package/dist/scw/errors/standard/quotas-exceeded-error.d.ts +34 -0
  111. package/dist/scw/errors/standard/quotas-exceeded-error.js +43 -0
  112. package/dist/scw/errors/standard/resource-expired-error.cjs +31 -0
  113. package/dist/scw/errors/standard/resource-expired-error.d.ts +16 -0
  114. package/dist/scw/errors/standard/resource-expired-error.js +31 -0
  115. package/dist/scw/errors/standard/resource-locked-error.cjs +20 -0
  116. package/dist/scw/errors/standard/resource-locked-error.d.ts +15 -0
  117. package/dist/scw/errors/standard/resource-locked-error.js +20 -0
  118. package/dist/scw/errors/standard/resource-not-found-error.cjs +24 -0
  119. package/dist/scw/errors/standard/resource-not-found-error.d.ts +15 -0
  120. package/dist/scw/errors/standard/resource-not-found-error.js +24 -0
  121. package/dist/scw/errors/standard/too-many-requests-error.cjs +58 -0
  122. package/dist/scw/errors/standard/too-many-requests-error.d.ts +32 -0
  123. package/dist/scw/errors/standard/too-many-requests-error.js +58 -0
  124. package/dist/scw/errors/standard/transient-state-error.cjs +31 -0
  125. package/dist/scw/errors/standard/transient-state-error.d.ts +16 -0
  126. package/dist/scw/errors/standard/transient-state-error.js +31 -0
  127. package/dist/scw/errors/types.cjs +15 -0
  128. package/dist/scw/errors/types.d.ts +9 -0
  129. package/dist/scw/errors/types.js +15 -0
  130. package/dist/scw/fetch/build-fetcher.cjs +60 -0
  131. package/dist/scw/fetch/build-fetcher.d.ts +23 -0
  132. package/dist/scw/fetch/build-fetcher.js +60 -0
  133. package/dist/scw/fetch/http-dumper.cjs +20 -0
  134. package/dist/scw/fetch/http-dumper.d.ts +18 -0
  135. package/dist/scw/fetch/http-dumper.js +20 -0
  136. package/dist/scw/fetch/http-interceptors.cjs +43 -0
  137. package/dist/scw/fetch/http-interceptors.d.ts +38 -0
  138. package/dist/scw/fetch/http-interceptors.js +43 -0
  139. package/dist/scw/fetch/resource-paginator.cjs +36 -0
  140. package/dist/scw/fetch/resource-paginator.d.ts +47 -0
  141. package/dist/scw/fetch/resource-paginator.js +36 -0
  142. package/dist/scw/fetch/response-parser.cjs +55 -0
  143. package/dist/scw/fetch/response-parser.d.ts +25 -0
  144. package/dist/scw/fetch/response-parser.js +55 -0
  145. package/dist/scw/fetch/types.d.ts +16 -0
  146. package/dist/scw/locality.d.ts +2 -0
  147. package/dist/vendor/base64/index.cjs +42 -0
  148. package/dist/vendor/base64/index.js +42 -0
  149. package/package.json +37 -0
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const sleep = require("./sleep.cjs");
4
+ const DEFAULT_TIMEOUT_SECONDS = 300;
5
+ const DEFAULT_MIN_DELAY_SECONDS = 1;
6
+ const DEFAULT_MAX_DELAY_SECONDS = 30;
7
+ function* createExponentialBackoffStrategy(minDelay, maxDelay) {
8
+ if (minDelay < 1 || maxDelay < 1 || minDelay > maxDelay) {
9
+ throw new Error(
10
+ "Waiter: minDelay must be >= 1 and maxDelay must be >= minDelay"
11
+ );
12
+ }
13
+ let attempt = 1;
14
+ const ceiling = Math.log(maxDelay / minDelay) / Math.log(2) + 1;
15
+ const randomInRange = (min, max) => min + Math.random() * (max - min);
16
+ while (true) {
17
+ if (attempt > ceiling) {
18
+ yield maxDelay;
19
+ } else {
20
+ yield randomInRange(minDelay, minDelay * 2 ** (attempt - 1));
21
+ }
22
+ attempt += 1;
23
+ }
24
+ }
25
+ const tryAtIntervals = async (retry, strategy, timeout = DEFAULT_TIMEOUT_SECONDS) => {
26
+ const timeoutTimestamp = Date.now() + timeout * 1e3;
27
+ let retryCount = 0;
28
+ while (Date.now() <= timeoutTimestamp) {
29
+ const delay = strategy.next(retryCount += 1).value * 1e3;
30
+ if (timeoutTimestamp <= Date.now() + delay) break;
31
+ await sleep.sleep(delay);
32
+ const { value, done } = await retry();
33
+ if (done) return value;
34
+ }
35
+ throw new Error(`Timeout after ${timeout}s`);
36
+ };
37
+ const waitForResource = (stop, fetcher, request, options, strategy = createExponentialBackoffStrategy(
38
+ options?.minDelay ?? DEFAULT_MIN_DELAY_SECONDS,
39
+ options?.maxDelay ?? DEFAULT_MAX_DELAY_SECONDS
40
+ )) => tryAtIntervals(
41
+ async () => {
42
+ const value = await fetcher(request);
43
+ return {
44
+ done: await stop(value),
45
+ value
46
+ };
47
+ },
48
+ strategy,
49
+ options?.timeout
50
+ );
51
+ exports.createExponentialBackoffStrategy = createExponentialBackoffStrategy;
52
+ exports.tryAtIntervals = tryAtIntervals;
53
+ exports.waitForResource = waitForResource;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Function to retry logic between each interval.
3
+ *
4
+ * @returns The result and if it's done
5
+ *
6
+ * @throws An exception might be thrown by the logic being run
7
+ *
8
+ * @internal
9
+ */
10
+ type Retry<T> = () => Promise<IteratorResult<T, T>>;
11
+ /**
12
+ * Generated interval strategy iterator.
13
+ *
14
+ * @internal
15
+ */
16
+ type IntervalStrategy = Generator<number, number, number>;
17
+ /**
18
+ * Creates a fixed interval strategy.
19
+ * It returns the same interval value whatever the retry count.
20
+ *
21
+ * @param interval - The time interval (in seconds) to wait between each run
22
+ * @returns A fixed interval generator
23
+ *
24
+ * @internal
25
+ */
26
+ export declare function createFixedIntervalStrategy(interval: number): IntervalStrategy;
27
+ /**
28
+ * Creates a fibonacci interval strategy.
29
+ *
30
+ * @param base - The base interval (in seconds) that will be multiplicated with the fibonacci number
31
+ * @param factor - The factor so the fibonacci suite will go slower or faster
32
+ * @returns A fibonnacci generator
33
+ *
34
+ * @internal
35
+ */
36
+ export declare function createFibonacciIntervalStrategy(base?: number, factor?: number): IntervalStrategy;
37
+ /**
38
+ * Creates an exponential backoff interval strategy.
39
+ *
40
+ * @param minDelay - The minimum delay before the next try in seconds
41
+ * @param maxDelay - The maximum delay before the next try in seconds
42
+ * @returns An exponential backoff generator
43
+ *
44
+ * @internal
45
+ */
46
+ export declare function createExponentialBackoffStrategy(minDelay: number, maxDelay: number): IntervalStrategy;
47
+ /**
48
+ * Tries a specific logic several times until it succeeds, timeouts, or throws an exception.
49
+ *
50
+ * @param retry - The function to retry logic between each interval
51
+ * @param strategy - A generated interval strategy iterator
52
+ * @param timeout - The maximum time elapsed before timeout error
53
+ *
54
+ * @throws An timeout exception or error thrown by the logic being run
55
+ *
56
+ * @internal
57
+ */
58
+ export declare const tryAtIntervals: <T>(retry: Retry<T>, strategy: IntervalStrategy, timeout?: number) => Promise<T>;
59
+ /**
60
+ * Represents the condition to stop waiting for a resource.
61
+ *
62
+ * @public
63
+ */
64
+ export type WaitForStopCondition<T> = (obj: T) => Promise<boolean>;
65
+ /**
66
+ * The options to wait until a resource is ready.
67
+ *
68
+ * @public
69
+ */
70
+ export interface WaitForOptions<T> {
71
+ /**
72
+ * Timeout in seconds.
73
+ *
74
+ * @defaultValue 300 seconds (5 minutes).
75
+ */
76
+ timeout?: number;
77
+ /**
78
+ * The minimum delay before the next try in seconds.
79
+ *
80
+ * @defaultValue 1 second.
81
+ */
82
+ minDelay?: number;
83
+ /**
84
+ * The maximum delay before the next try in seconds.
85
+ *
86
+ * @defaultValue 30 seconds.
87
+ */
88
+ maxDelay?: number;
89
+ /**
90
+ * The condition to stop trying.
91
+ *
92
+ * @defaultValue Waits for non-transient value.
93
+ */
94
+ stop?: WaitForStopCondition<T>;
95
+ }
96
+ type ResourceFetcher<T, R> = (request: R) => Promise<T>;
97
+ /**
98
+ * Fetches resource several times until an expected condition is reached, timeouts, or throws an exception.
99
+ *
100
+ * @param stop - The condition to stop waiting
101
+ * @param fetcher - The method to retrieve resource
102
+ * @param request - The resource request options
103
+ * @param options - The retry strategy options
104
+ * @param strategy - An optional custom strategy
105
+ *
106
+ * @returns A promise of resource
107
+ *
108
+ * @public
109
+ */
110
+ export declare const waitForResource: <R, T>(stop: WaitForStopCondition<T>, fetcher: ResourceFetcher<T, R>, request: R, options?: WaitForOptions<T>, strategy?: IntervalStrategy) => Promise<Awaited<T>>;
111
+ export {};
@@ -0,0 +1,53 @@
1
+ import { sleep } from "./sleep.js";
2
+ const DEFAULT_TIMEOUT_SECONDS = 300;
3
+ const DEFAULT_MIN_DELAY_SECONDS = 1;
4
+ const DEFAULT_MAX_DELAY_SECONDS = 30;
5
+ function* createExponentialBackoffStrategy(minDelay, maxDelay) {
6
+ if (minDelay < 1 || maxDelay < 1 || minDelay > maxDelay) {
7
+ throw new Error(
8
+ "Waiter: minDelay must be >= 1 and maxDelay must be >= minDelay"
9
+ );
10
+ }
11
+ let attempt = 1;
12
+ const ceiling = Math.log(maxDelay / minDelay) / Math.log(2) + 1;
13
+ const randomInRange = (min, max) => min + Math.random() * (max - min);
14
+ while (true) {
15
+ if (attempt > ceiling) {
16
+ yield maxDelay;
17
+ } else {
18
+ yield randomInRange(minDelay, minDelay * 2 ** (attempt - 1));
19
+ }
20
+ attempt += 1;
21
+ }
22
+ }
23
+ const tryAtIntervals = async (retry, strategy, timeout = DEFAULT_TIMEOUT_SECONDS) => {
24
+ const timeoutTimestamp = Date.now() + timeout * 1e3;
25
+ let retryCount = 0;
26
+ while (Date.now() <= timeoutTimestamp) {
27
+ const delay = strategy.next(retryCount += 1).value * 1e3;
28
+ if (timeoutTimestamp <= Date.now() + delay) break;
29
+ await sleep(delay);
30
+ const { value, done } = await retry();
31
+ if (done) return value;
32
+ }
33
+ throw new Error(`Timeout after ${timeout}s`);
34
+ };
35
+ const waitForResource = (stop, fetcher, request, options, strategy = createExponentialBackoffStrategy(
36
+ options?.minDelay ?? DEFAULT_MIN_DELAY_SECONDS,
37
+ options?.maxDelay ?? DEFAULT_MAX_DELAY_SECONDS
38
+ )) => tryAtIntervals(
39
+ async () => {
40
+ const value = await fetcher(request);
41
+ return {
42
+ done: await stop(value),
43
+ value
44
+ };
45
+ },
46
+ strategy,
47
+ options?.timeout
48
+ );
49
+ export {
50
+ createExponentialBackoffStrategy,
51
+ tryAtIntervals,
52
+ waitForResource
53
+ };
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const sleep = (ms) => new Promise((resolve) => {
4
+ setTimeout(resolve, ms);
5
+ });
6
+ exports.sleep = sleep;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Sleep for a specified number of time.
3
+ *
4
+ * @param ms - The number of milliseconds
5
+ * @returns The sleep promise
6
+ *
7
+ * @internal
8
+ */
9
+ export declare const sleep: (ms: number) => Promise<void>;
@@ -0,0 +1,6 @@
1
+ const sleep = (ms) => new Promise((resolve) => {
2
+ setTimeout(resolve, ms);
3
+ });
4
+ export {
5
+ sleep
6
+ };
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const composeRequestInterceptors = (interceptors) => async (request) => interceptors.reduce(
4
+ async (asyncResult, interceptor) => interceptor({ request: await asyncResult }),
5
+ Promise.resolve(request)
6
+ );
7
+ const composeResponseInterceptors = (interceptors) => async (response) => interceptors.reduce(
8
+ async (asyncResult, interceptor) => interceptor({ response: await asyncResult }),
9
+ Promise.resolve(response)
10
+ );
11
+ const composeResponseErrorInterceptors = (interceptors) => async (request, error) => {
12
+ let prevError = error;
13
+ for (const interceptor of interceptors) {
14
+ try {
15
+ const res = await interceptor({ request, error: prevError });
16
+ return res;
17
+ } catch (err) {
18
+ prevError = err;
19
+ }
20
+ }
21
+ throw prevError;
22
+ };
23
+ exports.composeRequestInterceptors = composeRequestInterceptors;
24
+ exports.composeResponseErrorInterceptors = composeResponseErrorInterceptors;
25
+ exports.composeResponseInterceptors = composeResponseInterceptors;
@@ -0,0 +1,25 @@
1
+ import type { RequestInterceptor, ResponseErrorInterceptor, ResponseInterceptor } from './types';
2
+ /**
3
+ * Composes request interceptors.
4
+ *
5
+ * @param interceptors - A list of request interceptors
6
+ * @returns An async composed interceptor
7
+ *
8
+ * @internal
9
+ */
10
+ export declare const composeRequestInterceptors: (interceptors: RequestInterceptor[]) => (request: Request) => Promise<Request>;
11
+ /**
12
+ * Composes response interceptors.
13
+ *
14
+ * @param interceptors - A list of response interceptors
15
+ * @returns An async composed interceptor
16
+ *
17
+ * @internal
18
+ */
19
+ export declare const composeResponseInterceptors: (interceptors: ResponseInterceptor[]) => (response: Response) => Promise<Response>;
20
+ /**
21
+ * Compose response error interceptors.
22
+ *
23
+ * @internal
24
+ */
25
+ export declare const composeResponseErrorInterceptors: (interceptors: ResponseErrorInterceptor[]) => (request: Request, error: unknown) => Promise<unknown>;
@@ -0,0 +1,25 @@
1
+ const composeRequestInterceptors = (interceptors) => async (request) => interceptors.reduce(
2
+ async (asyncResult, interceptor) => interceptor({ request: await asyncResult }),
3
+ Promise.resolve(request)
4
+ );
5
+ const composeResponseInterceptors = (interceptors) => async (response) => interceptors.reduce(
6
+ async (asyncResult, interceptor) => interceptor({ response: await asyncResult }),
7
+ Promise.resolve(response)
8
+ );
9
+ const composeResponseErrorInterceptors = (interceptors) => async (request, error) => {
10
+ let prevError = error;
11
+ for (const interceptor of interceptors) {
12
+ try {
13
+ const res = await interceptor({ request, error: prevError });
14
+ return res;
15
+ } catch (err) {
16
+ prevError = err;
17
+ }
18
+ }
19
+ throw prevError;
20
+ };
21
+ export {
22
+ composeRequestInterceptors,
23
+ composeResponseErrorInterceptors,
24
+ composeResponseInterceptors
25
+ };
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const addHeaderInterceptor = (key, value) => ({ request }) => {
4
+ const clone = request.clone();
5
+ if (value !== void 0) {
6
+ clone.headers.append(key, value);
7
+ }
8
+ return clone;
9
+ };
10
+ const addAsyncHeaderInterceptor = (key, getter) => async (request) => addHeaderInterceptor(key, await getter())(request);
11
+ exports.addAsyncHeaderInterceptor = addAsyncHeaderInterceptor;
12
+ exports.addHeaderInterceptor = addHeaderInterceptor;
@@ -0,0 +1,21 @@
1
+ import type { RequestInterceptor } from './types';
2
+ /**
3
+ * Adds an header to a request through an interceptor.
4
+ *
5
+ * @param key - The header key
6
+ * @param value - The header value
7
+ * @returns The Request interceptor
8
+ *
9
+ * @internal
10
+ */
11
+ export declare const addHeaderInterceptor: (key: string, value?: string) => RequestInterceptor;
12
+ /**
13
+ * Adds asynchronously an header to a request through an interceptor.
14
+ *
15
+ * @param key - The header key
16
+ * @param value - The header value as a Promise
17
+ * @returns The Request interceptor
18
+ *
19
+ * @internal
20
+ */
21
+ export declare const addAsyncHeaderInterceptor: (key: string, getter: () => Promise<string | undefined>) => RequestInterceptor;
@@ -0,0 +1,12 @@
1
+ const addHeaderInterceptor = (key, value) => ({ request }) => {
2
+ const clone = request.clone();
3
+ if (value !== void 0) {
4
+ clone.headers.append(key, value);
5
+ }
6
+ return clone;
7
+ };
8
+ const addAsyncHeaderInterceptor = (key, getter) => async (request) => addHeaderInterceptor(key, await getter())(request);
9
+ export {
10
+ addAsyncHeaderInterceptor,
11
+ addHeaderInterceptor
12
+ };
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Defines the interceptor for a `Request`.
3
+ * This allows you to intercept requests before starting.
4
+ *
5
+ * @example
6
+ * Adds a custom header to a request:
7
+ * ```
8
+ * const addCustomHeaderInterceptor
9
+ * ({ key, value }: { key: string; value: string }): RequestInterceptor =>
10
+ * ({ request }) => {
11
+ * const clone = request.clone()
12
+ * clone.headers.set(key, value)
13
+ *
14
+ * return clone
15
+ * }
16
+ * ```
17
+ *
18
+ * @public
19
+ */
20
+ export interface RequestInterceptor {
21
+ ({ request }: {
22
+ request: Readonly<Request>;
23
+ }): Request | Promise<Request>;
24
+ }
25
+ /**
26
+ * Defines the interceptor for a `Response`.
27
+ * This allows you to intercept responses before unmarshalling.
28
+ *
29
+ * @example
30
+ * Adds a delay before sending the response:
31
+ * ```
32
+ * const addDelayInterceptor: ResponseInterceptor = ({ response }) =>
33
+ * new Promise(resolve => {
34
+ * setTimeout(() => resolve(response), 1000)
35
+ * })
36
+ * ```
37
+ *
38
+ * @public
39
+ */
40
+ export interface ResponseInterceptor {
41
+ ({ response }: {
42
+ response: Readonly<Response>;
43
+ }): Response | Promise<Response>;
44
+ }
45
+ /**
46
+ * Defines the interceptor for a `Response` error.
47
+ * This allows you to intercept a response error before exiting the whole process.
48
+ * You can either rethrow an error, and resolve with a different response.
49
+ *
50
+ * @remarks
51
+ * You must return either:
52
+ * 1. An error (`throw error` or `Promise.reject(error)`)
53
+ * 2. Data (directly, or via a Promise)
54
+ *
55
+ * @example
56
+ * Reports error to tracking service:
57
+ * ```
58
+ * const reportErrorToTrackingService: ResponseErrorInterceptor = async ({
59
+ * request,
60
+ * error,
61
+ * }: {
62
+ * request: Request
63
+ * error: unknown
64
+ * }) => {
65
+ * await sendErrorToErrorService(request, error)
66
+ * throw error
67
+ * }
68
+ * ```
69
+ *
70
+ * @public
71
+ */
72
+ export interface ResponseErrorInterceptor {
73
+ ({ request, error }: {
74
+ request: Request;
75
+ error: unknown;
76
+ }): unknown;
77
+ }
78
+ /**
79
+ * Defines the network interceptors.
80
+ * Please check the documentation of {@link RequestInterceptor},
81
+ * {@link ResponseInterceptor} and {@link ResponseErrorInterceptor} for examples.
82
+ *
83
+ * @public
84
+ */
85
+ export interface NetworkInterceptors {
86
+ request?: RequestInterceptor;
87
+ response?: ResponseInterceptor;
88
+ responseError?: ResponseErrorInterceptor;
89
+ }
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const levelResolver = require("./level-resolver.cjs");
4
+ class ConsoleLogger {
5
+ constructor(logLevel, prefix = "", output = console) {
6
+ this.logLevel = logLevel;
7
+ this.prefix = prefix;
8
+ this.output = output;
9
+ this.level = levelResolver.LevelResolver[this.logLevel];
10
+ }
11
+ level;
12
+ makeMethod(method) {
13
+ return (message) => {
14
+ if (levelResolver.shouldLog(this.level, method)) {
15
+ this.output[method](this.prefix ? `${this.prefix} ${message}` : message);
16
+ }
17
+ };
18
+ }
19
+ debug = this.makeMethod("debug");
20
+ error = this.makeMethod("error");
21
+ info = this.makeMethod("info");
22
+ warn = this.makeMethod("warn");
23
+ }
24
+ exports.ConsoleLogger = ConsoleLogger;
@@ -0,0 +1,23 @@
1
+ import type { LogLevel } from './level-resolver.js';
2
+ import type { Logger } from './logger';
3
+ /**
4
+ * A Logger using console output.
5
+ *
6
+ * @param logLevel - The logger level name
7
+ * @param prefix - An optional logger message prefix
8
+ * @param output - The output to print logs, using by default the global console object
9
+ *
10
+ * @internal
11
+ */
12
+ export declare class ConsoleLogger implements Logger {
13
+ readonly logLevel: LogLevel;
14
+ private readonly prefix;
15
+ private output;
16
+ private level;
17
+ constructor(logLevel: LogLevel, prefix?: string, output?: typeof console);
18
+ private makeMethod;
19
+ debug: (message: string) => void;
20
+ error: (message: string) => void;
21
+ info: (message: string) => void;
22
+ warn: (message: string) => void;
23
+ }
@@ -0,0 +1,24 @@
1
+ import { LevelResolver, shouldLog } from "./level-resolver.js";
2
+ class ConsoleLogger {
3
+ constructor(logLevel, prefix = "", output = console) {
4
+ this.logLevel = logLevel;
5
+ this.prefix = prefix;
6
+ this.output = output;
7
+ this.level = LevelResolver[this.logLevel];
8
+ }
9
+ level;
10
+ makeMethod(method) {
11
+ return (message) => {
12
+ if (shouldLog(this.level, method)) {
13
+ this.output[method](this.prefix ? `${this.prefix} ${message}` : message);
14
+ }
15
+ };
16
+ }
17
+ debug = this.makeMethod("debug");
18
+ error = this.makeMethod("error");
19
+ info = this.makeMethod("info");
20
+ warn = this.makeMethod("warn");
21
+ }
22
+ export {
23
+ ConsoleLogger
24
+ };
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const consoleLogger = require("./console-logger.cjs");
4
+ let sdkLogger = new consoleLogger.ConsoleLogger("silent");
5
+ const setLogger = (logger) => {
6
+ sdkLogger = logger;
7
+ };
8
+ const enableConsoleLogger = (logLevel = "warn", prefix = "scaleway-sdk-js:") => setLogger(new consoleLogger.ConsoleLogger(logLevel, prefix));
9
+ const getLogger = () => sdkLogger;
10
+ exports.enableConsoleLogger = enableConsoleLogger;
11
+ exports.getLogger = getLogger;
12
+ exports.setLogger = setLogger;
@@ -0,0 +1,25 @@
1
+ import type { LogLevel } from './level-resolver.js';
2
+ import type { Logger } from './logger';
3
+ /**
4
+ * Sets a logger to be used within the SDK.
5
+ *
6
+ * @param logger - The Logger instance
7
+ *
8
+ * @public
9
+ */
10
+ export declare const setLogger: (logger: Readonly<Logger>) => void;
11
+ /**
12
+ * Sets the logger to console logger with given logLevel (log is disabled by default).
13
+ *
14
+ * @param logLevel - The Log level (default to 'warn')
15
+ * @param prefix - A Log message prefix (default to 'scaleway-sdk-js:')
16
+ *
17
+ * @public
18
+ */
19
+ export declare const enableConsoleLogger: (logLevel?: LogLevel, prefix?: string) => void;
20
+ /**
21
+ * Returns the active SDK logger.
22
+ *
23
+ * @internal
24
+ */
25
+ export declare const getLogger: () => Readonly<Logger>;
@@ -0,0 +1,12 @@
1
+ import { ConsoleLogger } from "./console-logger.js";
2
+ let sdkLogger = new ConsoleLogger("silent");
3
+ const setLogger = (logger) => {
4
+ sdkLogger = logger;
5
+ };
6
+ const enableConsoleLogger = (logLevel = "warn", prefix = "scaleway-sdk-js:") => setLogger(new ConsoleLogger(logLevel, prefix));
7
+ const getLogger = () => sdkLogger;
8
+ export {
9
+ enableConsoleLogger,
10
+ getLogger,
11
+ setLogger
12
+ };
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ var LevelResolver = /* @__PURE__ */ ((LevelResolver2) => {
4
+ LevelResolver2[LevelResolver2["silent"] = 0] = "silent";
5
+ LevelResolver2[LevelResolver2["error"] = 1] = "error";
6
+ LevelResolver2[LevelResolver2["warn"] = 2] = "warn";
7
+ LevelResolver2[LevelResolver2["info"] = 3] = "info";
8
+ LevelResolver2[LevelResolver2["debug"] = 4] = "debug";
9
+ return LevelResolver2;
10
+ })(LevelResolver || {});
11
+ const shouldLog = (currentLevel, level) => LevelResolver[level] <= currentLevel;
12
+ exports.LevelResolver = LevelResolver;
13
+ exports.shouldLog = shouldLog;
@@ -0,0 +1,9 @@
1
+ export declare enum LevelResolver {
2
+ silent = 0,
3
+ error = 1,
4
+ warn = 2,
5
+ info = 3,
6
+ debug = 4
7
+ }
8
+ export type LogLevel = keyof typeof LevelResolver;
9
+ export declare const shouldLog: (currentLevel: LevelResolver, level: LogLevel) => boolean;
@@ -0,0 +1,13 @@
1
+ var LevelResolver = /* @__PURE__ */ ((LevelResolver2) => {
2
+ LevelResolver2[LevelResolver2["silent"] = 0] = "silent";
3
+ LevelResolver2[LevelResolver2["error"] = 1] = "error";
4
+ LevelResolver2[LevelResolver2["warn"] = 2] = "warn";
5
+ LevelResolver2[LevelResolver2["info"] = 3] = "info";
6
+ LevelResolver2[LevelResolver2["debug"] = 4] = "debug";
7
+ return LevelResolver2;
8
+ })(LevelResolver || {});
9
+ const shouldLog = (currentLevel, level) => LevelResolver[level] <= currentLevel;
10
+ export {
11
+ LevelResolver,
12
+ shouldLog
13
+ };
@@ -0,0 +1,13 @@
1
+ import type { LogLevel } from './level-resolver.js';
2
+ /**
3
+ * Logger.
4
+ *
5
+ * @public
6
+ */
7
+ export interface Logger {
8
+ readonly logLevel: LogLevel;
9
+ debug: (message: string) => void;
10
+ info: (message: string) => void;
11
+ warn: (message: string) => void;
12
+ error: (message: string) => void;
13
+ }
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const isAccessKeyRegex = /^SCW[A-Z0-9]{17}$/i;
4
+ const isRegionRegex = /^[a-z]{2}-[a-z]{3}$/i;
5
+ const isUUIDRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;
6
+ const isZoneRegex = /^[a-z]{2}-[a-z]{3}-[1-9]$/i;
7
+ const isUUID = (str) => isUUIDRegex.test(str);
8
+ const isAccessKey = (str) => isAccessKeyRegex.test(str);
9
+ const isSecretKey = (str) => isUUID(str);
10
+ const isOrganizationId = (str) => isUUID(str);
11
+ const isProjectId = (str) => isUUID(str);
12
+ const isRegion = (str) => isRegionRegex.test(str);
13
+ const isZone = (str) => isZoneRegex.test(str);
14
+ const isURL = (str) => {
15
+ let url;
16
+ try {
17
+ url = new URL(str);
18
+ } catch {
19
+ return false;
20
+ }
21
+ return url.protocol === "http:" || url.protocol === "https:";
22
+ };
23
+ exports.isAccessKey = isAccessKey;
24
+ exports.isOrganizationId = isOrganizationId;
25
+ exports.isProjectId = isProjectId;
26
+ exports.isRegion = isRegion;
27
+ exports.isSecretKey = isSecretKey;
28
+ exports.isURL = isURL;
29
+ exports.isUUID = isUUID;
30
+ exports.isZone = isZone;