@scaleway/sdk 0.0.2-alpha.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 (56) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +28 -0
  3. package/dist/api/function/manual/FunctionAPI.js +436 -0
  4. package/dist/api/function/manual/WaitForFunctionAPI.js +27 -0
  5. package/dist/api/function/manual/types.js +1 -0
  6. package/dist/api/registry/manual/RegistryAPI.js +260 -0
  7. package/dist/api/registry/manual/WaitForRegistryAPI.js +27 -0
  8. package/dist/api/registry/manual/types.js +1 -0
  9. package/dist/helpers/API.js +12 -0
  10. package/dist/helpers/camelize.js +36 -0
  11. package/dist/helpers/forRegions.js +15 -0
  12. package/dist/helpers/is-browser.js +3 -0
  13. package/dist/helpers/json.js +6 -0
  14. package/dist/index.cjs +9449 -0
  15. package/dist/index.d.ts +1126 -0
  16. package/dist/index.js +13 -0
  17. package/dist/internal/async/interval-retrier.js +89 -0
  18. package/dist/internal/async/sleep.js +13 -0
  19. package/dist/internal/auth.js +68 -0
  20. package/dist/internal/interceptors/interceptor.js +11 -0
  21. package/dist/internal/interceptors/request.js +29 -0
  22. package/dist/internal/logger/console-logger.js +31 -0
  23. package/dist/internal/logger/index.js +38 -0
  24. package/dist/internal/logger/level-resolver.js +16 -0
  25. package/dist/internal/tools/string-validation.js +39 -0
  26. package/dist/internals.js +4 -0
  27. package/dist/node_modules/@scaleway/random-name/dist/index.js +254 -0
  28. package/dist/scw/client-ini-factory.js +24 -0
  29. package/dist/scw/client-ini-profile.js +30 -0
  30. package/dist/scw/client-settings.js +49 -0
  31. package/dist/scw/client.js +96 -0
  32. package/dist/scw/constants.js +4 -0
  33. package/dist/scw/errors/error-parser.js +121 -0
  34. package/dist/scw/errors/non-standard/invalid-request-mapper.js +34 -0
  35. package/dist/scw/errors/non-standard/unknown-resource-mapper.js +26 -0
  36. package/dist/scw/errors/scw-error.js +64 -0
  37. package/dist/scw/errors/standard/already-exists-error.js +26 -0
  38. package/dist/scw/errors/standard/denied-authentication-error.js +58 -0
  39. package/dist/scw/errors/standard/index.js +12 -0
  40. package/dist/scw/errors/standard/invalid-arguments-error.js +75 -0
  41. package/dist/scw/errors/standard/out-of-stock-error.js +24 -0
  42. package/dist/scw/errors/standard/permissions-denied-error.js +50 -0
  43. package/dist/scw/errors/standard/precondition-failed-error.js +62 -0
  44. package/dist/scw/errors/standard/quotas-exceeded-error.js +61 -0
  45. package/dist/scw/errors/standard/resource-expired-error.js +26 -0
  46. package/dist/scw/errors/standard/resource-locked-error.js +25 -0
  47. package/dist/scw/errors/standard/resource-not-found-error.js +25 -0
  48. package/dist/scw/errors/standard/transient-state-error.js +26 -0
  49. package/dist/scw/errors/types.js +26 -0
  50. package/dist/scw/fetch/build-fetcher.js +66 -0
  51. package/dist/scw/fetch/http-dumper.js +57 -0
  52. package/dist/scw/fetch/http-interceptors.js +80 -0
  53. package/dist/scw/fetch/resource-paginator.js +41 -0
  54. package/dist/scw/fetch/response-parser.js +46 -0
  55. package/dist/scw/marshalling.js +103 -0
  56. package/package.json +27 -0
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ export { createAdvancedScwClient, createScwClient } from './scw/client.js';
2
+ export { withProfile } from './scw/client-ini-factory.js';
3
+ export { enableConsoleLogger, setLogger } from './internal/logger/index.js';
4
+ import * as internals from './internals.js';
5
+ export { internals };
6
+ import * as index from './scw/errors/standard/index.js';
7
+ export { index as Errors };
8
+ import * as types from './api/registry/manual/types.js';
9
+ export { types as RegistryNS };
10
+ export { RegistryAPI } from './api/registry/manual/RegistryAPI.js';
11
+ import * as types$1 from './api/function/manual/types.js';
12
+ export { types$1 as FunctionNS };
13
+ export { FunctionAPI } from './api/function/manual/FunctionAPI.js';
@@ -0,0 +1,89 @@
1
+ import { sleep } from './sleep.js';
2
+
3
+ const DEFAULT_TIMEOUT = 5 * 60 * 1000;
4
+ const DEFAULT_INTERVAL = 1 * 1000;
5
+ /**
6
+ * Function to retry logic between each interval.
7
+ *
8
+ * @returns The result and if it's done
9
+ *
10
+ * @throws An exception might be thrown by the logic being run
11
+ *
12
+ * @internal
13
+ */
14
+
15
+ /**
16
+ * Creates a fixed interval strategy.
17
+ * It returns the same interval value whatever the retry count.
18
+ *
19
+ * @param interval - The time interval (in milliseconds) to wait between each run
20
+ * @returns A fixed interval generator
21
+ *
22
+ * @internal
23
+ */
24
+ function* createFixedIntervalStrategy(interval) {
25
+ while (true) yield interval;
26
+ }
27
+ /**
28
+ * Tries a specific logic several times until it succeeds, timeouts, or throws an exception.
29
+ *
30
+ * @param retry - The function to retry logic between each interval
31
+ * @param timeout - The maximum time elapsed before timeout error
32
+ * @param strategy - An optional generated interval strategy iterator
33
+ *
34
+ * @throws An timeout exception or error thrown by the logic being run
35
+ *
36
+ * @internal
37
+ */
38
+
39
+ const tryAtIntervals = async function (retry, strategy, timeout) {
40
+ if (timeout === void 0) {
41
+ timeout = DEFAULT_TIMEOUT;
42
+ }
43
+
44
+ const timeoutTimestamp = Date.now() + timeout;
45
+ let retryCount = 0;
46
+
47
+ while (Date.now() <= timeoutTimestamp) {
48
+ const {
49
+ value,
50
+ done
51
+ } = await retry();
52
+ if (done) return value; // Break if timeout has been reached
53
+
54
+ if (timeoutTimestamp <= Date.now()) break; // Wait before the next retry
55
+
56
+ await sleep(strategy.next(retryCount += 1).value);
57
+ }
58
+
59
+ throw new Error(`Timeout after ${timeout}ms`);
60
+ };
61
+
62
+ /**
63
+ * Fetch resource several times until an expected status is reached, timeouts, or throws an exception.
64
+ *
65
+ * @param status - The list of expected status
66
+ * @param fetcher - The method to retrieve resource
67
+ * @param request - The resource request options
68
+ * @param options - The retry strategy options
69
+ * @param strategy - An optional custom strategy
70
+ *
71
+ * @returns A promise of resource
72
+ *
73
+ * @internal
74
+ */
75
+ const waitForStatus = function (status, fetcher, request, options, strategy) {
76
+ if (strategy === void 0) {
77
+ strategy = createFixedIntervalStrategy((options == null ? void 0 : options.retryInterval) ?? DEFAULT_INTERVAL);
78
+ }
79
+
80
+ return tryAtIntervals(async () => {
81
+ const value = await fetcher(request);
82
+ return {
83
+ done: status.includes(value.status),
84
+ value
85
+ };
86
+ }, strategy, options == null ? void 0 : options.timeout);
87
+ };
88
+
89
+ export { createFixedIntervalStrategy, tryAtIntervals, waitForStatus };
@@ -0,0 +1,13 @@
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
+ const sleep = ms => new Promise(resolve => {
10
+ setTimeout(resolve, ms);
11
+ });
12
+
13
+ export { sleep };
@@ -0,0 +1,68 @@
1
+ import { assertValidAuthenticationSecrets } from '../scw/client-ini-profile.js';
2
+ import { addAsyncHeaderInterceptor, addHeaderInterceptor } from './interceptors/request.js';
3
+
4
+ const SESSION_HEADER_KEY = 'x-session-token';
5
+ const AUTH_HEADER_KEY = 'x-auth-token';
6
+
7
+ /**
8
+ * Authenticates with a session token.
9
+ *
10
+ * @param getToken - The token accessor
11
+ * @returns The request interceptor
12
+ *
13
+ * @internal
14
+ */
15
+ const authenticateWithSessionToken = getToken => addAsyncHeaderInterceptor(SESSION_HEADER_KEY, getToken);
16
+ /**
17
+ * Authenticates with a secrets.
18
+ *
19
+ * @param getToken - The secrets
20
+ * @returns The request interceptor
21
+ *
22
+ * @throws Error
23
+ * Thrown if the secrets are invalid.
24
+ *
25
+ * @internal
26
+ */
27
+
28
+ const authenticateWithSecrets = secrets => {
29
+ assertValidAuthenticationSecrets(secrets);
30
+ return addHeaderInterceptor(AUTH_HEADER_KEY, secrets.secretKey);
31
+ };
32
+ /**
33
+ * Obfuscates a token.
34
+ *
35
+ * @param key - The token
36
+ * @returns The obfuscated token
37
+ *
38
+ * @internal
39
+ */
40
+
41
+ const obfuscateToken = key => `${key.substring(0, 5)}xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`;
42
+ /**
43
+ * Obfuscates an UUID.
44
+ *
45
+ * @param key - The UUID
46
+ * @returns The obfuscated UUID
47
+ *
48
+ * @internal
49
+ */
50
+
51
+ const obfuscateUUID = key => `${key.substring(0, 8)}-xxxx-xxxx-xxxx-xxxxxxxxxxxx`;
52
+
53
+ /**
54
+ * Obfuscates headers entry.
55
+ *
56
+ * @param array - The header entry
57
+ * @returns The obfuscated entry
58
+ *
59
+ * @internal
60
+ */
61
+ const obfuscateAuthHeadersEntry = _ref => {
62
+ let [name, value] = _ref;
63
+ if (name === SESSION_HEADER_KEY) return [name, obfuscateToken(value)];
64
+ if (name === AUTH_HEADER_KEY) return [name, obfuscateUUID(value)];
65
+ return [name, value];
66
+ };
67
+
68
+ export { authenticateWithSecrets, authenticateWithSessionToken, obfuscateAuthHeadersEntry, obfuscateToken, obfuscateUUID };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Composes interceptors.
3
+ *
4
+ * @param interceptors - A list of interceptors (that modify an object instance)
5
+ * @returns An async composed interceptor
6
+ *
7
+ * @internal
8
+ */
9
+ const composeInterceptors = interceptors => async instance => interceptors.reduce(async (asyncResult, interceptor) => interceptor(await asyncResult), Promise.resolve(instance));
10
+
11
+ export { composeInterceptors };
@@ -0,0 +1,29 @@
1
+ /** Request Interceptor. */
2
+
3
+ /**
4
+ * Adds an header to a request through an interceptor.
5
+ *
6
+ * @param key - The header key
7
+ * @param value - The header value
8
+ * @returns The Request interceptor
9
+ *
10
+ * @internal
11
+ */
12
+ const addHeaderInterceptor = (key, value) => request => {
13
+ const clone = request.clone();
14
+ clone.headers.append(key, value);
15
+ return clone;
16
+ };
17
+ /**
18
+ * Adds asynchronously an header to a request through an interceptor.
19
+ *
20
+ * @param key - The header key
21
+ * @param value - The header value as a Promise
22
+ * @returns The Request interceptor
23
+ *
24
+ * @internal
25
+ */
26
+
27
+ const addAsyncHeaderInterceptor = (key, getter) => async request => addHeaderInterceptor(key, await getter())(request);
28
+
29
+ export { addAsyncHeaderInterceptor, addHeaderInterceptor };
@@ -0,0 +1,31 @@
1
+ import { LevelResolver, shouldLog } from './level-resolver.js';
2
+
3
+ /**
4
+ * A Logger using console output.
5
+ *
6
+ * @param logLevel - The logger level name
7
+ * @param output - The output to print logs, using by default the global console object
8
+ *
9
+ * @internal
10
+ */
11
+ class ConsoleLogger {
12
+ constructor(logLevel, output = console) {
13
+ this.logLevel = logLevel;
14
+ this.output = output;
15
+ this.level = void 0;
16
+ this.debug = this.makeMethod('debug');
17
+ this.error = this.makeMethod('error');
18
+ this.info = this.makeMethod('info');
19
+ this.warn = this.makeMethod('warn');
20
+ this.level = LevelResolver[this.logLevel];
21
+ }
22
+
23
+ makeMethod(method) {
24
+ return message => {
25
+ if (shouldLog(this.level, method)) this.output[method](message);
26
+ };
27
+ }
28
+
29
+ }
30
+
31
+ export { ConsoleLogger };
@@ -0,0 +1,38 @@
1
+ import { ConsoleLogger } from './console-logger.js';
2
+
3
+ let sdkLogger = /*#__PURE__*/new ConsoleLogger('silent');
4
+ /**
5
+ * Sets a logger to be used within the SDK.
6
+ *
7
+ * @param logger - The Logger instance
8
+ *
9
+ * @public
10
+ */
11
+
12
+ const setLogger = logger => {
13
+ sdkLogger = logger;
14
+ };
15
+ /**
16
+ * Sets the logger to console logger with given logLevel.
17
+ *
18
+ * @param logLevel - The Log level name
19
+ *
20
+ * @public
21
+ */
22
+
23
+ const enableConsoleLogger = function (logLevel) {
24
+ if (logLevel === void 0) {
25
+ logLevel = 'warn';
26
+ }
27
+
28
+ return setLogger(new ConsoleLogger(logLevel));
29
+ };
30
+ /**
31
+ * Returns the active SDK logger.
32
+ *
33
+ * @internal
34
+ */
35
+
36
+ const getLogger = () => sdkLogger;
37
+
38
+ export { enableConsoleLogger, getLogger, setLogger };
@@ -0,0 +1,16 @@
1
+ // eslint-disable-next-line eslint-comments/disable-enable-pair
2
+
3
+ /* eslint-disable @typescript-eslint/naming-convention */
4
+ let LevelResolver;
5
+
6
+ (function (LevelResolver) {
7
+ LevelResolver[LevelResolver["silent"] = 0] = "silent";
8
+ LevelResolver[LevelResolver["error"] = 1] = "error";
9
+ LevelResolver[LevelResolver["warn"] = 2] = "warn";
10
+ LevelResolver[LevelResolver["info"] = 3] = "info";
11
+ LevelResolver[LevelResolver["debug"] = 4] = "debug";
12
+ })(LevelResolver || (LevelResolver = {}));
13
+
14
+ const shouldLog = (currentLevel, level) => LevelResolver[level] <= currentLevel;
15
+
16
+ export { LevelResolver, shouldLog };
@@ -0,0 +1,39 @@
1
+ const isAccessKeyRegex = /^SCW[A-Z0-9]{17}$/i;
2
+ const isRegionRegex = /^[a-z]{2}-[a-z]{3}$/i;
3
+ 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;
4
+ const isZoneRegex = /^[a-z]{2}-[a-z]{3}-[1-9]$/i; // Returns true if the given string has a valid UUID format.
5
+
6
+ const isUUID = str => isUUIDRegex.test(str); // Returns true if the given string has a valid Scaleway access key format.
7
+
8
+
9
+ const isAccessKey = str => isAccessKeyRegex.test(str); // Returns true if the given string has a valid Scaleway secret key format.
10
+
11
+
12
+ const isSecretKey = str => isUUID(str); // Returns true if the given string has a valid Scaleway organization ID format.
13
+
14
+
15
+ const isOrganizationId = str => isUUID(str); // Returns true if the given string has a valid Scaleway project ID format.
16
+
17
+
18
+ const isProjectId = str => isUUID(str); // Returns true if the given string has a valid region format.
19
+
20
+
21
+ const isRegion = str => isRegionRegex.test(str); // Returns true if the given string has a valid zone format.
22
+
23
+
24
+ const isZone = str => isZoneRegex.test(str); // Returns true if the given string has a valid URL format and starts by `http(s):`.
25
+
26
+
27
+ const isURL = str => {
28
+ let url;
29
+
30
+ try {
31
+ url = new URL(str);
32
+ } catch {
33
+ return false;
34
+ }
35
+
36
+ return url.protocol === 'http:' || url.protocol === 'https:';
37
+ }; // Returns true if the given string has an email format.
38
+
39
+ export { isAccessKey, isOrganizationId, isProjectId, isRegion, isSecretKey, isURL, isUUID, isZone };
@@ -0,0 +1,4 @@
1
+ export { authenticateWithSessionToken } from './internal/auth.js';
2
+ export { unmarshalAnyRes } from './scw/marshalling.js';
3
+ export { API } from './helpers/API.js';
4
+ export { forRegions } from './helpers/forRegions.js';