Skip to content

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 fromWhat it holds
@eldrajs/sdkThe client, storage, images, analytics, attribution, business login, store amounts
@eldrajs/sdk/formatNumbers, prices and sorting
@eldrajs/sdk/format/dateDates and times
@eldrajs/sdk/format/listLists ("a, b og c")
@eldrajs/sdk/format/relative-timeRelative times ("fyrir 3 dögum")
@eldrajs/sdk/format/display-namesCountry, language and currency names
@eldrajs/sdk/format/intlinstallIcelandicIntl, for code that calls Intl itself
@eldrajs/sdk/tokensPrice tokens inside CMS text
@eldrajs/sdk/liveLive price and stock markers on prerendered pages
@eldrajs/sdk/viteThe 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.

ts
createCartSession(options?: { storage?: Storage | null; key?: string }): {
  read(): string | null;
  remember(cartId: string): void;
  forget(): void;
}
OptionTypeDefaultWhat it does
storagestorage or nullbrowser localStorageWhere the cart id is kept.
keystringeldra.cartIdThe storage key.

Returns an object that reads, remembers and forgets the cart id.

ts
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.

ts
createCurrencyPreference(options?: { storage?: Storage | null; key?: string }): {
  read(): string | null;
  remember(currency: string): void;
  forget(): void;
}
OptionTypeDefaultWhat it does
storagestorage or nullbrowser localStorageWhere the currency is kept.
keystringeldra.currencyThe storage key.

Returns an object that reads, remembers and forgets the currency code.

ts
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.

ts
createOrderAccessTokens(options?: { storage?: Storage | null; keyPrefix?: string }): {
  remember(orderId: string, token: string | undefined): void;
  read(orderId: string): string | null;
}
OptionTypeDefaultWhat it does
storagestorage or nullbrowser sessionStorageWhere the tokens are kept.
keyPrefixstringeldra.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.

ts
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:

VariantMax width
sm400 px
md800 px
lg1200 px
xl1920 px
full2560 px
uhd3840 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.

ts
responsiveImage(
  source: EldraImageSource,
  options: { sizes: string; variant?; aspectRatio?; width?; height?; originalWidth? }
): { src: string; srcset?: string; sizes?: string; width?: number; height?: number } | undefined
OptionTypeDefaultWhat it does
sizesstring—How wide the image is laid out, as an <img sizes> value. Required.
variant'sm' … 'uhd'mdThe variant in src, for a browser that ignores srcset.
aspectRationumber—Width over height of the box, such as 4 / 5. Sets width and height to reserve the space.
width, heightnumber—Explicit width and height. Used only when both are given; they win over everything else.
originalWidthnumberthe source's widthThe 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.

ts
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.

ts
imageSrcset(source: EldraImageSource, options?: { originalWidth?: number }): string | undefined
OptionTypeDefaultWhat it does
originalWidthnumberthe source's widthThe 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.

ts
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.

ts
imageUrl(source: EldraImageSource, variant: 'sm' | 'md' | 'lg' | 'xl' | 'full' | 'uhd' | 'original'): string | undefined

Returns 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.

ts
import { imageUrl } from '@eldrajs/sdk';

const ogImage = imageUrl(sweater.thumbnail, 'lg');

imageVariantFor ​

Picks the narrowest variant that covers a width at a pixel density.

ts
imageVariantFor(width: number, density?: number): 'sm' | 'md' | 'lg' | 'xl' | 'full' | 'uhd'
ParameterTypeDefaultWhat it does
widthnumber—The width in CSS pixels.
densitynumber1The device pixel ratio.

Returns the variant, or uhd when none is wide enough. Throws a RangeError for a width that is not positive.

ts
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.

ts
isEldraImage(source: EldraImageSource): boolean

Returns true for a resizable Eldra asset. false for an external URL, an SVG, a GIF or no URL.

ts
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.

