@scaleway/sdk-client 1.3.2 → 2.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 (65) hide show
  1. package/dist/helpers/json.js +6 -7
  2. package/dist/helpers/marshalling.d.ts +0 -8
  3. package/dist/helpers/marshalling.js +18 -22
  4. package/dist/internal/async/interval-retrier.js +2 -1
  5. package/dist/internal/interceptors/types.d.ts +7 -0
  6. package/dist/package.json.js +1 -1
  7. package/dist/scw/auth.d.ts +7 -0
  8. package/dist/scw/custom-marshalling.js +5 -7
  9. package/dist/scw/errors/error-parser.js +4 -4
  10. package/dist/scw/errors/non-standard/invalid-request-mapper.d.ts +1 -3
  11. package/dist/scw/errors/non-standard/invalid-request-mapper.js +27 -29
  12. package/dist/scw/errors/non-standard/unknown-resource-mapper.d.ts +1 -3
  13. package/dist/scw/errors/non-standard/unknown-resource-mapper.js +15 -17
  14. package/dist/scw/fetch/build-fetcher.js +2 -1
  15. package/dist/scw/fetch/http-interceptors.d.ts +7 -0
  16. package/dist/vendor/base64/index.js +16 -11
  17. package/package.json +2 -4
  18. package/dist/helpers/is-browser.cjs +0 -4
  19. package/dist/helpers/is-response.cjs +0 -4
  20. package/dist/helpers/json.cjs +0 -47
  21. package/dist/helpers/marshalling.cjs +0 -76
  22. package/dist/index.cjs +0 -58
  23. package/dist/internal/async/interval-retrier.cjs +0 -53
  24. package/dist/internal/async/sleep.cjs +0 -6
  25. package/dist/internal/interceptors/composer.cjs +0 -25
  26. package/dist/internal/interceptors/helpers.cjs +0 -12
  27. package/dist/internal/logger/console-logger.cjs +0 -24
  28. package/dist/internal/logger/index.cjs +0 -12
  29. package/dist/internal/logger/level-resolver.cjs +0 -13
  30. package/dist/internal/validations/string-validation.cjs +0 -30
  31. package/dist/package.json.cjs +0 -8
  32. package/dist/scw/api.cjs +0 -8
  33. package/dist/scw/auth.cjs +0 -25
  34. package/dist/scw/client-ini-factory.cjs +0 -66
  35. package/dist/scw/client-ini-profile.cjs +0 -23
  36. package/dist/scw/client-settings.cjs +0 -51
  37. package/dist/scw/client.cjs +0 -31
  38. package/dist/scw/constants.cjs +0 -11
  39. package/dist/scw/custom-marshalling.cjs +0 -152
  40. package/dist/scw/custom-types.cjs +0 -11
  41. package/dist/scw/errors/error-parser.cjs +0 -76
  42. package/dist/scw/errors/non-standard/invalid-request-mapper.cjs +0 -36
  43. package/dist/scw/errors/non-standard/unknown-resource-mapper.cjs +0 -23
  44. package/dist/scw/errors/scw-error.cjs +0 -43
  45. package/dist/scw/errors/standard/already-exists-error.cjs +0 -31
  46. package/dist/scw/errors/standard/denied-authentication-error.cjs +0 -37
  47. package/dist/scw/errors/standard/index.cjs +0 -28
  48. package/dist/scw/errors/standard/invalid-arguments-error.cjs +0 -54
  49. package/dist/scw/errors/standard/out-of-stock-error.cjs +0 -17
  50. package/dist/scw/errors/standard/permissions-denied-error.cjs +0 -29
  51. package/dist/scw/errors/standard/precondition-failed-error.cjs +0 -32
  52. package/dist/scw/errors/standard/quotas-exceeded-error.cjs +0 -43
  53. package/dist/scw/errors/standard/resource-expired-error.cjs +0 -31
  54. package/dist/scw/errors/standard/resource-locked-error.cjs +0 -20
  55. package/dist/scw/errors/standard/resource-not-found-error.cjs +0 -24
  56. package/dist/scw/errors/standard/too-many-requests-error.cjs +0 -58
  57. package/dist/scw/errors/standard/transient-state-error.cjs +0 -31
  58. package/dist/scw/errors/types.cjs +0 -15
  59. package/dist/scw/fetch/build-fetcher.cjs +0 -60
  60. package/dist/scw/fetch/http-dumper.cjs +0 -20
  61. package/dist/scw/fetch/http-interceptors.cjs +0 -43
  62. package/dist/scw/fetch/resource-paginator.cjs +0 -36
  63. package/dist/scw/fetch/response-parser.cjs +0 -55
  64. package/dist/scw/locality.cjs +0 -16
  65. package/dist/vendor/base64/index.cjs +0 -46
