@eldrajs/sdk 0.2.6 → 0.2.8

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.
@@ -0,0 +1,693 @@
1
+ /** Ceiling on the *computed* backoff. A `Retry-After` is honoured beyond it. */
2
+ const DEFAULT_RETRY_MAX_DELAY_MS = 5e3;
3
+ /**
4
+ * Ceiling on a honoured `Retry-After`. The header is the gateway's own answer
5
+ * and is followed as given — but a build must not be hostage to one: a limit
6
+ * counted per minute never needs longer than this, and a header that asks for
7
+ * an hour (a misconfiguration, or a proxy in front of the gateway) would
8
+ * otherwise hang a build with nothing said.
9
+ */
10
+ const MAX_RETRY_AFTER_MS = 6e4;
11
+ /** `429` is the rate limit itself; `503` is a gateway that is not up yet. */
12
+ const RETRYABLE_STATUS = /* @__PURE__ */ new Set([429, 503]);
13
+ /**
14
+ * Methods that may be repeated. Idempotence is the whole test: a `POST` that
15
+ * timed out may well have been applied, so asking again could duplicate it.
16
+ * Every gateway *read* is one of these.
17
+ */
18
+ const IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
19
+ "GET",
20
+ "HEAD",
21
+ "OPTIONS"
22
+ ]);
23
+ /**
24
+ * Transport failures worth repeating. `fetch` reports a dropped connection as a
25
+ * `TypeError` whose `cause` carries the real code, and a raw socket error
26
+ * carries one of these codes directly.
27
+ */
28
+ const RETRYABLE_ERROR_CODES = /* @__PURE__ */ new Set([
29
+ "ECONNRESET",
30
+ "ECONNREFUSED",
31
+ "ETIMEDOUT",
32
+ "EPIPE",
33
+ "EAI_AGAIN",
34
+ "UND_ERR_SOCKET",
35
+ "UND_ERR_CONNECT_TIMEOUT",
36
+ "UND_ERR_HEADERS_TIMEOUT",
37
+ "UND_ERR_BODY_TIMEOUT"
38
+ ]);
39
+ /**
40
+ * What a runtime says when the *network* failed, lower-cased and matched as a
41
+ * prefix. `fetch` raises a bare `TypeError` for two unrelated things — a
42
+ * connection that failed, and a request that was malformed (an unparseable
43
+ * URL, an invalid header name, a `GET` with a body) — and only the first is
44
+ * worth repeating: a malformed request will fail identically every time, so
45
+ * retrying it spends four waits per read, multiplied by a build's route count,
46
+ * on a bug that cannot succeed. The message is the only thing that separates
47
+ * them when no `code` is attached, so these are the known spellings, and a
48
+ * runtime whose wording is not here simply fails on the first attempt the way
49
+ * it did before any of this existed.
50
+ */
51
+ const NETWORK_ERROR_MESSAGES = [
52
+ "fetch failed",
53
+ "failed to fetch",
54
+ "load failed",
55
+ "networkerror when attempting to fetch",
56
+ "network error",
57
+ "error sending request",
58
+ "terminated"
59
+ ];
60
+ /**
61
+ * The policy a client was built with, with every unset or nonsensical value
62
+ * filled in. `attempts` counts the first try, so `1` — and `0`, which is what a
63
+ * consumer writes to mean "do not retry" — is one request and no waiting.
64
+ */
65
+ function resolveRetryPolicy(options) {
66
+ return {
67
+ attempts: positive(options?.attempts, 5, 1),
68
+ baseDelayMs: positive(options?.baseDelayMs, 250, 0),
69
+ maxDelayMs: positive(options?.maxDelayMs, DEFAULT_RETRY_MAX_DELAY_MS, 0)
70
+ };
71
+ }
72
+ function positive(value, fallback, floor) {
73
+ if (value === void 0 || !Number.isFinite(value)) return fallback;
74
+ return Math.max(floor, value);
75
+ }
76
+ function isIdempotentMethod(method) {
77
+ return IDEMPOTENT_METHODS.has((method ?? "GET").toUpperCase());
78
+ }
79
+ function isRetryableStatus(status) {
80
+ return RETRYABLE_STATUS.has(status);
81
+ }
82
+ /** Whether this rejection is the caller's own abort rather than a failure. */
83
+ function isAbortError(cause) {
84
+ return typeof cause === "object" && cause !== null && cause.name === "AbortError";
85
+ }
86
+ function isRetryableFetchError(cause) {
87
+ if (isAbortError(cause)) return false;
88
+ const code = errorCodeOf(cause);
89
+ if (code !== void 0) return RETRYABLE_ERROR_CODES.has(code);
90
+ if (!(cause instanceof TypeError)) return false;
91
+ const message = cause.message.toLowerCase();
92
+ return NETWORK_ERROR_MESSAGES.some((known) => message.startsWith(known));
93
+ }
94
+ /**
95
+ * The error's own `code`, or the one on its `cause` — `fetch` wraps a socket
96
+ * error in a `TypeError` and puts the code one level down.
97
+ */
98
+ function errorCodeOf(cause) {
99
+ const own = cause?.code;
100
+ if (typeof own === "string") return own;
101
+ const inner = cause?.cause?.code;
102
+ return typeof inner === "string" ? inner : void 0;
103
+ }
104
+ /**
105
+ * `Retry-After` as milliseconds to wait, or `null` when the header is absent or
106
+ * is neither a delay in seconds nor an HTTP-date. An HTTP-date already in the
107
+ * past is "now", never a negative wait.
108
+ */
109
+ function parseRetryAfter(value, nowMs) {
110
+ if (value === null || value === void 0) return null;
111
+ const raw = value.trim();
112
+ if (raw === "") return null;
113
+ if (/^\d+(?:\.\d+)?$/.test(raw)) return clampRetryAfter(Number(raw) * 1e3);
114
+ const date = Date.parse(raw);
115
+ if (!Number.isFinite(date)) return null;
116
+ return clampRetryAfter(date - nowMs);
117
+ }
118
+ function clampRetryAfter(ms) {
119
+ return Math.min(MAX_RETRY_AFTER_MS, Math.max(0, ms));
120
+ }
121
+ /**
122
+ * `baseDelayMs × 2^attempt`, capped, with equal jitter: half the window is
123
+ * fixed and half is random, so several builds (or several reads of one build)
124
+ * throttled by the same burst do not all come back in the same millisecond.
125
+ * `attempt` is zero-based — the index of the try that just failed.
126
+ */
127
+ function backoffDelayMs(attempt, policy, random = Math.random) {
128
+ const window = Math.min(policy.baseDelayMs * 2 ** attempt, policy.maxDelayMs);
129
+ return window / 2 + random() * (window / 2);
130
+ }
131
+ /**
132
+ * `fetch`, repeated while the answer is "not now".
133
+ *
134
+ * The caller's `AbortSignal` ends it immediately, during a wait as much as
135
+ * during a request: the rejection is the signal's own reason, so an aborted
136
+ * read is indistinguishable from one `fetch` aborted itself. A response that is
137
+ * going to be retried has its body released first — an unread body keeps the
138
+ * connection open, and a build makes thousands of these.
139
+ */
140
+ async function fetchWithRetry(doFetch, url, init, policy, deps = {}) {
141
+ const random = deps.random ?? Math.random;
142
+ const now = deps.now ?? Date.now;
143
+ const signal = init.signal ?? void 0;
144
+ const mayRetry = policy.attempts > 1 && isIdempotentMethod(init.method);
145
+ for (let attempt = 0;; attempt += 1) {
146
+ const lastAttempt = attempt >= policy.attempts - 1;
147
+ let response;
148
+ try {
149
+ response = await doFetch(url, init);
150
+ } catch (cause) {
151
+ if (!mayRetry || lastAttempt || !isRetryableFetchError(cause)) throw cause;
152
+ await wait(backoffDelayMs(attempt, policy, random), signal);
153
+ continue;
154
+ }
155
+ if (!mayRetry || lastAttempt || !isRetryableStatus(response.status)) return response;
156
+ const retryAfter = parseRetryAfter(headerOf(response, "retry-after"), now());
157
+ releaseBody(response);
158
+ await wait(retryAfter ?? backoffDelayMs(attempt, policy, random), signal);
159
+ }
160
+ }
161
+ function headerOf(response, name) {
162
+ return response.headers?.get?.(name) ?? null;
163
+ }
164
+ function releaseBody(response) {
165
+ try {
166
+ response.body?.cancel?.().catch(() => {});
167
+ } catch {}
168
+ }
169
+ function wait(ms, signal) {
170
+ return new Promise((resolve, reject) => {
171
+ if (signal?.aborted === true) {
172
+ reject(abortReason$1(signal));
173
+ return;
174
+ }
175
+ let onAbort;
176
+ const timer = setTimeout(() => {
177
+ if (onAbort !== void 0) signal?.removeEventListener("abort", onAbort);
178
+ resolve();
179
+ }, ms);
180
+ if (signal !== void 0) {
181
+ onAbort = () => {
182
+ clearTimeout(timer);
183
+ reject(abortReason$1(signal));
184
+ };
185
+ signal.addEventListener("abort", onAbort, { once: true });
186
+ }
187
+ });
188
+ }
189
+ function abortReason$1(signal) {
190
+ const reason = signal.reason;
191
+ if (reason !== void 0) return reason;
192
+ return new DOMException("This operation was aborted", "AbortError");
193
+ }
194
+ //#endregion
195
+ //#region src/client.ts
196
+ const apiBaseUrlEnvKeys = [
197
+ "ELDRA_API_BASE_URL",
198
+ "VITE_ELDRA_API_BASE_URL",
199
+ "NEXT_PUBLIC_ELDRA_API_BASE_URL",
200
+ "NUXT_PUBLIC_ELDRA_API_BASE_URL",
201
+ "PUBLIC_ELDRA_API_BASE_URL"
202
+ ];
203
+ const DEFAULT_ELDRA_API_BASE_URL = "https://web.eldra.app/api";
204
+ const orgIdEnvKeys = [
205
+ "ELDRA_ORG_ID",
206
+ "VITE_ELDRA_ORG_ID",
207
+ "NEXT_PUBLIC_ELDRA_ORG_ID",
208
+ "NUXT_PUBLIC_ELDRA_ORG_ID",
209
+ "PUBLIC_ELDRA_ORG_ID"
210
+ ];
211
+ let defaultClient;
212
+ var EldraHttpError = class extends Error {
213
+ status;
214
+ statusText;
215
+ body;
216
+ /** The gateway's problem `code`, such as `CONFLICT`, when the body carried one. */
217
+ code;
218
+ /**
219
+ * The gateway's problem `errorId` — the stable identifier for *which* failure this is, such as
220
+ * `CART_INSUFFICIENT_STOCK`. `code` names the class of failure (`CONFLICT`, `VALIDATION`) and
221
+ * several unrelated refusals share one, so a caller that reacts to a specific cause has to read
222
+ * this: a 409 on an add is `{ code: 'CONFLICT', errorId: 'CART_INSUFFICIENT_STOCK' }`, and
223
+ * telling it apart from any other conflict is what lets a storefront say "out of stock" rather
224
+ * than "something went wrong".
225
+ */
226
+ errorId;
227
+ constructor(response, body) {
228
+ super(`Web Studio request failed with ${response.status} ${response.statusText}`);
229
+ this.name = "EldraHttpError";
230
+ this.status = response.status;
231
+ this.statusText = response.statusText;
232
+ this.body = body;
233
+ this.code = problemString(body, "code");
234
+ this.errorId = problemString(body, "errorId");
235
+ }
236
+ };
237
+ /** One field of an RFC 9457 problem body, when the body is an object that carries it as a string. */
238
+ function problemString(body, key) {
239
+ if (body && typeof body === "object" && key in body) {
240
+ const value = body[key];
241
+ return typeof value === "string" ? value : void 0;
242
+ }
243
+ }
244
+ function initEldraClient(options) {
245
+ defaultClient = createEldraClient(options);
246
+ return defaultClient;
247
+ }
248
+ function getEldraClient() {
249
+ if (!defaultClient) throw new Error("Eldra client has not been initialized. Call initEldraClient() first.");
250
+ return defaultClient;
251
+ }
252
+ function createEldraClient(options) {
253
+ const httpClient = options.httpClient ?? createFetchHttpClient(options.fetch, options.retry);
254
+ const request = (requestOptions) => httpClient(createHttpRequest(options, requestOptions));
255
+ const getOrganization = (organizationOptions, context) => {
256
+ const orgId = resolveRequestOrgId(options, organizationOptions, context);
257
+ return request({
258
+ ...context,
259
+ orgId,
260
+ path: `/organization/v1/${encodeURIComponent(orgId)}`
261
+ });
262
+ };
263
+ /**
264
+ * The platform's own public read, cached for the life of the client: one in-flight promise serves
265
+ * every caller, so two `checkout.url()` calls in the same session make one request. A *failed*
266
+ * read is not remembered — the cache entry is dropped so the next call tries again rather than
267
+ * leaving a storefront with no checkout until it is reloaded.
268
+ *
269
+ * Two deliberate details. The request carries **no organisation header**: the gateway made this
270
+ * route org-independent on purpose, and `X-Org-Id` would put a public read behind the
271
+ * origin-to-organisation binding every org-scoped read goes through — a storefront reading it
272
+ * from a browser origin that is not registered would be refused. And the shared read carries **no
273
+ * caller's signal**: one caller abandoning its wait must not cancel the read every other caller
274
+ * is sharing, so a signal aborts only the waiting (`withAbort`), never the request.
275
+ */
276
+ let platformConfig;
277
+ const readPlatformConfig = (readOptions) => {
278
+ platformConfig ??= request({
279
+ path: "/platform/v1/config",
280
+ orgScoped: false
281
+ }).then(toPlatformConfig).catch((error) => {
282
+ platformConfig = void 0;
283
+ throw error;
284
+ });
285
+ return withAbort(platformConfig, readOptions?.signal);
286
+ };
287
+ const getOrganizationFeatureMap = async (organizationOptions, context) => {
288
+ return mapOrganizationFeatures((await getOrganization(organizationOptions, context)).features ?? []);
289
+ };
290
+ return {
291
+ request,
292
+ cms: {
293
+ list: (schemaApiId, listOptions, context) => request({
294
+ ...context,
295
+ path: `/cms/v1/schema/${encodeURIComponent(schemaApiId)}/entry`,
296
+ query: listOptions
297
+ }),
298
+ get: (schemaApiId, entryId, getOptions, context) => request({
299
+ ...context,
300
+ path: `/cms/v1/schema/${encodeURIComponent(schemaApiId)}/entry/${encodeURIComponent(entryId)}`,
301
+ query: getOptions
302
+ }),
303
+ getEntryByUniqueField: (schemaApiId, fieldId, entryIdentifier, getOptions, context) => request({
304
+ ...context,
305
+ path: `/cms/v1/schema/${encodeURIComponent(schemaApiId)}/entry/unique/${encodeURIComponent(fieldId)}/${encodeURIComponent(entryIdentifier)}`,
306
+ query: getOptions
307
+ }),
308
+ resolveEntryList: (entryList, resolveOptions, context) => request({
309
+ ...context,
310
+ method: "POST",
311
+ path: "/cms/v1/entry-list/resolve",
312
+ query: resolveEntryListQuery(resolveOptions),
313
+ body: resolveEntryListBody(entryList)
314
+ })
315
+ },
316
+ features: {
317
+ getOrganization,
318
+ list: async (organizationOptions, context) => {
319
+ return (await getOrganization(organizationOptions, context)).features ?? [];
320
+ },
321
+ isEnabled: async (feature, organizationOptions, context) => {
322
+ return (await getOrganizationFeatureMap(organizationOptions, context))[feature] === true;
323
+ },
324
+ getCapabilities: async (organizationOptions, context) => {
325
+ const features = await getOrganizationFeatureMap(organizationOptions, context);
326
+ const cms = features.CMS === true;
327
+ const ecommerce = features.ECOMMERCE === true;
328
+ return {
329
+ cms,
330
+ catalog: ecommerce,
331
+ products: ecommerce,
332
+ ecommerce,
333
+ features
334
+ };
335
+ },
336
+ getCommerce: async (organizationOptions, context) => {
337
+ return (await getOrganization(organizationOptions, context)).commerce ?? null;
338
+ },
339
+ getLocales: async (organizationOptions, context) => {
340
+ return toOrganizationLocales((await getOrganization(organizationOptions, context)).locales);
341
+ }
342
+ },
343
+ catalog: {
344
+ listProducts: (listOptions, context) => request({
345
+ ...context,
346
+ path: "/catalog/v1/products/list",
347
+ query: listOptions
348
+ }),
349
+ getProduct: (productId, getOptions, context) => request({
350
+ ...context,
351
+ path: `/catalog/v1/products/${encodeURIComponent(productId)}`,
352
+ query: getOptions
353
+ }),
354
+ listCategories: async (localeOptions, context) => await request({
355
+ ...context,
356
+ path: "/catalog/v1/categories",
357
+ query: localeOptions
358
+ }) ?? [],
359
+ listCollections: (listOptions, context) => request({
360
+ ...context,
361
+ path: "/catalog/v1/collections",
362
+ query: listOptions
363
+ }),
364
+ getCollection: (slug, localeOptions, context) => request({
365
+ ...context,
366
+ path: `/catalog/v1/collections/${encodeURIComponent(slug)}`,
367
+ query: localeOptions
368
+ }),
369
+ listCollectionProducts: (slug, listOptions, context) => request({
370
+ ...context,
371
+ path: `/catalog/v1/collections/${encodeURIComponent(slug)}/products`,
372
+ query: listOptions
373
+ }),
374
+ search: (query, searchOptions, context) => request({
375
+ ...context,
376
+ path: "/search/v1",
377
+ query: {
378
+ ...searchOptions,
379
+ q: query
380
+ }
381
+ })
382
+ },
383
+ cart: {
384
+ addItem: (input, context) => request({
385
+ ...context,
386
+ method: "POST",
387
+ path: "/shopping-cart/v1/cart/items",
388
+ body: input
389
+ }),
390
+ get: (cartId, localeOptions, context) => request({
391
+ ...context,
392
+ path: `/shopping-cart/v1/cart/${encodeURIComponent(cartId)}`,
393
+ query: localeOptions
394
+ }),
395
+ updateItem: (cartId, itemId, input, context) => request({
396
+ ...context,
397
+ method: "PATCH",
398
+ path: `/shopping-cart/v1/cart/${encodeURIComponent(cartId)}/items/${encodeURIComponent(itemId)}`,
399
+ body: input
400
+ }),
401
+ removeItem: (cartId, itemId, context) => request({
402
+ ...context,
403
+ method: "DELETE",
404
+ path: `/shopping-cart/v1/cart/${encodeURIComponent(cartId)}/items/${encodeURIComponent(itemId)}`
405
+ }),
406
+ applyDiscount: async (cartId, code, localeOptions, context) => {
407
+ const trimmed = code.trim();
408
+ const cart = await request({
409
+ ...context,
410
+ method: "PUT",
411
+ path: `/shopping-cart/v1/cart/${encodeURIComponent(cartId)}/discount`,
412
+ query: localeOptions,
413
+ body: { code: trimmed }
414
+ });
415
+ const discountCode = cart.discountCode;
416
+ return {
417
+ cart,
418
+ applied: typeof discountCode === "string" && discountCode.trim().toUpperCase() === trimmed.toUpperCase()
419
+ };
420
+ },
421
+ removeDiscount: (cartId, localeOptions, context) => request({
422
+ ...context,
423
+ method: "DELETE",
424
+ path: `/shopping-cart/v1/cart/${encodeURIComponent(cartId)}/discount`,
425
+ query: localeOptions
426
+ })
427
+ },
428
+ orders: {
429
+ get: (orderId, readOptions, context) => request({
430
+ ...context,
431
+ path: `/order/v1/${encodeURIComponent(orderId)}`,
432
+ headers: mergeHeaders(context?.headers, readOptions?.accessToken ? { "X-Order-Token": readOptions.accessToken } : void 0)
433
+ }),
434
+ recover: (token, context) => request({
435
+ ...context,
436
+ method: "POST",
437
+ path: "/order/v1/recover",
438
+ body: { token: token.trim() }
439
+ })
440
+ },
441
+ platform: { config: (readOptions) => readPlatformConfig(readOptions) },
442
+ checkout: { url: async (handoff, readOptions) => {
443
+ let checkoutUrl = null;
444
+ let cause;
445
+ try {
446
+ checkoutUrl = (await readPlatformConfig(readOptions)).checkoutUrl;
447
+ } catch (error) {
448
+ cause = error;
449
+ }
450
+ if (!checkoutUrl) throw cause === void 0 ? /* @__PURE__ */ new Error("The platform did not publish a checkout URL (GET /platform/v1/config).") : new Error(`Could not read the platform checkout URL (GET /platform/v1/config): ${describeCause(cause)}`, { cause });
451
+ return buildCheckoutUrl(checkoutUrl, handoff, options);
452
+ } },
453
+ inventory: { availability: (items, context) => request({
454
+ ...context,
455
+ method: "POST",
456
+ path: "/inventory/v1/stock/availability",
457
+ body: { items }
458
+ }) }
459
+ };
460
+ }
461
+ /**
462
+ * `{checkoutUrl}/checkout/{orgId}/{cartId}` — where a storefront sends the customer, with the
463
+ * locale as `lang` when it has one. Internal: the base URL comes from the platform's config, which
464
+ * only `checkout.url()` can read, so there is no public builder that takes a base of its own.
465
+ *
466
+ * The published base is checked rather than trusted. It ends up in a link a shopper clicks, so a
467
+ * value that is not an absolute `http(s)` URL is refused in terms a developer can act on instead of
468
+ * reaching the page as `TypeError: Invalid URL` — or, for a `javascript:` or `data:` base, as a
469
+ * working link. Every trailing slash is stripped, not just the last one, so a doubled one cannot
470
+ * leave `//checkout` in the path.
471
+ */
472
+ function buildCheckoutUrl(checkoutUrl, handoff, options) {
473
+ const orgId = handoff.orgId ?? resolveOrgId(options);
474
+ if (!orgId) throw new Error("Missing Web Studio organization ID.");
475
+ const base = checkoutUrl.replace(/\/+$/, "");
476
+ const path = `/checkout/${encodeURIComponent(orgId)}/${encodeURIComponent(handoff.cartId)}`;
477
+ let url;
478
+ try {
479
+ url = new URL(`${base}${path}`);
480
+ } catch (cause) {
481
+ throw unusableCheckoutUrl(checkoutUrl, cause);
482
+ }
483
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw unusableCheckoutUrl(checkoutUrl);
484
+ if (handoff.locale) url.searchParams.set("lang", handoff.locale);
485
+ return url.toString();
486
+ }
487
+ function unusableCheckoutUrl(checkoutUrl, cause) {
488
+ const message = `The platform published an unusable checkout URL (${JSON.stringify(checkoutUrl)}): it must be an absolute http(s) URL.`;
489
+ return cause === void 0 ? new Error(message) : new Error(message, { cause });
490
+ }
491
+ function describeCause(cause) {
492
+ return cause instanceof Error ? cause.message : String(cause);
493
+ }
494
+ /**
495
+ * The caller's own wait on a shared read. The read itself is not cancellable — it is one request
496
+ * serving every caller — so an aborted signal settles this caller's promise and leaves the request
497
+ * alone. The listener is removed either way, so a long-lived signal collects nothing.
498
+ */
499
+ function withAbort(promise, signal) {
500
+ if (signal === void 0) return promise;
501
+ if (signal.aborted) {
502
+ promise.catch(() => void 0);
503
+ return Promise.reject(abortReason(signal));
504
+ }
505
+ return new Promise((resolve, reject) => {
506
+ const onAbort = () => reject(abortReason(signal));
507
+ signal.addEventListener("abort", onAbort, { once: true });
508
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
509
+ });
510
+ }
511
+ function abortReason(signal) {
512
+ return signal.reason ?? /* @__PURE__ */ new Error("The platform config read was abandoned: the signal was aborted.");
513
+ }
514
+ /**
515
+ * The gateway answers `{ checkoutUrl: string | null }`. Anything else — a blank string, a missing
516
+ * key, a body that is not an object at all — is read as "no checkout published" rather than handed
517
+ * on as a URL, since the value goes straight into a link a shopper clicks.
518
+ */
519
+ function toPlatformConfig(body) {
520
+ const value = body?.checkoutUrl;
521
+ const checkoutUrl = typeof value === "string" ? value.trim() : "";
522
+ return { checkoutUrl: checkoutUrl === "" ? null : checkoutUrl };
523
+ }
524
+ function resolveRequestOrgId(clientOptions, organizationOptions, context) {
525
+ const orgId = organizationOptions?.orgId ?? context?.orgId ?? resolveOrgId(clientOptions);
526
+ if (!orgId) throw new Error("Missing Web Studio organization ID.");
527
+ return orgId;
528
+ }
529
+ /**
530
+ * The organisation's content locales, or `null`.
531
+ *
532
+ * Validated rather than passed through, and the validation is deliberately strict: whoever reads
533
+ * this decides which locale lives at which URL, so half an answer — a `default` that is not a
534
+ * string, a `supported` array with a blank entry — would put real visitors on paths no content
535
+ * exists at. Anything that is not a whole, usable record reads the same as "none configured".
536
+ *
537
+ * `default` is normalised to the front of `supported` (the gateway documents it there, and a
538
+ * consumer that trusted the order would otherwise prefix the default locale), and duplicates are
539
+ * collapsed while the remaining order is kept.
540
+ */
541
+ function toOrganizationLocales(value) {
542
+ if (value === null || typeof value !== "object") return null;
543
+ const defaultLocale = typeof value.default === "string" ? value.default.trim() : "";
544
+ if (defaultLocale === "") return null;
545
+ if (!Array.isArray(value.supported)) return null;
546
+ const supported = [defaultLocale];
547
+ for (const entry of value.supported) {
548
+ if (typeof entry !== "string") return null;
549
+ const locale = entry.trim();
550
+ if (locale === "") return null;
551
+ if (!supported.includes(locale)) supported.push(locale);
552
+ }
553
+ return {
554
+ default: defaultLocale,
555
+ supported
556
+ };
557
+ }
558
+ function mapOrganizationFeatures(features) {
559
+ const mapped = {};
560
+ for (const row of features) if (row.feature === "CMS" || row.feature === "ECOMMERCE") mapped[row.feature] = row.enabled;
561
+ return mapped;
562
+ }
563
+ function resolveEntryListQuery(options) {
564
+ return {
565
+ locale: options?.locale,
566
+ page: options?.page,
567
+ pageSize: options?.pageSize,
568
+ limit: options?.limit,
569
+ depth: options?.depth,
570
+ deep: options?.deep
571
+ };
572
+ }
573
+ function resolveEntryListBody(entryList) {
574
+ return {
575
+ schemas: entryList.schemas,
576
+ filters: entryList.filters,
577
+ displayAs: entryList.displayAs,
578
+ orderBy: entryList.orderBy,
579
+ pageSize: entryList.pageSize
580
+ };
581
+ }
582
+ function createHttpRequest(clientOptions, requestOptions) {
583
+ const method = requestOptions.method ?? (requestOptions.body === void 0 ? "GET" : "POST");
584
+ const headers = mergeHeaders(resolveRuntimeValue(clientOptions.headers), requestOptions.headers);
585
+ const orgId = requestOptions.orgScoped === false ? void 0 : requestOptions.orgId ?? resolveOrgId(clientOptions);
586
+ if (orgId) headers.set("X-Org-Id", orgId);
587
+ const previewToken = resolveRuntimeValue(clientOptions.previewToken);
588
+ if (previewToken) headers.set("X-Preview-Token", previewToken);
589
+ let body;
590
+ if (requestOptions.body !== void 0) {
591
+ headers.set("Content-Type", headers.get("Content-Type") ?? "application/json");
592
+ body = isRawBody(requestOptions.body) ? requestOptions.body : JSON.stringify(requestOptions.body);
593
+ }
594
+ return {
595
+ url: buildUrl(resolveApiBaseUrl(clientOptions), requestOptions.path, requestOptions.query),
596
+ method,
597
+ headers,
598
+ body,
599
+ signal: requestOptions.signal
600
+ };
601
+ }
602
+ function createFetchHttpClient(fetchImpl, retry) {
603
+ const retryPolicy = resolveRetryPolicy(retry);
604
+ return async (request) => {
605
+ const resolvedFetch = fetchImpl ?? globalThis.fetch;
606
+ if (!resolvedFetch) throw new Error("No fetch implementation is available. Pass fetch or httpClient to createEldraClient().");
607
+ const response = await fetchWithRetry(resolvedFetch, request.url, {
608
+ method: request.method,
609
+ headers: request.headers,
610
+ body: request.body,
611
+ signal: request.signal
612
+ }, retryPolicy);
613
+ const body = await readResponseBody(response);
614
+ if (!response.ok) throw new EldraHttpError(response, body);
615
+ return body;
616
+ };
617
+ }
618
+ function readResponseBody(response) {
619
+ if (response.status === 204) return Promise.resolve(void 0);
620
+ const contentType = response.headers.get("Content-Type") ?? "";
621
+ if (contentType.includes("application/json") || contentType.includes("application/problem+json")) return response.json();
622
+ return response.text();
623
+ }
624
+ function resolveApiBaseUrl(options) {
625
+ return resolveRuntimeValue(options.apiBaseUrl) ?? readFirstEnvValue(resolveRuntimeValue(options.env), apiBaseUrlEnvKeys) ?? "https://web.eldra.app/api";
626
+ }
627
+ function resolveOrgId(options) {
628
+ return resolveRuntimeValue(options.orgId) ?? readFirstEnvValue(resolveRuntimeValue(options.env), orgIdEnvKeys);
629
+ }
630
+ function readFirstEnvValue(env, keys) {
631
+ for (const key of keys) {
632
+ const value = env?.[key];
633
+ if (typeof value === "string" && value.trim() !== "") return value;
634
+ }
635
+ }
636
+ function resolveRuntimeValue(value) {
637
+ return typeof value === "function" ? value() : value;
638
+ }
639
+ function mergeHeaders(...sources) {
640
+ const headers = new Headers();
641
+ for (const source of sources) {
642
+ if (!source) continue;
643
+ new Headers(source).forEach((value, key) => headers.set(key, value));
644
+ }
645
+ return headers;
646
+ }
647
+ function buildUrl(apiBaseUrl, path, query) {
648
+ const url = new URL(`${apiBaseUrl.replace(/\/$/, "")}/${path.replace(/^\//, "")}`);
649
+ for (const [key, value] of Object.entries(query ?? {})) appendQueryValue(url.searchParams, key, value);
650
+ return url.toString();
651
+ }
652
+ /**
653
+ * Query parameters the gateway declares as repeatable (`explode: true`): one
654
+ * `key=` entry per value, never a comma-joined one. Every other array
655
+ * parameter (`sort`, `fields`) is declared `explode: false` and stays
656
+ * comma-separated.
657
+ *
658
+ * `filter` has to be in here — a filter token is `[groupIndex:]field:op:value`
659
+ * whose value may itself contain commas (`slug:in:a,b`), so joining several
660
+ * tokens into one parameter runs them together and every token after the first
661
+ * is lost. The catalog product filters (`categoryId`, `collectionId`, `option`
662
+ * on `GET /catalog/v1/products/list` and
663
+ * `GET /catalog/v1/collections/{slug}/products`) are declared the same way, and
664
+ * each is an OR over its values: comma-joined, `categoryId=a,b` is one id the
665
+ * catalogue has never heard of, so a shopper ticking two categories would see
666
+ * nothing rather than both.
667
+ */
668
+ const REPEATED_QUERY_KEYS = /* @__PURE__ */ new Set([
669
+ "filter",
670
+ "categoryId",
671
+ "collectionId",
672
+ "option"
673
+ ]);
674
+ function appendQueryValue(searchParams, key, value) {
675
+ if (value === void 0 || value === null || value === "") return;
676
+ if (Array.isArray(value)) {
677
+ if (REPEATED_QUERY_KEYS.has(key)) {
678
+ for (const entry of value) {
679
+ if (entry === void 0 || entry === null || entry === "") continue;
680
+ searchParams.append(key, String(entry));
681
+ }
682
+ return;
683
+ }
684
+ searchParams.set(key, value.map(String).join(","));
685
+ return;
686
+ }
687
+ searchParams.set(key, String(value));
688
+ }
689
+ function isRawBody(body) {
690
+ return typeof body === "string" || typeof FormData !== "undefined" && body instanceof FormData || typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams || typeof Blob !== "undefined" && body instanceof Blob || body instanceof ArrayBuffer;
691
+ }
692
+ //#endregion
693
+ export { initEldraClient as a, getEldraClient as i, EldraHttpError as n, resolveApiBaseUrl as o, createEldraClient as r, resolveOrgId as s, DEFAULT_ELDRA_API_BASE_URL as t };