Helpers
@eldrajs/sdk exports more than the client. This page lists every helper function, grouped by what you use it for. Most come from the package root. Formatting, price tokens and live value markers have their own entry points, so a page that does not use them does not load them.
| Import from | What it holds |
|---|---|
@eldrajs/sdk | The client, storage, images, analytics, attribution, business login, store amounts |
@eldrajs/sdk/format | Numbers, prices and sorting |
@eldrajs/sdk/format/date | Dates and times |
@eldrajs/sdk/format/list | Lists ("a, b og c") |
@eldrajs/sdk/format/relative-time | Relative times ("fyrir 3 dögum") |
@eldrajs/sdk/format/display-names | Country, language and currency names |
@eldrajs/sdk/format/intl | installIcelandicIntl, for code that calls Intl itself |
@eldrajs/sdk/tokens | Price tokens inside CMS text |
@eldrajs/sdk/live | Live price and stock markers on prerendered pages |
@eldrajs/sdk/vite | The Vite plugin; see The client |
The examples use a shop selling Lopi sweaters. Where a helper takes minor units, it says so. The króna has no minor unit, so 24.900 kr. is 24900 either way.
Cart and session storage
These three keep a small value in the browser between page loads. Each reads and writes through a storage you can replace. None of them throws when storage is missing, blocked or full: a read returns null and a write does nothing.
All three take any object with getItem, setItem and removeItem. Pass storage: null to keep nothing, for example on a server.
createCartSession
Keeps the shopper's cart id, so the basket survives a closed tab. Use it on every add to cart.
createCartSession(options?: { storage?: Storage | null; key?: string }): {
read(): string | null;
remember(cartId: string): void;
forget(): void;
}| Option | Type | Default | What it does |
|---|---|---|---|
storage | storage or null | browser localStorage | Where the cart id is kept. |
key | string | eldra.cartId | The storage key. |
Returns an object that reads, remembers and forgets the cart id.
import { createCartSession } from '@eldrajs/sdk';
const cartSession = createCartSession();
const cart = await eldra.cart.addItem({
cartId: cartSession.read() ?? undefined,
productId: lopiSweater.id,
variantId: greyMedium.id,
quantity: 1,
});
cartSession.remember(cart.id);The server can forget a cart
When a cart call fails with errorId CART_NOT_FOUND, call forget() and start a new cart.
createCurrencyPreference
Keeps the currency a visitor picked, for their next visit. Use it with a currency switcher.
createCurrencyPreference(options?: { storage?: Storage | null; key?: string }): {
read(): string | null;
remember(currency: string): void;
forget(): void;
}| Option | Type | Default | What it does |
|---|---|---|---|
storage | storage or null | browser localStorage | Where the currency is kept. |
key | string | eldra.currency | The storage key. |
Returns an object that reads, remembers and forgets the currency code.
import { createCurrencyPreference } from '@eldrajs/sdk';
const currency = createCurrencyPreference();
async function switchCurrency(code: string) {
currency.remember(code); // 'EUR'
const cartId = cartSession.read();
if (cartId) await eldra.cart.setCurrency(cartId, code);
}
const product = await eldra.catalog.getProduct(lopiSweater.id, {
currency: currency.read() ?? undefined,
});createOrderAccessTokens
Keeps an order's one-time access token for the rest of the browser tab. The order read needs that token unless the caller owns the order. Session storage keeps it out of URLs, logs and referrers.
createOrderAccessTokens(options?: { storage?: Storage | null; keyPrefix?: string }): {
remember(orderId: string, token: string | undefined): void;
read(orderId: string): string | null;
}| Option | Type | Default | What it does |
|---|---|---|---|
storage | storage or null | browser sessionStorage | Where the tokens are kept. |
keyPrefix | string | eldra.orderAccessToken. | Put before the order id to make each storage key. |
Returns an object that remembers and reads a token per order. remember ignores an undefined token.
import { createOrderAccessTokens } from '@eldrajs/sdk';
const orderTokens = createOrderAccessTokens();
orderTokens.remember(orderId, accessToken);
// On the order confirmation page:
const order = await eldra.orders.get(orderId, {
accessToken: orderTokens.read(orderId) ?? undefined,
});Images
A media URL from the API serves an 800 px copy. These helpers build URLs for the other sizes the media host serves, and a srcset across them. Anything that is not an Eldra media asset comes back unchanged. Choosing sizes, reserving space and art direction are in Images.
The variants and their widths are exported as ELDRA_IMAGE_VARIANT_WIDTHS:
| Variant | Max width |
|---|---|
sm | 400 px |
md | 800 px |
lg | 1200 px |
xl | 1920 px |
full | 2560 px |
uhd | 3840 px |
original is the uploaded file, untouched. The host only scales down, so a narrower original stays at its own width.
Every image helper takes a source: a URL string, or any object with a url, such as a product thumbnail, a mediaLinks item or a CMS media item. An object's contentType, width and height are used when present.
responsiveImage
Builds every attribute an <img> needs in one call. Use it for most images.
responsiveImage(
source: EldraImageSource,
options: { sizes: string; variant?; aspectRatio?; width?; height?; originalWidth? }
): { src: string; srcset?: string; sizes?: string; width?: number; height?: number } | undefined| Option | Type | Default | What it does |
|---|---|---|---|
sizes | string | — | How wide the image is laid out, as an <img sizes> value. Required. |
variant | 'sm' … 'uhd' | md | The variant in src, for a browser that ignores srcset. |
aspectRatio | number | — | Width over height of the box, such as 4 / 5. Sets width and height to reserve the space. |
width, height | number | — | Explicit width and height. Used only when both are given; they win over everything else. |
originalWidth | number | the source's width | The original's width. The srcset stops there. |
Returns attributes to spread onto <img>, or undefined when there is no URL. An external image gets its URL as src and no srcset.
import { responsiveImage } from '@eldrajs/sdk';
const image = responsiveImage(sweater.thumbnail, {
sizes: '(min-width: 1024px) 25vw, 50vw', // four across, two on phones
aspectRatio: 4 / 5,
});
// { src: '…/md', srcset: '…/sm 400w, …/md 800w, …', sizes: '…', width: 800, height: 1000 }imageSrcset
Builds only the srcset value. Use it when you set the other attributes yourself.
imageSrcset(source: EldraImageSource, options?: { originalWidth?: number }): string | undefined| Option | Type | Default | What it does |
|---|---|---|---|
originalWidth | number | the source's width | The original's width. Wider variants are dropped. An original wider than uhd is added last, at its width. |
Returns the srcset string, or undefined for anything that is not a resizable Eldra image.
import { imageSrcset } from '@eldrajs/sdk';
const srcset = imageSrcset(sweater.thumbnail, { originalWidth: 1500 });
// '…/sm 400w, …/md 800w, …/lg 1200w, …/xl 1500w'The source's width needs its height
The source's own size is only used when it has both width and height. With width alone, pass originalWidth.
imageUrl
The URL of one variant. Use it for a single fixed size, such as a social share image.
imageUrl(source: EldraImageSource, variant: 'sm' | 'md' | 'lg' | 'xl' | 'full' | 'uhd' | 'original'): string | undefinedReturns the variant's URL. A URL that already names a variant is switched. Any other URL comes back unchanged. undefined when there is no URL.
import { imageUrl } from '@eldrajs/sdk';
const ogImage = imageUrl(sweater.thumbnail, 'lg');imageVariantFor
Picks the narrowest variant that covers a width at a pixel density.
imageVariantFor(width: number, density?: number): 'sm' | 'md' | 'lg' | 'xl' | 'full' | 'uhd'| Parameter | Type | Default | What it does |
|---|---|---|---|
width | number | — | The width in CSS pixels. |
density | number | 1 | The device pixel ratio. |
Returns the variant, or uhd when none is wide enough. Throws a RangeError for a width that is not positive.
import { imageUrl, imageVariantFor } from '@eldrajs/sdk';
const thumb = imageUrl(sweater.thumbnail, imageVariantFor(300, 2)); // '…/md'isEldraImage
Tells whether a source is an Eldra media asset the host can resize.
isEldraImage(source: EldraImageSource): booleanReturns true for a resizable Eldra asset. false for an external URL, an SVG, a GIF or no URL.
import { isEldraImage } from '@eldrajs/sdk';
const loading = isEldraImage(banner) ? 'lazy' : 'eager';Analytics
analyticsTrackerScript
Builds the attributes of the analytics <script> tag. It reads the same options as the client, so the script and your reads always point at the same gateway. A theme on @eldrajs/theme-nuxt does this for you.
analyticsTrackerScript(options?: { orgId?; apiBaseUrl?; env?; eventOrigin?: string }): {
src: string;
defer: true;
crossorigin: 'anonymous';
'data-org': string;
'data-api'?: string;
} | undefined| Option | Type | Default | What it does |
|---|---|---|---|
orgId | string, or a function | read from env | The organisation the events count for. |
apiBaseUrl | string, or a function | read from env, else https://web.eldra.app/api | The script loads from this gateway's origin. |
env | object, or a function | — | Where to read orgId and apiBaseUrl, as on the client. |
eventOrigin | string | — | Where events go when you proxy them through your own domain. |
Returns the script attributes, or undefined when no organisation id is set. Leave the id unset in builds that should not report.
import { analyticsTrackerScript } from '@eldrajs/sdk';
const tracker = analyticsTrackerScript({ env: process.env });
useHead({ script: tracker ? [tracker] : [] });Events count only from a site address registered in Studio, under Settings → General → Site addresses. See Analytics tracker.
Campaign attribution
A merchant's campaign emails link to the shop with utm_source, utm_medium, utm_campaign and utm_id. These helpers note that landing. Once the visitor consents, cart.addItem sends it with every add, so Eldra credits the order to the campaign.
Nothing is kept before consent. The kit stores only the four campaign tags, never anything about the visitor. On a server nothing is kept at all. Kept landings expire after 30 days.
Each function takes { storage }. Give them all, and the client's campaignAttribution option, the same storage.
captureCampaignAttribution
Notes the campaign tags in a URL. Call it on the first page and after every navigation.
captureCampaignAttribution(
url?: string | URL,
options?: { storage?: Storage | null; maxAgeMs?: number }
): { campaignId?; utmSource?; utmMedium?; utmCampaign? } | null| Option | Type | Default | What it does |
|---|---|---|---|
url | string | URL | location.href | The URL to read the tags from. |
storage | storage or null | localStorage in a browser, none elsewhere | Where the landing is kept once the visitor consents. |
maxAgeMs | number | 30 days | How long the landing counts, from now. |
Returns the tags found, or null when the URL has none. Until consent, the landing is held in memory for this page load only.
import { captureCampaignAttribution } from '@eldrajs/sdk';
captureCampaignAttribution(); // the page the visitor landed on
router.afterEach((to, _from, failure) => {
if (!failure) captureCampaignAttribution(to.fullPath);
});grantCampaignAttributionConsent
Records that the visitor agreed. The landing from this page load is kept now, and later ones as they come. Call it from your consent tool.
grantCampaignAttributionConsent(options?: { storage?: Storage | null }): voidReturns nothing.
import { grantCampaignAttributionConsent, withdrawCampaignAttributionConsent } from '@eldrajs/sdk';
consentTool.onChange((choice) =>
choice.marketing ? grantCampaignAttributionConsent() : withdrawCampaignAttributionConsent()
);Consent is not stored
The kit does not remember consent between page loads. Call grantCampaignAttributionConsent() on every page load where consent stands.
withdrawCampaignAttributionConsent
Records that the visitor withdrew or refused consent. The kept landing is removed, and later carts carry none.
withdrawCampaignAttributionConsent(options?: { storage?: Storage | null }): voidReturns nothing.
import { withdrawCampaignAttributionConsent } from '@eldrajs/sdk';
cookieBanner.on('reject', () => withdrawCampaignAttributionConsent());readCampaignAttribution
Reads the kept landing. cart.addItem calls it for you, so most shops never need it.
readCampaignAttribution(options?: { storage?: Storage | null }): {
campaignId?; utmSource?; utmMedium?; utmCampaign?
} | nullReturns the kept tags, or null without consent, when nothing is kept or when it expired.
import { readCampaignAttribution } from '@eldrajs/sdk';
const landing = readCampaignAttribution();
if (landing?.utmCampaign === 'lopi-autumn') showAutumnBanner();clearCampaignAttribution
Forgets the landing, so later carts carry none until the next tagged visit. Consent is unchanged. Use it if you want one order per landing.
clearCampaignAttribution(options?: { storage?: Storage | null }): voidReturns nothing.
import { clearCampaignAttribution } from '@eldrajs/sdk';
onOrderConfirmed(() => clearCampaignAttribution());The legal background and the details of what is kept are in the package README, under Campaign attribution.
Business login
These helpers sign in a business customer through OpenID Connect with PKCE. They use only fetch and WebCrypto, so they run in any runtime. The full flow, token storage and security rules are in Business login.
shopIssuer
The issuer URL of an organisation's shop login.
shopIssuer(options: { keycloakBaseUrl: string; orgId: string }): stringReturns {keycloakBaseUrl}/realms/shop-{orgId}.
import { ELDRA_SHOP_CLIENT_ID, shopIssuer } from '@eldrajs/sdk';
const issuer = shopIssuer({ keycloakBaseUrl, orgId });
const clientId = ELDRA_SHOP_CLIENT_ID; // 'storefront'ELDRA_SHOP_CLIENT_ID is the default client id in every shop login, storefront.
createPkcePair
Makes a fresh PKCE verifier and its challenge. Make one per sign-in.
createPkcePair(): Promise<{ codeVerifier: string; codeChallenge: string; codeChallengeMethod: 'S256' }>Returns the verifier (43 characters) and its S256 challenge.
import { createPkcePair } from '@eldrajs/sdk';
const { codeVerifier, codeChallenge } = await createPkcePair();
await pendingLogins.set(state, { codeVerifier }); // keep the verifier on the serverpkceChallenge
The S256 challenge for a verifier you already have.
pkceChallenge(codeVerifier: string): Promise<string>Returns the base64url SHA-256 of the verifier.
import { pkceChallenge } from '@eldrajs/sdk';
const codeChallenge = await pkceChallenge(codeVerifier);buildAuthorizeUrl
The login page URL to send the customer to.
buildAuthorizeUrl(options: {
issuer: string;
clientId: string;
redirectUri: string;
state: string;
codeChallenge: string;
scope?: string;
prompt?: string;
uiLocales?: string | string[];
}): string| Option | Type | Default | What it does |
|---|---|---|---|
issuer | string | — | From shopIssuer. |
clientId | string | — | Usually ELDRA_SHOP_CLIENT_ID. |
redirectUri | string | — | Your callback URL. |
state | string | — | An unguessable, single-use value you check on the callback. |
codeChallenge | string | — | From createPkcePair. |
scope | string | openid | The OAuth scope. |
prompt | string | — | The OIDC prompt, such as login. |
uiLocales | string | string[] | — | Languages for the login pages, most preferred first. |
Returns the URL.
import { buildAuthorizeUrl } from '@eldrajs/sdk';
return redirect(
buildAuthorizeUrl({
issuer,
clientId: ELDRA_SHOP_CLIENT_ID,
redirectUri: 'https://lopi.is/auth/callback',
state,
codeChallenge,
uiLocales: ['is', 'en'],
})
);exchangeAuthorizationCode
Swaps the code from the callback for tokens. Server only.
exchangeAuthorizationCode(options: {
issuer: string;
clientId: string;
clientSecret?: string;
fetch?: typeof fetch;
code: string;
redirectUri: string;
codeVerifier: string;
}): Promise<{ accessToken; refreshToken; idToken; expiresAt: number; refreshExpiresAt: number | undefined }>| Option | Type | Default | What it does |
|---|---|---|---|
issuer | string | — | From shopIssuer. |
clientId | string | — | The client id. |
clientSecret | string | — | The storefront client's secret. |
fetch | typeof fetch | the global fetch | Pass one with a timeout. |
code | string | — | The code from the callback. |
redirectUri | string | — | The same redirectUri the login started with. |
codeVerifier | string | — | The verifier kept at the start of the login. |
Returns the tokens. expiresAt and refreshExpiresAt are epoch milliseconds. Throws EldraOidcError, with the OAuth error code, when the login server refuses.
import { exchangeAuthorizationCode } from '@eldrajs/sdk';
const tokens = await exchangeAuthorizationCode({
issuer,
clientId: ELDRA_SHOP_CLIENT_ID,
clientSecret: process.env.SHOP_CLIENT_SECRET,
code,
redirectUri: 'https://lopi.is/auth/callback',
codeVerifier,
fetch: (url, init) => fetch(url, { ...init, signal: AbortSignal.timeout(10_000) }),
});Never in a browser
The token calls take the client secret. Make them on a server only, and never log a token.
refreshTokens
Gets new tokens with a refresh token. Server only.
refreshTokens(options: {
issuer: string;
clientId: string;
clientSecret?: string;
fetch?: typeof fetch;
refreshToken: string;
}): Promise<EldraOidcTokens>issuer, clientId, clientSecret and fetch work as in exchangeAuthorizationCode.
Returns the new tokens, the same shape as exchangeAuthorizationCode. Throws EldraOidcError.
import { EldraOidcError, refreshTokens } from '@eldrajs/sdk';
try {
session.tokens = await refreshTokens({ issuer, clientId, clientSecret, refreshToken });
} catch (error) {
if (error instanceof EldraOidcError && error.error === 'invalid_grant') {
await sessions.delete(session.id); // the session is over
}
throw error;
}EldraOidcError carries status, error (the OAuth code, such as invalid_grant) and errorDescription.
buildLogoutUrl
The URL that ends the customer's session at the login server.
buildLogoutUrl(options: {
issuer: string;
clientId: string;
postLogoutRedirectUri: string;
idTokenHint?: string;
}): string| Option | Type | Default | What it does |
|---|---|---|---|
issuer | string | — | From shopIssuer. |
clientId | string | — | The client id. |
postLogoutRedirectUri | string | — | Where to send the customer after logout. |
idTokenHint | string | — | The id token, so no confirmation is asked. |
Returns the URL.
import { buildLogoutUrl } from '@eldrajs/sdk';
return redirect(
buildLogoutUrl({
issuer,
clientId: ELDRA_SHOP_CLIENT_ID,
postLogoutRedirectUri: 'https://lopi.is/',
idTokenHint: session.tokens.idToken,
}),
303
);bearer
Headers that carry an access token. Pass them as a call's headers.
bearer(accessToken: string): { Authorization: string }Returns { Authorization: 'Bearer <token>' }.
import { bearer } from '@eldrajs/sdk';
const me = await eldra.customer.me({ headers: bearer(session.tokens.accessToken) });customerHeaders
Headers for a priced catalog read, a cart write or a sales order. Server only.
customerHeaders(accessToken: string, customerId?: string): {
Authorization: string;
'X-Customer-Id'?: string;
}| Parameter | Type | Default | What it does |
|---|---|---|---|
accessToken | string | — | The customer's access token. |
customerId | string | — | The active company, when the person buys for more than one. |
Returns the Authorization header, plus X-Customer-Id when customerId is given.
import { customerHeaders } from '@eldrajs/sdk';
const headers = customerHeaders(session.tokens.accessToken, session.customerId);
const sweater = await eldra.catalog.getProduct(lopiSweater.id, {}, { headers });Store amounts
storeAmountsFromDelivery
Turns the public delivery settings into the amounts that ⟦store …⟧ price tokens show. Today that is the free-shipping threshold per currency. features.getStoreAmounts() reads and converts in one call, so you need this only when you already hold the delivery settings.
storeAmountsFromDelivery(accounts: unknown): {
freeShippingThreshold?: Record<string, number>;
}Returns { freeShippingThreshold: { ISK: 15000, EUR: 10000 } } in minor units, or {} when no active delivery method has a threshold. For each currency it takes the lowest threshold among active methods.
import { storeAmountsFromDelivery } from '@eldrajs/sdk';
const accounts = await eldra.request({ path: '/delivery/v1/provider-account' });
const storeAmounts = storeAmountsFromDelivery(accounts);
// { freeShippingThreshold: { ISK: 15000 } }Formatting
Chrome, Edge and Cloudflare Workers ship without Icelandic data. Intl there prints English with no error, so a server render and the browser disagree. These functions print Icelandic and English the same on every runtime. Every other locale goes to the runtime's own Intl.
Each takes the options of the Intl constructor it is named after and returns an object with the same methods. Formatters are cached per locale and options. Import only the entry points you use, since each one carries its own data. The rules and costs are in Icelandic formatting.
formatPrice
Writes an amount in major units as a price. From @eldrajs/sdk/format.
formatPrice(amount: number, currency: string, locale: string): stringReturns the price text.
import { formatPrice } from '@eldrajs/sdk/format';
formatPrice(24900, 'ISK', 'is-IS'); // '24.900 kr.'
formatPrice(24900, 'ISK', 'en-US'); // 'ISK 24,900'formatMinorAmount
Writes an amount in minor units exactly as @eldrajs/ui's Price does. Use it for amounts straight from the API. From @eldrajs/sdk/format.
formatMinorAmount(minor: number, format: {
locale: string;
currency?: string;
narrowSymbol?: boolean;
}): string| Option | Type | Default | What it does |
|---|---|---|---|
locale | string | — | The BCP 47 locale to write in. |
currency | string | — | ISO 4217. Left out or empty, the amount is a plain decimal. |
narrowSymbol | boolean | false | Use the narrow sign (kr 2,800) instead of ISK 2,800. |
Returns the text. It never throws for an unknown currency; it writes the code after the number.
import { formatMinorAmount } from '@eldrajs/sdk/format';
formatMinorAmount(24900, { currency: 'ISK', locale: 'is-IS' }); // '24.900 kr.'
formatMinorAmount(18900, { currency: 'EUR', locale: 'en-US' }); // '€189.00'currencyMinorDigits
How many minor units a currency counts in. From @eldrajs/sdk/format.
currencyMinorDigits(currency: string | undefined, locale?: string): numberReturns 0 for ISK, 2 for EUR, 3 for KWD, and 2 for no currency or an unknown code.
import { currencyMinorDigits } from '@eldrajs/sdk/format';
const major = 18900 / 10 ** currencyMinorDigits('EUR'); // 189numberFormat
new Intl.NumberFormat(locale, options) with the same text on every runtime. From @eldrajs/sdk/format.
numberFormat(locale: string, options?: Intl.NumberFormatOptions): Intl.NumberFormatReturns a number formatter.
import { numberFormat } from '@eldrajs/sdk/format';
numberFormat('is-IS').format(1234567.5); // '1.234.567,5'comparator
A sort function in a locale's alphabetical order. Icelandic uses its own order on every runtime. From @eldrajs/sdk/format.
comparator(locale: string): (a: string, b: string) => numberReturns a compare function for Array.prototype.sort.
import { comparator } from '@eldrajs/sdk/format';
['Ölfus', 'Akureyri', 'Þórshöfn', 'Ísafjörður'].sort(comparator('is-IS'));
// ['Akureyri', 'Ísafjörður', 'Þórshöfn', 'Ölfus']compareIcelandic(a, b) is the Icelandic compare function on its own.
dateTimeFormat
new Intl.DateTimeFormat(locale, options) with the same text on every runtime. From @eldrajs/sdk/format/date.
dateTimeFormat(locale: string, options?: Intl.DateTimeFormatOptions): Intl.DateTimeFormatReturns a date formatter. The time zone defaults to UTC, which is Iceland's time.
import { dateTimeFormat } from '@eldrajs/sdk/format/date';
dateTimeFormat('is-IS', { dateStyle: 'long' }).format(order.createdAt); // '1. desember 2026'Icelandic dates are UTC only
For Icelandic and English, a timeZone other than UTC or Reykjavík throws a RangeError.
listFormat
new Intl.ListFormat(locale, options) with the same text on every runtime. From @eldrajs/sdk/format/list.
listFormat(locale: string, options?: Intl.ListFormatOptions): Intl.ListFormatReturns a list formatter.
import { listFormat } from '@eldrajs/sdk/format/list';
listFormat('is-IS').format(['grár', 'hvítur', 'svartur']); // 'grár, hvítur og svartur'relativeTimeFormat
new Intl.RelativeTimeFormat(locale, options) with the same text on every runtime. From @eldrajs/sdk/format/relative-time.
relativeTimeFormat(locale: string, options?: Intl.RelativeTimeFormatOptions): Intl.RelativeTimeFormatReturns a relative time formatter.
import { relativeTimeFormat } from '@eldrajs/sdk/format/relative-time';
relativeTimeFormat('is-IS').format(-3, 'day'); // 'fyrir 3 dögum'displayNames
new Intl.DisplayNames(locale, options) with the same names on every runtime. From @eldrajs/sdk/format/display-names.
displayNames(locale: string, options: Intl.DisplayNamesOptions): Intl.DisplayNamesReturns a display names object. options.type is required, as with Intl.
import { displayNames } from '@eldrajs/sdk/format/display-names';
displayNames('is-IS', { type: 'region' }).of('DK'); // 'Danmörk'installIcelandicIntl
Makes code you do not control print Icelandic, such as a date picker or a chart library. It patches Intl.NumberFormat, Intl.DateTimeFormat, Number.prototype.toLocaleString and the Date.prototype.toLocale*String methods. Only Icelandic requests change. From @eldrajs/sdk/format/intl.
installIcelandicIntl(options?: { force?: boolean }): () => void| Option | Type | Default | What it does |
|---|---|---|---|
force | boolean | false | Patch even where the runtime has Icelandic (Node, Safari, Firefox), so every runtime prints the same. |
Returns a function that restores the runtime's Intl. A second call while installed changes nothing and returns a function that does nothing.
import { installIcelandicIntl } from '@eldrajs/sdk/format/intl';
installIcelandicIntl({ force: true }); // before anything formats, on server and client alikeCall it before anything formats
Call it once at startup. In a server render, call it with force on both server and client so the two match. Dates in a zone other than UTC stay with the runtime and can print in English.
Price tokens
A CMS text field can hold a price, one amount per currency, or a store setting:
⟦price#lop1 ISK=24900 EUR=17900⟧ a price, minor units per currency
⟦store freeShippingThreshold⟧ a store settingStudio writes these tokens; merchants never type them. A page shows the amount in the shopper's currency. When it cannot, it leaves out the sentence holding the token, never a wrong amount. Everything here is from @eldrajs/sdk/tokens.
resolveTokens
Writes every token in a text in the shopper's currency. Use it on any CMS text before you render it.
resolveTokens(text: string, options: {
currency: string | null | undefined;
locale: string;
storeAmounts?: StoreAmounts | null;
format?: (amount: number, currency: string, locale: string) => string;
}): string| Option | Type | Default | What it does |
|---|---|---|---|
currency | string | null | undefined | — | The shopper's currency. Without one, every sentence with a token is left out. |
locale | string | — | The locale to write money in: the organisation's regional format. |
storeAmounts | StoreAmounts | null | — | Amounts for ⟦store …⟧ tokens, from features.getStoreAmounts(). |
format | (amount, currency, locale) => string | formatPrice | Writes a major-unit amount. Pass your own so tokens match your <Price>. |
Returns the text with tokens written out. Text without tokens comes back as it is.
import { resolveTokens } from '@eldrajs/sdk/tokens';
const storeAmounts = await eldra.features.getStoreAmounts();
const text =
'Free shipping over ⟦store freeShippingThreshold⟧ in Iceland. Sweaters from ⟦price#lop1 ISK=24900 EUR=17900⟧ today.';
resolveTokens(text, { currency: 'EUR', locale: 'en-US', storeAmounts });
// 'Sweaters from €179.00 today.' (no EUR threshold, so the first sentence is left out)resolvePriceNode
Writes a rich-text price node in the shopper's currency. Use it where rich text holds a price as a node instead of bracket text.
resolvePriceNode(attrs: unknown, options: ResolveTokensOptions): string | nullReturns the price text, or null when it cannot be written. Takes the same options as resolveTokens.
import { resolvePriceNode } from '@eldrajs/sdk/tokens';
resolvePriceNode({ id: 'lop1', amounts: { ISK: 24900 } }, { currency: 'ISK', locale: 'is-IS' });
// '24.900 kr.'formatToken
Writes one parsed token in the shopper's currency.
formatToken(token: Token, options: ResolveTokensOptions): string | nullReturns the text, or null when the token has no amount in that currency.
import { formatToken, parseToken } from '@eldrajs/sdk/tokens';
const token = parseToken('price#lop1 ISK=24900');
const text = token && formatToken(token, { currency: 'ISK', locale: 'is-IS' }); // '24.900 kr.'tokenAmount
The minor-unit amount a token stands for in a currency.
tokenAmount(token: Token, currency: string | null | undefined, storeAmounts?: StoreAmounts | null): number | nullReturns the amount, or null when there is none.
import { tokenAmount } from '@eldrajs/sdk/tokens';
tokenAmount({ kind: 'price', id: 'lop1', amounts: { ISK: 24900 } }, 'ISK'); // 24900parseTokens
Splits a text into plain runs and tokens, in order. Use it to render tokens as your own components.
parseTokens(text: string): Array<string | Token | { kind: 'invalid'; raw: string }>Returns the segments. A stray bracket or a malformed token becomes an invalid segment.
import { parseTokens } from '@eldrajs/sdk/tokens';
parseTokens('Nú á ⟦price#lop1 ISK=24900⟧!');
// ['Nú á ', { kind: 'price', id: 'lop1', amounts: { ISK: 24900 } }, '!']parseToken
Parses the inside of one bracket pair.
parseToken(body: string): Token | nullReturns a price or store token, or null when it is not well formed.
import { parseToken } from '@eldrajs/sdk/tokens';
parseToken('store freeShippingThreshold'); // { kind: 'store', name: 'freeShippingThreshold' }serializeToken
Writes a token as Studio stores it, with currency codes sorted.
serializeToken(token: Token): stringReturns the bracketed token text.
import { serializeToken } from '@eldrajs/sdk/tokens';
serializeToken({ kind: 'price', id: 'lop1', amounts: { ISK: 24900, EUR: 17900 } });
// '⟦price#lop1 EUR=17900 ISK=24900⟧'priceNodeToken
Reads a rich-text price node's attributes as a token.
priceNodeToken(attrs: unknown): Token | nullReturns a price token for { id, amounts }, a store token for { setting }, or null.
import { priceNodeToken } from '@eldrajs/sdk/tokens';
priceNodeToken({ setting: 'freeShippingThreshold' }); // { kind: 'store', name: 'freeShippingThreshold' }hasTokens
A cheap check for any token bracket in a text.
hasTokens(text: string): booleanReturns true when the text holds ⟦ or ⟧.
import { hasTokens, resolveTokens } from '@eldrajs/sdk/tokens';
const html = hasTokens(body) ? resolveTokens(body, options) : body;lengthText
The text a maxLength check should count. Each token counts as 10 characters (TOKEN_TEXT_LENGTH), about the length of a written price.
lengthText(text: string): stringReturns the text with each well-formed token replaced by 10 characters.
import { lengthText } from '@eldrajs/sdk/tokens';
lengthText('Yfir ⟦store freeShippingThreshold⟧').length <= 40; // trueminorUnitDigits, toMajorUnits and toMinorUnits
Convert between major and minor units for a currency.
minorUnitDigits(currency: string): number
toMajorUnits(amount: number, currency: string): number
toMinorUnits(amount: number, currency: string): numberReturns the digit count (ISK 0, EUR 2), or the converted amount. toMinorUnits rounds.
import { toMajorUnits, toMinorUnits } from '@eldrajs/sdk/tokens';
toMinorUnits(179, 'EUR'); // 17900
toMajorUnits(24900, 'ISK'); // 24900The entry point also exports TOKEN_OPEN (⟦), TOKEN_CLOSE (⟧), STORE_TOKEN_NAMES and TOKEN_TEXT_LENGTH.
Live value markers
A prerendered page bakes in its prices and stock. Live markers tag each value, so a Cloudflare Worker can swap in current values when it serves the page. The baked text stays as the fallback. Everything here is from @eldrajs/sdk/live. It needs no framework and no DOM.
A marker is <kind>:<id>:<field>. kind is product or variant. The money fields are price, compareAt, minPrice and maxPrice; the state fields are available and stock. The full attribute grammar is in the package README, under Live value markers.
liveMoneyAttributes
The attributes for the element whose text is a price. Spread them onto that element.
liveMoneyAttributes(input: {
kind: 'product' | 'variant';
id: string;
field: 'price' | 'compareAt' | 'minPrice' | 'maxPrice';
minor: number;
currency?: string;
locale: string;
narrowSymbol?: boolean;
}): Record<string, string>| Field | Type | Default | What it does |
|---|---|---|---|
kind | 'product' | 'variant' | — | Whose value it is. |
id | string | — | The product or variant id. |
field | money field | — | Which price it is. |
minor | number | — | The baked amount in minor units. Rounded. |
currency | string | — | ISO 4217. Left out when the store published none. |
locale | string | — | The locale the text was written in. |
narrowSymbol | boolean | — | Set when the text used the narrow sign. |
Returns the attributes, or {} when the id cannot be marked or the amount is not finite.
import { liveMoneyAttributes } from '@eldrajs/sdk/live';
liveMoneyAttributes({
kind: 'variant',
id: 'v_123',
field: 'price',
minor: 24900,
currency: 'ISK',
locale: 'is-IS',
});
// { 'data-eldra-live': 'variant:v_123:price', 'data-eldra-minor': '24900',
// 'data-eldra-locale': 'is-IS', 'data-eldra-currency': 'ISK' }Mark the value, not its container
Put the marker on the element whose text is the value. A Worker replaces that element's text.
liveStateAttributes
The attributes for an element whose state is availability or stock.
liveStateAttributes(
input:
| { kind; id; field: 'available'; state: boolean }
| { kind; id; field: 'stock'; state: 'in' | 'low' | 'out' | 'preorder'; quantity?: number | null }
): Record<string, string>Returns the attributes, or {} when the id cannot be marked. quantity is added only for an integer.
import { liveStateAttributes } from '@eldrajs/sdk/live';
liveStateAttributes({ kind: 'product', id: 'p_9', field: 'stock', state: 'low', quantity: 3 });
// { 'data-eldra-live': 'product:p_9:stock', 'data-eldra-state': 'low', 'data-eldra-quantity': '3' }formatLiveMoney
Writes a fresh amount for a marked money element, from the element's own attributes. Use it in the Worker that rewrites pages.
formatLiveMoney(attributes: (name: string) => string | null, minor: number): string | nullReturns the text @eldrajs/ui's Price would render, or null when the element is not a marked money value.
import { formatLiveMoney } from '@eldrajs/sdk/live';
rewriter.on('[data-eldra-live]', {
element(el) {
const text = formatLiveMoney((name) => el.getAttribute(name), 19900); // '19.900 kr.'
if (text !== null) el.setInnerContent(text);
},
});collectLiveIds
Finds every product and variant id a rendered page marks, without a DOM. Use it in a build to know what to refresh.
collectLiveIds(html: string): { product: string[]; variant: string[] }Returns the ids, each list sorted and without repeats.
import { collectLiveIds } from '@eldrajs/sdk/live';
collectLiveIds(html); // { product: ['p_9'], variant: ['v_123'] }liveMarker and parseLiveMarker
Write and read the marker string itself.
liveMarker(kind: 'product' | 'variant', id: string, field: LiveField): string | null
parseLiveMarker(value: string): { kind; id; field } | nullReturns "<kind>:<id>:<field>", or the parsed parts. null for an id outside [A-Za-z0-9._-] or anything that is not one marker.
import { liveMarker, parseLiveMarker } from '@eldrajs/sdk/live';
liveMarker('variant', 'v_123', 'price'); // 'variant:v_123:price'
parseLiveMarker('product:p_9:available'); // { kind: 'product', id: 'p_9', field: 'available' }isLiveMoneyField and isLiveStateField
Tell a money field from a state field.
isLiveMoneyField(field: string): boolean
isLiveStateField(field: string): booleanReturns true when the field is of that kind.
import { isLiveMoneyField, parseLiveMarker } from '@eldrajs/sdk/live';
const marker = parseLiveMarker(value);
if (marker && isLiveMoneyField(marker.field)) refreshPrice(marker.id);The entry point also exports the attribute names as constants: LIVE_ATTRIBUTE, LIVE_MINOR_ATTRIBUTE, LIVE_CURRENCY_ATTRIBUTE, LIVE_LOCALE_ATTRIBUTE, LIVE_NARROW_ATTRIBUTE, LIVE_STATE_ATTRIBUTE and LIVE_QUANTITY_ATTRIBUTE.