@@ -1,6 +0,0 @@
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;
@@ -1,25 +0,0 @@
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;
@@ -1,12 +0,0 @@
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;
@@ -1,24 +0,0 @@
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;
@@ -1,12 +0,0 @@
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;
@@ -1,13 +0,0 @@
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;
@@ -1,30 +0,0 @@
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;
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3
- const version = "1.3.1";
4
- const pkg = {
5
- version
6
- };
7
- exports.default = pkg;
8
- exports.version = version;
package/dist/scw/api.cjs DELETED
@@ -1,8 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- class API {
4
- constructor(client) {
5
- this.client = client;
6
- }
7
- }
8
- exports.API = API;
package/dist/scw/auth.cjs DELETED
@@ -1,25 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const helpers = require("../internal/interceptors/helpers.cjs");
4
- const clientIniProfile = require("./client-ini-profile.cjs");
5
- const constants = require("./constants.cjs");
6
- const authenticateWithSessionToken = (getToken) => helpers.addAsyncHeaderInterceptor(constants.SESSION_HEADER_KEY, getToken);
7
- const authenticateWithSecrets = (secrets) => {
8
- clientIniProfile.assertValidAuthenticationSecrets(secrets);
9
- return helpers.addHeaderInterceptor(constants.AUTH_HEADER_KEY, secrets.secretKey);
10
- };
11
- const obfuscateToken = (key) => `${key.substring(0, 5)}xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`;
12
- const obfuscateUUID = (key) => `${key.substring(0, 8)}-xxxx-xxxx-xxxx-xxxxxxxxxxxx`;
13
- const obfuscateAuthHeadersEntry = ([
14
- name,
15
- value
16
- ]) => {
17
- if (name === constants.SESSION_HEADER_KEY) return [name, obfuscateToken(value)];
18
- if (name === constants.AUTH_HEADER_KEY) return [name, obfuscateUUID(value)];
19
- return [name, value];
20
- };
21
- exports.authenticateWithSecrets = authenticateWithSecrets;
22
- exports.authenticateWithSessionToken = authenticateWithSessionToken;
23
- exports.obfuscateAuthHeadersEntry = obfuscateAuthHeadersEntry;
24
- exports.obfuscateToken = obfuscateToken;
25
- exports.obfuscateUUID = obfuscateUUID;
@@ -1,66 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const auth = require("./auth.cjs");
4
- const clientIniProfile = require("./client-ini-profile.cjs");
5
- const withProfile = (profile) => (settings) => {
6
- const newSettings = { ...settings };
7
- if (profile.apiURL) {
8
- newSettings.apiURL = profile.apiURL;
9
- }
10
- if (profile.defaultOrganizationId) {
11
- newSettings.defaultOrganizationId = profile.defaultOrganizationId;
12
- }
13
- if (profile.defaultProjectId) {
14
- newSettings.defaultProjectId = profile.defaultProjectId;
15
- }
16
- if (profile.defaultRegion) {
17
- newSettings.defaultRegion = profile.defaultRegion;
18
- }
19
- if (profile.defaultZone) {
20
- newSettings.defaultZone = profile.defaultZone;
21
- }
22
- if (clientIniProfile.hasAuthenticationSecrets(profile)) {
23
- newSettings.interceptors = [
24
- {
25
- request: auth.authenticateWithSecrets(profile)
26
- },
27
- ...newSettings.interceptors
28
- ];
29
- }
30
- return newSettings;
31
- };
32
- const withHTTPClient = (httpClient) => (settings) => ({ ...settings, httpClient });
33
- const withDefaultPageSize = (defaultPageSize) => (settings) => ({ ...settings, defaultPageSize });
34
- const withUserAgent = (userAgent) => (settings) => ({ ...settings, userAgent });
35
- const withUserAgentSuffix = (userAgent) => (settings) => ({
36
- ...settings,
37
- userAgent: settings.userAgent ? `${settings.userAgent} ${userAgent}` : userAgent
38
- });
39
- const withAdditionalInterceptors = (interceptors) => (settings) => ({
40
- ...settings,
41
- interceptors: settings.interceptors.concat(interceptors)
42
- });
43
- const withLegacyInterceptors = () => (settings) => {
44
- if (!settings.requestInterceptors && !settings.responseInterceptors) {
45
- return settings;
46
- }
47
- const allInterceptors = settings.interceptors.concat(
48
- (settings.requestInterceptors ?? []).map((obj) => ({
49
- request: obj
50
- })),
51
- (settings.responseInterceptors ?? []).map((obj) => ({
52
- response: obj
53
- }))
54
- );
55
- return {
56
- ...settings,
57
- interceptors: allInterceptors
58
- };
59
- };
60
- exports.withAdditionalInterceptors = withAdditionalInterceptors;
61
- exports.withDefaultPageSize = withDefaultPageSize;
62
- exports.withHTTPClient = withHTTPClient;
63
- exports.withLegacyInterceptors = withLegacyInterceptors;
64
- exports.withProfile = withProfile;
65
- exports.withUserAgent = withUserAgent;
66
- exports.withUserAgentSuffix = withUserAgentSuffix;
@@ -1,23 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const stringValidation = require("../internal/validations/string-validation.cjs");
4
- const hasAuthenticationSecrets = (obj) => typeof obj.accessKey === "string" && obj.accessKey !== "" && typeof obj.secretKey === "string" && obj.secretKey !== "";
5
- function assertValidAuthenticationSecrets(obj) {
6
- if (!(obj.accessKey && obj.secretKey)) {
7
- throw new Error(
8
- `Invalid secrets, accessKey & secretKey must be defined. See https://www.scaleway.com/en/docs/identity-and-access-management/iam/how-to/create-api-keys/`
9
- );
10
- }
11
- if (!stringValidation.isAccessKey(obj.accessKey)) {
12
- throw new Error(
13
- `Invalid access key format '${obj.accessKey}', expected SCWXXXXXXXXXXXXXXXXX format. See https://www.scaleway.com/en/docs/identity-and-access-management/iam/how-to/create-api-keys/`
14
- );
15
- }
16
- if (!stringValidation.isSecretKey(obj.secretKey)) {
17
- throw new Error(
18
- `Invalid secret key format '${obj.secretKey}', expected a UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx. See https://www.scaleway.com/en/docs/identity-and-access-management/iam/how-to/create-api-keys/`
19
- );
20
- }
21
- }
22
- exports.assertValidAuthenticationSecrets = assertValidAuthenticationSecrets;
23
- exports.hasAuthenticationSecrets = hasAuthenticationSecrets;
@@ -1,51 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const stringValidation = require("../internal/validations/string-validation.cjs");
4
- const assertValidSettings = (obj) => {
5
- if (obj.defaultOrganizationId !== void 0) {
6
- if (typeof obj.defaultOrganizationId !== "string" || obj.defaultOrganizationId.length === 0) {
7
- throw new Error("Default organization ID cannot be empty");
8
- }
9
- if (!stringValidation.isOrganizationId(obj.defaultOrganizationId)) {
10
- throw new Error(
11
- `Invalid organization ID format '${obj.defaultOrganizationId}', expected a UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`
12
- );
13
- }
14
- }
15
- if (obj.defaultProjectId !== void 0) {
16
- if (typeof obj.defaultProjectId !== "string" || obj.defaultProjectId.length === 0) {
17
- throw new Error("Default project ID cannot be empty");
18
- }
19
- if (!stringValidation.isProjectId(obj.defaultProjectId)) {
20
- throw new Error(
21
- `Invalid project ID format '${obj.defaultProjectId}', expected a UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`
22
- );
23
- }
24
- }
25
- if (obj.defaultRegion && !stringValidation.isRegion(obj.defaultRegion)) {
26
- throw new Error(`Invalid default region format '${obj.defaultRegion}'`);
27
- }
28
- if (obj.defaultZone && !stringValidation.isZone(obj.defaultZone)) {
29
- throw new Error(`Invalid default zone format '${obj.defaultZone}'`);
30
- }
31
- if (obj.apiURL && !stringValidation.isURL(obj.apiURL)) {
32
- throw new Error(`Invalid URL ${obj.apiURL}`);
33
- }
34
- if (obj.apiURL?.endsWith("/")) {
35
- throw new Error(
36
- `Invalid URL ${obj.apiURL}: it should not have a trailing slash`
37
- );
38
- }
39
- if (typeof obj.httpClient !== typeof fetch) {
40
- throw new Error(`Invalid HTTP Client`);
41
- }
42
- if (obj.defaultPageSize !== void 0 && (typeof obj.defaultPageSize !== "number" || Number.isNaN(obj.defaultPageSize) || obj.defaultPageSize <= 0)) {
43
- throw new Error(
44
- `Invalid defaultPageSize ${obj.defaultPageSize}: it should be a number above 0`
45
- );
46
- }
47
- if (typeof obj.userAgent !== "string") {
48
- throw new Error(`Invalid User-Agent`);
49
- }
50
- };
51
- exports.assertValidSettings = assertValidSettings;
@@ -1,31 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const index = require("../internal/logger/index.cjs");
4
- const clientIniFactory = require("./client-ini-factory.cjs");
5
- const clientSettings = require("./client-settings.cjs");
6
- const constants = require("./constants.cjs");
7
- const buildFetcher = require("./fetch/build-fetcher.cjs");
8
- const DEFAULT_SETTINGS = {
9
- apiURL: "https://api.scaleway.com",
10
- httpClient: fetch,
11
- interceptors: [],
12
- userAgent: constants.userAgent
13
- };
14
- const createAdvancedClient = (...configs) => {
15
- const settings = configs.concat([clientIniFactory.withLegacyInterceptors()]).reduce(
16
- (currentSettings, config) => config(currentSettings),
17
- DEFAULT_SETTINGS
18
- );
19
- clientSettings.assertValidSettings(settings);
20
- index.getLogger().info(`init Scaleway SDK version ${constants.version}`);
21
- return {
22
- fetch: buildFetcher.buildFetcher(settings, settings.httpClient),
23
- settings
24
- };
25
- };
26
- const createClient = (settings = {}) => createAdvancedClient(
27
- clientIniFactory.withProfile(settings),
28
- clientIniFactory.withAdditionalInterceptors(settings.interceptors ?? [])
29
- );
30
- exports.createAdvancedClient = createAdvancedClient;
31
- exports.createClient = createClient;
@@ -1,11 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const _package = require("../package.json.cjs");
4
- const { version } = _package.default;
5
- const userAgent = `scaleway-sdk-js/${version}`;
6
- const SESSION_HEADER_KEY = "x-session-token";
7
- const AUTH_HEADER_KEY = "x-auth-token";
8
- exports.AUTH_HEADER_KEY = AUTH_HEADER_KEY;
9
- exports.SESSION_HEADER_KEY = SESSION_HEADER_KEY;
10
- exports.userAgent = userAgent;
11
- exports.version = version;
@@ -1,152 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const json = require("../helpers/json.cjs");
4
- const marshalling = require("../helpers/marshalling.cjs");
5
- const index = require("../vendor/base64/index.cjs");
6
- const customTypes = require("./custom-types.cjs");
7
- const unmarshalMoney = (data) => {
8
- if (!json.isJSONObject(data)) {
9
- throw new TypeError(
10
- `Unmarshalling the type 'Money' failed as data isn't a dictionary.`
11
- );
12
- }
13
- return {
14
- currencyCode: data.currency_code,
15
- nanos: data.nanos,
16
- units: data.units
17
- };
18
- };
19
- const unmarshalServiceInfo = (data) => {
20
- if (!json.isJSONObject(data)) {
21
- throw new TypeError(
22
- `Unmarshalling the type 'ServiceInfo' failed as data isn't a dictionary.`
23
- );
24
- }
25
- return {
26
- description: data.description,
27
- documentationUrl: data.documentation_url,
28
- name: data.name,
29
- version: data.version
30
- };
31
- };
32
- const unmarshalScwFile = (data) => {
33
- if (!json.isJSONObject(data)) {
34
- throw new TypeError(
35
- `Unmarshalling the type 'ScwFile' failed as data isn't a dictionary.`
36
- );
37
- }
38
- return {
39
- content: data.content,
40
- contentType: data.content_type,
41
- name: data.name
42
- };
43
- };
44
- const unmarshalTimeSeriesPoint = (data) => {
45
- if (!Array.isArray(data)) {
46
- throw new TypeError(
47
- `Unmarshalling the type 'TimeSeriesPoint' failed as data isn't an array.`
48
- );
49
- }
50
- return {
51
- timestamp: marshalling.unmarshalDate(data[0]),
52
- value: data[1]
53
- };
54
- };
55
- const unmarshalTimeSeries = (data) => {
56
- if (!json.isJSONObject(data)) {
57
- throw new TypeError(
58
- `Unmarshalling the type 'TimeSeries' failed as data isn't a dictionary.`
59
- );
60
- }
61
- return {
62
- metadata: data.metadata,
63
- name: data.name,
64
- points: marshalling.unmarshalArrayOfObject(data.points, unmarshalTimeSeriesPoint)
65
- };
66
- };
67
- const unmarshalDecimal = (data) => {
68
- if (!(typeof data === "object")) {
69
- throw new TypeError(
70
- `Unmarshalling the type 'Decimal' failed as data isn't an object.`
71
- );
72
- }
73
- if (data === null) {
74
- return null;
75
- }
76
- if (!("value" in data)) {
77
- throw new TypeError(
78
- `Unmarshalling the type 'Decimal' failed as data object does not have a 'value' key.`
79
- );
80
- }
81
- if (!(typeof data.value === "string")) {
82
- throw new TypeError(
83
- `Unmarshalling the type 'Decimal' failed as 'value' is not a string.`
84
- );
85
- }
86
- return new customTypes.Decimal(data.value);
87
- };
88
- const marshalScwFile = (obj) => ({
89
- content: obj.content,
90
- content_type: obj.contentType,
91
- name: obj.name
92
- });
93
- const marshalBlobToScwFile = async (blob) => ({
94
- content: index.fromByteArray(new Uint8Array(await blob.arrayBuffer())),
95
- content_type: blob.type,
96
- name: "file"
97
- });
98
- const marshalMoney = (obj) => ({
99
- currency_code: obj.currencyCode,
100
- nanos: obj.nanos,
101
- units: obj.units
102
- });
103
- const marshalTimeSeriesPoint = (obj) => ({
104
- timestamp: obj.timestamp?.toISOString(),
105
- value: obj.value
106
- });
107
- const marshalTimeSeries = (obj) => ({
108
- metadata: obj.metadata,
109
- name: obj.name,
110
- points: obj.points.map((elt) => marshalTimeSeriesPoint(elt))
111
- });
112
- const marshalDecimal = (obj) => ({
113
- value: obj.toString()
114
- });
115
- const unmarshalDates = (obj, keys) => {
116
- if (Array.isArray(obj)) {
117
- return obj.map((v) => unmarshalDates(v, keys));
118
- }
119
- if (obj && typeof obj === "object") {
120
- return Object.entries(obj).reduce(
121
- (acc, [key, value]) => ({
122
- ...acc,
123
- [key]: typeof value === "string" && keys.includes(key) ? new Date(value) : unmarshalDates(value, keys)
124
- }),
125
- {}
126
- );
127
- }
128
- return obj;
129
- };
130
- const unmarshalAnyRes = (obj, ignoreKeys = [], dateKeys) => {
131
- if (!json.isJSONObject(obj)) {
132
- throw new TypeError(`Data isn't a dictionary.`);
133
- }
134
- return json.camelizeKeys(
135
- dateKeys && dateKeys.length > 0 ? unmarshalDates(obj, dateKeys) : obj,
136
- ignoreKeys
137
- );
138
- };
139
- exports.marshalBlobToScwFile = marshalBlobToScwFile;
140
- exports.marshalDecimal = marshalDecimal;
141
- exports.marshalMoney = marshalMoney;
142
- exports.marshalScwFile = marshalScwFile;
143
- exports.marshalTimeSeries = marshalTimeSeries;
144
- exports.marshalTimeSeriesPoint = marshalTimeSeriesPoint;
145
- exports.unmarshalAnyRes = unmarshalAnyRes;
146
- exports.unmarshalDates = unmarshalDates;
147
- exports.unmarshalDecimal = unmarshalDecimal;
148
- exports.unmarshalMoney = unmarshalMoney;
149
- exports.unmarshalScwFile = unmarshalScwFile;
150
- exports.unmarshalServiceInfo = unmarshalServiceInfo;
151
- exports.unmarshalTimeSeries = unmarshalTimeSeries;
152
- exports.unmarshalTimeSeriesPoint = unmarshalTimeSeriesPoint;
@@ -1,11 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- class Decimal {
4
- str;
5
- constructor(v) {
6
- this.str = v;
7
- }
8
- toString = () => this.str;
9
- marshal = () => ({ value: this.str });
10
- }
11
- exports.Decimal = Decimal;
@@ -1,76 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const invalidRequestMapper = require("./non-standard/invalid-request-mapper.cjs");
4
- const unknownResourceMapper = require("./non-standard/unknown-resource-mapper.cjs");
5
- const scwError = require("./scw-error.cjs");
6
- const alreadyExistsError = require("./standard/already-exists-error.cjs");
7
- const deniedAuthenticationError = require("./standard/denied-authentication-error.cjs");
8
- const invalidArgumentsError = require("./standard/invalid-arguments-error.cjs");
9
- const outOfStockError = require("./standard/out-of-stock-error.cjs");
10
- const permissionsDeniedError = require("./standard/permissions-denied-error.cjs");
11
- const preconditionFailedError = require("./standard/precondition-failed-error.cjs");
12
- const quotasExceededError = require("./standard/quotas-exceeded-error.cjs");
13
- const resourceExpiredError = require("./standard/resource-expired-error.cjs");
14
- const resourceLockedError = require("./standard/resource-locked-error.cjs");
15
- const resourceNotFoundError = require("./standard/resource-not-found-error.cjs");
16
- const tooManyRequestsError = require("./standard/too-many-requests-error.cjs");
17
- const transientStateError = require("./standard/transient-state-error.cjs");
18
- const unmarshalStandardError = (type, status, body) => {
19
- let error;
20
- switch (type) {
21
- case "denied_authentication":
22
- error = deniedAuthenticationError.DeniedAuthenticationError;
23
- break;
24
- case "invalid_arguments":
25
- error = invalidArgumentsError.InvalidArgumentsError;
26
- break;
27
- case "out_of_stock":
28
- error = outOfStockError.OutOfStockError;
29
- break;
30
- case "permissions_denied":
31
- error = permissionsDeniedError.PermissionsDeniedError;
32
- break;
33
- case "precondition_failed":
34
- error = preconditionFailedError.PreconditionFailedError;
35
- break;
36
- case "quotas_exceeded":
37
- error = quotasExceededError.QuotasExceededError;
38
- break;
39
- case "expired":
40
- error = resourceExpiredError.ResourceExpiredError;
41
- break;
42
- case "not_found":
43
- error = resourceNotFoundError.ResourceNotFoundError;
44
- break;
45
- case "locked":
46
- error = resourceLockedError.ResourceLockedError;
47
- break;
48
- case "transient_state":
49
- error = transientStateError.TransientStateError;
50
- break;
51
- case "already_exists":
52
- error = alreadyExistsError.AlreadyExistsError;
53
- break;
54
- case "too_many_requests":
55
- error = tooManyRequestsError.TooManyRequestsError;
56
- break;
57
- default:
58
- return null;
59
- }
60
- return error.fromJSON(status, body);
61
- };
62
- const unmarshalNonStandardError = (type, status, body) => {
63
- switch (type) {
64
- case "unknown_resource":
65
- return unknownResourceMapper.UnknownResourceMapper.fromJSON(status, body);
66
- case "invalid_request_error":
67
- return invalidRequestMapper.InvalidRequestMapper.fromJSON(status, body);
68
- default:
69
- return null;
70
- }
71
- };
72
- const parseScalewayError = (status, body) => {
73
- const parsableError = typeof body.type === "string" && (unmarshalStandardError(body.type, status, body) ?? unmarshalNonStandardError(body.type, status, body));
74
- return parsableError || new scwError.ScalewayError(status, body);
75
- };
76
- exports.parseScalewayError = parseScalewayError;
@@ -1,36 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const scwError = require("../scw-error.cjs");
4
- const invalidArgumentsError = require("../standard/invalid-arguments-error.cjs");
5
- const quotasExceededError = require("../standard/quotas-exceeded-error.cjs");
6
- const types = require("../types.cjs");
7
- class InvalidRequestMapper {
8
- static fromJSON(status, obj) {
9
- if (typeof obj.message === "string" && obj.message.toLowerCase().includes("quota exceeded for this resource")) {
10
- return new quotasExceededError.QuotasExceededError(status, obj, [
11
- {
12
- current: 0,
13
- quota: 0,
14
- resource: typeof obj.resource === "string" ? obj.resource : ""
15
- }
16
- ]);
17
- }
18
- const fields = obj.fields && types.isRecordOfStringArray(obj.fields) ? obj.fields : {};
19
- const fieldsMessages = Object.entries(fields);
20
- if (fieldsMessages.length) {
21
- return new invalidArgumentsError.InvalidArgumentsError(
22
- status,
23
- obj,
24
- fieldsMessages.map(
25
- ([argumentName, messages]) => messages.map((helpMessage) => ({
26
- argumentName,
27
- helpMessage,
28
- reason: "constraint"
29
- }))
30
- ).flat()
31
- );
32
- }
33
- return new scwError.ScalewayError(status, obj);
34
- }
35
- }
36
- exports.InvalidRequestMapper = InvalidRequestMapper;
@@ -1,23 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const stringValidation = require("../../../internal/validations/string-validation.cjs");
4
- const scwError = require("../scw-error.cjs");
5
- const resourceNotFoundError = require("../standard/resource-not-found-error.cjs");
6
- class UnknownResourceMapper {
7
- static fromJSON(status, obj) {
8
- const messageParts = typeof obj.message === "string" ? obj.message.split(/"|'/) : [];
9
- if (messageParts.length === 3 && stringValidation.isUUID(messageParts[1])) {
10
- return new resourceNotFoundError.ResourceNotFoundError(
11
- status,
12
- obj,
13
- // transform `Security group ` to `security_group`
14
- // `.replaceAll()` may be too recent to use yet.
15
- // that's why we're using `.split(' ').join('_')` for now.
16
- messageParts[0].trim().toLowerCase().split(" ").join("_"),
17
- messageParts[1]
18
- );
19
- }
20
- return new scwError.ScalewayError(status, obj);
21
- }
22
- }
23
- exports.UnknownResourceMapper = UnknownResourceMapper;