ts
analyticsTrackerScript(options?: { orgId?; apiBaseUrl?; env?; eventOrigin?: string }): {
  src: string;
  defer: true;
  crossorigin: 'anonymous';
  'data-org': string;
  'data-api'?: string;
} | undefined
OptionTypeDefaultWhat it does
orgIdstring, or a functionread from envThe organisation the events count for.
apiBaseUrlstring, or a functionread from env, else https://web.eldra.app/apiThe script loads from this gateway's origin.
envobject, or a function—Where to read orgId and apiBaseUrl, as on the client.
eventOriginstring—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.

ts
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.

ts
captureCampaignAttribution(
  url?: string | URL,
  options?: { storage?: Storage | null; maxAgeMs?: number }
): { campaignId?; utmSource?; utmMedium?; utmCampaign? } | null
OptionTypeDefaultWhat it does
urlstring | URLlocation.hrefThe URL to read the tags from.
storagestorage or nulllocalStorage in a browser, none elsewhereWhere the landing is kept once the visitor consents.
maxAgeMsnumber30 daysHow 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.

ts
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.

ts
grantCampaignAttributionConsent(options?: { storage?: Storage | null }): void

Returns nothing.

ts
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.

ts
withdrawCampaignAttributionConsent(options?: { storage?: Storage | null }): void

Returns nothing.

ts
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.

ts
readCampaignAttribution(options?: { storage?: Storage | null }): {
  campaignId?; utmSource?; utmMedium?; utmCampaign?
} | null

Returns the kept tags, or null without consent, when nothing is kept or when it expired.

ts
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.

ts
clearCampaignAttribution(options?: { storage?: Storage | null }): void

Returns nothing.

ts
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.

ts
shopIssuer(options: { keycloakBaseUrl: string; orgId: string }): string

Returns {keycloakBaseUrl}/realms/shop-{orgId}.

ts
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.

ts
createPkcePair(): Promise<{ codeVerifier: string; codeChallenge: string; codeChallengeMethod: 'S256' }>

Returns the verifier (43 characters) and its S256 challenge.

ts
import { createPkcePair } from '@eldrajs/sdk';

const { codeVerifier, codeChallenge } = await createPkcePair();
await pendingLogins.set(state, { codeVerifier }); // keep the verifier on the server

pkceChallenge ​

The S256 challenge for a verifier you already have.

ts
pkceChallenge(codeVerifier: string): Promise<string>

Returns the base64url SHA-256 of the verifier.

ts
import { pkceChallenge } from '@eldrajs/sdk';

const codeChallenge = await pkceChallenge(codeVerifier);

buildAuthorizeUrl ​

The login page URL to send the customer to.

ts
buildAuthorizeUrl(options: {
  issuer: string;
  clientId: string;
  redirectUri: string;
  state: string;
  codeChallenge: string;
  scope?: string;
  prompt?: string;
  uiLocales?: string | string[];
}): string
OptionTypeDefaultWhat it does
issuerstring—From shopIssuer.
clientIdstring—Usually ELDRA_SHOP_CLIENT_ID.
redirectUristring—Your callback URL.
statestring—An unguessable, single-use value you check on the callback.
codeChallengestring—From createPkcePair.
scopestringopenidThe OAuth scope.
promptstring—The OIDC prompt, such as login.
uiLocalesstring | string[]—Languages for the login pages, most preferred first.

Returns the URL.

ts
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.

ts
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 }>
OptionTypeDefaultWhat it does
issuerstring—From shopIssuer.
clientIdstring—The client id.
clientSecretstring—The storefront client's secret.
fetchtypeof fetchthe global fetchPass one with a timeout.
codestring—The code from the callback.
redirectUristring—The same redirectUri the login started with.
codeVerifierstring—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.

ts
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.

ts
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.

ts
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.

ts
buildLogoutUrl(options: {
  issuer: string;
  clientId: string;
  postLogoutRedirectUri: string;
  idTokenHint?: string;
}): string
OptionTypeDefaultWhat it does
issuerstring—From shopIssuer.
clientIdstring—The client id.
postLogoutRedirectUristring—Where to send the customer after logout.
idTokenHintstring—The id token, so no confirmation is asked.

