@scaleway/sdk-client 2.1.0 → 2.2.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 (53) hide show
  1. package/dist/_virtual/_rolldown/runtime.js +11 -0
  2. package/dist/helpers/is-browser.js +1 -3
  3. package/dist/helpers/is-response.js +8 -3
  4. package/dist/helpers/json.js +47 -40
  5. package/dist/helpers/marshalling.js +88 -59
  6. package/dist/index.js +6 -47
  7. package/dist/internal/async/interval-retrier.js +64 -49
  8. package/dist/internal/async/sleep.js +10 -4
  9. package/dist/internal/interceptors/composer.js +34 -23
  10. package/dist/internal/interceptors/helpers.js +22 -9
  11. package/dist/internal/logger/console-logger.js +27 -22
  12. package/dist/internal/logger/index.js +23 -7
  13. package/dist/internal/logger/level-resolver.js +9 -12
  14. package/dist/internal/validations/string-validation.js +20 -21
  15. package/dist/internals.js +8 -0
  16. package/dist/package.js +32 -0
  17. package/dist/scw/api.js +10 -7
  18. package/dist/scw/auth.js +60 -17
  19. package/dist/scw/client-ini-factory.js +127 -57
  20. package/dist/scw/client-ini-profile.js +23 -19
  21. package/dist/scw/client-settings.js +25 -49
  22. package/dist/scw/client.js +76 -25
  23. package/dist/scw/constants.js +3 -8
  24. package/dist/scw/custom-marshalling.js +147 -121
  25. package/dist/scw/custom-types.js +11 -10
  26. package/dist/scw/errors/error-parser.js +83 -61
  27. package/dist/scw/errors/non-standard/invalid-request-mapper.js +20 -29
  28. package/dist/scw/errors/non-standard/unknown-resource-mapper.js +9 -16
  29. package/dist/scw/errors/scw-error.js +42 -39
  30. package/dist/scw/errors/standard/already-exists-error.js +20 -29
  31. package/dist/scw/errors/standard/denied-authentication-error.js +43 -34
  32. package/dist/scw/errors/standard/index.js +20 -18
  33. package/dist/scw/errors/standard/invalid-arguments-error.js +51 -50
  34. package/dist/scw/errors/standard/out-of-stock-error.js +18 -15
  35. package/dist/scw/errors/standard/permissions-denied-error.js +30 -26
  36. package/dist/scw/errors/standard/precondition-failed-error.js +32 -29
  37. package/dist/scw/errors/standard/quotas-exceeded-error.js +43 -38
  38. package/dist/scw/errors/standard/resource-expired-error.js +20 -29
  39. package/dist/scw/errors/standard/resource-locked-error.js +19 -18
  40. package/dist/scw/errors/standard/resource-not-found-error.js +19 -22
  41. package/dist/scw/errors/standard/too-many-requests-error.js +41 -54
  42. package/dist/scw/errors/standard/transient-state-error.js +20 -29
  43. package/dist/scw/errors/types.js +12 -12
  44. package/dist/scw/fetch/build-fetcher.js +49 -54
  45. package/dist/scw/fetch/http-dumper.js +50 -16
  46. package/dist/scw/fetch/http-interceptors.d.ts +1 -3
  47. package/dist/scw/fetch/http-interceptors.js +52 -34
  48. package/dist/scw/fetch/resource-paginator.js +52 -28
  49. package/dist/scw/fetch/response-parser.js +48 -49
  50. package/dist/scw/locality.js +12 -14
  51. package/dist/vendor/base64/index.js +31 -39
  52. package/package.json +1 -1
  53. package/dist/package.json.js +0 -8
@@ -1,31 +1,82 @@
1
1
  import { getLogger } from "../internal/logger/index.js";
2
- import { withLegacyInterceptors, withAdditionalInterceptors, withProfile } from "./client-ini-factory.js";
3
- import { assertValidSettings } from "./client-settings.js";
4
2
  import { userAgent, version } from "./constants.js";
3
+ import { withAdditionalInterceptors, withLegacyInterceptors, withProfile } from "./client-ini-factory.js";
4
+ import { assertValidSettings } from "./client-settings.js";
5
5
  import { buildFetcher } from "./fetch/build-fetcher.js";
