@eldrajs/sdk 0.5.4 → 0.5.5

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.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,8 @@ platform repository.
9
9
 
10
10
  ## Unreleased
11
11
 
12
+ - **Price tokens (WS-1474, WS-1473).** New entry `@eldrajs/sdk/tokens`: a price inside any text, `⟦price#a3f EUR=10000 ISK=1500000⟧` (minor units per currency, never converted) or a store setting, `⟦store freeShippingThreshold⟧`. `resolveTokens(text, { currency, locale, storeAmounts, format })` writes each in the shopper's currency and leaves out a sentence whose price has no amount in it, keeping the builder preview's payload; `resolvePriceNode` does the same for a rich-text `price` node. Also `parseTokens`, `serializeToken`, `toMajorUnits`/`toMinorUnits`, and `lengthText`, what a `maxLength` counts (each token as `TOKEN_TEXT_LENGTH`, 10). `features.getStoreAmounts()` reads the free-shipping threshold per currency, the lowest among the active delivery methods (`GET /delivery/v1/provider-account`), as `StoreAmounts`.
13
+ - **The organisation's regional format (WS-1277).** `features.getRegion()` answers `{ countryCode, formatLocale, timeZone }` (`EldraOrganizationRegion`, the organisation read's `region`) or `null`: the locale Studio says to format money, numbers and dates with, and the time zone to show them in, independent of the content locale. Validated: a malformed tag, an unknown time zone or a country that is not two letters answers `null`, never a value `Intl` would throw on. `formatLocale` is canonicalised and `countryCode` upper-cased. `EldraOrganizationDetails` carries `region`.
12
14
  - **A store's default currency (WS-1399; contract 6.22.0).** `EldraOrganizationCommerce` carries `defaultCurrency`, what pages are built in and a visitor starts in. A store may turn its own currency off: `currency` stays ISK, and `currencies` then leaves it out.
13
15
  - **Selling in more than one currency (WS-1391; contracts 6.19.0, 6.20.0, 6.21.0).** `createCurrencyPreference()` keeps the currency a visitor picked (`read`, `remember`, `forget`; `localStorage` `eldra.currency`); `cart.setCurrency(cartId, currency)` changes a cart's currency (`PUT /shopping-cart/v1/cart/{cartID}/currency`); `catalog.getProduct` takes `currency`; `EldraOrganizationCommerce` carries `currencies` (what the storefront may offer, the store currency first); `paymentProviders` on the organisation is typed as `EldraOrganizationPaymentProvider[]`, each with the `currencies` it takes (missing means ISK only).
14
16
  - **A 3840 px image variant, `uhd`.** A full-width image on a high-density screen wants about 3840 px, and
@@ -24,8 +26,7 @@ platform repository.
24
26
  - **Several discount codes on one cart (contract 6.9.0).** `applyDiscount` and `applyCode` (as `DISCOUNT`) now add
25
27
  a code after the cart's codes instead of replacing it; each applies to what the codes before it left. Three new
26
28
  409 refusals leave the cart as it was: `CART_DISCOUNT_NOT_COMBINABLE` (the code and one on the cart cannot be
27
- combined; `errors.blockingCode` names the one on the cart), `CART_DISCOUNT_CODES_LIMIT_REACHED` (`errors.limit`,
28
- 6) and `CART_DISCOUNT_ALREADY_APPLIED`. `EldraHttpError` gains `errors`, the problem's `errors` object when the
29
+ combined; `errors.blockingCode` names the one on the cart), `CART_DISCOUNT_CODES_LIMIT_REACHED` (`errors.limit`, 6) and `CART_DISCOUNT_ALREADY_APPLIED`. `EldraHttpError` gains `errors`, the problem's `errors` object when the
29
30
  body carries one. The cart carries `discountCodes` (`{code, amount}` in the order added; the type is
30
31
  `EldraCartDiscountCodeEntry`); `cart.removeDiscountEntry(cartId, code, options?)` removes one code and
31
32
  `removeDiscount` now removes every code. `applyDiscount`'s `applied` reads `discountCodes` (falling back to
@@ -36,7 +37,7 @@ platform repository.
36
37
  - **Several gift cards on one cart (contract 6.8.0).** A cart holds any number of gift cards beside its discount
37
38
  code: `applyGiftCard` and `applyCode` now add a card after the others instead of replacing one, and the same card
38
39
  again is 409 `CART_GIFT_CARD_ALREADY_APPLIED`. The cart carries `giftCards` (`{entryId, last4, balance, applied,
39
- amountDue}` in the order applied; the type is `EldraCartGiftCardEntry`) and the cart-wide `amountDue`.
40
+ amountDue}` in the order applied; the type is `EldraCartGiftCardEntry`) and the cart-wide `amountDue`.
40
41
  `cart.removeGiftCardEntry(cartId, entryId, options?)` removes one card; `removeGiftCard` now removes every card.
41
42
  The cart's `giftCard` and `EldraCartGiftCard` are deprecated: the contract answers them for one more
42
43
  version. The contract fixtures are regenerated from 6.8.0.
@@ -118,7 +119,7 @@ serving public contract 6.15.0 (core merged main's 6.14.0 first).
118
119
  - Sales orders and delivery locations (contract 6.15.0) for a signed-in business customer's active
119
120
  company: `customer.locations(context)` (`GET /customer/v1/locations`, answered as the `{ data }`
120
121
  envelope like every other list, the default first, `data` `[]` for none), `salesOrders.preview(input, context)`, `salesOrders.create(input, { idempotencyKey },
121
- context)`, `salesOrders.list(options, context)` and `salesOrders.get(id, context)`. `create`
122
+ context)`, `salesOrders.list(options, context)` and `salesOrders.get(id, context)`. `create`
122
123
  requires the idempotency key (1 to 255 printable ASCII characters, no spaces) and rejects with
123
124
  `EldraIdempotencyKeyError` (a `TypeError`) without a usable one, sending nothing. Catch that class,
124
125
  not every `TypeError`: a lost connection is a `TypeError` too and is retried with the key. Keep the key across
@@ -1,3 +1,52 @@
1
+ // src/storeAmounts.ts
2
+ /**
3
+ * Major to minor units with the runtime's own `Intl`, not the bundled formatter `./tokens` uses:
4
+ * this runs inside the client, and a currency's decimal count is the same in every locale, so the
5
+ * client need not carry the formatter for it.
6
+ */
7
+ function toMinorUnits(amount, currency) {
8
+ let digits = 2;
9
+ try {
10
+ digits = new Intl.NumberFormat("en", {
11
+ style: "currency",
12
+ currency
13
+ }).resolvedOptions().maximumFractionDigits ?? 2;
14
+ } catch {}
15
+ return Math.round(amount * 10 ** digits);
16
+ }
17
+ /**
18
+ * The store's amounts for `⟦store …⟧` tokens (WS-1473), from the public delivery read
19
+ * (`GET /delivery/v1/provider-account`): `{ freeShippingThreshold: { ISK: 1500000, EUR: 10000 } }`,
20
+ * in minor units.
21
+ *
22
+ * `freeShippingThreshold` in a currency is the **lowest** threshold among the active delivery
23
+ * methods that sell in it: "free shipping over" the least a shopper can spend to get it. A method
24
+ * publishes its threshold per currency in `currencyPrices` (Core, WS-1473), and before that only in
25
+ * its own `currency`; both are read, so this works against either gateway. A threshold of `0` is
26
+ * kept (that method always ships free). A currency no method has a threshold in is absent, and a
27
+ * token naming it hides its sentence rather than guessing.
28
+ */
29
+ function storeAmountsFromDelivery(accounts) {
30
+ const lowest = {};
31
+ const offer = (currency, threshold) => {
32
+ if (typeof currency !== "string" || !/^[A-Z]{3}$/.test(currency)) return;
33
+ if (typeof threshold !== "number" || !Number.isFinite(threshold) || threshold < 0) return;
34
+ const minor = toMinorUnits(threshold, currency);
35
+ if (lowest[currency] === void 0 || minor < lowest[currency]) lowest[currency] = minor;
36
+ };
37
+ for (const account of Array.isArray(accounts) ? accounts : []) {
38
+ if (account === null || typeof account !== "object") continue;
39
+ const { currency, freeShippingThreshold, currencyPrices, status } = account;
40
+ if (typeof status === "string" && status.toUpperCase() !== "ACTIVE") continue;
41
+ offer(currency, freeShippingThreshold);
42
+ for (const price of Array.isArray(currencyPrices) ? currencyPrices : []) {
43
+ if (price === null || typeof price !== "object") continue;
44
+ const entry = price;
45
+ offer(entry.currency, entry.freeShippingThreshold);
46
+ }
47
+ }
48
+ return Object.keys(lowest).length === 0 ? {} : { freeShippingThreshold: lowest };
49
+ }
1
50
  // src/storage.ts
2
51
  const DEFAULT_CART_KEY = "eldra.cartId";
3
52
  const DEFAULT_CURRENCY_KEY = "eldra.currency";
@@ -563,7 +612,14 @@ function createEldraClient(options) {
563
612
  },
