arky-sdk
v0.26.143
Published
Official TypeScript SDK for Arky - website backend for custom frontends
Maintainers
Readme
arky-sdk
Official TypeScript SDK for Arky. It gives a storefront everything it needs (products, carts, checkout with Stripe or Monri, sign-in, forms, bookings, orders, content), plus the Admin client for staff tools and scripts.
Install
npm install --save-exact arky-sdk@<version>Pin the exact version, so the Server, Admin and storefronts move together.
Start here
| You are building | Call | Import from |
|---|---|---|
| A website or web app | initialize({ storeId, salesChannelId }, options): the client plus reactive atoms, a cart store per buyer, package and market, a headless checkout and a booking calendar | arky-sdk/storefront |
| Server code, or your own state layer | createStorefront({ storeId, salesChannelId }, options): the plain storefront client, the same calls without atoms | arky-sdk/storefront |
| Staff tools, scripts, back offices | createAdmin({ apiUrl, accountToken? }) | arky-sdk/admin |
| A React app | createArkyReact<AdminClient>() or createArkyReact<StorefrontClient>(): TanStack Query options and keys for every call of that client (React) | arky-sdk/react |
arky-sdk/storefront exports everything a storefront needs: both clients, the helpers (prices, blocks, images, paging, payments, forms), the error classes and every type. arky-sdk/utils holds the helpers on their own, and arky-sdk/types the types with the error classes and constants.
How every call works
- One params object, then request options. A call takes one object of Arky's own fields, then optional request options:
signal,headers,onSuccess,onError, and on the storefrontlocale,marketandorder_tokenfor that one request. Each client has its own type for them: the Admin client takesAdminRequestOptions, withoutlocale,marketandorder_token, and the storefrontStorefrontRequestOptions. A call with nothing to send, such ascustomer.getMe(), takes only the options. Admin calls that act on a store name itsstore_id. - One verb per kind of action.
find…reads a list.get…reads one record or view:get({ id }),get({ slug })where a record has slugs,getByKey({ key }). Records change throughcreate,updateanddelete. A cart or a checkout changes throughadd…,remove…,set…(replace a value) andselect…(pick one of the offered choices). Business actions keep their own names:quote,shipTo,checkout,place,submit,cancel,pause,requestCode,verify. - One casing rule. Arky's data is snake_case: params, answers, atoms and the helpers' results. The SDK's own setup options and callbacks are camelCase:
apiUrl,createId,onComplete. - Every list answers a page.
{ items, cursor }, withcursor: nullon the last page. Pass the cursor back to read the next page, or letreadAllPages(read)collect them andpaginate(read)walk them. A missing record is anArkyApiErrorwith status 404 and its record's own code, such asPRODUCT.NOT_FOUND(see Errors). - The app picks every id. A create takes the record's
id, a canonical UUID v4 the app makes once per user action and sends again on every retry. The same request under the same id answers the stored record; a different request under it is refused (409). The SDK never makes an id up: storefront calls that leave theidout take it from yourcreateIdfactory. - Changes carry the version they read. Updates and actions send
expected_updated_at(theupdated_atyou read); a stale one is refused with 409. The cart store sends it for you. Stock actions and two conversation actions name what they read instead. A stock action names the stock level (its id, orexpected_level_idon a movement or a unit receipt) and itsaction_id(a unit receipt names its new unit'sid), and an adjustment names the count it corrects inexpected_count(the level'son_hand, or itsunavailablewithfrom_set_aside). Assigning a conversation names the assignee you read (expected_account_id), and changing its reply email the selection you read (expected_reply). A value that moved is refused with 409GENERAL.CONFLICT. A package's access row has no version, so its delete names only the row's id. - A cart keeps its market. A cart call names the cart's own market: another one is refused with
409 CART.OTHER_MARKET, so a cart kept from another market is read, or moved with anupdatewhosemarket_idis the context's, before anything is added. - Plan access. A store without plan access refuses storefront changes with
402 STORE.SUBSCRIPTION_REQUIRED, an email change and the code request for it included; buyers can still identify, sign in with a code, sign out, read and edit their profile, and read what they hold. - Context is explicit. Storefront requests carry
X-Arky-Store-IdandX-Arky-Sales-Channel-Id, plus the locale and the market you set withsetContext({ locale, market }). A call names the package it reads, and the company or one of its locations it acts for, never both. Every commercial call (packages, their items, products, bookings and carts) names its market, even when the named channel sells in one: without it Arky refuses with 409SALES_CHANNEL.MARKET_REQUIRED, and a market the channel doesn't sell in withSALES_CHANNEL.MARKET_NOT_LISTED. A request through an archived sales channel of the store is refused with 409SALES_CHANNEL.NOT_ACTIVE, which leaves the shopper's session as it is. Content reads need no market. A locale outside the store's languages is refused withSTORE.LANGUAGE_NOT_SUPPORTED. - Errors carry a code. Everything the SDK throws at runtime is an
ArkyErrorwith acodethat you map to your own text. ATypeErrormeans your code passed a wrong value. See Errors.
1. Set up the store
import { createOrderToken, initialize } from "arky-sdk/storefront";
const arky = initialize({ storeId: "5e9b3d71-c826-4a04-b7f5-0d2a8e6c4f19", salesChannelId: "e5a8c2d7-3b91-4f06-9d4e-1c7b6a0f3e28" }, {
locale: "en",
market: "eu",
createVisitorIdentity: () => ({ customer_id: crypto.randomUUID(), session_id: crypto.randomUUID() }),
createSessionId: () => crypto.randomUUID(),
createId: () => crypto.randomUUID(),
createOrderToken,
});
const setup = await arky.store.load();
const packages = await arky.eshop.package.find();
const shopPackage = packages.find((candidate) => candidate.key === "public");
console.log(setup.name, setup.languages, arky.currency.get(), shopPackage?.id);- The four factories are required. The app picks every customer, session and record id and every order token;
createOrderTokenmakes a token in the shape Arky accepts. Without theminitializethrows. apiUrldefaults tohttps://api.arky.io. The store and sales-channel IDs are required canonical UUID v4 values. They are public identifiers and authenticate no person.- Sessions are kept in
localStorage, separately for each API URL, store and sales channel. During server rendering, pass a request-localsessionStorageadapter.visitorIdentityrestores a visitor pair your app picked earlier. arky.store.load()reads the store's setup and the current market and fills thesetup,marketandcurrencyatoms; the market'spayment_option_idslists its payment options, and each quote'spayment_option_idslists the ones that can pay that cart. The client reads each market once:arky.client.store.market.getCurrent()answers the current one from the same read.arky.getSetup()only answers the setup:name,timezone,languages,payment_options,customer_sign_in, which is{ type: "store" }when the store signs its own customers in, or{ type: "network", network_id }when they sign in through the network (Network customer sign-in), andseller, which is{ type: "seller", name, address }with the store's legal name and postal address, or{ type: "none" }. The setup is read once per client. A409 PAYMENT_METHOD.TERMS_CHANGEDrefusal (the store changed an option's saved-card wording) drops it, so the nextgetSetup()orstore.load()reads the new wording.- Packages. A package is a set of things you can buy, get or rent; a shop is a package with priced items.
eshop.package.find()lists the packages open to this buyer in the current market and sales channel as a plain array, each with itsblocks(its name and texts) and its accesslevel. Pick yours by itskey; every item, product, booking and cart call names itspackage_id.packageis a reserved word in strict TypeScript, so a local holding one isshopPackageormemberPackage; properties such aseshop.packageare fine. setContext({ locale, market })changes the language or the market. A market change clears every cart view; each market keeps its own carts and its own cart store, and switching back reads them again.
The store has the same calls as the plain client, under the same names. On top of them it has atoms (session, setup, market, currency, locale, …) and three helpers, each for one buyer and package in the current market: eshop.cart(scope), eshop.checkoutFlow(scope) and eshop.bookingCalendar(scope). The plain client's own cart calls stay reachable at arky.client.eshop.cart.
2. Products
A package sells products, booking services and packages through its priced items. eshop.packageItem.find pages them, one answer per priced item in the current market:
import { findBlock, formatMinor, getBlockTextValue, getImageUrl } from "arky-sdk/storefront";
import type { Media, StorefrontPackageItem } from "arky-sdk/storefront";
const page = await arky.eshop.packageItem.find({ package_id, include_price: true, selection: { types: ["product"] }, limit: 24 });
const imageIds = page.items.flatMap((item) => {
const image = findBlock(item.content, "image");
return image?.type === "media" && image.value ? [image.value] : [];
});
const images = await arky.media.find({ ids: imageIds });
const imageById = new Map<string, Media>(images.map((image) => [image.id, image]));
const rows = page.items.map((item: StorefrontPackageItem) => {
const image = findBlock(item.content, "image");
const summary = item.price_summary;
return {
name: getBlockTextValue(findBlock(item.content, "name"), "en"),
image: image?.type === "media" && image.value ? getImageUrl(imageById.get(image.value), "medium") : null,
from: summary && item.currency ? formatMinor(summary.min_amount, item.currency, "en") : "",
href: `/products/${item.content.slugs.en}`,
};
});
console.log(rows, page.cursor);- One search for every priced item. An answer names its
package_item_id,package_idandmarket_id, what it lists (item), itspositionand the listed record'scontent(key,slugs,blocks,categories).selectionnarrows and orders the answers:types(product,booking_service,package),text,categories(for products and booking services) and block filtersblockson the listed record;price: { min_amount?, max_amount? }andprice_basis(product_unit,booking_option,package_neverorpackage_everywith itscadence). Every price of one item has the same basis, so an item matches when its basis is the one asked for and its lowest to highest price overlaps the range. Search is per item, not per variant: a storefront that needs one variant filters its own read of the item's prices;sort:package_order(the default) orstarting_price(needsprice_basis), anddirection,ascunless you ask fordesc.textmatches words and word starts of an item's text, or the listed record's exact key, and keeps the order you ask for.
- Prices in search. With
include_price: trueand an access level that shows prices, an answer has itscurrencyandprice_summary,{ basis, min_amount, max_amount, price_count }over the item's prices on sale. A package's item holds exactly one price, and its answer names it asprice_id. - Pages. A page holds 20 answers unless you ask for more, and a page can come back short with a
cursor: follow it. - Media.
media.find({ ids })takes any number of ids, reads them 100 at a time and answers a plain array, and an answer that isn't a list or names a file it didn't ask for is refused (ArkyErroranswer_mismatch);content.loadandloadEntriesread their media through it. Storefront reads answer Public files, with their URL atcontent.original.url. Images also come asthumbnail,small,mediumandlarge, andgetImageUrl(media, size)picks one. Private files have null metadata URLs andgetImageUrlreturns null for them. - Texts are blocks.
findBlock(record, key)finds a block andgetBlockTextValue(block, locale)reads its text in the language you name, never another; an empty string means there is none.
A product page reads the product by its slug in the current language, then the prices of its item:
const product = await arky.eshop.product.get({ slug: "classic", package_id });
const { items: choices } = await arky.eshop.packageItem.findPrices({ package_item_id: product.package_item_id, package_id, include_price: true });
const byKey = await arky.eshop.product.getByKey({ key: "classic-x1", package_id });
console.log(choices.map((choice) => [choice.price_id, choice.content.sku, choice.price?.unit_price.amount]), byKey.id);- Reads.
gettakes{ id }or{ slug }; a key is read withgetByKey({ key }). Both answer the product with thepackage_item_idof its item in that package and the current market. Booking services and categories read the same way; collections, forms, markets, packages and their offerings read by{ id }or withgetByKey({ key }). - Prices.
packageItem.findPrices({ package_item_id })pages an item's prices, its exact choices. Each names itsprice_id, thesellableit prices (aproduct_variant,booking_offeringorpackage), itscontent(sku,blocksand the pricebasis) and, withinclude_price: true, itsprice, which carries the full reference (package_id,package_item_id,price_id) a cart line names. - More reads.
packageItem.getByParent({ item: { type: "product", product_id } })reads the item of a record in the current market,productVariant.get({ product_id, id })reads one variant, with its price when you passinclude_price: true, andproduct.findByIds({ ids, package_id })reads up to 100 products in one request, answering{ items, cursor: null }with the ones the package sells now, in the order asked. Staff read up to 100 variants witheshop.productVariant.find({ store_id, ids }), which takes no other filter, sort or page.
3. Cart
arky.eshop.cart({ buyer, package_id }) answers the cart store of that buyer and package in the current market: the same store on every call, shared with the checkout flow and the booking calendar of the same scope. A shopper who switches market gets that market's cart store. A store kept from before the switch refuses its next call with CartError context_changed. Storefront cart reads answer the buyer's copy of the cart, StorefrontCart, and the line helpers take it. Its quote is the buyer's copy too, StorefrontCartQuote: a package line's package leaves out each item's allocation weight, and its start leaves out the reason the store team wrote for an amendment.
const cart = arky.eshop.cart({ buyer: { type: "customer" }, package_id });
cart.item_count.subscribe((count) => console.log("items", count));
cart.status.subscribe((status) => console.log(status.error?.code));
await cart.ensure();
await cart.addProduct({ variant_id, quantity: 1, price: { package_id, package_item_id, price_id } });
const [line] = cart.product_items.get();
if (line) {
await cart.setProductQuantity({ line_item_id: line.id, quantity: 2 });
await cart.removeItem({ line_item_id: line.id });
}- Atoms:
cart,product_items,booking_items,package_items,item_count(product units, one per booking line, and each package line's quantity);quote_resultandpromotion_codes, wherepromotion_codesholds every code the quote lists, each with itsstate:applied,stopped(a promotion ahead of it stopped the ones after it) ornot_applied(it takes nothing off this cart);status:loading,syncing,fetching_quote,processing_checkout,errorandquote_error, where an error is{ code, message }.
- Reads:
ensure()loads the cart this browser selected for the buyer, package and market, or creates one under an id fromcreateId, kept across a lost answer.load()only loads;create({ id?, place_of_sale? })only creates. A store whose branches issue fiscal receipts names the cart's place of sale,{ type: "store_location", store_location_id }or{ type: "none" }, when it creates the cart or later withsetPlaceOfSale({ place_of_sale }). With no session,load()answersnulland sends nothing, so a visitor who only browses never becomes a Customer; the first write identifies the visitor. A selected cart that now names another buyer, package or market ends the selection: another buyer or package is refused once withCartErrorother_cart, another market reads as no cart. - Changes: each answers the changed cart and sends the cart id and version for you. Line ids come from
createIdwhen you leave them out.- lines:
addProduct,addBooking,addPackage,setProductQuantity({ line_item_id, quantity }),removeItem({ line_item_id }),clear(); - checkout details:
shipTo({ destination, contact_email? }),setDeliveryGroups({ delivery_groups }),selectShippingMethod({ shipping_method_id }),setBillingAddress({ billing_address }),setBuyer({ buyer })(a company buyer'spurchase_order_number; the buyer stays the one this cart store is for, elseCartErrornot_ready),setPlaceOfSale({ place_of_sale }),setPromotionCodes({ promotion_codes }), which replaces the whole list, so pass the codes you keep plus the new one; - package deliveries:
setFutureDeliveries({ packages })andquoteFutureDeliveries({ packages }).
- lines:
- Quote and checkout:
quote({ contact_email? }),checkout(...),retainCheckout(...),pendingCheckout()andrecoverCheckout().checkoutandrecoverCheckoutanswer the placed order; the cart store keeps no copy of it. Most pages use the checkout flow instead. - After a failed write: a write whose answer is lost, or that is refused because the cart changed (409), drops the view:
cartandquote_resultturnnull, and the nextensure()reads the current cart.reset()drops the view by hand;clear()empties the cart in Arky. A change made while another change to the same cart is still being sent is refused withCartErrorbusybefore anything is sent, and the view keeps the first change's answer. - Prices. Every line names the exact price it is bought at,
price: { package_id, package_item_id, price_id }, one of its item's prices read withpackageItem.findPrices, so product, booking and package lines name it the same way. A cart is priced from its own package only: a club's prices are the products the club package lists, bought in a cart of that package, and money off for its members in another shop is a promotion with apackagecondition.
A cart line names its variant. To show names, quote the cart and read its products:
import { findBlock, getBlockTextValue } from "arky-sdk/storefront";
const cart = arky.eshop.cart({ buyer: { type: "customer" }, package_id });
await cart.ensure();
const quote = await cart.quote();
console.log(quote.lines.map((line) => (line.type === "product" ? getBlockTextValue(findBlock(line.product, "name"), "en") : line.type)), quote.totals.total);The quote is in the store's locale, and each product line's snapshot keeps the variant's variant_sku and variant_blocks as they were quoted. A product line's compare_at is its price's comparison amount, or null when the price has none. A product line also names its product ({ id, key, blocks }) and its variant's shipping_profile_id (null when the variant doesn't ship), so a page names the line and shipTo groups shipped lines by profile without reading any variant. The cart's own product lines answer their product_id, which a cart update never sends back. A delivery's money is { price, discounts, tax }, where only a delivery's tax may be follow_goods. quote.ready is false while quote.blockers lists what is missing: a delivery, a shipping choice, a billing address, a taken booking slot, and so on. Each delivery's offers name their shipping method by shipping_method_key and shipping_method_blocks, so a page can show "Courier €45". A rate that needs a weight Arky doesn't know is left out of offers and listed in the delivery's unavailable with its code (SHIPPING.WEIGHT_UNKNOWN).
Arky works out every amount a page shows, so a page never adds up money itself:
- Line totals. Each product, booking and package line has
totals: { subtotal, discount, tax, total }, a booking line's for all itscapacity_unitsand a package line's the sum of its items, each of which (get_product,rent_product) has its owntotals.totalissubtotal - discount + taxin a tax-exclusive market andsubtotal - discountin an inclusive one. - Delivery totals. Each delivery has
totalsin the same shape,nulluntil its shipping is chosen. The quote'stotalsare the sums of the line and delivery totals, so the parts always add up tototals.total. - One shipping method for the whole cart.
shipping_choices: [{ shipping_method_id, amount }]lists each method that serves every delivery, with the sum of its offers, which is whatselectShippingMethod({ shipping_method_id })sets before delivery promotions and tax. - Delivery estimates. A delivery's and an offer's
delivery_estimateis{ min, max }in business days, ornull.
4. Checkout
arky.eshop.checkoutFlow({ buyer, package_id }) is a headless checkout for your own cart page: steps, state and errors, and no UI.
import { mountCheckoutAction } from "arky-sdk/storefront";
const checkout = arky.eshop.checkoutFlow({ buyer: { type: "customer" }, package_id });
checkout.state.subscribe((state) => console.log(state.step, state.error?.code));
let state = await checkout.open();
checkout.setContact({ contact_email: { email: "[email protected]", language: "en" } });
state = await checkout.shipTo({ destination: { type: "delivery", address } });
for (const delivery of state.quote?.deliveries ?? []) {
const [offer] = delivery.offers;
if (offer) {
state = await checkout.selectShipping({
delivery_group_id: delivery.delivery_group_id,
shipping_method_id: offer.shipping_method_id,
rate_id: offer.rate_id,
});
}
}
if (state.step === "payment") state = await checkout.place({ return_url: (orderId) => `${location.origin}/order?order_id=${orderId}` });
const placed = state.placed;
if (placed && placed.payment_action.type !== "none") {
await mountCheckoutAction({ action: placed.payment_action, payment_id: placed.payment_id, element: "#payment" });
}- Steps.
state.stepis one of:cart: no lines, a line that can't be bought as it is (a taken booking slot, a price that can't hold its fixed per-unit fee:tax_unavailable, a package that would put the buyer under a second purchase minimum:package_minimum_conflict, or aswitchoramendline whose change Arky refuses:package_change_refused, with that refusal'scode), or a cart that needs a payment none of the market's payment options can take (payment_unavailable, with the reason'scode), named inquote.blockers. A package change keeps its membership, so its new minimum never counts as a second one. While one of the buyer's memberships has a package change waiting, a line for a package of the offering that change moves into is blocked withpackage_change_scheduled, and placing it is refused withPACKAGE_MEMBER.CHANGE_SCHEDULED;details: the contact email, an address, the billing address, a purchase order number or the place of sale is missing (place_of_sale_required: set it withsetPlaceOfSale), the chosen branch doesn't sell now (place_of_sale_not_active), a company buyer at a place whose fiscal system is TaxCore has no verified tax ID for that country that TaxCore takes (fiscal_buyer_tax_id_required), a package line still needs a delivery (package_delivery_required, a renewingswitchline's new shipping profile included), or a delivery no longer fits its lines (delivery_unavailable: set it again withshipTo);shipping: a delivery needs its shipping choice;payment: ready to place;paying: the order waits for its payment, or a kept checkout waits forrecover();placed: paid, to pay later (cash on delivery), unconfirmed (the provider's answer needs checking) or free.- Every blocker kind has its step; a kind this SDK doesn't know yet holds the
cartstep.
- State: the
cart, thequotewith itsblockers,contact_email,contact_name({ first_name, last_name }ornull),destination(read from the cart's delivery),billing_address, the chosenpayment_option_id(the quote's suggestion until you pick one), thependingrequest, theplacedorder with itspayment_method_idandpayment_method_setup(set when placing saves a card), itspaymentandoutcome,busyanderror. - Steps you call. Each step that reads or writes Arky answers the new state.
setContactandselectPaymentOptiononly change the state.open()andrefresh()(quote again);setContact({ contact_email: { email, language }, contact_name? }),shipTo({ destination }),setPlaceOfSale({ place_of_sale }),setBillingAddress({ billing_address });selectShipping({ delivery_group_id, shipping_method_id, rate_id })andselectPaymentOption({ payment_option_id });setPromotionCodes({ promotion_codes });place({ return_url?, save_payment_method?, payment_method_terms? });reset()leavesplacedorpayingand keeps the contact, for a buyer who keeps shopping on the same page.open()drops a finished order by itself and keeps one still waiting for its payment.
- Contact. The order's contact is an email with the language its emails are written in, plus an optional
contact_namewith bothfirst_nameandlast_namethat the SDK never fills in.open()names no contact: the page sets it withsetContactfrom its own field, the billing address or the session, in the page language, and the flow stays ondetailsuntil then. EachsetContactstates the whole contact, so a name it leaves out is cleared. AftersetContact, every quote sends the email, so a guest can use a promotion code limited to one use per customer. A company buyer's purchase order number is set withcheckout.cart.setBuyer({ buyer }). - Placing.
placepays with one of the quote's payment options, or places a free order at a zero total. The quote'spayment_option_idslists only the options that can pay this cart, so pick from it as it is. A paid package is paid by card at checkout: a cart with a package line that charges money or saves a card lists only card options, and Arky refuses cash on delivery and manual options for it withCART.CARD_REQUIRED. When the cart needs a payment and no option can take it, the quote showspayment_unavailablewith the reason'scode(CART.CARD_REQUIRED,CART.DEDICATED_SETUP_NEEDS_STRIPE,PAYMENT_METHOD.TERMS_UNAVAILABLEorCART.PAYMENT_OPTION_UNAVAILABLE), and checkout answers that code. When a package line'ssaves_cardin the quote is true, the order saves the buyer's card:place({ payment_method_terms })passes the card wording the buyer accepted, the flow sendssave_payment_method: { type: "save", terms }, andplacewithout that wording, or withsave_payment_method: false, is refused withnot_readybefore anything is sent. Without such a line the flow sends{ type: "dont_save" }unless the page passessave_payment_method: truewith the wording. At a zero total a saved card sends the selected payment option instead of a free order, and Arky saves the card a renewing package needs through Stripe's setup; the quote then lists only Stripe options with saved-card wording in its language. Passstate.placed.payment_method_setuptomountPaymentMethodSetup({ setup, element }), confirm it, then calleshop.paymentMethod.completeSetup({ id: state.placed.payment_method_id }). Arky refuses that place withCART.NOTHING_DUEwhen no line saves a card. A Monri store can't take such a cart, because Arky saves a Monri card only from a paid checkout: its quote showspayment_unavailablewithCART.DEDICATED_SETUP_NEEDS_STRIPE. - On account. A company buyer with on-account terms checks out through the cart store instead:
checkout.cart.checkout({ contact_email: { email, language }, payment: { type: "on_account", payment_option_id } }). A cart with a package line that charges money or saves a card is never put on account (CART.ON_ACCOUNT_PAID_PACKAGE). A store that sells a membership paid by invoice sells a product and, once it is paid, gives the package through a zero-price order, or assigns it when the package needs no order. - After placing:
recover()finishes a kept checkout,resumePayment()reopens the order's checkout payment page while its payment window is open,refreshPayment()reads the payment again, andopenOrder({ order_id, url })reopens an order after a payment redirect.openOrderanswers{ state, url }, whereurlis the link without its order token. - Errors: every step throws a
CheckoutFlowErrorand records{ code, message }instate.error. The codes are:busy(a step is already running),not_readyandpending(recover the kept checkout first);presentation_changed: the state then shows the new quote, which the buyer reviews before placing again;refused,interrupted(try again orrecover()),unavailable(no browser storage or lock) andfailed.
Paying with Stripe or Monri
mountCheckoutAction({ action, payment_id, element, onComplete?, onValidationError? }) mounts the payment form into element (a selector or an element). It answers what it mounted, or null when the order has nothing to pay:
- Stripe mounts Stripe's embedded Checkout.
onCompleteruns when Stripe reports the payment done; callcheckout.refreshPayment()then, or read the order page after thereturn_urlredirect. - Monri mounts Monri's card form. It needs the
payment_idand the buyer's billing details, so call the mount'sconfirmfrom your pay button.onValidationErrorgets aMonriCheckoutErrorwith codeinvalid_cardwhile the card details are wrong, andnullwhen they are fine.
import { mountCheckoutAction, MonriCheckoutError } from "arky-sdk/storefront";
const placed = arky.eshop.checkoutFlow({ buyer: { type: "customer" }, package_id }).state.get().placed;
if (placed && placed.payment_action.type === "monri_components") {
const mount = await mountCheckoutAction({ action: placed.payment_action, payment_id: placed.payment_id, element: "#payment" });
if (mount?.type === "monri_components") {
try {
await mount.confirm({
full_name: "Ana Horvat",
address: "Main Street 1",
city: "Zagreb",
zip: "10000",
phone: "+385 1 234 567",
country: "HR",
email: "[email protected]",
});
} catch (error) {
if (!(error instanceof MonriCheckoutError)) throw error;
console.log(error.code);
}
}
}A MonriCheckoutError says what went wrong:
invalid_detailslets the buyer correct the form;unknown_resultmeans the payment needs checking, so never start a second checkout;already_submitted,invalid_actionandunavailable(Monri needs an HTTPS page).
Saved cards use eshop.paymentMethod.requestSetup, startSetup, mountPaymentMethodSetup({ setup, element }) and its confirm({ return_url }), then completeSetup, which answers the card as Arky holds it without asking Stripe; Stripe's own setup post is what makes it ready. A Monri option refuses this setup (PAYMENT_METHOD.DEDICATED_SETUP_NEEDS_STRIPE), because Arky saves a Monri card only from a paid checkout.
A membership replaces its card by saving a new one and selecting it: eshop.packageMember.selectPaymentMethod({ id, expected_updated_at, payment_method_id }) charges any renewal that's owed, and resume then restarts a blocked membership. A Stripe card is saved with the setup above. A Monri membership's buyer places a paid checkout under the Monri option with place({ save_payment_method: true, payment_method_terms }) and, once its payment succeeds, selects state.placed.payment_method_id. Arky has no payment page for an owed renewal order.
Each checkout action and card setup carries runs_on, which says where the payment runs: { type: "provider" }, or { type: "simulator", api_url } on a test store. These two mounts handle both, so the same site code works on a test store and a live one. A network's store-billing card setup also works with mountPaymentMethodSetup. On a test store the mount draws a test payment form in the page's own words: pass simulator_texts: { title, description, complete, decline, expire, cancel } to mountCheckoutAction and mountPaymentMethodSetup. A simulated payment mounted without them is refused with ArkyError not_ready; a live payment ignores them.
5. Order page
An order email links to the order with a #order_token=... fragment, so a guest can open it in any browser:
import { latestPayment, paymentAmounts, paymentOutcome } from "arky-sdk/storefront";
const opened = await arky.eshop.order.fromLink({ id: orderId, url: location.href });
history.replaceState(history.state, "", opened.url);
const payments = await arky.eshop.order.findPayments({ order_id: opened.order.id }, { order_token: opened.order_token });
const latest = latestPayment(payments);
console.log(opened.order.number, latest ? paymentOutcome(latest) : null, paymentAmounts(payments).net_paid);order.fromLink({ id, url })checks the token, reads the order with it, keeps the token for that order and answers{ order, url, order_token }, whereurlis the link without the token. A link without a token uses the token kept at checkout, or the customer's session. A malformed token is anArkyErrorwith codeinvalid_link.- Tokens are sent only when you pass them. Order reads send a token only as the request option
{ order_token }. The order, its payments and fulfillments,resumePayment,downloadAsset, cancellations, reschedules and returns accept it.order.retainedToken({ order_id })answers the kept one. Keep payment provider return URLs free of the token. paymentOutcome(payment)says what a payment means to the shopper:paid,awaiting,unconfirmed(the provider's answer is unclear and the team settles it, so tell the shopper you will email them) orfailed.latestPayment(payments)picks the newest.paymentAmounts(payments)adds up an order's payments (StorefrontPayment[]) as Arky does:paid,refunded,refund_pending,disputedandnet_paid.disputednets each reinstatement against its withdrawal, and counts a withdrawal Stripe reports in another currency as the dispute's own amount. It leaves out what is still owed, because that also subtracts the order's credits, which a storefront doesn't read.- Buyer's copies. Storefront order, payment and return reads answer the buyer's copies (
StorefrontOrder,StorefrontPayment,StorefrontReturn), which leave out what only the store team sees, such as who recorded a payment;paymentOutcome,paymentAmountsand the line helpers take them. - Invoices. A storefront order carries light copies
{ id, type, created_at }. Anunissued_invoicenames itsreason:awaiting_outside_number,awaiting_receipts,counter_heldorblocked. Issuedinvoiceandreversed_invoicecopies carry their number and issue time;credit_noteandreversalalso name the invoice they correct.outside_invoiceandoutside_credit_notecarry the merchant’s number and document ({ type: "link", url }with an HTTPS URL or{ type: "paper" }), and an outside credit note names its creditedinvoice_id.eshop.order.getInvoice({ order_id, invoice_id })reads a full document with the same Order access. Arky documents hold frozen seller, buyer, lines and totals;fiscal_receiptsnames their pending or numbered receipts. Payments belong to the Order. - Receipts. A storefront order carries its fiscal
receipts, oldest first, as light copies{ id, type, document, created_at }.typeissale,advance,next_advance,advance_settle,advance_return,advance_correction,final,refund,correctionorcopy, anddocumentnames the fiscal system with the receipt'sstate:tax_core(donewith itsinvoice_numberandverification_url),fbih_printer(donewith itsreceipt_number) orcroatia_ciswith itsnumber(donewith itsjir). Atax_corereceipt issued on another device isdone_on_other_devicewith itsinvoice_number. Anfbih_printerreceipt written by hand iswritten_by_handwith itshand_number, thenprinting_after_handanddone_after_handwith the printedreceipt_number, orprint_failed_after_handwhile the print waits for staff; one issued on another device isdone_on_other_devicewith itsreceipt_number, a string.
To order again, reorder({ id, order_id, buyer, package_id }) builds a new cart from the products the order bought directly, in the package you name (normally the buyer's current one) and the current market, at that package's prices there, with the same access as creating a cart there. The buyer is the order's own (CART.REORDER_BUYER). A product that package doesn't sell in that market, or that can't be bought now, is left out and listed in left_out; when nothing is left, Arky refuses with CART.REORDER_NOTHING_LEFT. The new cart becomes this browser's cart for that buyer, package and market, so the cart store's load() reads it:
const reordered = await arky.client.eshop.cart.reorder({
id: crypto.randomUUID(),
order_id: orderId,
buyer: { type: "customer" },
package_id,
});
const cart = await arky.eshop.cart({ buyer: { type: "customer" }, package_id }).load();
console.log(cart?.id === reordered.cart.cart.id, reordered.left_out.map((line) => line.variant_id));6. Customer sign-in
arky.session.subscribe((session) => console.log(session?.type));
await arky.customer.requestCode({ contact: { type: "email", email: "[email protected]", language: "en" } });
await arky.customer.verify({ code: "123456" });
const me = await arky.customer.getMe();
if (me) {
await arky.customer.updateMe({
expected_updated_at: me.customer.updated_at,
profile: [{ id: crypto.randomUUID(), key: "first_name", type: "text", value: "Ana" }],
});
}
const { items: orders } = await arky.eshop.order.find({ limit: 20 });
console.log(orders.length);
const signedOut = await arky.customer.logout();
console.log(signedOut.type);- Visitors, customers and contacts. A visitor signs in with a code sent to an email or a phone number, in a store that signs its own customers in: a store of an
Isolatednetwork, or any test store.requestCode({ contact })takes{ type: "email", email, language }or{ type: "phone", number, language }(E.164, such as+38761234567) and sends the code by email or SMS in that language, one of the store's languages. The code message's id comes fromcreateId; a lost answer is retried under the same id, so the customer gets one message. The accepted code signs in to the store's own account for that address: a code for an address whose account is already linked to a customer of the store signs the visitor in to that customer, and otherwise the visitor's own customer is linked to the account. Either way the address becomes a confirmed contact. A customer'scontactsare where the store writes to the person, eachunconfirmed_emailorunconfirmed_phone(typed in, not proved) orconfirmed_emailorconfirmed_phone(the person proved it); they never sign anyone in, and several customers may hold one address. Itslinksshow{ type: "own" }for each account that signs in to it, never the account. A store of aConnectednetwork refuses its own customer codes with409 CUSTOMER_SIGN_IN.NETWORK_SIGN_IN: its customers sign in through the network (Network customer sign-in). verifysigns the customer in under a new session id fromcreateSessionId. Itssessionisstore_customer_signed_in_by_emailwith theemailorstore_customer_signed_in_by_phonewith thenumberit signed in with, and the client'ssession.signed_in_withnames that address. When the visitor signs in as a customer who already exists, Arky merges the visitor's cart into that customer's cart, and the cart store follows it. A staff invite's message gives its templatecode,emailornumber, andcode_days; the page its link opens passes them back asverify({ code, email })orverify({ code, number }). An invite opens only with its own code.- Sign-in refusals carry their own codes:
CUSTOMER_SIGN_IN.CODE_RECENT(a new code within the configured interval, sixty seconds in production),CUSTOMER_SIGN_IN.CODE_INVALID(a wrong or expired code, or none waiting) andCUSTOMER_SIGN_IN.ATTEMPTS_EXHAUSTED(too many wrong codes for the address). - No session, no visitor. With no session,
getMe()answersnulland sends nothing, aseshop.cart.getCurrentand a cart store'sload()do. The first write, such as a code request, a cart or a form submission, identifies the visitor. - Signing out.
logout()forgets the session in this browser and answers{ type: "revoked", session_id }when Arky confirmed it,{ type: "unconfirmed", session_id }when the request failed, so an earlier copy of the session may still work until it expires, or{ type: "local_only" }when there was no session. - Session lifetime. A signed-in session's access token lasts an hour; the SDK refreshes it on the first 401 and keeps every cart and checkout view. Every tab of a browser uses the one stored session: the SDK reads it for each request, refreshes it in one tab at a time under a Web Lock, uses a session another tab already refreshed instead of refreshing again, and reports a session another tab changed to
onAuthStateChanged. A browser without Web Locks refuses the refresh withArkyErrorstorage. A browser that refuses storage keeps the session in that tab only, and the client'ssessionStorageUnavailableis thentrue, so the site can tell the shopper that other tabs won't share the sign-in. Only Arky's own refusal of that refresh (401GENERAL.UNAUTHENTICATEDor 403GENERAL.UNAUTHORIZEDin Arky's error body) clears the session and reports it toonAuthStateChangedand thesessionatom. Any other failed refresh, such as a 401 or 403 from a proxy, a 429 or a 5xx, fails that request with the refresh's error and keeps the session for the next try. A refresh whose answer was lost after Arky made the new session has already replaced the old one, so the next refresh is refused and the shopper signs in again. A visitor whose token Arky itself refuses (401GENERAL.UNAUTHENTICATEDin Arky's error body, for example after the visitor session expired) is replaced: the SDK identifies a new visitor and sends the request once more. Any other 401, such as a proxy's, fails that request and keeps the visitor. Changing the shopper, signing out or switching markets clears checkout contact, delivery, payment selection and the displayed order. A late response from the previous context cannot restore them; a kept checkout request stays in the browser for explicit recovery by the customer who kept it, and another customer signed in on the same browser neither sees it nor is blocked by it. - Contacts. On a signed-in session,
requestCodesends a code to another email or number, andverifyContact({ address, code })confirms it as a contact and adds it to the person's sign-in, whereaddressis{ type: "email", email }or{ type: "phone", number }.addContact({ expected_updated_at, contact, sms })saves an unconfirmed contact,updateContact({ expected_updated_at, address, language, sms })changes the language its messages are written in or a phone's SMS consent, andremoveContact({ expected_updated_at, address })removes it; removing a contact never ends a sign-in. A customer holds each address once (CUSTOMER_CONTACT.EXISTS) and at most the configured number of contacts (CUSTOMER_CONTACT.LIMIT).unsubscribe({ address })andresubscribe({ address })record one email's choice. Each answer isCustomerMe,{ customer, session }, and the stored session takes its customer at once.removeLink()removes the signed-in customer's own link, ends this browser's session and answers{ removed: true }; a customer's last link stays while it owns a saved card or holds a company membership (CUSTOMER_LINK.LAST_LINK). - A visitor fills in its own record. A visitor that never signs in uses
getMe,updateMe,addContact,updateContactandremoveContacttoo, so a booking page saves the person's name, phone and SMS consent without a sign-in. Only a code confirms an address: a visitor's contacts stay unconfirmed untilrequestCodeandverifysign it in. - Name and SMS consent. A customer's
updateMe, a visitor's included, also takesname({ first_name, last_name },nullto clear). Each phone contact holds its own SMS consent:sms: "on"records the customer's own yes for that number only, a number starts with SMS off unless the save that adds it turns it on, and the read showssmsas{ type: "off" }or{ type: "on", at }. The store team's customer read answers{ type: "off", at }, when the number's SMS became off, or{ type: "on", at, by }.
Network customer sign-in
In a Connected network, a customer signs in once through the network and opens a key at each store they use:
import { createNetworkCustomer } from "arky-sdk/storefront";
const network = createNetworkCustomer({ apiUrl: "https://api.arky.io", networkId: "0f6a3c84-2d19-4e75-b8a1-5c9e7d3b2f60" });
const session_id = crypto.randomUUID();
await network.requestCode({ session_id, reach: { type: "network" }, contact: { type: "email", email: "[email protected]", language: "en" } });
await network.verify({ session_id, code: "123456" });
const { items: stores } = await network.store.find();
const key = await network.store.openKey({ store_id: stores[0].store_id, id: crypto.randomUUID(), visitor_token: arky.customer.visitorToken });
arky.customer.useStoreKey(key);- Reach.
{ type: "network" }is the network's own portal: it opens every store the person uses and may change the person's logins.{ type: "store", store_id }is one store's own page: it reaches that store only (403 NETWORK_CUSTOMER_SIGN_IN.STORE_NOT_REACHEDat another) and never changes logins (409 ACCOUNT_LOGIN.NETWORK_REACH_REQUIRED). AnIsolatednetwork refuses the network sign-in (409 NETWORK_CUSTOMER_SIGN_IN.NOT_CONNECTED), and so does a test store (409 NETWORK_CUSTOMER_SIGN_IN.TEST_STORE). - The code.
requestCode({ session_id, reach, contact })answers{ session_id, code_expires_at }alike for every address and sends the code through the network's own Resend or Twilio login, with its customer texts in the contact's language (409 NETWORK.CUSTOMER_TEXT_MISSINGwithout one,NETWORK.RESEND_MISSINGorNETWORK.TWILIO_MISSINGwithout the login). The samesession_idand contact while the code is open answer the same pending sign-in.NETWORK_CUSTOMER_SIGN_IN.CODES_BUSYmeans the network's code budget is spent for now, andNETWORK_CUSTOMER_SIGN_IN.CODE_RECENTthat a code to that address went out moments ago.verify({ session_id, code })keeps the sign-in in this browser; a wrong, expired or replaced code answersNETWORK_CUSTOMER_SIGN_IN.CODE_INVALID, too manyNETWORK_CUSTOMER_SIGN_IN.ATTEMPTS_EXHAUSTED. - Store keys. A network sign-in never acts in a store itself.
store.openKey({ store_id, id, visitor_token })opens that store's key for the customer linked to the person there, else for the visitor whosevisitor_tokenit passes (arky.customer.visitorToken, ornull), else for a new customer, and the sign-in's address becomes a confirmed contact there.arky.customer.useStoreKey(key)makes the key the storefront client's session, so every storefront call works as for any signed-in customer. A key lives as long as its sign-in and has no refresh token: when Arky refuses it, the storefront client forgets it and identifies a new visitor. A key the store revoked can't be opened again by the same sign-in (409 NETWORK_CUSTOMER_SIGN_IN.KEY_REVOKED).store.acceptInvite({ store_id, id, code, sent_to })redeems that store's invite inside a sign-in with reach{ type: "store", store_id }and answers its key the same way, opened under the app-pickedid: the sameidagain answers that key, so a lost answer is sent again as it was, and anidthat names another record is refused with409. - The person's account.
getMe()answers{ account_id, logins, session }: the customer logins (customer_emailandcustomer_phone) and this sign-in'sreachandsigned_in_with. With reachnetwork,login.requestCode({ contact }),login.verify({ address, code, confirm_join })andlogin.remove({ address })change the logins, and every change tells the person's other logins. An address that belongs to another account of the network answers409 ACCOUNT_LOGIN.JOIN_CONFIRMATION_REQUIREDand joins that account only withconfirm_join: true;ACCOUNT_LOGIN.JOIN_LINKED_APARTnames a store where both are linked to different customers, which merges them first. The other refusals areACCOUNT_LOGIN.TAKEN,ACCOUNT_LOGIN.LIMIT,ACCOUNT_LOGIN.LAST_LOGIN,ACCOUNT_LOGIN.EMAIL_SESSION_REQUIRED(adding an email needs a sign-in with an email the account holds) andACCOUNT_LOGIN.OLDER_EMAIL_REQUIRED.store.find()lists the stores the person is linked to,store.removeLink({ store_id })removes the person's own link there, anddeleteAccount()deletes the account through a sign-in with its oldest email (409 ACCOUNT.ANCHOR_SESSION_REQUIRED), or answers409 ACCOUNT.MEMBER_SESSION_REQUIREDfor an account with memberships, which only its own member session deletes. A delete that would take a store customer's last link while that customer's saved card or company membership needs it answers409 CUSTOMER_LINK.LAST_LINK, as every account delete does. - Session. The client sends the
network_customer_access_token, refreshes once when Arky refuses it, and forgets the sign-in when Arky refuses the refresh. Itssessionis{ id, reach },onAuthStateChangedreports changes, andlogout()answers{ type: "ended", session_id },{ type: "unconfirmed", session_id }or{ type: "local_only" }.
7. Forms
import { FormAnswerError } from "arky-sdk/storefront";
const form = await arky.forms.getByKey({ key: "contact" });
try {
await arky.forms.submit({ form, values: { email: "[email protected]", message: "Hello" }, language: "en" });
} catch (error) {
if (error instanceof FormAnswerError) console.log(error.questionKey, error.code);
else throw error;
}- Submitting.
forms.submittakes the loadedformand a{ key: value }map, checks each value against its question and builds the answers. You can also passform_id,questions_updated_atandanswersthat you built yourself. - Answer errors. A value that doesn't fit throws a
FormAnswerErrorwith the question's key and a code:required,invalid,too_short,too_long,pattern_mismatch,too_small,too_large,unknown_option,too_many_files(more than the question'smax_files),file_size(an empty file),file_nameorunknown_question. - Lengths and patterns. Text lengths count characters as Arky does, so an emoji counts once. A question's
patternis checked before sending only where JavaScript reads it as Arky does: a pattern with\d,\wor\b(Unicode classes in Arky), or one JavaScript can't read, is left to Arky, which answers the question's field error. - Empty answers are left out. File answers carry
Fileobjects and are sent as multipart. Arky's configured limits refuse what is too big (production: 10 MiB a file, 20 files and 50 MiB a request): 413FORM_SUBMISSION.FILE_TOO_LARGE, 409FORM_SUBMISSION.TOO_MANY_FILESand 413GENERAL.PAYLOAD_TOO_LARGE. - The form a shopper sees.
forms.getandforms.getByKeyanswerStorefrontForm:id,key,questions,questions_updated_atandstatus, without the store's email and stage settings. - Changed forms. When the form's questions changed since you loaded it, Arky refuses with 409
FORM_SUBMISSION.FORM_CHANGED: load it again.
A long form can keep its answers in the browser until they are sent, so a lost answer survives a reload:
import { formValuesFromAnswers } from "arky-sdk/storefront";
const application = await arky.forms.getByKey({ key: "partner-application" });
const saved = await arky.forms.pendingSubmission({ form_id: application.id });
const restored = saved ? formValuesFromAnswers(saved.answers) : {};
const kept = saved ?? (await arky.forms.retainSubmission({ form: application, values: { company: "Kafana d.o.o." }, language: "en" }));
const sent = await arky.forms.recoverSubmission({ form_id: kept.form_id });
console.log(restored, sent?.id);retainSubmission keeps the whole submission, answers included, under an id from createId; it can't hold files. The same answers again answer the kept one; different ones are refused with DurableRequestError pending until it is sent. pendingSubmission reads it back and recoverSubmission sends it under the same id.
8. Bookings
arky.eshop.bookingCalendar({ buyer, package_id }) builds a month calendar and the free slots of a booking service, and adds a chosen slot to that buyer's cart:
const { items: services } = await arky.eshop.packageItem.find({ package_id, selection: { types: ["booking_service"] }, limit: 20 });
const calendar = arky.eshop.bookingCalendar({ buyer: { type: "customer" }, package_id });
const [service] = services;
if (service?.item.type === "booking_service") {
const state = await calendar.select({ booking_service_id: service.item.booking_service_id, store_location_id });
const day = state.days.find((cell) => cell.available);
if (day) calendar.selectDate({ date: day.iso });
const [slot] = calendar.state.get().slots;
if (slot) await calendar.addToCart({ slot });
}- State:
- the service:
booking_service,store_location_id(the branch the visit is at),booking_choices(the prices of its offerings in this package and market),booking_resources({ id, key, blocks, timezone }, from the availability rows),selected_booking_resource_id,availability,timezone(null: each slot in its resource's timezone) andloading; - the calendar:
monthanddays(date,iso,available,is_selected,is_in_range,is_today,blank), plus thecalendar.month_labelatom with the shown month in the store's language; - the choice:
selected_date,slots(booking_offering_id,store_location_id,booking_resource_id,price_ref,price,from,to,timezone,time_text,date_text,is_multi_day) andselected_slot.
- the service:
- Calls. Steps that read Arky answer the new state; picks only change the state.
- reads:
select({ booking_service_id, store_location_id }),prevMonth(),nextMonth(),selectResource({ booking_resource_id })andloadMoreChoices(); - picks:
selectDate({ date }),selectFirstAvailableDate(),selectSlot({ slot })andsetTimezone({ timezone }); addToCart({ slot, id?, capacity_units?, form_submission_id?, add_ons? })answers the cart. Passadd_onsfor an offering that has add-ons, each once; without them the line names none. The line names the slot's branch; its resource is{ type: "resource", booking_resource_id }afterselectResource, else{ type: "any" }, so Arky picks one.
- reads:
- Sign-out and language. Signing out or another buyer signing in empties the calendar, member prices included; call
selectagain. A language change writes the slot texts again in the new language. - Prices and resources.
selectreads the service and the first page of its item's prices; a slot shows once its offering's price is loaded, so callloadMoreChoices()whilebooking_choices_cursoris set. The resources come with the availability: each row names its resource'sresource_keyandresource_blocks, sobooking_resourceslists{ id, key, blocks, timezone }and the calendar reads no resource. - Months and time zones. A month read covers the shown month and a day on each side, up to 20 offerings a request, following
cursoruntil every offering is in: Arky ends a page before the offering that would pass its slot budget and answers the cursor of the rest. A slot shows in its resource's timezone (slot.timezone) under that zone's date, as a venue's own site shows it;setTimezone({ timezone })shows every slot in one zone instead, such as the visitor's for an online service. - Stays. A slot that crosses midnight, such as a night's stay, is
is_multi_day: itstime_textis the date range, and its days areis_in_rangeonce it is chosen. A booking lasts at most 24 hours, so a stay of several nights is one booking a night; with a booking of the same service already in the cart, the calendar opens on the month that booking ends in.
The cart and the checkout are the same as for products: the checkoutFlow of the same scope sees the booking lines.
- Without the calendar, read the service with
bookingService.get({ id, package_id }), its offerings' prices withpackageItem.findPrices({ package_item_id, package_id }), and the free slots at one branch withbookingService.getAvailability({ package_id, booking_service_id, store_location_id, from, to })(at most 60 days per read; followcursor). Each row names itsbooking_offering_id,store_location_idandbooking_resource_id. Add a slot withcart.addBooking({ booking_offering_id, store_location_id, resource, requested_interval, add_ons, capacity_units, price }), whereresourceis{ type: "any" }or{ type: "resource", booking_resource_id },add_onsnames each of the offering's add-ons once, every one being required, with the booker's resource pick for it ({ add_on_id, resource, form_submission_id?, add_ons }, empty when the offering has none); Arky picks the offering that fills each add-on and refuses picks that break the offering's rules withCART.BOOKING_ADD_ON_INVALIDandpriceis{ package_id, package_item_id, price_id }.bookingOffering.get({ id, package_id })reads one offering with its price, andbookingResource.get({ id, offering_id, package_id })one resource it can use. - What the quote plans. Each quote booking line has
availability:availablewithspotsand theplan,historywith theplan, orunavailablewith itscode. The plan names the resource Arky picked, the line'sinterval, itstotal_intervalwith every add-on, and each add-on's own interval and resource. - Taken slots. The quote checks the slot again: a taken slot is a
booking_unavailableblocker. - Later changes.
eshop.order.cancelBookingItemandrescheduleBookingItemchange a booking after the order; both name the line asorder_booking_item_id. - The patient's answer. An upcoming booking's
status.attendanceis{ type: "upcoming", response }, whereresponseisunanswered,comingorchange_requestedwith itsat; a reschedule sets it back tounanswered.eshop.order.answerBookingItem({ order_id, order_booking_item_id, starts_at, answer })records the signed-in customer'sanswer("coming"or"change_requested") for the start they saw. A reminder carries a signed answer link:eshop.order.answerBookingByLink({ token, answer })needs no session and answers{ order_id, order_booking_item_id, starts_at, response }. A stale start is refused with409 GENERAL.CONFLICTand an answer after the start withORDER.BOOKING_CHANGE_CLOSED. - Resources.
eshop.bookingResource.get({ id, offering_id, package_id })accepts an id or a slug in the client’s locale. Slugs are unique per store and language; the supplied offering must be visible and be able to use that resource. A booking resource has no type: its categories say what it is. Itshoursname the branch of each window ({ store_location_id, from, to }, times of day in milliseconds). - Order booking lines. A booking line names its
store_location_id,customer_id,intervalandtotal_interval(with every add-on), itsadd_ons(each with its own offering, service, resource,interval,price{ type: "free" }or{ type: "listed", price, amount }, andstatusheldortaken_off) andchanges, the staff changes to the line (line,add_on,add_on_addedoroffering_changed, withbyandat).
9. Content and media
const site = await arky.content.load({ collection: { key: "website" } });
const title = site.object("info")?.text("title");
const post = await arky.content.load({ entry: { collection_id, slug: "launch" } }, { locale: "it" });
const posts = await arky.content.loadEntries({ collection_id, limit: 20 });
const older = posts.cursor ? await arky.content.loadEntries({ collection_id, limit: 20, cursor: posts.cursor }) : null;
console.log(title, site.media("hero")?.id, post.text("title"), posts.items.length, older?.items.length);content.loadreads one collection ({ id }or{ key }) or one entry ({ id },{ collection_id, key }or{ collection_id, slug }), with the media its blocks name.loadEntriesreads one page of a collection's entries (limit, 20 unless named, at most 100) with the media they name and answers{ items, cursor }; passcursorback for the next page. It never walks the whole collection.- Accessors. The answer has
record,blocks,media_by_idand accessors in the call's locale:block(key),text(key),media(key),object(key)andlist(key). Text is read in the exact language asked for, never another, and an accessor for a block of another type throws. - Missing entries. A key or slug that matches no entry throws an
ArkyErrorwith codenot_found. - Plain reads:
content.collection.get({ id }),content.collection.getByKey({ key }),content.entry.get({ id })andcontent.entry.find, which takescollection_idwithkey,slug,queryorfilters, or a list ofids. - Storefront shapes. These routes answer
StorefrontCollectionandStorefrontEntry. A collection hastype: "public"; an entry keeps its key and slugs intype: { type: "public", key, slugs }, so a loaded entry's URL usespost.record.type.slugs.it. Public entry create and update still takekeyandslugsas request fields. - Shared entries. After the customer signs in,
sharedEntries.find({ collection_id?, limit?, cursor? }),get({ id })andfileLink({ id, media_id, variant })read the entries shared with that customer asStorefrontSharedEntry. A file link answers{ url, expires_at }and lasts five minutes. These reads use the customer's session and each read is logged. Public content reads do not expose Private, Shared or Note entries.
Errors
Everything the SDK throws at runtime is an ArkyError with a code; map the code to your own text. Each class works with instanceof whichever entry point made it.
| Class | When | Codes |
|---|---|---|
| ArkyApiError | Arky answered with its own refusal | Arky's own, such as GENERAL.CONFLICT, GENERAL.NOT_FOUND and FORM_SUBMISSION.FORM_CHANGED, exactly as the Server sent it; it also has statusCode and validationErrors |
| CartPresentationChangedError | a checkout's quote changed (an ArkyApiError with code COMMERCE.PRESENTATION_CHANGED) | carries the new quote |
| ArkyNetworkError | no readable answer: no answer at all, a success that isn't JSON, or a refusal without Arky's error body, such as a proxy's 502 page (with its statusCode) | network, aborted, unreadable_answer |
| DurableRequestError | a retry-safe request couldn't run | storage (no localStorage or Web Locks; nothing was sent), busy, pending, answer_mismatch, settled_elsewhere |
| CartError | th