Returns the URL.

ts
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.

ts
bearer(accessToken: string): { Authorization: string }

Returns { Authorization: 'Bearer <token>' }.

ts
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.

ts
customerHeaders(accessToken: string, customerId?: string): {
  Authorization: string;
  'X-Customer-Id'?: string;
}
ParameterTypeDefaultWhat it does
accessTokenstring—The customer's access token.
customerIdstring—The active company, when the person buys for more than one.

Returns the Authorization header, plus X-Customer-Id when customerId is given.

ts
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.

ts
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.

ts
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.

ts
formatPrice(amount: number, currency: string, locale: string): string

Returns the price text.

ts
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.

ts
formatMinorAmount(minor: number, format: {
  locale: string;
  currency?: string;
  narrowSymbol?: boolean;
}): string
OptionTypeDefaultWhat it does
localestring—The BCP 47 locale to write in.
currencystring—ISO 4217. Left out or empty, the amount is a plain decimal.
narrowSymbolbooleanfalseUse 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.

ts
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.

ts
currencyMinorDigits(currency: string | undefined, locale?: string): number

Returns 0 for ISK, 2 for EUR, 3 for KWD, and 2 for no currency or an unknown code.

ts
import { currencyMinorDigits } from '@eldrajs/sdk/format';

const major = 18900 / 10 ** currencyMinorDigits('EUR'); // 189

numberFormat ​

new Intl.NumberFormat(locale, options) with the same text on every runtime. From @eldrajs/sdk/format.

ts
numberFormat(locale: string, options?: Intl.NumberFormatOptions): Intl.NumberFormat

Returns a number formatter.

ts
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.

ts
comparator(locale: string): (a: string, b: string) => number

Returns a compare function for Array.prototype.sort.

ts
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.

ts
dateTimeFormat(locale: string, options?: Intl.DateTimeFormatOptions): Intl.DateTimeFormat

Returns a date formatter. The time zone defaults to UTC, which is Iceland's time.

ts
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.

ts
listFormat(locale: string, options?: Intl.ListFormatOptions): Intl.ListFormat

Returns a list formatter.

ts
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.

ts
relativeTimeFormat(locale: string, options?: Intl.RelativeTimeFormatOptions): Intl.RelativeTimeFormat

Returns a relative time formatter.

ts
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.

ts
displayNames(locale: string, options: Intl.DisplayNamesOptions): Intl.DisplayNames

Returns a display names object. options.type is required, as with Intl.

ts
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.

ts
installIcelandicIntl(options?: { force?: boolean }): () => void
OptionTypeDefaultWhat it does
forcebooleanfalsePatch 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.

ts
import { installIcelandicIntl } from '@eldrajs/sdk/format/intl';

installIcelandicIntl({ force: true }); // before anything formats, on server and client alike

Call 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:

text
⟦price#lop1 ISK=24900 EUR=17900⟧   a price, minor units per currency
⟦store freeShippingThreshold⟧      a store setting

Studio 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.

ts
resolveTokens(text: string, options: {
  currency: string | null | undefined;
  locale: string;
  storeAmounts?: StoreAmounts | null;
  format?: (amount: number, currency: string, locale: string) => string;
}): string
OptionTypeDefaultWhat it does
currencystring | null | undefined—The shopper's currency. Without one, every sentence with a token is left out.
localestring—The locale to write money in: the organisation's regional format.
storeAmountsStoreAmounts | null—Amounts for ⟦store …⟧ tokens, from features.getStoreAmounts().
format(amount, currency, locale) => stringformatPriceWrites 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.

ts
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.

ts
resolvePriceNode(attrs: unknown, options: ResolveTokensOptions): string | null

Returns the price text, or null when it cannot be written. Takes the same options as resolveTokens.

ts
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.

ts
formatToken(token: Token, options: ResolveTokensOptions): string | null

Returns the text, or null when the token has no amount in that currency.

ts
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.

