@commercelayer/provisioning-sdk 2.10.2 → 3.0.0-beta.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 (199) hide show
  1. package/LICENSE +1 -1
  2. package/lib/actions.cjs +4 -0
  3. package/lib/actions.cjs.map +1 -0
  4. package/lib/actions.d.cts +15 -0
  5. package/lib/actions.d.ts +15 -0
  6. package/lib/actions.js +3 -0
  7. package/lib/actions.js.map +1 -0
  8. package/lib/{index.d.mts → api-BY0jb79k.d.cts} +540 -496
  9. package/lib/api-e4p3q-SB.d.ts +1636 -0
  10. package/lib/api.cjs +62 -0
  11. package/lib/api.cjs.map +1 -0
  12. package/lib/api.d.cts +2 -0
  13. package/lib/api.d.ts +2 -0
  14. package/lib/api.js +17 -0
  15. package/lib/api.js.map +1 -0
  16. package/lib/binding.cjs +14 -0
  17. package/lib/binding.cjs.map +1 -0
  18. package/lib/binding.d.cts +21 -0
  19. package/lib/binding.d.ts +21 -0
  20. package/lib/binding.js +5 -0
  21. package/lib/binding.js.map +1 -0
  22. package/lib/bundle.cjs +34 -0
  23. package/lib/bundle.cjs.map +1 -0
  24. package/lib/bundle.d.cts +27 -0
  25. package/lib/bundle.d.ts +25 -0
  26. package/lib/bundle.js +19 -0
  27. package/lib/bundle.js.map +1 -0
  28. package/lib/chunk-35GNS3WW.js +57 -0
  29. package/lib/chunk-35GNS3WW.js.map +1 -0
  30. package/lib/chunk-3ELZDTFF.js +41 -0
  31. package/lib/chunk-3ELZDTFF.js.map +1 -0
  32. package/lib/chunk-3FP4NVLD.cjs +16 -0
  33. package/lib/chunk-3FP4NVLD.cjs.map +1 -0
  34. package/lib/chunk-3XLKYXM6.cjs +84 -0
  35. package/lib/chunk-3XLKYXM6.cjs.map +1 -0
  36. package/lib/chunk-4Z4U45XQ.js +808 -0
  37. package/lib/chunk-4Z4U45XQ.js.map +1 -0
  38. package/lib/chunk-5KN7B3T2.cjs +118 -0
  39. package/lib/chunk-5KN7B3T2.cjs.map +1 -0
  40. package/lib/chunk-63TTSE4U.cjs +93 -0
  41. package/lib/chunk-63TTSE4U.cjs.map +1 -0
  42. package/lib/chunk-6I5KGZAU.js +90 -0
  43. package/lib/chunk-6I5KGZAU.js.map +1 -0
  44. package/lib/chunk-7OPCEEJV.cjs +88 -0
  45. package/lib/chunk-7OPCEEJV.cjs.map +1 -0
  46. package/lib/chunk-BWDFMGX6.cjs +84 -0
  47. package/lib/chunk-BWDFMGX6.cjs.map +1 -0
  48. package/lib/chunk-C6AOOHOR.cjs +61 -0
  49. package/lib/chunk-C6AOOHOR.cjs.map +1 -0
  50. package/lib/chunk-CFU5DNH2.cjs +19 -0
  51. package/lib/chunk-CFU5DNH2.cjs.map +1 -0
  52. package/lib/chunk-CLOSZJSZ.cjs +66 -0
  53. package/lib/chunk-CLOSZJSZ.cjs.map +1 -0
  54. package/lib/chunk-DTD2FIJ3.js +17 -0
  55. package/lib/chunk-DTD2FIJ3.js.map +1 -0
  56. package/lib/chunk-E2ERI2EX.js +114 -0
  57. package/lib/chunk-E2ERI2EX.js.map +1 -0
  58. package/lib/chunk-ELYBYKRM.cjs +32 -0
  59. package/lib/chunk-ELYBYKRM.cjs.map +1 -0
  60. package/lib/chunk-F2RLD5SN.cjs +816 -0
  61. package/lib/chunk-F2RLD5SN.cjs.map +1 -0
  62. package/lib/chunk-FOU52N6P.js +86 -0
  63. package/lib/chunk-FOU52N6P.js.map +1 -0
  64. package/lib/chunk-FWF7HBWB.js +78 -0
  65. package/lib/chunk-FWF7HBWB.js.map +1 -0
  66. package/lib/chunk-GES5UXTI.js +64 -0
  67. package/lib/chunk-GES5UXTI.js.map +1 -0
  68. package/lib/chunk-HAZ53WDW.cjs +26 -0
  69. package/lib/chunk-HAZ53WDW.cjs.map +1 -0
  70. package/lib/chunk-HOL7SMFN.cjs +59 -0
  71. package/lib/chunk-HOL7SMFN.cjs.map +1 -0
  72. package/lib/chunk-IW2T22VR.js +3 -0
  73. package/lib/chunk-IW2T22VR.js.map +1 -0
  74. package/lib/chunk-N567T7FT.cjs +4 -0
  75. package/lib/chunk-N567T7FT.cjs.map +1 -0
  76. package/lib/chunk-QRZGS4TB.js +30 -0
  77. package/lib/chunk-QRZGS4TB.js.map +1 -0
  78. package/lib/chunk-RDLVNJEW.js +82 -0
  79. package/lib/chunk-RDLVNJEW.js.map +1 -0
  80. package/lib/chunk-U2CAAK2J.js +59 -0
  81. package/lib/chunk-U2CAAK2J.js.map +1 -0
  82. package/lib/chunk-UB3WPGDV.js +12 -0
  83. package/lib/chunk-UB3WPGDV.js.map +1 -0
  84. package/lib/chunk-UYATAIX7.js +24 -0
  85. package/lib/chunk-UYATAIX7.js.map +1 -0
  86. package/lib/chunk-VAL4CE5R.js +82 -0
  87. package/lib/chunk-VAL4CE5R.js.map +1 -0
  88. package/lib/chunk-VFTFSHXQ.cjs +88 -0
  89. package/lib/chunk-VFTFSHXQ.cjs.map +1 -0
  90. package/lib/chunk-W6XILXYS.cjs +61 -0
  91. package/lib/chunk-W6XILXYS.cjs.map +1 -0
  92. package/lib/chunk-WRVLCJQZ.cjs +43 -0
  93. package/lib/chunk-WRVLCJQZ.cjs.map +1 -0
  94. package/lib/chunk-YS5PCY5D.js +76 -0
  95. package/lib/chunk-YS5PCY5D.js.map +1 -0
  96. package/lib/chunk-YYHZPR4Z.js +59 -0
  97. package/lib/chunk-YYHZPR4Z.js.map +1 -0
  98. package/lib/chunk-Z4IAVXOO.cjs +80 -0
  99. package/lib/chunk-Z4IAVXOO.cjs.map +1 -0
  100. package/lib/commercelayer.cjs +38 -0
  101. package/lib/commercelayer.cjs.map +1 -0
  102. package/lib/commercelayer.d.cts +58 -0
  103. package/lib/commercelayer.d.ts +56 -0
  104. package/lib/commercelayer.js +7 -0
  105. package/lib/commercelayer.js.map +1 -0
  106. package/lib/enum.cjs +52 -0
  107. package/lib/enum.cjs.map +1 -0
  108. package/lib/enum.d.cts +2 -0
  109. package/lib/enum.d.ts +2 -0
  110. package/lib/enum.js +3 -0
  111. package/lib/enum.js.map +1 -0
  112. package/lib/error-CVRdwnY9.d.cts +33 -0
  113. package/lib/error-CVRdwnY9.d.ts +33 -0
  114. package/lib/index.cjs +57 -0
  115. package/lib/index.cjs.map +1 -0
  116. package/lib/index.d.cts +14 -0
  117. package/lib/index.d.ts +9 -1591
  118. package/lib/index.js +26 -1
  119. package/lib/index.js.map +1 -0
  120. package/lib/model.cjs +4 -0
  121. package/lib/model.cjs.map +1 -0
  122. package/lib/model.d.cts +2 -0
  123. package/lib/model.d.ts +2 -0
  124. package/lib/model.js +3 -0
  125. package/lib/model.js.map +1 -0
  126. package/lib/resources/api_credentials.cjs +15 -0
  127. package/lib/resources/api_credentials.cjs.map +1 -0
  128. package/lib/resources/api_credentials.d.cts +5 -0
  129. package/lib/resources/api_credentials.d.ts +2 -0
  130. package/lib/resources/api_credentials.js +7 -0
  131. package/lib/resources/api_credentials.js.map +1 -0
  132. package/lib/resources/application_memberships.cjs +15 -0
  133. package/lib/resources/application_memberships.cjs.map +1 -0
  134. package/lib/resources/application_memberships.d.cts +5 -0
  135. package/lib/resources/application_memberships.d.ts +2 -0
  136. package/lib/resources/application_memberships.js +7 -0
  137. package/lib/resources/application_memberships.js.map +1 -0
  138. package/lib/resources/identity_providers.cjs +15 -0
  139. package/lib/resources/identity_providers.cjs.map +1 -0
  140. package/lib/resources/identity_providers.d.cts +5 -0
  141. package/lib/resources/identity_providers.d.ts +2 -0
  142. package/lib/resources/identity_providers.js +7 -0
  143. package/lib/resources/identity_providers.js.map +1 -0
  144. package/lib/resources/membership_profiles.cjs +15 -0
  145. package/lib/resources/membership_profiles.cjs.map +1 -0
  146. package/lib/resources/membership_profiles.d.cts +5 -0
  147. package/lib/resources/membership_profiles.d.ts +2 -0
  148. package/lib/resources/membership_profiles.js +7 -0
  149. package/lib/resources/membership_profiles.js.map +1 -0
  150. package/lib/resources/memberships.cjs +15 -0
  151. package/lib/resources/memberships.cjs.map +1 -0
  152. package/lib/resources/memberships.d.cts +5 -0
  153. package/lib/resources/memberships.d.ts +2 -0
  154. package/lib/resources/memberships.js +7 -0
  155. package/lib/resources/memberships.js.map +1 -0
  156. package/lib/resources/organizations.cjs +15 -0
  157. package/lib/resources/organizations.cjs.map +1 -0
  158. package/lib/resources/organizations.d.cts +5 -0
  159. package/lib/resources/organizations.d.ts +2 -0
  160. package/lib/resources/organizations.js +7 -0
  161. package/lib/resources/organizations.js.map +1 -0
  162. package/lib/resources/permissions.cjs +15 -0
  163. package/lib/resources/permissions.cjs.map +1 -0
  164. package/lib/resources/permissions.d.cts +5 -0
  165. package/lib/resources/permissions.d.ts +2 -0
  166. package/lib/resources/permissions.js +7 -0
  167. package/lib/resources/permissions.js.map +1 -0
  168. package/lib/resources/roles.cjs +15 -0
  169. package/lib/resources/roles.cjs.map +1 -0
  170. package/lib/resources/roles.d.cts +5 -0
  171. package/lib/resources/roles.d.ts +2 -0
  172. package/lib/resources/roles.js +7 -0
  173. package/lib/resources/roles.js.map +1 -0
  174. package/lib/resources/users.cjs +15 -0
  175. package/lib/resources/users.cjs.map +1 -0
  176. package/lib/resources/users.d.cts +5 -0
  177. package/lib/resources/users.d.ts +2 -0
  178. package/lib/resources/users.js +7 -0
  179. package/lib/resources/users.js.map +1 -0
  180. package/lib/resources/versions.cjs +15 -0
  181. package/lib/resources/versions.cjs.map +1 -0
  182. package/lib/resources/versions.d.cts +5 -0
  183. package/lib/resources/versions.d.ts +2 -0
  184. package/lib/resources/versions.js +7 -0
  185. package/lib/resources/versions.js.map +1 -0
  186. package/lib/static.cjs +17 -0
  187. package/lib/static.cjs.map +1 -0
  188. package/lib/static.d.cts +18 -0
  189. package/lib/static.d.ts +18 -0
  190. package/lib/static.js +8 -0
  191. package/lib/static.js.map +1 -0
  192. package/lib/version.cjs +20 -0
  193. package/lib/version.cjs.map +1 -0
  194. package/lib/version.d.cts +12 -0
  195. package/lib/version.d.ts +12 -0
  196. package/lib/version.js +3 -0
  197. package/lib/version.js.map +1 -0
  198. package/package.json +36 -26
  199. package/lib/index.mjs +0 -1