564
613
  getLocales: async (organizationOptions, context) => {
565
614
  return toOrganizationLocales((await getOrganization(organizationOptions, context)).locales);
566
- }
615
+ },
616
+ getRegion: async (organizationOptions, context) => {
617
+ return toOrganizationRegion((await getOrganization(organizationOptions, context)).region);
618
+ },
619
+ getStoreAmounts: async (context) => storeAmountsFromDelivery(await request({
620
+ ...context,
621
+ path: "/delivery/v1/provider-account"
622
+ }))
567
623
  },
568
624
  catalog: {
569
625
  /**
@@ -945,6 +1001,47 @@ function toOrganizationLocales(value) {
945
1001
  supported
946
1002
  };
947
1003
  }
1004
+ /**
1005
+ * The organisation's regional format, validated. Every field ends up in an `Intl` constructor on
1006
+ * every price and date a storefront prints, and `Intl` throws a `RangeError` on a malformed tag or
1007
+ * an unknown zone — so a record with any unusable field reads as "none published" (`null`) and the
1008
+ * consumer falls back to its own locale, instead of a storefront that cannot render a price.
1009
+ */
1010
+ function toOrganizationRegion(value) {
1011
+ if (value === null || typeof value !== "object") return null;
1012
+ const record = value;
1013
+ const formatLocale = canonicalLocale(record.formatLocale);
1014
+ if (formatLocale === null) return null;
1015
+ const timeZone = knownTimeZone(record.timeZone);
1016
+ if (timeZone === null) return null;
1017
+ const rawCountry = record.countryCode ?? "";
1018
+ if (typeof rawCountry !== "string") return null;
1019
+ const countryCode = rawCountry.trim().toUpperCase();
1020
+ if (countryCode !== "" && !/^[A-Z]{2}$/.test(countryCode)) return null;
1021
+ return {
1022
+ countryCode,
1023
+ formatLocale,
1024
+ timeZone
1025
+ };
1026
+ }
1027
+ function canonicalLocale(value) {
1028
+ if (typeof value !== "string" || value.trim() === "") return null;
1029
+ try {
1030
+ return Intl.getCanonicalLocales(value.trim())[0] ?? null;
1031
+ } catch {
1032
+ return null;
1033
+ }
1034
+ }
1035
+ function knownTimeZone(value) {
1036
+ if (typeof value !== "string" || value.trim() === "") return null;
1037
+ const timeZone = value.trim();
1038
+ try {
1039
+ new Intl.DateTimeFormat("en", { timeZone });
1040
+ return timeZone;
1041
+ } catch {
1042
+ return null;
1043
+ }
1044
+ }
948
1045
  function mapOrganizationFeatures(features) {
949
1046
  const mapped = {};
950
1047
  for (const row of features) if (row.feature === "CMS" || row.feature === "ECOMMERCE") mapped[row.feature] = row.enabled;
@@ -1102,4 +1199,4 @@ function appendQueryValue(searchParams, key, value) {
1102
1199
  function isRawBody(body) {
1103
1200
  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;
1104
1201
  }
1105
- export { createOrderAccessTokens as _, getEldraClient as a, resolveApiBaseUrl as c, clearCampaignAttribution as d, grantCampaignAttributionConsent as f, createCurrencyPreference as g, createCartSession as h, createEldraClient as i, resolveOrgId as l, withdrawCampaignAttributionConsent as m, EldraHttpError as n, initEldraClient as o, readCampaignAttribution as p, EldraIdempotencyKeyError as r, isEldraError as s, DEFAULT_ELDRA_API_BASE_URL as t, captureCampaignAttribution as u };
1202
+ export { createOrderAccessTokens as _, getEldraClient as a, resolveApiBaseUrl as c, clearCampaignAttribution as d, grantCampaignAttributionConsent as f, createCurrencyPreference as g, createCartSession as h, createEldraClient as i, resolveOrgId as l, withdrawCampaignAttributionConsent as m, EldraHttpError as n, initEldraClient as o, readCampaignAttribution as p, EldraIdempotencyKeyError as r, isEldraError as s, DEFAULT_ELDRA_API_BASE_URL as t, captureCampaignAttribution as u, storeAmountsFromDelivery as v };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { $ as EldraFormSubmitResult, $t as EldraShopUser, A as EldraCollection, At as EldraProductVariant, B as EldraCustomerMembership, Bt as EldraSalesOrderLine, C as EldraCmsEntryListFilterCriterion, Cn as EldraCurrencyPreference, Ct as EldraProductExtensions, D as EldraCmsResolveEntryListOptions, Dn as createCartSession, Dt as EldraProductOption, E as EldraCmsListOptions, En as EldraOrderAccessTokens, Et as EldraProductMediaLink, F as EldraCreateSalesOrderOptions, Ft as EldraRetryOptions, G as EldraFeatureClient, Gt as EldraSalesOrderPreviewInput, H as EldraErrorId, Ht as EldraSalesOrderListItem, I as EldraCustomerClient, It as EldraSalesOrder, J as EldraFormField, Jt as EldraSalesOrderWarning, K as EldraFormActionKind, Kt as EldraSalesOrderPreviewLine, L as EldraCustomerLocation, Lt as EldraSalesOrderCredit, M as EldraCollectionListOptions, Mt as EldraRecoveredBasketItem, N as EldraCollectionProductsOptions, Nt as EldraRequestContext, O as EldraCmsResolveEntryListResponse, On as createCurrencyPreference, Ot as EldraProductOptionValue, P as EldraCreateSalesOrderInput, Pt as EldraRequestOptions, Q as EldraFormSubmitInput, Qt as EldraShopErrorId, R as EldraCustomerLocationList, Rt as EldraSalesOrderDelivery, S as EldraCmsEntryListEntry, Sn as EldraCartSessionOptions, St as EldraProductDetails, T as EldraCmsGetOptions, Tn as EldraOrderAccessTokenOptions, Tt as EldraProductListItem, U as EldraFeature, Ut as EldraSalesOrderListOptions, V as EldraDiscountResult, Vt as EldraSalesOrderList, W as EldraFeatureCapabilities, Wt as EldraSalesOrderPreview, X as EldraFormFieldType, Xt as EldraSearchOptions, Y as EldraFormFieldOption, Yt as EldraSalesOrdersClient, Z as EldraFormLocalized, Zt as EldraSearchResponse, _ as EldraClient, _n as clearCampaignAttribution, _t as EldraPaginated, a as EldraCartClient, an as EldraContract, at as EldraLocaleOptions, b as EldraCmsEntryList, bn as withdrawCampaignAttributionConsent, bt as EldraPlatformReadOptions, c as EldraCartGiftCardEntry, cn as EldraContractMethod, ct as EldraOrderLine, d as EldraCatalogClient, dn as EldraContractProp, dt as EldraOrganizationCommerce, en as EldraStockAvailability, et as EldraFormTokenResult, f as EldraCatalogGetProductOptions, fn as EldraContractQuery, ft as EldraOrganizationDetails, g as EldraCheckoutUrlOptions, gn as captureCampaignAttribution, gt as EldraPageMeta, h as EldraCheckoutClient, hn as EldraCampaignAttributionOptions, ht as EldraOrganizationOptions, i as EldraCartAppliedCode, in as RuntimeValue, it as EldraInventoryClient, j as EldraCollectionList, jt as EldraRecoveredBasket, k as EldraCmsResolvedEntryList, kn as createOrderAccessTokens, kt as EldraProductThumbnail, l as EldraCartItem, ln as EldraContractPath, lt as EldraOrderReadOptions, m as EldraCategory, mn as EldraCampaignAttribution, mt as EldraOrganizationLocales, n as EldraBrand, nn as EldraStockAvailabilityItem, nt as EldraHttpClient, o as EldraCartDiscountCodeEntry, on as EldraContractBody, ot as EldraOrder, p as EldraCatalogListProductsOptions, pn as EldraContractResponse, pt as EldraOrganizationFeature, q as EldraFormDefinition, qt as EldraSalesOrderStatus, r as EldraCart, rn as RuntimeEnv, rt as EldraHttpRequest, s as EldraCartGiftCard, sn as EldraContractItem, st as EldraOrderDiscountCode, t as EldraAddCartItemInput, tn as EldraStockAvailabilityInput, tt as EldraFormsClient, u as EldraCartTotals, un as EldraContractPaths, ut as EldraOrdersClient, v as EldraClientOptions, vn as grantCampaignAttributionConsent, vt as EldraPlatformClient, w as EldraCmsGetEntryByUniqueFieldOptions, wn as EldraKeyValueStorage, wt as EldraProductList, x as EldraCmsEntryListDisplayMode, xn as EldraCartSession, xt as EldraProblemErrors, y as EldraCmsClient, yn as readCampaignAttribution, yt as EldraPlatformConfig, z as EldraCustomerMe, zt as EldraSalesOrderErrorId } from "./types-BrMiT2QA.js";
1
+ import { $ as EldraFormSubmitResult, $t as EldraShopErrorId, A as EldraCollection, An as createOrderAccessTokens, At as EldraProductThumbnail, B as EldraCustomerMembership, Bt as EldraSalesOrderErrorId, C as EldraCmsEntryListFilterCriterion, Cn as EldraCartSessionOptions, Ct as EldraProductDetails, D as EldraCmsResolveEntryListOptions, Dn as EldraOrderAccessTokens, Dt as EldraProductMediaLink, E as EldraCmsListOptions, En as EldraOrderAccessTokenOptions, Et as EldraProductListItem, F as EldraCreateSalesOrderOptions, Ft as EldraRequestOptions, G as EldraFeatureClient, Gt as EldraSalesOrderPreview, H as EldraErrorId, Ht as EldraSalesOrderList, I as EldraCustomerClient, It as EldraRetryOptions, J as EldraFormField, Jt as EldraSalesOrderStatus, K as EldraFormActionKind, Kt as EldraSalesOrderPreviewInput, L as EldraCustomerLocation, Lt as EldraSalesOrder, M as EldraCollectionListOptions, Mt as EldraRecoveredBasket, N as EldraCollectionProductsOptions, Nt as EldraRecoveredBasketItem, O as EldraCmsResolveEntryListResponse, On as createCartSession, Ot as EldraProductOption, P as EldraCreateSalesOrderInput, Pt as EldraRequestContext, Q as EldraFormSubmitInput, Qt as EldraSearchResponse, R as EldraCustomerLocationList, Rt as EldraSalesOrderCredit, S as EldraCmsEntryListEntry, Sn as EldraCartSession, St as EldraProblemErrors, T as EldraCmsGetOptions, Tn as EldraKeyValueStorage, Tt as EldraProductList, U as EldraFeature, Ut as EldraSalesOrderListItem, V as EldraDiscountResult, Vt as EldraSalesOrderLine, W as EldraFeatureCapabilities, Wt as EldraSalesOrderListOptions, X as EldraFormFieldType, Xt as EldraSalesOrdersClient, Y as EldraFormFieldOption, Yt as EldraSalesOrderWarning, Z as EldraFormLocalized, Zt as EldraSearchOptions, _ as EldraClient, _n as captureCampaignAttribution, _t as EldraPageMeta, a as EldraCartClient, an as RuntimeValue, at as EldraLocaleOptions, b as EldraCmsEntryList, bn as readCampaignAttribution, bt as EldraPlatformConfig, c as EldraCartGiftCardEntry, cn as EldraContractItem, ct as EldraOrderLine, d as EldraCatalogClient, dn as EldraContractPaths, dt as EldraOrganizationCommerce, en as EldraShopUser, et as EldraFormTokenResult, f as EldraCatalogGetProductOptions, fn as EldraContractProp, ft as EldraOrganizationDetails, g as EldraCheckoutUrlOptions, gn as EldraCampaignAttributionOptions, gt as EldraOrganizationRegion, h as EldraCheckoutClient, hn as EldraCampaignAttribution, ht as EldraOrganizationOptions, i as EldraCartAppliedCode, in as RuntimeEnv, it as EldraInventoryClient, j as EldraCollectionList, jt as EldraProductVariant, k as EldraCmsResolvedEntryList, kn as createCurrencyPreference, kt as EldraProductOptionValue, l as EldraCartItem, ln as EldraContractMethod, lt as EldraOrderReadOptions, m as EldraCategory, mn as EldraContractResponse, mt as EldraOrganizationLocales, n as EldraBrand, nn as EldraStockAvailabilityInput, nt as EldraHttpClient, o as EldraCartDiscountCodeEntry, on as EldraContract, ot as EldraOrder, p as EldraCatalogListProductsOptions, pn as EldraContractQuery, pt as EldraOrganizationFeature, q as EldraFormDefinition, qt as EldraSalesOrderPreviewLine, r as EldraCart, rn as EldraStockAvailabilityItem, rt as EldraHttpRequest, s as EldraCartGiftCard, sn as EldraContractBody, st as EldraOrderDiscountCode, t as EldraAddCartItemInput, tn as EldraStockAvailability, tt as EldraFormsClient, u as EldraCartTotals, un as EldraContractPath, ut as EldraOrdersClient, v as EldraClientOptions, vn as clearCampaignAttribution, vt as EldraPaginated, w as EldraCmsGetEntryByUniqueFieldOptions, wn as EldraCurrencyPreference, wt as EldraProductExtensions, x as EldraCmsEntryListDisplayMode, xn as withdrawCampaignAttributionConsent, xt as EldraPlatformReadOptions, y as EldraCmsClient, yn as grantCampaignAttributionConsent, yt as EldraPlatformClient, z as EldraCustomerMe, zt as EldraSalesOrderDelivery } from "./types-CycfDCTm.js";
2
+ import { a as StoreAmounts } from "./tokens-f4IxlaN0.js";
2
3
  export declare const DEFAULT_ELDRA_API_BASE_URL = "https://web.eldra.app/api";
3
4
  export declare class EldraHttpError extends Error {
4
5
  readonly status: number;
@@ -232,4 +233,17 @@ interface EldraResponsiveImage {
232
233
  * as `src` and no `srcset`. Returns `undefined` when there is no URL to render.
233
234
  */
234
235
  export declare function responsiveImage(source: EldraImageSource, options: EldraResponsiveImageOptions): EldraResponsiveImage | undefined;
235
- export { type EldraAddCartItemInput, type EldraAuthorizeUrlOptions, type EldraBrand, type EldraCampaignAttribution, type EldraCampaignAttributionOptions, type EldraCart, type EldraCartAppliedCode, type EldraCartClient, type EldraCartDiscountCodeEntry, type EldraCartGiftCard, type EldraCartGiftCardEntry, type EldraCartItem, type EldraCartSession, type EldraCartSessionOptions, type EldraCartTotals, type EldraCatalogClient, type EldraCatalogGetProductOptions, type EldraCatalogListProductsOptions, type EldraCategory, type EldraCheckoutClient, type EldraCheckoutUrlOptions, type EldraClient, type EldraClientOptions, type EldraCmsClient, type EldraCmsEntryList, type EldraCmsEntryListDisplayMode, type EldraCmsEntryListEntry, type EldraCmsEntryListFilterCriterion, type EldraCmsGetEntryByUniqueFieldOptions, type EldraCmsGetOptions, type EldraCmsListOptions, type EldraCmsResolveEntryListOptions, type EldraCmsResolveEntryListResponse, type EldraCmsResolvedEntryList, type EldraCollection, type EldraCollectionList, type EldraCollectionListOptions, type EldraCollectionProductsOptions, type EldraContract, type EldraContractBody, type EldraContractItem, type EldraContractMethod, type EldraContractPath, type EldraContractPaths, type EldraContractProp, type EldraContractQuery, type EldraContractResponse, type EldraCreateSalesOrderInput, type EldraCreateSalesOrderOptions, type EldraCurrencyPreference, type EldraCustomerClient, type EldraCustomerLocation, type EldraCustomerLocationList, type EldraCustomerMe, type EldraCustomerMembership, type EldraDiscountResult, type EldraErrorId, type EldraExchangeCodeOptions, type EldraFeature, type EldraFeatureCapabilities, type EldraFeatureClient, type EldraFormActionKind, type EldraFormDefinition, type EldraFormField, type EldraFormFieldOption, type EldraFormFieldType, type EldraFormLocalized, type EldraFormSubmitInput, type EldraFormSubmitResult, type EldraFormTokenResult, type EldraFormsClient, type EldraHttpClient, type EldraHttpErrorWith, type EldraHttpRequest, type EldraImageSource, type EldraImageSrcsetOptions, type EldraImageVariant, type EldraInventoryClient, type EldraKeyValueStorage, type EldraLocaleOptions, type EldraLogoutUrlOptions, type EldraOidcTokens, type EldraOrder, type EldraOrderAccessTokenOptions, type EldraOrderAccessTokens, type EldraOrderDiscountCode, type EldraOrderLine, type EldraOrderReadOptions, type EldraOrdersClient, type EldraOrganizationCommerce, type EldraOrganizationDetails, type EldraOrganizationFeature, type EldraOrganizationLocales, type EldraOrganizationOptions, type EldraPageMeta, type EldraPaginated, type EldraPkcePair, type EldraPlatformClient, type EldraPlatformConfig, type EldraPlatformReadOptions, type EldraProblemErrors, type EldraProductDetails, type EldraProductExtensions, type EldraProductList, type EldraProductListItem, type EldraProductMediaLink, type EldraProductOption, type EldraProductOptionValue, type EldraProductThumbnail, type EldraProductVariant, type EldraRecoveredBasket, type EldraRecoveredBasketItem, type EldraRefreshTokensOptions, type EldraRequestContext, type EldraRequestOptions, type EldraResponsiveImage, type EldraResponsiveImageOptions, type EldraRetryOptions, type EldraSalesOrder, type EldraSalesOrderCredit, type EldraSalesOrderDelivery, type EldraSalesOrderErrorId, type EldraSalesOrderLine, type EldraSalesOrderList, type EldraSalesOrderListItem, type EldraSalesOrderListOptions, type EldraSalesOrderPreview, type EldraSalesOrderPreviewInput, type EldraSalesOrderPreviewLine, type EldraSalesOrderStatus, type EldraSalesOrderWarning, type EldraSalesOrdersClient, type EldraSearchOptions, type EldraSearchResponse, type EldraShopErrorId, type EldraShopUser, type EldraSizedImageVariant, type EldraStockAvailability, type EldraStockAvailabilityInput, type EldraStockAvailabilityItem, type EldraTokenClientOptions, type EldraTrackerScript, type EldraTrackerScriptOptions, type RuntimeEnv, type RuntimeValue, captureCampaignAttribution, clearCampaignAttribution, createCartSession, createCurrencyPreference, createOrderAccessTokens, grantCampaignAttributionConsent, readCampaignAttribution, withdrawCampaignAttributionConsent };
236
+ /**
237
+ * The store's amounts for `⟦store …⟧` tokens (WS-1473), from the public delivery read
238
+ * (`GET /delivery/v1/provider-account`): `{ freeShippingThreshold: { ISK: 1500000, EUR: 10000 } }`,
239
+ * in minor units.
240
+ *
241
+ * `freeShippingThreshold` in a currency is the **lowest** threshold among the active delivery
242
+ * methods that sell in it: "free shipping over" the least a shopper can spend to get it. A method
243
+ * publishes its threshold per currency in `currencyPrices` (Core, WS-1473), and before that only in
244
+ * its own `currency`; both are read, so this works against either gateway. A threshold of `0` is
245
+ * kept (that method always ships free). A currency no method has a threshold in is absent, and a
246
+ * token naming it hides its sentence rather than guessing.
247
+ */
248
+ export declare function storeAmountsFromDelivery(accounts: unknown): StoreAmounts;
249
+ export { type EldraAddCartItemInput, type EldraAuthorizeUrlOptions, type EldraBrand, type EldraCampaignAttribution, type EldraCampaignAttributionOptions, type EldraCart, type EldraCartAppliedCode, type EldraCartClient, type EldraCartDiscountCodeEntry, type EldraCartGiftCard, type EldraCartGiftCardEntry, type EldraCartItem, type EldraCartSession, type EldraCartSessionOptions, type EldraCartTotals, type EldraCatalogClient, type EldraCatalogGetProductOptions, type EldraCatalogListProductsOptions, type EldraCategory, type EldraCheckoutClient, type EldraCheckoutUrlOptions, type EldraClient, type EldraClientOptions, type EldraCmsClient, type EldraCmsEntryList, type EldraCmsEntryListDisplayMode, type EldraCmsEntryListEntry, type EldraCmsEntryListFilterCriterion, type EldraCmsGetEntryByUniqueFieldOptions, type EldraCmsGetOptions, type EldraCmsListOptions, type EldraCmsResolveEntryListOptions, type EldraCmsResolveEntryListResponse, type EldraCmsResolvedEntryList, type EldraCollection, type EldraCollectionList, type EldraCollectionListOptions, type EldraCollectionProductsOptions, type EldraContract, type EldraContractBody, type EldraContractItem, type EldraContractMethod, type EldraContractPath, type EldraContractPaths, type EldraContractProp, type EldraContractQuery, type EldraContractResponse, type EldraCreateSalesOrderInput, type EldraCreateSalesOrderOptions, type EldraCurrencyPreference, type EldraCustomerClient, type EldraCustomerLocation, type EldraCustomerLocationList, type EldraCustomerMe, type EldraCustomerMembership, type EldraDiscountResult, type EldraErrorId, type EldraExchangeCodeOptions, type EldraFeature, type EldraFeatureCapabilities, type EldraFeatureClient, type EldraFormActionKind, type EldraFormDefinition, type EldraFormField, type EldraFormFieldOption, type EldraFormFieldType, type EldraFormLocalized, type EldraFormSubmitInput, type EldraFormSubmitResult, type EldraFormTokenResult, type EldraFormsClient, type EldraHttpClient, type EldraHttpErrorWith, type EldraHttpRequest, type EldraImageSource, type EldraImageSrcsetOptions, type EldraImageVariant, type EldraInventoryClient, type EldraKeyValueStorage, type EldraLocaleOptions, type EldraLogoutUrlOptions, type EldraOidcTokens, type EldraOrder, type EldraOrderAccessTokenOptions, type EldraOrderAccessTokens, type EldraOrderDiscountCode, type EldraOrderLine, type EldraOrderReadOptions, type EldraOrdersClient, type EldraOrganizationCommerce, type EldraOrganizationDetails, type EldraOrganizationFeature, type EldraOrganizationLocales, type EldraOrganizationOptions, type EldraOrganizationRegion, type EldraPageMeta, type EldraPaginated, type EldraPkcePair, type EldraPlatformClient, type EldraPlatformConfig, type EldraPlatformReadOptions, type EldraProblemErrors, type EldraProductDetails, type EldraProductExtensions, type EldraProductList, type EldraProductListItem, type EldraProductMediaLink, type EldraProductOption, type EldraProductOptionValue, type EldraProductThumbnail, type EldraProductVariant, type EldraRecoveredBasket, type EldraRecoveredBasketItem, type EldraRefreshTokensOptions, type EldraRequestContext, type EldraRequestOptions, type EldraResponsiveImage, type EldraResponsiveImageOptions, type EldraRetryOptions, type EldraSalesOrder, type EldraSalesOrderCredit, type EldraSalesOrderDelivery, type EldraSalesOrderErrorId, type EldraSalesOrderLine, type EldraSalesOrderList, type EldraSalesOrderListItem, type EldraSalesOrderListOptions, type EldraSalesOrderPreview, type EldraSalesOrderPreviewInput, type EldraSalesOrderPreviewLine, type EldraSalesOrderStatus, type EldraSalesOrderWarning, type EldraSalesOrdersClient, type EldraSearchOptions, type EldraSearchResponse, type EldraShopErrorId, type EldraShopUser, type EldraSizedImageVariant, type EldraStockAvailability, type EldraStockAvailabilityInput, type EldraStockAvailabilityItem, type EldraTokenClientOptions, type EldraTrackerScript, type EldraTrackerScriptOptions, type RuntimeEnv, type RuntimeValue, type StoreAmounts, captureCampaignAttribution, clearCampaignAttribution, createCartSession, createCurrencyPreference, createOrderAccessTokens, grantCampaignAttributionConsent, readCampaignAttribution, withdrawCampaignAttributionConsent };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as createOrderAccessTokens, a as getEldraClient, c as resolveApiBaseUrl, d as clearCampaignAttribution, f as grantCampaignAttributionConsent, g as createCurrencyPreference, h as createCartSession, i as createEldraClient, l as resolveOrgId, m as withdrawCampaignAttributionConsent, n as EldraHttpError, o as initEldraClient, p as readCampaignAttribution, r as EldraIdempotencyKeyError, s as isEldraError, t as DEFAULT_ELDRA_API_BASE_URL, u as captureCampaignAttribution } from "./client-Bh_8g5xj.js";
1
+ import { _ as createOrderAccessTokens, a as getEldraClient, c as resolveApiBaseUrl, d as clearCampaignAttribution, f as grantCampaignAttributionConsent, g as createCurrencyPreference, h as createCartSession, i as createEldraClient, l as resolveOrgId, m as withdrawCampaignAttributionConsent, n as EldraHttpError, o as initEldraClient, p as readCampaignAttribution, r as EldraIdempotencyKeyError, s as isEldraError, t as DEFAULT_ELDRA_API_BASE_URL, u as captureCampaignAttribution, v as storeAmountsFromDelivery } from "./client-DKlrCcLO.js";
2
2
  // src/oidc.ts
3
3
  var EldraOidcError = class extends Error {
4
4
  status;
@@ -259,4 +259,4 @@ function responsiveImage(source, options) {
259
259
  }
260
260
  return image;
261
261
  }
262
- export { DEFAULT_ELDRA_API_BASE_URL, ELDRA_IMAGE_VARIANT_WIDTHS, ELDRA_SHOP_CLIENT_ID, EldraHttpError, EldraIdempotencyKeyError, EldraOidcError, analyticsTrackerScript, bearer, buildAuthorizeUrl, buildLogoutUrl, captureCampaignAttribution, clearCampaignAttribution, createCartSession, createCurrencyPreference, createEldraClient, createOrderAccessTokens, createPkcePair, customerHeaders, exchangeAuthorizationCode, getEldraClient, grantCampaignAttributionConsent, imageSrcset, imageUrl, imageVariantFor, initEldraClient, isEldraError, isEldraImage, pkceChallenge, readCampaignAttribution, refreshTokens, responsiveImage, shopIssuer, withdrawCampaignAttributionConsent };
262
+ export { DEFAULT_ELDRA_API_BASE_URL, ELDRA_IMAGE_VARIANT_WIDTHS, ELDRA_SHOP_CLIENT_ID, EldraHttpError, EldraIdempotencyKeyError, EldraOidcError, analyticsTrackerScript, bearer, buildAuthorizeUrl, buildLogoutUrl, captureCampaignAttribution, clearCampaignAttribution, createCartSession, createCurrencyPreference, createEldraClient, createOrderAccessTokens, createPkcePair, customerHeaders, exchangeAuthorizationCode, getEldraClient, grantCampaignAttributionConsent, imageSrcset, imageUrl, imageVariantFor, initEldraClient, isEldraError, isEldraImage, pkceChallenge, readCampaignAttribution, refreshTokens, responsiveImage, shopIssuer, storeAmountsFromDelivery, withdrawCampaignAttributionConsent };
@@ -0,0 +1,121 @@
1
+ /**
2
+ * **Price tokens**: a price inside any CMS text field, held as one merchant-entered amount per
3
+ * currency and written in the shopper's currency when the page renders (WS-1474), or a store
4
+ * setting such as the free-shipping threshold, whose amounts live in the store's own settings
5
+ * (WS-1473).
6
+ *
7
+ * A token sits inside an ordinary string between U+27E6 `⟦` and U+27E7 `⟧`, characters reserved for
8
+ * tokens so they can never collide with Studio's `{{variable}}` syntax:
9
+ *
10
+ * ```text
11
+ * ⟦price#a3f ISK=1500000 EUR=10000⟧ one price, amounts in minor units per currency
12
+ * ⟦store freeShippingThreshold⟧ a store setting
13
+ * ```
14
+ *
15
+ * - `#a3f` is a short id (`[a-z0-9]{3,8}`) tying one price's copies across a field's locales.
16
+ * - Each amount is an ISO 4217 code and a non-negative integer in that currency's **minor units**,
17
+ * entered by the merchant for that currency: never converted from another one.
18
+ * - Exactly one space separates the parts; there is no escaping. Studio writes tokens, merchants
19
+ * never type them, and Core refuses a malformed one on write.
20
+ *
21
+ * Rich text carries the same price as an inline `price` node (`@eldrajs/rich-text`), not bracket
22
+ * text; {@link resolvePriceNode} resolves its attributes with the same rules.
23
+ *
24
+ * **What a page shows**: the amount for the shopper's currency, formatted like every other price.
25
+ * When it cannot (no amount in that currency, an unknown setting, a malformed token), the
26
+ * **sentence** holding the token is left out, never converted, never another currency's amount,
27
+ * never a raw token: {@link resolveTokens}.
28
+ *
29
+ * Framework-free and side-effect free; the shared contract is
30
+ * `side-session-notes/…/price-tokens-spec.md` until it lands in `docs/themes.md`.
31
+ */
32
+ declare const TOKEN_OPEN = "⟦";
33
+ declare const TOKEN_CLOSE = "⟧";
34
+ /** The store settings a `⟦store …⟧` token may name. */
35
+ declare const STORE_TOKEN_NAMES: readonly ["freeShippingThreshold"];
36
+ type StoreTokenName = (typeof STORE_TOKEN_NAMES)[number];
37
+ /** A price: amounts in minor units, keyed by ISO 4217 code. */
38
+ interface PriceToken {
39
+ kind: 'price';
40
+ id: string;
41
+ amounts: Record<string, number>;
42
+ }
43
+ /** A store setting the site fills in from the store's own settings. */
44
+ interface StoreToken {
45
+ kind: 'store';
46
+ name: string;
47
+ }
48
+ /** Bracketed text that is not a well-formed token; it never resolves. */
49
+ interface InvalidToken {
50
+ kind: 'invalid';
51
+ raw: string;
52
+ }
53
+ type Token = PriceToken | StoreToken;
54
+ type TokenSegment = string | Token | InvalidToken;
55
+ /**
56
+ * Amounts the store publishes for its settings, in minor units per currency:
57
+ * `{ freeShippingThreshold: { ISK: 1500000, EUR: 10000 } }`.
58
+ */
59
+ type StoreAmounts = Partial<Record<string, Record<string, number>>>;
60
+ interface ResolveTokensOptions {
61
+ /** The shopper's currency, ISO 4217. Absent: nothing resolves, every token's sentence hides. */
62
+ currency: string | null | undefined;
63
+ /** The locale money is written in: the organisation's regional format. */
64
+ locale: string;
65
+ /** The store's own amounts, for `⟦store …⟧` tokens. */
66
+ storeAmounts?: StoreAmounts | null;
67
+ /**
68
+ * Writes a major-unit amount. Default `formatPrice` (`@eldrajs/sdk/format`); a theme passes its
69
+ * own so a token and a `<Price>` beside it can never disagree.
70
+ */
71
+ format?: (amount: number, currency: string, locale: string) => string;
72
+ }
73
+ /** Whether the text holds any token bracket at all; the cheap test before anything else. */
74
+ declare function hasTokens(text: string): boolean;
75
+ /** The token inside one pair of brackets, or `null` when it is not well formed. */
76
+ declare function parseToken(body: string): Token | null;
77
+ /**
78
+ * The text split into plain runs and tokens, in order. A stray bracket, or a bracket pair that is
79
+ * not a well-formed token, becomes an `invalid` segment.
80
+ */
81
+ declare function parseTokens(text: string): TokenSegment[];
82
+ /** The token as Studio writes it: `⟦price#a3f EUR=10000 ISK=1500000⟧`, codes sorted. */
83
+ declare function serializeToken(token: Token): string;
84
+ /** How many minor units a major unit of the currency has: `ISK` 0, `EUR` 2, `KWD` 3. */
85
+ declare function minorUnitDigits(currency: string): number;
86
+ /** A minor-unit amount in major units: `toMajorUnits(10050, 'EUR')` is `100.5`. */
87
+ declare function toMajorUnits(amount: number, currency: string): number;
88
+ /** A major-unit amount in minor units, rounded: what Studio stores from what a merchant types. */
89
+ declare function toMinorUnits(amount: number, currency: string): number;
90
+ /** The minor-unit amount a token stands for in the currency, or `null` when it has none. */
91
+ declare function tokenAmount(token: Token, currency: string | null | undefined, storeAmounts?: StoreAmounts | null): number | null;
92
+ /** One token written in the shopper's currency, or `null` when it cannot be. */
93
+ declare function formatToken(token: Token, options: ResolveTokensOptions): string | null;
94
+ /**
95
+ * A rich-text `price` node's attributes as a token: `{ id, amounts }` is a price, `{ setting }` a
96
+ * store setting. `null` for attributes that are neither.
97
+ */
98
+ declare function priceNodeToken(attrs: unknown): Token | null;
99
+ /** A rich-text `price` node written in the shopper's currency, or `null` when it cannot be. */
100
+ declare function resolvePriceNode(attrs: unknown, options: ResolveTokensOptions): string | null;
101
+ /**
102
+ * How many characters one token counts as toward a field's `maxLength`: about what a written price
103
+ * is ("15.000 kr.", "€100.00"), not the length of its bracket text, which grows with every
104
+ * currency and would refuse "Free delivery over ⟦store freeShippingThreshold⟧" in a 40-character
105
+ * field.
106
+ */
107
+ declare const TOKEN_TEXT_LENGTH = 10;
108
+ /**
109
+ * The text a `maxLength` validator counts: each well-formed token replaced by
110
+ * {@link TOKEN_TEXT_LENGTH} characters, everything else as it is, so the validator keeps counting
111
+ * the way it already does. Core and Studio count this, never the raw value.
112
+ */
113
+ declare function lengthText(text: string): string;
114
+ /**
115
+ * The text with every token written in the shopper's currency. A sentence holding a token that
116
+ * cannot be written is left out whole, keeping any preview payload it carried (see `STEGA_CHARS`),
117
+ * so a missing amount reads as a shorter text, never as a broken one. Text without tokens is
118
+ * returned as it is.
119
+ */
120
+ declare function resolveTokens(text: string, options: ResolveTokensOptions): string;
121
+ export { toMajorUnits as C, serializeToken as S, tokenAmount as T, parseToken as _, StoreAmounts as a, resolvePriceNode as b, TOKEN_CLOSE as c, Token as d, TokenSegment as f, minorUnitDigits as g, lengthText as h, STORE_TOKEN_NAMES as i, TOKEN_OPEN as l, hasTokens as m, PriceToken as n, StoreToken as o, formatToken as p, ResolveTokensOptions as r, StoreTokenName as s, InvalidToken as t, TOKEN_TEXT_LENGTH as u, parseTokens as v, toMinorUnits as w, resolveTokens as x, priceNodeToken as y };
@@ -0,0 +1,2 @@
1
+ import { C as toMajorUnits, S as serializeToken, T as tokenAmount, _ as parseToken, a as StoreAmounts, b as resolvePriceNode, c as TOKEN_CLOSE, d as Token, f as TokenSegment, g as minorUnitDigits, h as lengthText, i as STORE_TOKEN_NAMES, l as TOKEN_OPEN, m as hasTokens, n as PriceToken, o as StoreToken, p as formatToken, r as ResolveTokensOptions, s as StoreTokenName, t as InvalidToken, u as TOKEN_TEXT_LENGTH, v as parseTokens, w as toMinorUnits, x as resolveTokens, y as priceNodeToken } from "./tokens-f4IxlaN0.js";
2
+ export { InvalidToken, PriceToken, ResolveTokensOptions, STORE_TOKEN_NAMES, StoreAmounts, StoreToken, StoreTokenName, TOKEN_CLOSE, TOKEN_OPEN, TOKEN_TEXT_LENGTH, Token, TokenSegment, formatToken, hasTokens, lengthText, minorUnitDigits, parseToken, parseTokens, priceNodeToken, resolvePriceNode, resolveTokens, serializeToken, toMajorUnits, toMinorUnits, tokenAmount };
package/dist/tokens.js ADDED
@@ -0,0 +1,245 @@
1
+ import { n as numberFormat, t as formatPrice } from "./number-nkpzAc71.js";
2
+ // src/tokens.ts
3
+ /**
4
+ * **Price tokens**: a price inside any CMS text field, held as one merchant-entered amount per
5
+ * currency and written in the shopper's currency when the page renders (WS-1474), or a store
6
+ * setting such as the free-shipping threshold, whose amounts live in the store's own settings
7
+ * (WS-1473).
8
+ *
9
+ * A token sits inside an ordinary string between U+27E6 `⟦` and U+27E7 `⟧`, characters reserved for
10
+ * tokens so they can never collide with Studio's `{{variable}}` syntax:
11
+ *
12
+ * ```text
13
+ * ⟦price#a3f ISK=1500000 EUR=10000⟧ one price, amounts in minor units per currency
14
+ * ⟦store freeShippingThreshold⟧ a store setting
15
+ * ```
16
+ *
17
+ * - `#a3f` is a short id (`[a-z0-9]{3,8}`) tying one price's copies across a field's locales.
18
+ * - Each amount is an ISO 4217 code and a non-negative integer in that currency's **minor units**,
19
+ * entered by the merchant for that currency: never converted from another one.
20
+ * - Exactly one space separates the parts; there is no escaping. Studio writes tokens, merchants
21
+ * never type them, and Core refuses a malformed one on write.
22
+ *
23
+ * Rich text carries the same price as an inline `price` node (`@eldrajs/rich-text`), not bracket
24
+ * text; {@link resolvePriceNode} resolves its attributes with the same rules.
25
+ *
26
+ * **What a page shows**: the amount for the shopper's currency, formatted like every other price.
27
+ * When it cannot (no amount in that currency, an unknown setting, a malformed token), the
28
+ * **sentence** holding the token is left out, never converted, never another currency's amount,
29
+ * never a raw token: {@link resolveTokens}.
30
+ *
31
+ * Framework-free and side-effect free; the shared contract is
32
+ * `side-session-notes/…/price-tokens-spec.md` until it lands in `docs/themes.md`.
33
+ */
34
+ const TOKEN_OPEN = "⟦";
35
+ const TOKEN_CLOSE = "⟧";
36
+ /** The store settings a `⟦store …⟧` token may name. */
37
+ const STORE_TOKEN_NAMES = ["freeShippingThreshold"];
38
+ const ID = /^[a-z0-9]{3,8}$/;
39
+ const CURRENCY = /^[A-Z]{3}$/;
40
+ const AMOUNT = /^(0|[1-9][0-9]*)$/;
41
+ const NAME = /^[a-z][A-Za-z0-9]*$/;
42
+ /** A bracket pair with no bracket inside it. */
43
+ const TOKEN_RUN = /⟦([^⟦⟧]*)⟧/g;
44
+ /** Studio's preview payload (`@eldrajs/theme-core/stega`): kept when its sentence is left out. */
45
+ const STEGA_CHARS = /[​‌]/g;
46
+ /** Whether the text holds any token bracket at all; the cheap test before anything else. */
47
+ function hasTokens(text) {
48
+ return text.includes("⟦") || text.includes("⟧");
49
+ }
50
+ /** The token inside one pair of brackets, or `null` when it is not well formed. */
51
+ function parseToken(body) {
52
+ const parts = body.split(" ");
53
+ const head = parts[0] ?? "";
54
+ if (head === "store") {
55
+ const name = parts[1] ?? "";
56
+ return parts.length === 2 && NAME.test(name) ? {
57
+ kind: "store",
58
+ name
59
+ } : null;
60
+ }
61
+ if (!head.startsWith("price#")) return null;
62
+ const id = head.slice(6);
63
+ if (!ID.test(id)) return null;
64
+ const amounts = {};
65
+ for (const part of parts.slice(1)) {
66
+ const [code, amount, extra] = part.split("=");
67
+ if (extra !== void 0 || code === void 0 || amount === void 0) return null;
68
+ if (!CURRENCY.test(code) || !AMOUNT.test(amount) || code in amounts) return null;
69
+ const value = Number(amount);
70
+ if (!Number.isSafeInteger(value)) return null;
71
+ amounts[code] = value;
72
+ }
73
+ return {
74
+ kind: "price",
75
+ id,
76
+ amounts
77
+ };
78
+ }
79
+ /**
80
+ * The text split into plain runs and tokens, in order. A stray bracket, or a bracket pair that is
81
+ * not a well-formed token, becomes an `invalid` segment.
82
+ */
83
+ function parseTokens(text) {
84
+ if (!hasTokens(text)) return text === "" ? [] : [text];
85
+ const segments = [];
86
+ let at = 0;
87
+ const pushText = (run) => {
88
+ if (run === "") return;
89
+ const stray = run.search(/[⟦⟧]/);
90
+ if (stray === -1) {
91
+ segments.push(run);
92
+ return;
93
+ }
94
+ if (stray > 0) segments.push(run.slice(0, stray));
95
+ segments.push({
96
+ kind: "invalid",
97
+ raw: run.slice(stray)
98
+ });
99
+ };
100
+ TOKEN_RUN.lastIndex = 0;
101
+ for (let match = TOKEN_RUN.exec(text); match !== null; match = TOKEN_RUN.exec(text)) {
102
+ pushText(text.slice(at, match.index));
103
+ segments.push(parseToken(match[1] ?? "") ?? {
104
+ kind: "invalid",
105
+ raw: match[0]
106
+ });
107
+ at = match.index + match[0].length;
108
+ }
109
+ pushText(text.slice(at));
110
+ return segments;
111
+ }
112
+ /** The token as Studio writes it: `⟦price#a3f EUR=10000 ISK=1500000⟧`, codes sorted. */
113
+ function serializeToken(token) {
114
+ if (token.kind === "store") return `⟦store ${token.name}⟧`;
115
+ const amounts = Object.keys(token.amounts).sort().map((code) => ` ${code}=${token.amounts[code]}`).join("");
116
+ return `⟦price#${token.id}${amounts}⟧`;
117
+ }
118
+ /** How many minor units a major unit of the currency has: `ISK` 0, `EUR` 2, `KWD` 3. */
119
+ function minorUnitDigits(currency) {
120
+ try {
121
+ return numberFormat("en", {
122
+ style: "currency",
123
+ currency
124
+ }).resolvedOptions().maximumFractionDigits;
125
+ } catch {
126
+ return 2;
127
+ }
128
+ }
129
+ /** A minor-unit amount in major units: `toMajorUnits(10050, 'EUR')` is `100.5`. */
130
+ function toMajorUnits(amount, currency) {
131
+ return amount / 10 ** minorUnitDigits(currency);
132
+ }
133
+ /** A major-unit amount in minor units, rounded: what Studio stores from what a merchant types. */
134
+ function toMinorUnits(amount, currency) {
135
+ return Math.round(amount * 10 ** minorUnitDigits(currency));
136
+ }
137
+ /** The minor-unit amount a token stands for in the currency, or `null` when it has none. */
138
+ function tokenAmount(token, currency, storeAmounts) {
139
+ if (currency === null || currency === void 0 || currency === "") return null;
140
+ const amount = (token.kind === "price" ? token.amounts : storeAmounts?.[token.name])?.[currency];
141
+ return typeof amount === "number" && Number.isFinite(amount) && amount >= 0 ? amount : null;
142
+ }
143
+ /** One token written in the shopper's currency, or `null` when it cannot be. */
144
+ function formatToken(token, options) {
145
+ const amount = tokenAmount(token, options.currency, options.storeAmounts);
146
+ if (amount === null) return null;
147
+ const currency = options.currency;
148
+ const format = options.format ?? formatPrice;
149
+ try {
150
+ return format(toMajorUnits(amount, currency), currency, options.locale);
151
+ } catch {
152
+ return null;
153
+ }
154
+ }
155
+ /**
156
+ * A rich-text `price` node's attributes as a token: `{ id, amounts }` is a price, `{ setting }` a
157
+ * store setting. `null` for attributes that are neither.
158
+ */
159
+ function priceNodeToken(attrs) {
160
+ if (attrs === null || typeof attrs !== "object") return null;
161
+ const { id, amounts, setting } = attrs;
162
+ if (typeof setting === "string" && NAME.test(setting)) return {
163
+ kind: "store",
164
+ name: setting
165
+ };
166
+ if (typeof id !== "string" || !ID.test(id)) return null;
167
+ if (amounts === null || typeof amounts !== "object" || Array.isArray(amounts)) return null;
168
+ const clean = {};
169
+ for (const [code, amount] of Object.entries(amounts)) {
170
+ if (!CURRENCY.test(code)) return null;
171
+ if (typeof amount !== "number" || !Number.isSafeInteger(amount) || amount < 0) return null;
172
+ clean[code] = amount;
173
+ }
174
+ return {
175
+ kind: "price",
176
+ id,
177
+ amounts: clean
178
+ };
179
+ }
180
+ /** A rich-text `price` node written in the shopper's currency, or `null` when it cannot be. */
181
+ function resolvePriceNode(attrs, options) {
182
+ const token = priceNodeToken(attrs);
183
+ return token === null ? null : formatToken(token, options);
184
+ }
185
+ /**
186
+ * How many characters one token counts as toward a field's `maxLength`: about what a written price
187
+ * is ("15.000 kr.", "€100.00"), not the length of its bracket text, which grows with every
188
+ * currency and would refuse "Free delivery over ⟦store freeShippingThreshold⟧" in a 40-character
189
+ * field.
190
+ */
191
+ const TOKEN_TEXT_LENGTH = 10;
192
+ /**
193
+ * The text a `maxLength` validator counts: each well-formed token replaced by
194
+ * {@link TOKEN_TEXT_LENGTH} characters, everything else as it is, so the validator keeps counting
195
+ * the way it already does. Core and Studio count this, never the raw value.
196
+ */
197
+ function lengthText(text) {
198
+ if (!hasTokens(text)) return text;
199
+ return parseTokens(text).map((segment) => typeof segment === "string" ? segment : segment.kind === "invalid" ? segment.raw : "0".repeat(10)).join("");
200
+ }
201
+ /** The text's sentences, by `Intl.Segmenter` where the runtime has it, else the whole text. */
202
+ function sentences(text, locale) {
203
+ const Segmenter = Intl.Segmenter;
204
+ if (Segmenter === void 0) return [text];
205
+ try {
206
+ return Array.from(new Segmenter(locale, { granularity: "sentence" }).segment(text), (s) => s.segment);
207
+ } catch {
208
+ return [text];
209
+ }
210
+ }
211
+ /** One sentence with its tokens written out, or `null` when any of them cannot be. */
212
+ function resolveSentence(sentence, options) {
213
+ let out = "";
214
+ for (const segment of parseTokens(sentence)) {
215
+ if (typeof segment === "string") {
216
+ out += segment;
217
+ continue;
218
+ }
219
+ if (segment.kind === "invalid") return null;
220
+ const written = formatToken(segment, options);
221
+ if (written === null) return null;
222
+ out += written;
223
+ }
224
+ return out;
225
+ }
226
+ /**
227
+ * The text with every token written in the shopper's currency. A sentence holding a token that
228
+ * cannot be written is left out whole, keeping any preview payload it carried (see `STEGA_CHARS`),
229
+ * so a missing amount reads as a shorter text, never as a broken one. Text without tokens is
230
+ * returned as it is.
231
+ */
232
+ function resolveTokens(text, options) {
233
+ if (!hasTokens(text)) return text;
234
+ const whole = resolveSentence(text, options);
235
+ if (whole !== null) return whole;
236
+ let kept = "";
237
+ let payload = "";
238
+ for (const sentence of sentences(text, options.locale)) {
239
+ const written = resolveSentence(sentence, options);
240
+ if (written !== null) kept += written;
241
+ else payload += (sentence.match(STEGA_CHARS) ?? []).join("");
242
+ }
243
+ return kept.trimEnd() + payload;
244
+ }
245
+ export { STORE_TOKEN_NAMES, TOKEN_CLOSE, TOKEN_OPEN, TOKEN_TEXT_LENGTH, formatToken, hasTokens, lengthText, minorUnitDigits, parseToken, parseTokens, priceNodeToken, resolvePriceNode, resolveTokens, serializeToken, toMajorUnits, toMinorUnits, tokenAmount };
@@ -1,3 +1,4 @@
1
+ import { a as StoreAmounts } from "./tokens-f4IxlaN0.js";
1
2
  interface EldraKeyValueStorage {
2
3
  getItem(key: string): string | null;
3
4
  setItem(key: string, value: string): void;
@@ -293,6 +294,23 @@ interface EldraOrganizationLocales {
293
294
  /** Every configured locale, `default` first, e.g. `["en-US", "is-IS"]`. */
294
295
  supported: string[];
295
296
  }
297
+ /**
298
+ * The organisation's **regional format**, as the public organisation read publishes it under
299
+ * `region` (the gateway's `dto_OrganizationRegion`): how money, numbers and dates are written and
300
+ * which clock they are read on. It is the merchant's choice in Studio and is independent of the
301
+ * content locale — an English-language Icelandic store writes `4.790 kr.` and `26. nóvember 2026`.
302
+ *
303
+ * Hand-written for the same reason `EldraOrganizationCommerce` is — the organisation read backs
304
+ * every `features.*` method and has to resolve without the Vite plugin's generated `contract.ts`.
305
+ */
306
+ interface EldraOrganizationRegion {
307
+ /** ISO 3166-1 alpha-2, upper case, e.g. `IS`; `''` until the merchant sets a country. */
308
+ countryCode: string;
309
+ /** BCP 47 tag, canonicalised, to format with (`Intl.NumberFormat`, `Intl.DateTimeFormat`), e.g. `is-IS`. */
310
+ formatLocale: string;
311
+ /** IANA time zone to show the organisation's dates and times in, e.g. `Atlantic/Reykjavik`. */
312
+ timeZone: string;
313
+ }
296
314
  interface EldraOrganizationDetails {
297
315
  id: string;
298
316
  name: string;
@@ -302,6 +320,8 @@ interface EldraOrganizationDetails {
302
320
  commerce?: EldraOrganizationCommerce | null;
303
321
  /** See `EldraOrganizationLocales`: absent, or `null`, until the organisation configures any. */
304
322
  locales?: EldraOrganizationLocales | null;
323
+ /** See `EldraOrganizationRegion`: read it through `features.getRegion()`, which validates it. */
324
+ region?: EldraOrganizationRegion | null;
305
325
  paymentProviders?: EldraOrganizationPaymentProvider[];
306
326
  createdAt?: string;
307
327
  updatedAt?: string;
@@ -369,6 +389,23 @@ interface EldraFeatureClient {
369
389
  * `default` is always first in `supported`, and duplicates are collapsed.
370
390
  */
371
391
  getLocales(options?: EldraOrganizationOptions, context?: EldraRequestContext): Promise<EldraOrganizationLocales | null>;
392
+ /**
393
+ * The organisation's regional format: `{ countryCode, formatLocale, timeZone }`, or `null` when
394
+ * it publishes none. Reads the same organisation document the other `features` methods read.
395
+ *
396
+ * Validated rather than passed through: a `formatLocale` that is not a well-formed BCP 47 tag, a
397
+ * `timeZone` this runtime's `Intl` does not know, or a `countryCode` that is neither empty nor two
398
+ * letters makes the whole record `null` — the same answer as "none published", so a consumer
399
+ * falls back to its own locale instead of throwing a `RangeError` from `Intl` on every price.
400
+ * `formatLocale` is canonicalised (`is-is` → `is-IS`) and `countryCode` upper-cased.
401
+ */
402
+ getRegion(options?: EldraOrganizationOptions, context?: EldraRequestContext): Promise<EldraOrganizationRegion | null>;
403
+ /**
404
+ * The store's amounts for `⟦store …⟧` price tokens (WS-1473), in minor units per currency:
405
+ * `freeShippingThreshold` is the lowest free-shipping threshold among the active delivery
406
+ * methods selling in each currency (`storeAmountsFromDelivery`). Read it once at build time.
407
+ */
408
+ getStoreAmounts(context?: EldraRequestContext): Promise<StoreAmounts>;
372
409
  }
373
410
  interface EldraClient {
374
411
  request<T = unknown>(options: EldraRequestOptions): Promise<T>;
@@ -789,4 +826,4 @@ interface EldraFormsClient {
789
826
  /** `POST /site/v1/forms/subscriptions/unsubscribe?token=` (a GET of the link is only a page). */
790
827
  unsubscribe(token: string, context?: EldraRequestContext): Promise<EldraFormTokenResult>;
791
828
  }
792
- export { EldraFormSubmitResult as $, EldraShopUser as $t, EldraCollection as A, EldraProductVariant as At, EldraCustomerMembership as B, EldraSalesOrderLine as Bt, EldraCmsEntryListFilterCriterion as C, EldraCurrencyPreference as Cn, EldraProductExtensions as Ct, EldraCmsResolveEntryListOptions as D, createCartSession as Dn, EldraProductOption as Dt, EldraCmsListOptions as E, EldraOrderAccessTokens as En, EldraProductMediaLink as Et, EldraCreateSalesOrderOptions as F, EldraRetryOptions as Ft, EldraFeatureClient as G, EldraSalesOrderPreviewInput as Gt, EldraErrorId as H, EldraSalesOrderListItem as Ht, EldraCustomerClient as I, EldraSalesOrder as It, EldraFormField as J, EldraSalesOrderWarning as Jt, EldraFormActionKind as K, EldraSalesOrderPreviewLine as Kt, EldraCustomerLocation as L, EldraSalesOrderCredit as Lt, EldraCollectionListOptions as M, EldraRecoveredBasketItem as Mt, EldraCollectionProductsOptions as N, EldraRequestContext as Nt, EldraCmsResolveEntryListResponse as O, createCurrencyPreference as On, EldraProductOptionValue as Ot, EldraCreateSalesOrderInput as P, EldraRequestOptions as Pt, EldraFormSubmitInput as Q, EldraShopErrorId as Qt, EldraCustomerLocationList as R, EldraSalesOrderDelivery as Rt, EldraCmsEntryListEntry as S, EldraCartSessionOptions as Sn, EldraProductDetails as St, EldraCmsGetOptions as T, EldraOrderAccessTokenOptions as Tn, EldraProductListItem as Tt, EldraFeature as U, EldraSalesOrderListOptions as Ut, EldraDiscountResult as V, EldraSalesOrderList as Vt, EldraFeatureCapabilities as W, EldraSalesOrderPreview as Wt, EldraFormFieldType as X, EldraSearchOptions as Xt, EldraFormFieldOption as Y, EldraSalesOrdersClient as Yt, EldraFormLocalized as Z, EldraSearchResponse as Zt, EldraClient as _, clearCampaignAttribution as _n, EldraPaginated as _t, EldraCartClient as a, EldraContract as an, EldraLocaleOptions as at, EldraCmsEntryList as b, withdrawCampaignAttributionConsent as bn, EldraPlatformReadOptions as bt, EldraCartGiftCardEntry as c, EldraContractMethod as cn, EldraOrderLine as ct, EldraCatalogClient as d, EldraContractProp as dn, EldraOrganizationCommerce as dt, EldraStockAvailability as en, EldraFormTokenResult as et, EldraCatalogGetProductOptions as f, EldraContractQuery as fn, EldraOrganizationDetails as ft, EldraCheckoutUrlOptions as g, captureCampaignAttribution as gn, EldraPageMeta as gt, EldraCheckoutClient as h, EldraCampaignAttributionOptions as hn, EldraOrganizationOptions as ht, EldraCartAppliedCode as i, RuntimeValue as in, EldraInventoryClient as it, EldraCollectionList as j, EldraRecoveredBasket as jt, EldraCmsResolvedEntryList as k, createOrderAccessTokens as kn, EldraProductThumbnail as kt, EldraCartItem as l, EldraContractPath as ln, EldraOrderReadOptions as lt, EldraCategory as m, EldraCampaignAttribution as mn, EldraOrganizationLocales as mt, EldraBrand as n, EldraStockAvailabilityItem as nn, EldraHttpClient as nt, EldraCartDiscountCodeEntry as o, EldraContractBody as on, EldraOrder as ot, EldraCatalogListProductsOptions as p, EldraContractResponse as pn, EldraOrganizationFeature as pt, EldraFormDefinition as q, EldraSalesOrderStatus as qt, EldraCart as r, RuntimeEnv as rn, EldraHttpRequest as rt, EldraCartGiftCard as s, EldraContractItem as sn, EldraOrderDiscountCode as st, EldraAddCartItemInput as t, EldraStockAvailabilityInput as tn, EldraFormsClient as tt, EldraCartTotals as u, EldraContractPaths as un, EldraOrdersClient as ut, EldraClientOptions as v, grantCampaignAttributionConsent as vn, EldraPlatformClient as vt, EldraCmsGetEntryByUniqueFieldOptions as w, EldraKeyValueStorage as wn, EldraProductList as wt, EldraCmsEntryListDisplayMode as x, EldraCartSession as xn, EldraProblemErrors as xt, EldraCmsClient as y, readCampaignAttribution as yn, EldraPlatformConfig as yt, EldraCustomerMe as z, EldraSalesOrderErrorId as zt };
829
+ export { EldraFormSubmitResult as $, EldraShopErrorId as $t, EldraCollection as A, createOrderAccessTokens as An, EldraProductThumbnail as At, EldraCustomerMembership as B, EldraSalesOrderErrorId as Bt, EldraCmsEntryListFilterCriterion as C, EldraCartSessionOptions as Cn, EldraProductDetails as Ct, EldraCmsResolveEntryListOptions as D, EldraOrderAccessTokens as Dn, EldraProductMediaLink as Dt, EldraCmsListOptions as E, EldraOrderAccessTokenOptions as En, EldraProductListItem as Et, EldraCreateSalesOrderOptions as F, EldraRequestOptions as Ft, EldraFeatureClient as G, EldraSalesOrderPreview as Gt, EldraErrorId as H, EldraSalesOrderList as Ht, EldraCustomerClient as I, EldraRetryOptions as It, EldraFormField as J, EldraSalesOrderStatus as Jt, EldraFormActionKind as K, EldraSalesOrderPreviewInput as Kt, EldraCustomerLocation as L, EldraSalesOrder as Lt, EldraCollectionListOptions as M, EldraRecoveredBasket as Mt, EldraCollectionProductsOptions as N, EldraRecoveredBasketItem as Nt, EldraCmsResolveEntryListResponse as O, createCartSession as On, EldraProductOption as Ot, EldraCreateSalesOrderInput as P, EldraRequestContext as Pt, EldraFormSubmitInput as Q, EldraSearchResponse as Qt, EldraCustomerLocationList as R, EldraSalesOrderCredit as Rt, EldraCmsEntryListEntry as S, EldraCartSession as Sn, EldraProblemErrors as St, EldraCmsGetOptions as T, EldraKeyValueStorage as Tn, EldraProductList as Tt, EldraFeature as U, EldraSalesOrderListItem as Ut, EldraDiscountResult as V, EldraSalesOrderLine as Vt, EldraFeatureCapabilities as W, EldraSalesOrderListOptions as Wt, EldraFormFieldType as X, EldraSalesOrdersClient as Xt, EldraFormFieldOption as Y, EldraSalesOrderWarning as Yt, EldraFormLocalized as Z, EldraSearchOptions as Zt, EldraClient as _, captureCampaignAttribution as _n, EldraPageMeta as _t, EldraCartClient as a, RuntimeValue as an, EldraLocaleOptions as at, EldraCmsEntryList as b, readCampaignAttribution as bn, EldraPlatformConfig as bt, EldraCartGiftCardEntry as c, EldraContractItem as cn, EldraOrderLine as ct, EldraCatalogClient as d, EldraContractPaths as dn, EldraOrganizationCommerce as dt, EldraShopUser as en, EldraFormTokenResult as et, EldraCatalogGetProductOptions as f, EldraContractProp as fn, EldraOrganizationDetails as ft, EldraCheckoutUrlOptions as g, EldraCampaignAttributionOptions as gn, EldraOrganizationRegion as gt, EldraCheckoutClient as h, EldraCampaignAttribution as hn, EldraOrganizationOptions as ht, EldraCartAppliedCode as i, RuntimeEnv as in, EldraInventoryClient as it, EldraCollectionList as j, EldraProductVariant as jt, EldraCmsResolvedEntryList as k, createCurrencyPreference as kn, EldraProductOptionValue as kt, EldraCartItem as l, EldraContractMethod as ln, EldraOrderReadOptions as lt, EldraCategory as m, EldraContractResponse as mn, EldraOrganizationLocales as mt, EldraBrand as n, EldraStockAvailabilityInput as nn, EldraHttpClient as nt, EldraCartDiscountCodeEntry as o, EldraContract as on, EldraOrder as ot, EldraCatalogListProductsOptions as p, EldraContractQuery as pn, EldraOrganizationFeature as pt, EldraFormDefinition as q, EldraSalesOrderPreviewLine as qt, EldraCart as r, EldraStockAvailabilityItem as rn, EldraHttpRequest as rt, EldraCartGiftCard as s, EldraContractBody as sn, EldraOrderDiscountCode as st, EldraAddCartItemInput as t, EldraStockAvailability as tn, EldraFormsClient as tt, EldraCartTotals as u, EldraContractPath as un, EldraOrdersClient as ut, EldraClientOptions as v, clearCampaignAttribution as vn, EldraPaginated as vt, EldraCmsGetEntryByUniqueFieldOptions as w, EldraCurrencyPreference as wn, EldraProductExtensions as wt, EldraCmsEntryListDisplayMode as x, withdrawCampaignAttributionConsent as xn, EldraPlatformReadOptions as xt, EldraCmsClient as y, grantCampaignAttributionConsent as yn, EldraPlatformClient as yt, EldraCustomerMe as z, EldraSalesOrderDelivery as zt };
package/dist/vite.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { in as RuntimeValue, rn as RuntimeEnv } from "./types-BrMiT2QA.js";
1
+ import { an as RuntimeValue, in as RuntimeEnv } from "./types-CycfDCTm.js";
2
2
  import { Plugin } from "vite";
3
3
  export interface EldraVitePluginOptions {
4
4
  apiBaseUrl?: RuntimeValue<string>;
package/dist/vite.js CHANGED
@@ -1,4 +1,4 @@
1
- import "./client-Bh_8g5xj.js";
1
+ import "./client-DKlrCcLO.js";
2
2
  import { access, mkdir, writeFile } from "node:fs/promises";
3
3
  import { dirname, resolve } from "node:path";
4
4
  import openapiTS, { astToString } from "openapi-typescript";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eldrajs/sdk",
3
- "version": "0.5.4",
3
+ "version": "0.5.5",
4
4
  "description": "Framework-free client for the Eldra Web Studio public storefront API: CMS, catalog, cart, checkout handoff, orders, inventory. Types generated from your gateway's OpenAPI document and CMS schemas at build time.",
5
5
  "keywords": [
6
6
  "cms",
@@ -59,6 +59,10 @@
59
59
  "types": "./dist/format/intl.d.ts",
60
60
  "import": "./dist/format/intl.js"
61
61
  },
62
+ "./tokens": {
63
+ "types": "./dist/tokens.d.ts",
64
+ "import": "./dist/tokens.js"
65
+ },
62
66
  "./package.json": "./package.json"
63
67
  },
64
68
  "publishConfig": {