ts
tokenAmount(token: Token, currency: string | null | undefined, storeAmounts?: StoreAmounts | null): number | null

Returns the amount, or null when there is none.

ts
import { tokenAmount } from '@eldrajs/sdk/tokens';

tokenAmount({ kind: 'price', id: 'lop1', amounts: { ISK: 24900 } }, 'ISK'); // 24900

parseTokens ​

Splits a text into plain runs and tokens, in order. Use it to render tokens as your own components.

ts
parseTokens(text: string): Array<string | Token | { kind: 'invalid'; raw: string }>

Returns the segments. A stray bracket or a malformed token becomes an invalid segment.

ts
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.

ts
parseToken(body: string): Token | null

Returns a price or store token, or null when it is not well formed.

ts
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.

ts
serializeToken(token: Token): string

Returns the bracketed token text.

ts
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.

ts
priceNodeToken(attrs: unknown): Token | null

Returns a price token for { id, amounts }, a store token for { setting }, or null.

ts
import { priceNodeToken } from '@eldrajs/sdk/tokens';

priceNodeToken({ setting: 'freeShippingThreshold' }); // { kind: 'store', name: 'freeShippingThreshold' }

hasTokens ​

A cheap check for any token bracket in a text.

ts
hasTokens(text: string): boolean

Returns true when the text holds ⟦ or ⟧.

ts
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.

ts
lengthText(text: string): string

Returns the text with each well-formed token replaced by 10 characters.

ts
import { lengthText } from '@eldrajs/sdk/tokens';

lengthText('Yfir ⟦store freeShippingThreshold⟧').length <= 40; // true

minorUnitDigits, toMajorUnits and toMinorUnits ​

Convert between major and minor units for a currency.

ts
minorUnitDigits(currency: string): number
toMajorUnits(amount: number, currency: string): number
toMinorUnits(amount: number, currency: string): number

Returns the digit count (ISK 0, EUR 2), or the converted amount. toMinorUnits rounds.

ts
import { toMajorUnits, toMinorUnits } from '@eldrajs/sdk/tokens';

toMinorUnits(179, 'EUR'); // 17900
toMajorUnits(24900, 'ISK'); // 24900

The 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.

ts
liveMoneyAttributes(input: {
  kind: 'product' | 'variant';
  id: string;
  field: 'price' | 'compareAt' | 'minPrice' | 'maxPrice';
  minor: number;
  currency?: string;
  locale: string;
  narrowSymbol?: boolean;
}): Record<string, string>
FieldTypeDefaultWhat it does
kind'product' | 'variant'—Whose value it is.
idstring—The product or variant id.
fieldmoney field—Which price it is.
minornumber—The baked amount in minor units. Rounded.
currencystring—ISO 4217. Left out when the store published none.
localestring—The locale the text was written in.
narrowSymbolboolean—Set when the text used the narrow sign.

Returns the attributes, or {} when the id cannot be marked or the amount is not finite.

ts
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.

ts
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.

ts
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.

ts
formatLiveMoney(attributes: (name: string) => string | null, minor: number): string | null

Returns the text @eldrajs/ui's Price would render, or null when the element is not a marked money value.

ts
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.

ts
collectLiveIds(html: string): { product: string[]; variant: string[] }

Returns the ids, each list sorted and without repeats.

ts
import { collectLiveIds } from '@eldrajs/sdk/live';

collectLiveIds(html); // { product: ['p_9'], variant: ['v_123'] }

liveMarker and parseLiveMarker ​

Write and read the marker string itself.

ts
liveMarker(kind: 'product' | 'variant', id: string, field: LiveField): string | null
parseLiveMarker(value: string): { kind; id; field } | null

Returns "<kind>:<id>:<field>", or the parsed parts. null for an id outside [A-Za-z0-9._-] or anything that is not one marker.

ts
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.

ts
isLiveMoneyField(field: string): boolean
isLiveStateField(field: string): boolean

Returns true when the field is of that kind.

ts
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.

Eldra