@@ -0,0 +1,808 @@
1
+ import { binding } from './chunk-DTD2FIJ3.js';
2
+
3
+ // ../sdk-runtime/src/debug.ts
4
+ var PREFIX = "clsdk";
5
+ var debugEnv = () => {
6
+ try {
7
+ return typeof process !== "undefined" ? process.env?.DEBUG ?? "" : "";
8
+ } catch {
9
+ return "";
10
+ }
11
+ };
12
+ var toMatcher = (pattern) => new RegExp(`^${pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`);
13
+ var isEnabled = (namespace) => {
14
+ const env = debugEnv();
15
+ if (!env) return false;
16
+ return env.split(",").map((p) => p.trim()).filter(Boolean).some((p) => toMatcher(p).test(namespace));
17
+ };
18
+ var interpolate = (pattern, args) => {
19
+ let i = 0;
20
+ const out = pattern.replace(/%[oOjsdi%]/g, (token) => {
21
+ if (token === "%%") return "%";
22
+ if (i >= args.length) return token;
23
+ const arg = args[i++];
24
+ switch (token) {
25
+ case "%s":
26
+ return String(arg);
27
+ case "%d":
28
+ case "%i":
29
+ return String(Number(arg));
30
+ default:
31
+ try {
32
+ return JSON.stringify(arg);
33
+ } catch {
34
+ return String(arg);
35
+ }
36
+ }
37
+ });
38
+ const rest = args.slice(i);
39
+ return rest.length > 0 ? `${out} ${rest.map((a) => safeStringify(a)).join(" ")}` : out;
40
+ };
41
+ var safeStringify = (value) => {
42
+ if (typeof value === "string") return value;
43
+ try {
44
+ return JSON.stringify(value) ?? String(value);
45
+ } catch {
46
+ return String(value);
47
+ }
48
+ };
49
+ var debug = (namespace) => {
50
+ const full = `${PREFIX}:${namespace}`;
51
+ return (pattern, ...args) => {
52
+ if (!isEnabled(full)) return;
53
+ console.error(`${full} ${interpolate(pattern, args)}`);
54
+ };
55
+ };
56
+ var debug_default = debug;
57
+
58
+ // ../sdk-runtime/src/fetch.ts
59
+ var debug2 = debug_default("fetch");
60
+ var FetchError = class _FetchError extends Error {
61
+ static NAME = "FetchError";
62
+ static isFetchError = (error) => {
63
+ return error instanceof _FetchError;
64
+ };
65
+ #errors;
66
+ #status;
67
+ #statusText;
68
+ #request;
69
+ constructor(status, statusText, body, request) {
70
+ super(statusText);
71
+ this.#status = status;
72
+ this.#statusText = statusText;
73
+ if (body) this.#errors = body.errors;
74
+ if (request) this.#request = request;
75
+ this.name = _FetchError.NAME;
76
+ }
77
+ get errors() {
78
+ return this.#errors;
79
+ }
80
+ get status() {
81
+ return this.#status;
82
+ }
83
+ get statusText() {
84
+ return this.#statusText;
85
+ }
86
+ get request() {
87
+ return this.#request;
88
+ }
89
+ };
90
+ var fetchURL = async (url, requestOptions, clientOptions) => {
91
+ debug2("fetch: %s, %O, native[%s]", url, requestOptions || {}, clientOptions?.fetch ? "no" : "yes");
92
+ const interceptors = clientOptions?.interceptors;
93
+ if (interceptors?.request?.onSuccess)
94
+ ({ url, options: requestOptions } = await interceptors.request.onSuccess({ url, options: requestOptions }));
95
+ const fetchClient = clientOptions?.fetch || fetch;
96
+ let response = await fetchClient(url, requestOptions);
97
+ if (response.ok) {
98
+ if (interceptors?.rawReader?.onSuccess) await interceptors.rawReader.onSuccess(response);
99
+ if (interceptors?.response?.onSuccess) response = await interceptors.response.onSuccess(response);
100
+ } else {
101
+ if (interceptors?.rawReader?.onFailure) await interceptors.rawReader.onFailure(response);
102
+ }
103
+ const responseBody = response.body && response.status !== 204 ? await response.json().then((json) => {
104
+ debug2("response: %O", json);
105
+ return json;
106
+ }).catch((err) => {
107
+ debug2("error: %s", err.message);
108
+ if (response.ok) throw new SdkError({ message: "Error parsing API response body", type: "parse" /* PARSE */ });
109
+ }) : void 0;
110
+ if (!response.ok) {
111
+ let error = new FetchError(response.status, response.statusText, responseBody, requestOptions);
112
+ if (interceptors?.response?.onFailure) error = await interceptors.response.onFailure(error);
113
+ if (error) throw error;
114
+ }
115
+ return responseBody;
116
+ };
117
+
118
+ // ../sdk-runtime/src/error.ts
119
+ var ErrorType = /* @__PURE__ */ ((ErrorType2) => {
120
+ ErrorType2["CLIENT"] = "client";
121
+ ErrorType2["REQUEST"] = "request";
122
+ ErrorType2["RESPONSE"] = "response";
123
+ ErrorType2["CANCEL"] = "cancel";
124
+ ErrorType2["PARSE"] = "parse";
125
+ ErrorType2["TIMEOUT"] = "timeout";
126
+ ErrorType2["TOKEN_REFRESH"] = "token-refresh";
127
+ return ErrorType2;
128
+ })(ErrorType || {});
129
+ var SdkError = class _SdkError extends Error {
130
+ static NAME = "SdkError";
131
+ static isSdkError(error) {
132
+ return error && [_SdkError.NAME, ApiError.NAME].includes(error.name) && Object.values(ErrorType).includes(error.type);
133
+ }
134
+ type;
135
+ code;
136
+ source;
137
+ constructor(error) {
138
+ super(error.message);
139
+ this.name = _SdkError.NAME;
140
+ this.type = error.type || "client" /* CLIENT */;
141
+ }
142
+ };
143
+ var ApiError = class _ApiError extends SdkError {
144
+ static NAME = "ApiError";
145
+ static isApiError(error) {
146
+ return SdkError.isSdkError(error) && error.name === _ApiError.NAME && error.type === "response" /* RESPONSE */;
147
+ }
148
+ errors = [];
149
+ status;
150
+ statusText;
151
+ // constructor(error: SdkError)
152
+ constructor(error) {
153
+ super({ ...error, type: "response" /* RESPONSE */ });
154
+ this.name = _ApiError.NAME;
155
+ }
156
+ first() {
157
+ return this.errors?.length > 0 ? this.errors[0] : void 0;
158
+ }
159
+ };
160
+ var isRequestError = (error) => {
161
+ return error instanceof TypeError && error.message !== "fetch failed";
162
+ };
163
+ var isCancelError = (error) => {
164
+ return error instanceof DOMException && error.name === "AbortError";
165
+ };
166
+ var isTimeoutError = (error) => {
167
+ return error instanceof DOMException && error.name === "TimeoutError";
168
+ };
169
+ var isExpiredTokenError = (error) => {
170
+ const invalidTokenCodes = [
171
+ "INVALID_TOKEN"
172
+ /*, 'UNAUTHORIZED' */
173
+ ];
174
+ return ApiError.isApiError(error) && error.status === 401 && (invalidTokenCodes.includes(error.code || "") || error.errors && error.errors.length > 0 && invalidTokenCodes.includes(error.errors[0].code));
175
+ };
176
+ var handleError = (error) => {
177
+ if (SdkError.isSdkError(error) || ApiError.isApiError(error)) throw error;
178
+ let sdkError = new SdkError({ message: error.message });
179
+ if (FetchError.isFetchError(error)) {
180
+ const apiError = new ApiError(sdkError);
181
+ apiError.type = "response" /* RESPONSE */;
182
+ apiError.status = error.status;
183
+ apiError.statusText = error.statusText;
184
+ apiError.code = String(apiError.status);
185
+ apiError.errors = error.errors || [];
186
+ if (!apiError.message && apiError.statusText) apiError.message = apiError.statusText;
187
+ sdkError = apiError;
188
+ } else if (isRequestError(error)) {
189
+ sdkError.type = "request" /* REQUEST */;
190
+ } else if (isCancelError(error)) {
191
+ sdkError.type = "cancel" /* CANCEL */;
192
+ } else if (isTimeoutError(error)) {
193
+ sdkError.type = "timeout" /* TIMEOUT */;
194
+ } else {
195
+ sdkError.type = "client" /* CLIENT */;
196
+ sdkError.source = error;
197
+ }
198
+ throw sdkError;
199
+ };
200
+ function isSdkError(error) {
201
+ return SdkError.isSdkError(error);
202
+ }
203
+ function isApiError(error) {
204
+ return ApiError.isApiError(error);
205
+ }
206
+
207
+ // ../sdk-runtime/src/util.ts
208
+ var extractTokenData = (token) => {
209
+ try {
210
+ const data = JSON.parse(atob(token.split(".")[1]));
211
+ return {
212
+ organization: data.organization.slug,
213
+ domain: data.iss ? String(data.iss).replace("https://auth.", "") : void 0,
214
+ expiration: data.exp
215
+ };
216
+ } catch (_err) {
217
+ return void 0;
218
+ }
219
+ };
220
+ var isTokenExpired = (token) => {
221
+ try {
222
+ const tokenData = extractTokenData(token);
223
+ return tokenData?.expiration ? tokenData.expiration * 1e3 - Date.now() < 0 : false;
224
+ } catch (_err) {
225
+ return false;
226
+ }
227
+ };
228
+
229
+ // ../sdk-runtime/src/config.ts
230
+ var config = {
231
+ default: {
232
+ domain: "commercelayer.io",
233
+ pageNumber: 1,
234
+ pageSize: 10
235
+ },
236
+ client: {
237
+ timeout: 15e3,
238
+ requiredAttributes: ["organization", "accessToken"]
239
+ },
240
+ jsonapi: {
241
+ maxResourceIncluded: 2
242
+ }
243
+ };
244
+ var config_default = config;
245
+
246
+ // ../sdk-runtime/src/client.ts
247
+ var CLIENT_HEADER_NAME = "X-CL-SDK";
248
+ var debug3 = debug_default("client");
249
+ var baseURL = (organization, domain, apiVersion) => {
250
+ const versionSegment = apiVersion ? `/${apiVersion}` : "";
251
+ const subdomain = binding.subdomain ?? organization.toLowerCase();
252
+ return `https://${subdomain}.${domain || config_default.default.domain}/api${versionSegment}`;
253
+ };
254
+ var ApiClient = class _ApiClient {
255
+ static create(options) {
256
+ if ((!options.organization || !options.domain) && options.accessToken) {
257
+ const tokenData = extractTokenData(options.accessToken);
258
+ if (!options.organization && tokenData?.organization) options.organization = tokenData.organization;
259
+ if (!options.domain && tokenData?.domain) options.domain = tokenData.domain;
260
+ }
261
+ const required = binding.subdomain ? config_default.client.requiredAttributes.filter((a) => a !== "organization") : config_default.client.requiredAttributes;
262
+ for (const attr of required) if (!options[attr]) throw new SdkError({ message: `Undefined '${attr}' parameter` });
263
+ return new _ApiClient(options);
264
+ }
265
+ #baseUrl;
266
+ #accessToken;
267
+ #organization;
268
+ #domain;
269
+ #apiVersion;
270
+ #clientConfig;
271
+ #interceptors;
272
+ constructor(options) {
273
+ debug3("new client instance %O", options);
274
+ this.#apiVersion = options.apiVersion;
275
+ this.#baseUrl = baseURL(options.organization ?? "", options.domain, this.#apiVersion);
276
+ this.#accessToken = options.accessToken;
277
+ this.#organization = options.organization ?? "";
278
+ this.#domain = options.domain;
279
+ const fetchConfig = {
280
+ timeout: options.timeout || config_default.client.timeout,
281
+ fetch: options.fetch,
282
+ refreshToken: options.refreshToken
283
+ };
284
+ const customHeaders = this.customHeaders(options.headers);
285
+ const headers = {
286
+ ...customHeaders,
287
+ Accept: "application/vnd.api+json",
288
+ "Content-Type": "application/vnd.api+json",
289
+ Authorization: "Bearer " + this.#accessToken
290
+ };
291
+ if (options.telemetry !== false) headers[CLIENT_HEADER_NAME] = `js/${binding.name}-v${binding.sdkVersion}`;
292
+ if (options.userAgent) headers["User-Agent"] = options.userAgent;
293
+ fetchConfig.headers = headers;
294
+ this.#clientConfig = fetchConfig;
295
+ debug3("fetch config: %O", fetchConfig);
296
+ this.#interceptors = {};
297
+ }
298
+ get interceptors() {
299
+ return this.#interceptors;
300
+ }
301
+ get requestHeaders() {
302
+ if (!this.#clientConfig.headers) this.#clientConfig.headers = {};
303
+ return this.#clientConfig.headers;
304
+ }
305
+ /*
306
+ set requestHeaders(headers: RequestHeaders) {
307
+ this.#clientConfig.headers = { ...this.#clientConfig.headers, ...headers }
308
+ }
309
+ */
310
+ config(config2) {
311
+ debug3("config %o", config2);
312
+ const def = this.#clientConfig;
313
+ if (!def.headers) def.headers = {};
314
+ if (config2.timeout) def.timeout = config2.timeout;
315
+ if (config2.userAgent) this.userAgent(config2.userAgent);
316
+ if (config2.fetch) this.#clientConfig.fetch = config2.fetch;
317
+ if (config2.refreshToken) this.#clientConfig.refreshToken = config2.refreshToken;
318
+ if (config2.apiVersion !== void 0) this.#apiVersion = config2.apiVersion;
319
+ if (config2.organization || config2.domain || config2.apiVersion !== void 0)
320
+ this.#baseUrl = baseURL(
321
+ config2.organization || this.#organization,
322
+ config2.domain || this.#domain,
323
+ this.#apiVersion
324
+ );
325
+ if (config2.organization) this.#organization = config2.organization;
326
+ if (config2.domain) this.#domain = config2.domain;
327
+ if (config2.accessToken) {
328
+ this.#accessToken = config2.accessToken;
329
+ def.headers.Authorization = "Bearer " + this.#accessToken;
330
+ }
331
+ if (config2.headers) def.headers = { ...def.headers, ...this.customHeaders(config2.headers) };
332
+ return this;
333
+ }
334
+ userAgent(userAgent) {
335
+ if (userAgent) this.requestHeaders["User-Agent"] = userAgent;
336
+ return this;
337
+ }
338
+ async request(method, path, body, options) {
339
+ debug3("request %s %s, %O, %O", method, path, body || {}, options || {});
340
+ if (options?.userAgent) debug3("User-Agent header ignored in request config");
341
+ const baseUrl = options?.organization || options?.apiVersion !== void 0 ? baseURL(options.organization || this.#organization, options.domain, options.apiVersion ?? this.#apiVersion) : this.#baseUrl;
342
+ const url = new URL(`${baseUrl}/${path}`);
343
+ const bodyData = body ? JSON.stringify({ data: body }) : void 0;
344
+ const headers = { ...this.requestHeaders, ...this.customHeaders(options?.headers) };
345
+ const accessToken = options?.accessToken || this.#accessToken;
346
+ if (accessToken) headers.Authorization = "Bearer " + accessToken;
347
+ const refreshToken = options?.refreshToken || this.#clientConfig.refreshToken;
348
+ const fetchFunction = options?.fetch || this.#clientConfig.fetch;
349
+ const requestOptions = { method, body: bodyData, headers };
350
+ const timeout = options?.timeout || this.#clientConfig.timeout;
351
+ if (timeout) {
352
+ if (AbortSignal?.timeout) requestOptions.signal = AbortSignal.timeout(timeout);
353
+ else debug3("Timeout not set. Undefined function: %s", "AbortSignal.timeout");
354
+ }
355
+ if (options?.params)
356
+ Object.entries(options?.params).forEach(([name, value]) => {
357
+ url.searchParams.append(name, String(value));
358
+ });
359
+ const clientOptions = {
360
+ interceptors: this.interceptors,
361
+ fetch: fetchFunction
362
+ };
363
+ try {
364
+ return await fetchURL(url, requestOptions, clientOptions).catch((error) => handleError(error));
365
+ } catch (err) {
366
+ if (isExpiredTokenError(err) && refreshToken && isTokenExpired(accessToken)) {
367
+ debug3("Access token has expired");
368
+ const newAccessToken = await refreshToken(this.#accessToken).catch((e) => {
369
+ debug3("Refresh token error: %s", e.message);
370
+ const tokenError = new SdkError({ message: "Error refreshing access token", type: "token-refresh" /* TOKEN_REFRESH */ });
371
+ tokenError.source = e;
372
+ throw tokenError;
373
+ });
374
+ if (newAccessToken) {
375
+ debug3("Access token refreshed");
376
+ this.config({ accessToken: newAccessToken });
377
+ this.#accessToken = newAccessToken;
378
+ if (requestOptions.headers)
379
+ requestOptions.headers.Authorization = `Bearer ${newAccessToken}`;
380
+ const response = await fetchURL(url, requestOptions, clientOptions).catch(
381
+ (error) => handleError(error)
382
+ );
383
+ return response;
384
+ }
385
+ } else throw err;
386
+ }
387
+ }
388
+ customHeaders(headers) {
389
+ const customHeaders = {};
390
+ if (headers) {
391
+ for (const [name, value] of Object.entries(headers))
392
+ if (!["accept", "content-type", "authorization", "user-agent", CLIENT_HEADER_NAME.toLowerCase()].includes(
393
+ name.toLowerCase()
394
+ ))
395
+ customHeaders[name] = value;
396
+ }
397
+ return customHeaders;
398
+ }
399
+ get currentAccessToken() {
400
+ return this.#accessToken;
401
+ }
402
+ get currentOrganization() {
403
+ return this.#organization;
404
+ }
405
+ /** The API version pinned via `apiVersion`, or `undefined` when requests are unversioned. */
406
+ get currentApiVersion() {
407
+ return this.#apiVersion;
408
+ }
409
+ };
410
+ var client_default = ApiClient;
411
+
412
+ // ../sdk-runtime/src/jsonapi.ts
413
+ var debug4 = debug_default("jsonapi");
414
+ var denormalize = (response) => {
415
+ if (!response) return response;
416
+ let denormalizedResponse;
417
+ if (response.links) delete response.links;
418
+ const data = response.data;
419
+ const included = response.included;
420
+ if (!data) denormalizedResponse = data;
421
+ else {
422
+ if (Array.isArray(data)) denormalizedResponse = data.map((res) => denormalizeResource(res, included));
423
+ else denormalizedResponse = denormalizeResource(data, included);
424
+ }
425
+ return denormalizedResponse;
426
+ };
427
+ var findIncluded = (rel, included = []) => {
428
+ const inc = included.find((inc2) => {
429
+ return rel.id === inc2.id && rel.type === inc2.type;
430
+ });
431
+ return inc || rel;
432
+ };
433
+ var denormalizeResource = (res, included, chain = []) => {
434
+ debug4("denormalize resource: %O, %o", res, included || {});
435
+ if (!res) return res;
436
+ const resource = {
437
+ id: res.id,
438
+ type: res.type,
439
+ ...res.attributes
440
+ };
441
+ if (res.relationships)
442
+ Object.keys(res.relationships).forEach((key) => {
443
+ const rel = res.relationships[key].data;
444
+ if (rel) {
445
+ if (chain.filter((r) => r.id === rel.id && r.type === rel.type).length >= config_default.jsonapi.maxResourceIncluded)
446
+ resource[key] = rel;
447
+ else {
448
+ if (Array.isArray(rel))
449
+ resource[key] = rel.map(
450
+ (r) => denormalizeResource(findIncluded(r, included), included, [...chain, r])
451
+ );
452
+ else resource[key] = denormalizeResource(findIncluded(rel, included), included, [...chain, rel]);
453
+ }
454
+ } else if (rel === null) resource[key] = null;
455
+ });
456
+ debug4("denormalized resource: %O", resource);
457
+ return resource;
458
+ };
459
+ var normalize = (resource) => {
460
+ debug4("normalize resource: %O", resource);
461
+ const attributes = {};
462
+ const relationships = {};
463
+ for (const field in resource) {
464
+ if (["type", "id"].includes(field)) continue;
465
+ const value = resource[field];
466
+ if (Array.isArray(value) && value.length === 1 && isResourceType(value[0]) && value[0].id === null) {
467
+ relationships[field] = { data: [] };
468
+ } else if (value && isResourceType(value) && value.id === null) {
469
+ relationships[field] = { data: null };
470
+ } else if (value && (isResourceId(value) || Array.isArray(value) && isResourceId(value[0]))) {
471
+ relationships[field] = { data: value };
472
+ } else attributes[field] = value;
473
+ }
474
+ const normalized = {
475
+ type: resource.type,
476
+ attributes,
477
+ relationships
478
+ };
479
+ if (isResourceId(resource)) normalized.id = resource.id;
480
+ debug4("normalized resource: %O", normalized);
481
+ return normalized;
482
+ };
483
+
484
+ // ../sdk-runtime/src/query.ts
485
+ var debug5 = debug_default("query");
486
+ var arrayFilters = ["_any", "_all", "_in", "_not_in_or_null"];
487
+ var isArrayFilter = (filter) => {
488
+ return arrayFilters.some((f) => filter.endsWith(f));
489
+ };
490
+ var objectFilters = ["_jcont"];
491
+ var isObjectFilter = (filter) => {
492
+ return objectFilters.some((f) => filter.endsWith(f));
493
+ };
494
+ var isParamsList = (params) => {
495
+ return params && (params.filters || params.pageNumber || params.pageSize || params.sort || params.pageAfter || params.pageBefore);
496
+ };
497
+ var generateQueryStringParams = (params, res) => {
498
+ debug5("generate query string params: %O, %O", params, res);
499
+ const qp = {};
500
+ if (!params) return qp;
501
+ if (params.include) qp.include = params.include.join(",");
502
+ if (params.fields) {
503
+ if (Array.isArray(params.fields)) params.fields = { [res.type || res]: params.fields };
504
+ Object.entries(params.fields).forEach(([p, v]) => {
505
+ qp[`fields[${p}]`] = v.join(",");
506
+ });
507
+ }
508
+ if (isParamsList(params)) {
509
+ if (params.sort) {
510
+ if (Array.isArray(params.sort)) qp.sort = params.sort.join(",");
511
+ else
512
+ qp.sort = Object.entries(params.sort).map(([k, v]) => `${v === "desc" ? "-" : ""}${k}`).join(",");
513
+ }
514
+ if (params.pageNumber) qp["page[number]"] = String(params.pageNumber);
515
+ if (params.pageSize) qp["page[size]"] = String(params.pageSize);
516
+ if (params.pageAfter) qp["page[after]"] = String(params.pageAfter);
517
+ if (params.pageBefore) qp["page[before]"] = String(params.pageBefore);
518
+ if (params.filters) {
519
+ Object.entries(params.filters).forEach(([p, v]) => {
520
+ let val;
521
+ if (Array.isArray(v)) {
522
+ if (!isArrayFilter(p))
523
+ throw new SdkError({
524
+ message: `Incorrect filter [${p}]: Array value is supported only for the following filters: ${arrayFilters.join(", ")}`,
525
+ type: "request" /* REQUEST */
526
+ });
527
+ val = v.join(",");
528
+ } else if (typeof v === "object") {
529
+ if (!isObjectFilter(p))
530
+ throw new SdkError({
531
+ message: `Incorrect filter [${p}]: Object value is supported only for the following filters: ${objectFilters.join(", ")}`,
532
+ type: "request" /* REQUEST */
533
+ });
534
+ val = JSON.stringify(v);
535
+ } else val = String(v);
536
+ qp[`filter[q][${p}]`] = val;
537
+ });
538
+ }
539
+ }
540
+ debug5("query string params: %O", qp);
541
+ return qp;
542
+ };
543
+
544
+ // ../sdk-runtime/src/resource.ts
545
+ var debug6 = debug_default("resource");
546
+ var ListResponse = class extends Array {
547
+ meta;
548
+ constructor(meta, data) {
549
+ super(...data || []);
550
+ this.meta = meta;
551
+ }
552
+ first() {
553
+ return this.length ? this[0] : void 0;
554
+ }
555
+ last() {
556
+ return this.length ? this[this.length - 1] : void 0;
557
+ }
558
+ get(index) {
559
+ return this.length && index >= 0 ? this[index] : void 0;
560
+ }
561
+ hasNextPage() {
562
+ return this.meta.currentPage < this.meta.pageCount;
563
+ }
564
+ hasPrevPage() {
565
+ return this.meta.currentPage > 1;
566
+ }
567
+ getRecordCount() {
568
+ return this.meta.recordCount;
569
+ }
570
+ getPageCount() {
571
+ return this.meta.pageCount;
572
+ }
573
+ get recordCount() {
574
+ return this.meta.recordCount;
575
+ }
576
+ get pageCount() {
577
+ return this.meta.pageCount;
578
+ }
579
+ };
580
+ var parseCursorLink = (url) => {
581
+ if (!url) return void 0;
582
+ let params;
583
+ try {
584
+ params = new URL(url).searchParams;
585
+ } catch {
586
+ return void 0;
587
+ }
588
+ const after = params.get("page[after]") ?? void 0;
589
+ const before = params.get("page[before]") ?? void 0;
590
+ return after != null || before != null ? { before, after } : void 0;
591
+ };
592
+ var buildListMeta = (res, links, params) => {
593
+ const recordsPerPage = params?.pageSize || config_default.default.pageSize;
594
+ if (res.meta?.page_count == null) {
595
+ return {
596
+ // Offset fields aren't applicable to cursor pagination; kept as NaN so the
597
+ // shared `meta.*` interface still resolves (see ListMeta).
598
+ pageCount: NaN,
599
+ recordCount: NaN,
600
+ currentPage: NaN,
601
+ recordsPerPage,
602
+ cursor: {
603
+ prev: parseCursorLink(links?.prev),
604
+ next: parseCursorLink(links?.next)
605
+ }
606
+ };
607
+ }
608
+ return {
609
+ pageCount: Number(res.meta?.page_count),
610
+ recordCount: Number(res.meta?.record_count),
611
+ currentPage: params?.pageNumber || config_default.default.pageNumber,
612
+ recordsPerPage
613
+ };
614
+ };
615
+ var ApiResourceAdapter = class _ApiResourceAdapter {
616
+ static adapter;
617
+ constructor() {
618
+ }
619
+ static init(config2) {
620
+ _ApiResourceAdapter.adapter = new ResourceAdapter(config2);
621
+ debug6("resource adapter initialized");
622
+ return _ApiResourceAdapter.get();
623
+ }
624
+ static get(config2) {
625
+ if (config2) return _ApiResourceAdapter.init(config2);
626
+ else {
627
+ if (_ApiResourceAdapter.adapter) return _ApiResourceAdapter.adapter;
628
+ else throw new SdkError({ message: "Commerce Layer not initialized" });
629
+ }
630
+ }
631
+ static config(config2) {
632
+ _ApiResourceAdapter.get().config(config2);
633
+ }
634
+ };
635
+ var ResourceAdapter = class {
636
+ #client;
637
+ #config = {};
638
+ constructor(config2) {
639
+ this.#client = client_default.create(config2);
640
+ this.localConfig(config2);
641
+ }
642
+ localConfig(config2) {
643
+ Object.assign(this.#config, config2);
644
+ }
645
+ config(config2) {
646
+ debug6("config %o", config2);
647
+ this.localConfig(config2);
648
+ this.#client.config(config2);
649
+ return this;
650
+ }
651
+ get client() {
652
+ return this.#client;
653
+ }
654
+ async singleton(resource, params, options, path) {
655
+ debug6("singleton: %o, %O, %O", resource, params || {}, options || {});
656
+ const queryParams = generateQueryStringParams(params, resource);
657
+ if (options?.params) Object.assign(queryParams, options?.params);
658
+ const res = await this.#client.request("GET", `${path || resource.type}`, void 0, {
659
+ ...options,
660
+ params: queryParams
661
+ });
662
+ const r = denormalize(res);
663
+ return r;
664
+ }
665
+ async retrieve(resource, params, options) {
666
+ debug6("retrieve: %o, %O, %O", resource, params || {}, options || {});
667
+ const queryParams = generateQueryStringParams(params, resource);
668
+ if (options?.params) Object.assign(queryParams, options?.params);
669
+ const res = await this.#client.request("GET", `${resource.type}/${resource.id}`, void 0, {
670
+ ...options,
671
+ params: queryParams
672
+ });
673
+ const r = denormalize(res);
674
+ return r;
675
+ }
676
+ async list(resource, params, options) {
677
+ debug6("list: %o, %O, %O", resource, params || {}, options || {});
678
+ const queryParams = generateQueryStringParams(params, resource);
679
+ if (options?.params) Object.assign(queryParams, options?.params);
680
+ const usesCursor = queryParams["page[after]"] != null || queryParams["page[before]"] != null;
681
+ if (!usesCursor && !queryParams["page[number]"]) queryParams["page[number]"] = "1";
682
+ const res = await this.#client.request("GET", `${resource.type}`, void 0, { ...options, params: queryParams });
683
+ const links = res.links;
684
+ const r = denormalize(res);
685
+ return new ListResponse(buildListMeta(res, links, params), r);
686
+ }
687
+ async create(resource, params, options) {
688
+ debug6("create: %o, %O, %O", resource, params || {}, options || {});
689
+ const queryParams = generateQueryStringParams(params, resource);
690
+ if (options?.params) Object.assign(queryParams, options?.params);
691
+ const data = normalize(resource);
692
+ const res = await this.#client.request("POST", resource.type, data, { ...options, params: queryParams });
693
+ const r = denormalize(res);
694
+ return r;
695
+ }
696
+ async update(resource, params, options, path) {
697
+ debug6("update: %o, %O, %O", resource, params || {}, options || {});
698
+ const queryParams = generateQueryStringParams(params, resource);
699
+ if (options?.params) Object.assign(queryParams, options?.params);
700
+ const data = normalize(resource);
701
+ const res = await this.#client.request("PATCH", path || `${resource.type}/${resource.id}`, data, {
702
+ ...options,
703
+ params: queryParams
704
+ });
705
+ const r = denormalize(res);
706
+ return r;
707
+ }
708
+ async delete(resource, options) {
709
+ debug6("delete: %o, %O", resource, options || {});
710
+ await this.#client.request("DELETE", `${resource.type}/${resource.id}`, void 0, options);
711
+ }
712
+ /**
713
+ * Calls a non-CRUD endpoint hosted at a sub-path of a resource, e.g.
714
+ * `POST memberships/:id/resend`. These endpoints are not described by the
715
+ * public resources schema, so they are declared in a target config and
716
+ * emitted from it.
717
+ */
718
+ async action(cmd, path, payload, options) {
719
+ debug6("action: %o %o, %O", cmd, path, options || {});
720
+ const queryParams = {};
721
+ if (options?.params) Object.assign(queryParams, options.params);
722
+ const data = payload && isResourceId(payload) ? normalize(payload) : payload;
723
+ await this.#client.request(cmd, path, data, { ...options, params: queryParams });
724
+ }
725
+ async fetch(resource, path, params, options) {
726
+ debug6("fetch: %o, %O, %O", path, params || {}, options || {});
727
+ const queryParams = generateQueryStringParams(params, resource);
728
+ if (options?.params) Object.assign(queryParams, options?.params);
729
+ const res = await this.#client.request("GET", path, void 0, { ...options, params: queryParams });
730
+ const links = res.links;
731
+ const r = denormalize(res);
732
+ if (Array.isArray(r)) {
733
+ const p = params;
734
+ return new ListResponse(buildListMeta(res, links, p), r);
735
+ } else return r;
736
+ }
737
+ };
738
+ var ApiResourceBase = class {
739
+ static TYPE;
740
+ #resources;
741
+ constructor(adapter) {
742
+ debug6("new resource instance: %s", this.type());
743
+ if (adapter) this.#resources = adapter;
744
+ }
745
+ get resources() {
746
+ return this.#resources || ApiResourceAdapter.get();
747
+ }
748
+ /**
749
+ * Returns a copy of this resource instance bound to a specific
750
+ * `ResourceAdapter`. Used by the bundle client so each client instance
751
+ * routes requests through its own adapter (its own access token) instead
752
+ * of the process-global static adapter. Resource classes are type-only
753
+ * exports, so we clone via `this.constructor` rather than referencing the
754
+ * class directly.
755
+ */
756
+ withAdapter(adapter) {
757
+ return new this.constructor(adapter);
758
+ }
759
+ relationshipOneToOne(id) {
760
+ return id === null || typeof id === "string" ? { id, type: this.type() } : { id: id.id, type: this.type() };
761
+ }
762
+ relationshipOneToMany(...ids) {
763
+ return ids === null || ids.length === 0 || ids[0] === null ? [{ id: null, type: this.type() }] : ids.map((id) => {
764
+ return { id, type: this.type() };
765
+ });
766
+ }
767
+ path() {
768
+ return this.type();
769
+ }
770
+ // reference, reference_origin and metadata attributes are always updatable
771
+ async update(resource, params, options) {
772
+ return this.resources.update({ ...resource, type: this.type() }, params, options);
773
+ }
774
+ };
775
+ var ApiResource = class extends ApiResourceBase {
776
+ async retrieve(id, params, options) {
777
+ const resId = typeof id === "string" ? { type: this.type(), id } : id;
778
+ if (!resId.id) throw new SdkError({ message: "Resource id cannot be blank" });
779
+ return this.resources.retrieve(resId, params, options);
780
+ }
781
+ async list(params, options) {
782
+ return this.resources.list({ type: this.type() }, params, options);
783
+ }
784
+ async count(filter, options) {
785
+ const params = {
786
+ filters: isParamsList(filter) ? filter.filters : filter,
787
+ pageNumber: 1,
788
+ pageSize: 1
789
+ };
790
+ const response = await this.list(params, options);
791
+ return Promise.resolve(response.meta.recordCount);
792
+ }
793
+ };
794
+ var ApiSingleton = class extends ApiResourceBase {
795
+ async retrieve(params, options) {
796
+ return this.resources.singleton({ type: this.type() }, params, options, this.path());
797
+ }
798
+ };
799
+ var isResourceId = (resource) => {
800
+ return resource?.type && resource.id && binding.resourceList.includes(resource.type);
801
+ };
802
+ var isResourceType = (resource) => {
803
+ return resource?.type && binding.resourceList.includes(resource.type);
804
+ };
805
+
806
+ export { ApiResource, ApiResourceAdapter, ApiSingleton, debug_default, isApiError, isSdkError, isTokenExpired };
807
+ //# sourceMappingURL=chunk-4Z4U45XQ.js.map
808
+ //# sourceMappingURL=chunk-4Z4U45XQ.js.map