6
- const DEFAULT_SETTINGS = {
7
- apiURL: "https://api.scaleway.com",
8
- httpClient: fetch,
9
- interceptors: [],
10
- userAgent
6
+ /** Default {@link Settings} values. */
7
+ var DEFAULT_SETTINGS = {
8
+ apiURL: "https://api.scaleway.com",
9
+ httpClient: fetch,
10
+ interceptors: [],
11
+ userAgent
11
12
  };
13
+ /**
14
+ * Creates a Scaleway client with advanced options.
15
+ * You can either use existing factories
16
+ * (like `withProfile`, `withUserAgentSuffix`, etc)
17
+ * or write your own using the interface `ClientConfig`.
18
+ *
19
+ * @example
20
+ * Creates a client with factories:
21
+ * ```
22
+ * createAdvancedClient(
23
+ * (obj: Settings) => ({
24
+ * ...obj,
25
+ * defaultPageSize: 100 ,
26
+ * httpClient: myFetchWrapper,
27
+ * }),
28
+ * withUserAgentSuffix('bot-name/1.0'),
29
+ * )
30
+ * ```
31
+ *
32
+ * @throws Error
33
+ * Thrown if the setup fails.
34
+ *
35
+ * @public
36
+ */
12
37
  const createAdvancedClient = (...configs) => {
13
- const settings = configs.concat([withLegacyInterceptors()]).reduce(
14
- (currentSettings, config) => config(currentSettings),
15
- DEFAULT_SETTINGS
16
- );
17
- assertValidSettings(settings);
18
- getLogger().info(`init Scaleway SDK version ${version}`);
19
- return {
20
- fetch: buildFetcher(settings, settings.httpClient),
21
- settings
22
- };
23
- };
24
- const createClient = (settings = {}) => createAdvancedClient(
25
- withProfile(settings),
26
- withAdditionalInterceptors(settings.interceptors ?? [])
27
- );
28
- export {
29
- createAdvancedClient,
30
- createClient
38
+ const settings = configs.concat([withLegacyInterceptors()]).reduce((currentSettings, config) => config(currentSettings), DEFAULT_SETTINGS);
39
+ assertValidSettings(settings);
40
+ getLogger().info(`init Scaleway SDK version ${version}`);
41
+ return {
42
+ fetch: buildFetcher(settings, settings.httpClient),
43
+ settings
44
+ };
31
45
  };
46
+ /**
47
+ * Creates a Scaleway client with a profile.
48
+ *
49
+ * @example
50
+ * Creates a client with credentials & default values (see https://www.scaleway.com/en/docs/identity-and-access-management/iam/how-to/create-api-keys/):
51
+ * ```
52
+ * import { createClient } from '@scaleway/sdk'
53
+ *
54
+ * createClient({
55
+ * accessKey: 'SCWXXXXXXXXXXXXXXXXX',
56
+ * secretKey: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
57
+ * defaultProjectId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
58
+ * defaultRegion: 'fr-par',
59
+ * defaultZone: 'fr-par-1',
60
+ * })
61
+ * ```
62
+ *
63
+ * @example
64
+ * Creates a client by loading values from the environment (see https://www.scaleway.com/en/docs/identity-and-access-management/iam/how-to/create-api-keys/)
65
+ * or the config file created by CLI `scw init` (see https://www.scaleway.com/en/cli/):
66
+ * ```
67
+ * import { loadProfileFromConfigurationFile } from '@scaleway/configuration-loader'
68
+ * import { createClient } from '@scaleway/sdk'
69
+ *
70
+ * createClient({
71
+ * ...await loadProfileFromConfigurationFile(),
72
+ * defaultZone: 'fr-par-3',
73
+ * })
74
+ * ```
75
+ *
76
+ * @throws Error
77
+ * Thrown if the setup fails.
78
+ *
79
+ * @public
80
+ */
81
+ const createClient = (settings = {}) => createAdvancedClient(withProfile(settings), withAdditionalInterceptors(settings.interceptors ?? []));
82
+ export { createAdvancedClient, createClient };
@@ -1,11 +1,6 @@
1
- import pkg from "../package.json.js";
2
- const { version } = pkg;
1
+ import package_default from "../package.js";
2
+ const { version } = package_default;
3
3
  const userAgent = `scaleway-sdk-js/${version}`;
4
4
  const SESSION_HEADER_KEY = "x-session-token";
5
5
  const AUTH_HEADER_KEY = "x-auth-token";
6
- export {
7
- AUTH_HEADER_KEY,
8
- SESSION_HEADER_KEY,
9
- userAgent,
10
- version
11
- };
6
+ export { AUTH_HEADER_KEY, SESSION_HEADER_KEY, userAgent, version };
@@ -1,150 +1,176 @@
1
- import { isJSONObject, camelizeKeys } from "../helpers/json.js";
1
+ import { camelizeKeys, isJSONObject } from "../helpers/json.js";
2
2
  import { unmarshalArrayOfObject, unmarshalDate } from "../helpers/marshalling.js";
3
3
  import { fromByteArray } from "../vendor/base64/index.js";
4
4
  import { Decimal } from "./custom-types.js";
5
+ /**
6
+ * Unmarshals {@link Money}
7
+ *
8
+ * @internal
9
+ */
5
10
  const unmarshalMoney = (data) => {
6
- if (!isJSONObject(data)) {
7
- throw new TypeError(
8
- `Unmarshalling the type 'Money' failed as data isn't a dictionary.`
9
- );
10
- }
11
- return {
12
- currencyCode: data.currency_code,
13
- nanos: data.nanos,
14
- units: data.units
15
- };
11
+ if (!isJSONObject(data)) throw new TypeError(`Unmarshalling the type 'Money' failed as data isn't a dictionary.`);
12
+ return {
13
+ currencyCode: data.currency_code,
14
+ nanos: data.nanos,
15
+ units: data.units
16
+ };
16
17
  };
18
+ /**
19
+ * Unmarshals {@link ServiceInfo}.
20
+ *
21
+ * @internal
22
+ */
17
23
  const unmarshalServiceInfo = (data) => {
18
- if (!isJSONObject(data)) {
19
- throw new TypeError(
20
- `Unmarshalling the type 'ServiceInfo' failed as data isn't a dictionary.`
21
- );
22
- }
23
- return {
24
- description: data.description,
25
- documentationUrl: data.documentation_url,
26
- name: data.name,
27
- version: data.version
28
- };
24
+ if (!isJSONObject(data)) throw new TypeError(`Unmarshalling the type 'ServiceInfo' failed as data isn't a dictionary.`);
25
+ return {
26
+ description: data.description,
27
+ documentationUrl: data.documentation_url,
28
+ name: data.name,
29
+ version: data.version
30
+ };
29
31
  };
32
+ /**
33
+ * Unmarshals {@link ScwFile}.
34
+ *
35
+ * @internal
36
+ */
30
37
  const unmarshalScwFile = (data) => {
31
- if (!isJSONObject(data)) {
32
- throw new TypeError(
33
- `Unmarshalling the type 'ScwFile' failed as data isn't a dictionary.`
34
- );
35
- }
36
- return {
37
- content: data.content,
38
- contentType: data.content_type,
39
- name: data.name
40
- };
38
+ if (!isJSONObject(data)) throw new TypeError(`Unmarshalling the type 'ScwFile' failed as data isn't a dictionary.`);
39
+ return {
40
+ content: data.content,
41
+ contentType: data.content_type,
42
+ name: data.name
43
+ };
41
44
  };
45
+ /**
46
+ * Unmarshals {@link TimeSeriesPoint}
47
+ *
48
+ * @remarks To optimize the size of this message,
49
+ * the JSON is compressed in an array instead of a dictionary.
50
+ * Example: `["2019-08-08T15:00:00Z", 0.2]`.
51
+ *
52
+ * @internal
53
+ */
42
54
  const unmarshalTimeSeriesPoint = (data) => {
43
- if (!Array.isArray(data)) {
44
- throw new TypeError(
45
- `Unmarshalling the type 'TimeSeriesPoint' failed as data isn't an array.`
46
- );
47
- }
48
- return {
49
- timestamp: unmarshalDate(data[0]),
50
- value: data[1]
51
- };
55
+ if (!Array.isArray(data)) throw new TypeError(`Unmarshalling the type 'TimeSeriesPoint' failed as data isn't an array.`);
56
+ return {
57
+ timestamp: unmarshalDate(data[0]),
58
+ value: data[1]
59
+ };
52
60
  };
61
+ /**
62
+ * Unmarshals {@link TimeSeries}
63
+ *
64
+ * @internal
65
+ */
53
66
  const unmarshalTimeSeries = (data) => {
54
- if (!isJSONObject(data)) {
55
- throw new TypeError(
56
- `Unmarshalling the type 'TimeSeries' failed as data isn't a dictionary.`
57
- );
58
- }
59
- return {
60
- metadata: data.metadata,
61
- name: data.name,
62
- points: unmarshalArrayOfObject(data.points, unmarshalTimeSeriesPoint)
63
- };
67
+ if (!isJSONObject(data)) throw new TypeError(`Unmarshalling the type 'TimeSeries' failed as data isn't a dictionary.`);
68
+ return {
69
+ metadata: data.metadata,
70
+ name: data.name,
71
+ points: unmarshalArrayOfObject(data.points, unmarshalTimeSeriesPoint)
72
+ };
64
73
  };
74
+ /**
75
+ * Unmarshals {@link Decimal}
76
+ *
77
+ * @internal
78
+ */
65
79
  const unmarshalDecimal = (data) => {
66
- if (!(typeof data === "object")) {
67
- throw new TypeError(
68
- `Unmarshalling the type 'Decimal' failed as data isn't an object.`
69
- );
70
- }
71
- if (data === null) {
72
- return null;
73
- }
74
- if (!("value" in data)) {
75
- throw new TypeError(
76
- `Unmarshalling the type 'Decimal' failed as data object does not have a 'value' key.`
77
- );
78
- }
79
- if (!(typeof data.value === "string")) {
80
- throw new TypeError(
81
- `Unmarshalling the type 'Decimal' failed as 'value' is not a string.`
82
- );
83
- }
84
- return new Decimal(data.value);
80
+ if (!(typeof data === "object")) throw new TypeError(`Unmarshalling the type 'Decimal' failed as data isn't an object.`);
81
+ if (data === null) return null;
82
+ if (!("value" in data)) throw new TypeError(`Unmarshalling the type 'Decimal' failed as data object does not have a 'value' key.`);
83
+ if (!(typeof data.value === "string")) throw new TypeError(`Unmarshalling the type 'Decimal' failed as 'value' is not a string.`);
84
+ return new Decimal(data.value);
85
85
  };
86
+ /**
87
+ * Marshals {@link ScwFile}.
88
+ *
89
+ * @internal
90
+ */
86
91
  const marshalScwFile = (obj) => ({
87
- content: obj.content,
88
- content_type: obj.contentType,
89
- name: obj.name
92
+ content: obj.content,
93
+ content_type: obj.contentType,
94
+ name: obj.name
90
95
  });
96
+ /**
97
+ * Marshals {@link Blob}.
98
+ *
99
+ * @internal
100
+ */
91
101
  const marshalBlobToScwFile = async (blob) => ({
92
- content: fromByteArray(new Uint8Array(await blob.arrayBuffer())),
93
- content_type: blob.type,
94
- name: "file"
102
+ content: fromByteArray(new Uint8Array(await blob.arrayBuffer())),
103
+ content_type: blob.type,
104
+ name: "file"
95
105
  });
106
+ /**
107
+ * Marshals {@link Money}
108
+ *
109
+ * @internal
110
+ */
96
111
  const marshalMoney = (obj) => ({
97
- currency_code: obj.currencyCode,
98
- nanos: obj.nanos,
99
- units: obj.units
112
+ currency_code: obj.currencyCode,
113
+ nanos: obj.nanos,
114
+ units: obj.units
100
115
  });
116
+ /**
117
+ * Marshals {@link TimeSeriesPoint}
118
+ *
119
+ * @internal
120
+ */
101
121
  const marshalTimeSeriesPoint = (obj) => ({
102
- timestamp: obj.timestamp?.toISOString(),
103
- value: obj.value
122
+ timestamp: obj.timestamp?.toISOString(),
123
+ value: obj.value
104
124
  });
125
+ /**
126
+ * Marshals {@link TimeSeries}
127
+ *
128
+ * @internal
129
+ */
105
130
  const marshalTimeSeries = (obj) => ({
106
- metadata: obj.metadata,
107
- name: obj.name,
108
- points: obj.points.map((elt) => marshalTimeSeriesPoint(elt))
109
- });
110
- const marshalDecimal = (obj) => ({
111
- value: obj.toString()
131
+ metadata: obj.metadata,
132
+ name: obj.name,
133
+ points: obj.points.map((elt) => marshalTimeSeriesPoint(elt))
112
134
  });
135
+ /**
136
+ * Marshals {@link Decimal}
137
+ *
138
+ * @internal
139
+ */
140
+ const marshalDecimal = (obj) => ({ value: obj.toString() });
141
+ /**
142
+ * Unmarshals record to convert iso dates from string to Dates.
143
+ *
144
+ * @param obj - The input
145
+ * @param keys - The keys requiring a conversion
146
+ * @returns The updated input
147
+ *
148
+ * @internal
149
+ */
113
150
  const unmarshalDates = (obj, keys) => {
114
- if (Array.isArray(obj)) {
115
- return obj.map((v) => unmarshalDates(v, keys));
116
- }
117
- if (obj && typeof obj === "object") {
118
- const result = {};
119
- for (const [key, value] of Object.entries(obj)) {
120
- result[key] = typeof value === "string" && keys.includes(key) ? new Date(value) : unmarshalDates(value, keys);
121
- }
122
- return result;
123
- }
124
- return obj;
151
+ if (Array.isArray(obj)) return obj.map((v) => unmarshalDates(v, keys));
152
+ if (obj && typeof obj === "object") {
153
+ const result = {};
154
+ for (const [key, value] of Object.entries(obj)) result[key] = typeof value === "string" && keys.includes(key) ? new Date(value) : unmarshalDates(value, keys);
155
+ return result;
156
+ }
157
+ return obj;
125
158
  };
159
+ /**
160
+ * Unmarshals input to a record with camilized keys and instanciated Date.
161
+ *
162
+ * @param obj - The input
163
+ * @param ignoreKeys - The keys which should be not be transformed
164
+ * @param dateKeys - The keys which should be transformed to Date
165
+ * @returns The record
166
+ *
167
+ * @throws TypeError
168
+ * Thrown if the input isn't {@link JSONObject}.
169
+ *
170
+ * @internal
171
+ */
126
172
  const unmarshalAnyRes = (obj, ignoreKeys = [], dateKeys) => {
127
- if (!isJSONObject(obj)) {
128
- throw new TypeError(`Data isn't a dictionary.`);
129
- }
130
- return camelizeKeys(
131
- dateKeys && dateKeys.length > 0 ? unmarshalDates(obj, dateKeys) : obj,
132
- ignoreKeys
133
- );
134
- };
135
- export {
136
- marshalBlobToScwFile,
137
- marshalDecimal,
138
- marshalMoney,
139
- marshalScwFile,
140
- marshalTimeSeries,
141
- marshalTimeSeriesPoint,
142
- unmarshalAnyRes,
143
- unmarshalDates,
144
- unmarshalDecimal,
145
- unmarshalMoney,
146
- unmarshalScwFile,
147
- unmarshalServiceInfo,
148
- unmarshalTimeSeries,
149
- unmarshalTimeSeriesPoint
173
+ if (!isJSONObject(obj)) throw new TypeError(`Data isn't a dictionary.`);
174
+ return camelizeKeys(dateKeys && dateKeys.length > 0 ? unmarshalDates(obj, dateKeys) : obj, ignoreKeys);
150
175
  };
176
+ export { marshalBlobToScwFile, marshalDecimal, marshalMoney, marshalScwFile, marshalTimeSeries, unmarshalAnyRes, unmarshalDecimal, unmarshalMoney, unmarshalScwFile, unmarshalServiceInfo, unmarshalTimeSeries, unmarshalTimeSeriesPoint };
@@ -1,11 +1,12 @@
1
- class Decimal {
2
- str;
3
- constructor(v) {
4
- this.str = v;
5
- }
6
- toString = () => this.str;
7
- marshal = () => ({ value: this.str });
8
- }
9
- export {
10
- Decimal
1
+ /** A representation of a decimal value, such as 2.5.
2
+ * Comparable to language-native decimal formats, such as Java's BigDecimal or Python's decimal.Decimal.
3
+ * Lookup protobuf google.type.Decimal for details */
4
+ var Decimal = class {
5
+ str;
6
+ constructor(v) {
7
+ this.str = v;
8
+ }
9
+ toString = () => this.str;
10
+ marshal = () => ({ value: this.str });
11
11
  };
12
+ export { Decimal };
@@ -1,76 +1,98 @@
1
+ import { ScalewayError } from "./scw-error.js";
2
+ import { InvalidArgumentsError } from "./standard/invalid-arguments-error.js";
3
+ import { QuotasExceededError } from "./standard/quotas-exceeded-error.js";
1
4
  import { mapInvalidRequestFromJSON } from "./non-standard/invalid-request-mapper.js";
5
+ import { ResourceNotFoundError } from "./standard/resource-not-found-error.js";
2
6
  import { mapUnknownResourceFromJSON } from "./non-standard/unknown-resource-mapper.js";
3
- import { ScalewayError } from "./scw-error.js";
4
7
  import { AlreadyExistsError } from "./standard/already-exists-error.js";
5
8
  import { DeniedAuthenticationError } from "./standard/denied-authentication-error.js";
6
- import { InvalidArgumentsError } from "./standard/invalid-arguments-error.js";
7
9
  import { OutOfStockError } from "./standard/out-of-stock-error.js";
8
10
  import { PermissionsDeniedError } from "./standard/permissions-denied-error.js";
9
11
  import { PreconditionFailedError } from "./standard/precondition-failed-error.js";
10
- import { QuotasExceededError } from "./standard/quotas-exceeded-error.js";
11
12
  import { ResourceExpiredError } from "./standard/resource-expired-error.js";
12
13
  import { ResourceLockedError } from "./standard/resource-locked-error.js";
13
- import { ResourceNotFoundError } from "./standard/resource-not-found-error.js";
14
14
  import { TooManyRequestsError } from "./standard/too-many-requests-error.js";
15
15
  import { TransientStateError } from "./standard/transient-state-error.js";
16
- const unmarshalStandardError = (type, status, body) => {
17
- let error;
18
- switch (type) {
19
- case "denied_authentication":
20
- error = DeniedAuthenticationError;
21
- break;
22
- case "invalid_arguments":
23
- error = InvalidArgumentsError;
24
- break;
25
- case "out_of_stock":
26
- error = OutOfStockError;
27
- break;
28
- case "permissions_denied":
29
- error = PermissionsDeniedError;
30
- break;
31
- case "precondition_failed":
32
- error = PreconditionFailedError;
33
- break;
34
- case "quotas_exceeded":
35
- error = QuotasExceededError;
36
- break;
37
- case "expired":
38
- error = ResourceExpiredError;
39
- break;
40
- case "not_found":
41
- error = ResourceNotFoundError;
42
- break;
43
- case "locked":
44
- error = ResourceLockedError;
45
- break;
46
- case "transient_state":
47
- error = TransientStateError;
48
- break;
49
- case "already_exists":
50
- error = AlreadyExistsError;
51
- break;
52
- case "too_many_requests":
53
- error = TooManyRequestsError;
54
- break;
55
- default:
56
- return null;
57
- }
58
- return error.fromJSON(status, body);
16
+ /**
17
+ * Unmarshals a standard error from raw body.
18
+ *
19
+ * @param type - The error type
20
+ * @param status - The status code
21
+ * @param body - The error response
22
+ * @returns The standard error if found
23
+ *
24
+ * @internal
25
+ */
26
+ var unmarshalStandardError = (type, status, body) => {
27
+ let error;
28
+ switch (type) {
29
+ case "denied_authentication":
30
+ error = DeniedAuthenticationError;
31
+ break;
32
+ case "invalid_arguments":
33
+ error = InvalidArgumentsError;
34
+ break;
35
+ case "out_of_stock":
36
+ error = OutOfStockError;
37
+ break;
38
+ case "permissions_denied":
39
+ error = PermissionsDeniedError;
40
+ break;
41
+ case "precondition_failed":
42
+ error = PreconditionFailedError;
43
+ break;
44
+ case "quotas_exceeded":
45
+ error = QuotasExceededError;
46
+ break;
47
+ case "expired":
48
+ error = ResourceExpiredError;
49
+ break;
50
+ case "not_found":
51
+ error = ResourceNotFoundError;
52
+ break;
53
+ case "locked":
54
+ error = ResourceLockedError;
55
+ break;
56
+ case "transient_state":
57
+ error = TransientStateError;
58
+ break;
59
+ case "already_exists":
60
+ error = AlreadyExistsError;
61
+ break;
62
+ case "too_many_requests":
63
+ error = TooManyRequestsError;
64
+ break;
65
+ default: return null;
66
+ }
67
+ return error.fromJSON(status, body);
59
68
  };
60
- const unmarshalNonStandardError = (type, status, body) => {
61
- switch (type) {
62
- case "unknown_resource":
63
- return mapUnknownResourceFromJSON(status, body);
64
- case "invalid_request_error":
65
- return mapInvalidRequestFromJSON(status, body);
66
- default:
67
- return null;
68
- }
69
+ /**
70
+ * Unmarshals a non-standard error from raw body.
71
+ *
72
+ * @param type - The error type
73
+ * @param status - The status code
74
+ * @param body - The error response
75
+ * @returns The non-standard error if found
76
+ *
77
+ * @internal
78
+ */
79
+ var unmarshalNonStandardError = (type, status, body) => {
80
+ switch (type) {
81
+ case "unknown_resource": return mapUnknownResourceFromJSON(status, body);
82
+ case "invalid_request_error": return mapInvalidRequestFromJSON(status, body);
83
+ default: return null;
84
+ }
69
85
  };
86
+ /**
87
+ * Parses Scaleway error from raw body.
88
+ *
89
+ * @param status - The status code
90
+ * @param body - The error response
91
+ * @returns The resolved error
92
+ *
93
+ * @internal
94
+ */
70
95
  const parseScalewayError = (status, body) => {
71
- const parsableError = typeof body.type === "string" && (unmarshalStandardError(body.type, status, body) ?? unmarshalNonStandardError(body.type, status, body));
72
- return parsableError || new ScalewayError(status, body);
73
- };
74
- export {
75
- parseScalewayError
96
+ return typeof body.type === "string" && (unmarshalStandardError(body.type, status, body) ?? unmarshalNonStandardError(body.type, status, body)) || new ScalewayError(status, body);
76
97
  };
98
+ export { parseScalewayError };
@@ -1,34 +1,25 @@
1
+ import { isRecordOfStringArray } from "../types.js";
1
2
  import { ScalewayError } from "../scw-error.js";
2
3
  import { InvalidArgumentsError } from "../standard/invalid-arguments-error.js";
3
4
  import { QuotasExceededError } from "../standard/quotas-exceeded-error.js";
4
- import { isRecordOfStringArray } from "../types.js";
5
+ /**
6
+ * InvalidRequest error is only returned by the instance API.
7
+ *
8
+ * @public
9
+ */
5
10
  const mapInvalidRequestFromJSON = (status, obj) => {
6
- if (typeof obj.message === "string" && obj.message.toLowerCase().includes("quota exceeded for this resource")) {
7
- return new QuotasExceededError(status, obj, [
8
- {
9
- current: 0,
10
- quota: 0,
11
- resource: typeof obj.resource === "string" ? obj.resource : ""
12
- }
13
- ]);
14
- }
15
- const fields = obj.fields && isRecordOfStringArray(obj.fields) ? obj.fields : {};
16
- const fieldsMessages = Object.entries(fields);
17
- if (fieldsMessages.length) {
18
- return new InvalidArgumentsError(
19
- status,
20
- obj,
21
- fieldsMessages.flatMap(
22
- ([argumentName, messages]) => messages.map((helpMessage) => ({
23
- argumentName,
24
- helpMessage,
25
- reason: "constraint"
26
- }))
27
- )
28
- );
29
- }
30
- return new ScalewayError(status, obj);
31
- };
32
- export {
33
- mapInvalidRequestFromJSON
11
+ if (typeof obj.message === "string" && obj.message.toLowerCase().includes("quota exceeded for this resource")) return new QuotasExceededError(status, obj, [{
12
+ current: 0,
13
+ quota: 0,
14
+ resource: typeof obj.resource === "string" ? obj.resource : ""
15
+ }]);
16
+ const fields = obj.fields && isRecordOfStringArray(obj.fields) ? obj.fields : {};
17
+ const fieldsMessages = Object.entries(fields);
18
+ if (fieldsMessages.length) return new InvalidArgumentsError(status, obj, fieldsMessages.flatMap(([argumentName, messages]) => messages.map((helpMessage) => ({
19
+ argumentName,
20
+ helpMessage,
21
+ reason: "constraint"
22
+ }))));
23
+ return new ScalewayError(status, obj);
34
24
  };
25
+ export { mapInvalidRequestFromJSON };