@zappie/sdk 0.29.0 → 0.29.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/{client-B8lItidz.d.ts → client-CW_OWZ0l.d.ts} +1 -1
- package/dist/config/index.d.ts +8 -4
- package/dist/debug.js +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/persist/catalogue.d.ts +1 -1
- package/dist/server/index.d.ts +7 -4
- package/dist/testing/index.d.ts +1 -1
- package/dist/transport/mappers.js +1 -1
- package/dist/transport/rest.js +1 -1
- package/dist/transport/selected-menu.d.ts +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @zappie/sdk
|
|
2
2
|
|
|
3
|
+
## 0.29.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- f089b13: A menu still loads when one of its items can't be read. A maximum quantity of 0 on an item or a choice now means no limit. An item whose maximum is below its minimum shows as unavailable. An item the SDK can't read at all is left out of the menu, and the console names it.
|
|
8
|
+
|
|
9
|
+
## 0.29.1
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 529f284: Verify's hint for an error a check has no code for now says what such a failure means and where to look: the report's message, the check's screenshot and `verify.trace.zip` in the artifacts folder. A check that is not released yet says so and that verify skips it, and the reset step no longer names an internal plan. Each eslint-plugin-zappie option now describes itself in its schema, with its default, and the rule docs end without a semicolon. The SDK's budget docs give each budget's unit, in KiB, and its default. The SDK and verify call the store's identifier the business tag, as the dashboard does, and the starter README's verify example uses the real storefront API address.
|
|
14
|
+
|
|
3
15
|
## 0.29.0
|
|
4
16
|
|
|
5
17
|
### Minor Changes
|
|
@@ -330,7 +330,7 @@ interface StorageLike {
|
|
|
330
330
|
/** Settings for your storefront client. Each client keeps its own credentials and caches. */
|
|
331
331
|
type ZappieConfig = {
|
|
332
332
|
/**
|
|
333
|
-
*
|
|
333
|
+
* Your business tag, as the dashboard shows it under Settings, Business. The SDK names saved carts and caches by it and never sends
|
|
334
334
|
* it: the API finds the store from your key. Required.
|
|
335
335
|
*/
|
|
336
336
|
store: string;
|
package/dist/config/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Default site budgets: 200
|
|
2
|
+
* Default site budgets: 200 KiB gzipped JavaScript, 50 KiB gzipped CSS, 2500 ms LCP and 3000 ms until the first product card is tappable.
|
|
3
|
+
* A KiB is 1,024 bytes.
|
|
3
4
|
*/
|
|
4
5
|
declare const DEFAULT_BUDGETS: {
|
|
5
6
|
readonly jsKbGz: 200;
|
|
@@ -17,7 +18,7 @@ type RouteCssBudget = number | Record<string, number>;
|
|
|
17
18
|
* The store, theme and optional build policies you export from zappie.config.ts.
|
|
18
19
|
*/
|
|
19
20
|
type ZappieSiteConfig = {
|
|
20
|
-
/**
|
|
21
|
+
/** Your business tag, the same one you pass to `createZappie()`. Find it in the dashboard under Settings, Business. Required and non-empty. */
|
|
21
22
|
store: string;
|
|
22
23
|
/** Branch slugs for this site. When set, it needs at least one non-empty slug, each listed once. */
|
|
23
24
|
branches?: string[];
|
|
@@ -70,11 +71,13 @@ type ZappieSiteConfig = {
|
|
|
70
71
|
};
|
|
71
72
|
/** Each budget left out uses DEFAULT_BUDGETS. */
|
|
72
73
|
budgets?: {
|
|
74
|
+
/** The gzipped JavaScript, in KiB, each route loads with the client entry. Default: 200. */
|
|
73
75
|
jsKbGz?: number;
|
|
74
|
-
/** Every client stylesheet together, gzipped, in KiB. `zappie check` enforces it only while `routeCssKbGz` is unset. */
|
|
76
|
+
/** Every client stylesheet together, gzipped, in KiB. Default: 50. `zappie check` enforces it only while `routeCssKbGz` is unset. */
|
|
75
77
|
cssKbGz?: number;
|
|
78
|
+
/** The menu's largest contentful paint budget, in milliseconds. Default: 2500. `zappie verify` fails a menu over 2500 ms whatever this says. */
|
|
76
79
|
lcpMs?: number;
|
|
77
|
-
/** V15's limit for the first product card to become tappable. Values below 3000 use 3000. */
|
|
80
|
+
/** V15's limit, in milliseconds, for the first product card to become tappable. Default: 3000. Values below 3000 use 3000. */
|
|
78
81
|
tappableMs?: number;
|
|
79
82
|
/**
|
|
80
83
|
* The gzipped CSS, in KiB, a route may load on its first load: the shared base plus that route's own stylesheets.
|
|
@@ -95,6 +98,7 @@ type ZappieSiteConfig = {
|
|
|
95
98
|
* `zappie verify` fails. Unset, verify warns above 50 percent and never fails.
|
|
96
99
|
*/
|
|
97
100
|
unusedCssPercent?: number;
|
|
101
|
+
/** Why a budget is above its default. Without a reason, a raised budget is a config error. With one, it is a warning. */
|
|
98
102
|
override?: {
|
|
99
103
|
reason: string;
|
|
100
104
|
};
|
package/dist/debug.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var VERSION=true?"0.29.
|
|
1
|
+
var VERSION=true?"0.29.2":"0.0.0-development";function installDebug(client){if(typeof window==="undefined"||client.mode!=="test"){return}const events=[];let quote;const emit=(name,detail)=>{const event={name,detail,at:new Date().toISOString()};events.push(event);window.dispatchEvent(new CustomEvent("zappie:event",{detail:event}))};globalThis.__zappieEmit=emit;window.__zappie={version:VERSION,store:client.config.store,async catalogue(){await client.cart.hydrate();const branch=(await client.store.get()).branches.find(value=>value.id===client.cart.getSnapshot().branchId);return{branch,menu:await client.menu.get({branch:branch.id})}},cart:Object.assign(()=>client.cart.getSnapshot(),{async inject(input){await client.cart.hydrate();if(input.lines.length>100||input.lines.some(line=>!Number.isInteger(line.quantity??1)||(line.quantity??1)<1||(line.quantity??1)>99)){throw new Error("Use up to 100 cart lines with whole quantities from 1 to 99.")}const snapshot=client.cart.getSnapshot();const value={v:1,menuVersion:client._internal.cartCatalogue().version,updatedAt:Date.now(),fulfilment:snapshot.fulfilment,promoCode:snapshot.promoCode,lines:input.lines.map((line,index)=>({...line,id:`debug_${index}`,name:line.itemId,quantity:line.quantity??1,choices:(line.choices??[]).map(choice=>({...choice,quantity:choice.quantity??1})),inputs:line.inputs??{},addedAt:new Date().toISOString()}))};const scope=client.config.cart?.storageScope;(client.config.storage??window.localStorage).setItem(`zappie:cart:v1:${client.config.store}:${snapshot.branchId}${scope?`:${scope}`:""}`,JSON.stringify(value))}}),quote:()=>quote,events};client.on("add_to_cart",detail=>emit("add_to_cart",detail));client.cart.subscribe(()=>{const state=client.cart.state;const next="quote"in state?state.quote:void 0;if(next&&next!==quote){quote=next;emit("quote",next)}})}export{installDebug};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as ZappieError, T as Transport, R as RequestCtx, g as MenuFulfilment, h as MenuResponse, k as SearchRequest, l as SearchPage, m as MenuVersion } from './client-
|
|
1
|
+
import { a as ZappieError, T as Transport, R as RequestCtx, g as MenuFulfilment, h as MenuResponse, k as SearchRequest, l as SearchPage, m as MenuVersion } from './client-CW_OWZ0l.js';
|
|
2
2
|
import { SelectedMenuRequest, SelectedMenuResponse } from './transport/selected-menu.js';
|
|
3
|
-
export { A as API_VERSION, E as ErrorDetails, e as MenuReadOptions, M as MenuResource, n as ReadOptions, S as StorageLike, c as StoreResource, Z as Zappie, b as ZappieClientOptions, b as ZappieConfig, f as ZappieErrorCode, d as ZappieEvents, o as createZappie, p as isZappieError } from './client-
|
|
3
|
+
export { A as API_VERSION, E as ErrorDetails, e as MenuReadOptions, M as MenuResource, n as ReadOptions, S as StorageLike, c as StoreResource, Z as Zappie, b as ZappieClientOptions, b as ZappieConfig, f as ZappieErrorCode, d as ZappieEvents, o as createZappie, p as isZappieError } from './client-CW_OWZ0l.js';
|
|
4
4
|
import { g as CartIssue, a as Quote, b as CartLineInput, C as CartLine, Q as QuoteRequest, i as WireQuote } from './types-CuPaBf6k.js';
|
|
5
5
|
export { A as AppliedPerk, j as CartFix, c as CartFulfilment, e as CartIssueCode, d as CartModule, k as CartSnapshot, f as CartState, l as CartSyncAdapter, m as CartSyncDocument, n as CheckoutCustomer, D as DeliveryAddress, P as PendingFulfilment, o as WireFix, W as WireFulfilment, p as WireIssue, q as WireLine, h as WireMoney } from './types-CuPaBf6k.js';
|
|
6
6
|
import { I as Item, O as OptionGroup, M as Money, a as Menu, B as Branch, S as Store, C as CategoryPage } from './models-C77LjkK8.js';
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ZappieCartError}from"./cart/errors.js";import{holdsForLater,isHeldQuote}from"./cart/held.js";import{previewItem}from"./cart/preview.js";import{estimateUnitPrice}from"./cart/price.js";import{resolveSourceMenu,withDefaultMenu}from"./cart/source-menu.js";import{validateLine}from"./cart/validate.js";import{createZappie}from"./client.js";import{API_VERSION}from"./config.js";import{ZappieError,isZappieError}from"./errors.js";export*from"./models.js";import{format,money}from"./money.js";import{RestTransport}from"./transport/rest.js";var VERSION=true?"0.29.
|
|
1
|
+
import{ZappieCartError}from"./cart/errors.js";import{holdsForLater,isHeldQuote}from"./cart/held.js";import{previewItem}from"./cart/preview.js";import{estimateUnitPrice}from"./cart/price.js";import{resolveSourceMenu,withDefaultMenu}from"./cart/source-menu.js";import{validateLine}from"./cart/validate.js";import{createZappie}from"./client.js";import{API_VERSION}from"./config.js";import{ZappieError,isZappieError}from"./errors.js";export*from"./models.js";import{format,money}from"./money.js";import{RestTransport}from"./transport/rest.js";var VERSION=true?"0.29.2":"0.0.0-development";export{API_VERSION,RestTransport,VERSION,ZappieCartError,ZappieError,createZappie,estimateUnitPrice,format,holdsForLater,isHeldQuote,isZappieError,money,previewItem,resolveSourceMenu,validateLine,withDefaultMenu};
|
package/dist/internal.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { q as CATALOGUE_MAX_AGE_MS, r as CATALOGUE_MAX_BYTES, s as CatalogueScope, t as SavedCatalogue, u as catalogueDigest, w as catalogueKey, x as createCatalogueStorage, y as createSavedCatalogue } from '../client-
|
|
1
|
+
export { q as CATALOGUE_MAX_AGE_MS, r as CATALOGUE_MAX_BYTES, s as CatalogueScope, t as SavedCatalogue, u as catalogueDigest, w as catalogueKey, x as createCatalogueStorage, y as createSavedCatalogue } from '../client-CW_OWZ0l.js';
|
|
2
2
|
import '../models-C77LjkK8.js';
|
|
3
3
|
import '../types-CuPaBf6k.js';
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Branch, Store, Menu, Item, Formatters } from '../index.js';
|
|
2
|
-
import { C as Cache } from '../client-
|
|
2
|
+
import { C as Cache } from '../client-CW_OWZ0l.js';
|
|
3
3
|
import { ZappieError, Zappie, ZappieConfig, Transport, StorageLike, StoreResource, MenuResource, ZappieEvents, MenuReadOptions } from '../index.js';
|
|
4
4
|
export { VERSION } from '../index.js';
|
|
5
5
|
import { CartModule, CartLineInput } from '../index.js';
|
|
@@ -975,7 +975,7 @@ type RouteCssBudget = number | Record<string, number>;
|
|
|
975
975
|
* The store, theme and optional build policies you export from zappie.config.ts.
|
|
976
976
|
*/
|
|
977
977
|
type ZappieSiteConfig = {
|
|
978
|
-
/**
|
|
978
|
+
/** Your business tag, the same one you pass to `createZappie()`. Find it in the dashboard under Settings, Business. Required and non-empty. */
|
|
979
979
|
store: string;
|
|
980
980
|
/** Branch slugs for this site. When set, it needs at least one non-empty slug, each listed once. */
|
|
981
981
|
branches?: string[];
|
|
@@ -1028,11 +1028,13 @@ type ZappieSiteConfig = {
|
|
|
1028
1028
|
};
|
|
1029
1029
|
/** Each budget left out uses DEFAULT_BUDGETS. */
|
|
1030
1030
|
budgets?: {
|
|
1031
|
+
/** The gzipped JavaScript, in KiB, each route loads with the client entry. Default: 200. */
|
|
1031
1032
|
jsKbGz?: number;
|
|
1032
|
-
/** Every client stylesheet together, gzipped, in KiB. `zappie check` enforces it only while `routeCssKbGz` is unset. */
|
|
1033
|
+
/** Every client stylesheet together, gzipped, in KiB. Default: 50. `zappie check` enforces it only while `routeCssKbGz` is unset. */
|
|
1033
1034
|
cssKbGz?: number;
|
|
1035
|
+
/** The menu's largest contentful paint budget, in milliseconds. Default: 2500. `zappie verify` fails a menu over 2500 ms whatever this says. */
|
|
1034
1036
|
lcpMs?: number;
|
|
1035
|
-
/** V15's limit for the first product card to become tappable. Values below 3000 use 3000. */
|
|
1037
|
+
/** V15's limit, in milliseconds, for the first product card to become tappable. Default: 3000. Values below 3000 use 3000. */
|
|
1036
1038
|
tappableMs?: number;
|
|
1037
1039
|
/**
|
|
1038
1040
|
* The gzipped CSS, in KiB, a route may load on its first load: the shared base plus that route's own stylesheets.
|
|
@@ -1053,6 +1055,7 @@ type ZappieSiteConfig = {
|
|
|
1053
1055
|
* `zappie verify` fails. Unset, verify warns above 50 percent and never fails.
|
|
1054
1056
|
*/
|
|
1055
1057
|
unusedCssPercent?: number;
|
|
1058
|
+
/** Why a budget is above its default. Without a reason, a raised budget is a config error. With one, it is a warning. */
|
|
1056
1059
|
override?: {
|
|
1057
1060
|
reason: string;
|
|
1058
1061
|
};
|
package/dist/testing/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as Cache } from '../client-
|
|
1
|
+
import { C as Cache } from '../client-CW_OWZ0l.js';
|
|
2
2
|
import { Transport, ZappieErrorCode, StorageLike, StoreResource, MenuResource, ZappieEvents, MenuReadOptions } from '../index.js';
|
|
3
3
|
import { Store, Menu, Formatters } from '../index.js';
|
|
4
4
|
export { VERSION } from '../index.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ZappieError}from"../errors.js";import{money}from"../money.js";var UnsupportedValue=class extends Error{};function record(value){if(!value||typeof value!=="object"||Array.isArray(value)){throw new ZappieError("server_error","Invalid storefront response object")}return value}function text(value){if(typeof value!=="string"){throw new ZappieError("server_error","Invalid storefront response string")}return value}function list(value){if(!Array.isArray(value)){throw new ZappieError("server_error","Invalid storefront response list")}return value}function number(value){if(typeof value!=="number"||!Number.isFinite(value)){throw new ZappieError("server_error","Invalid storefront response number")}return value}function nonnegative(value){const result=number(value);if(result<0){throw new ZappieError("server_error","Negative selection or quantity bound")}return result}function bounds(
|
|
1
|
+
import{ZappieError}from"../errors.js";import{money}from"../money.js";var UnsupportedValue=class extends Error{};function record(value){if(!value||typeof value!=="object"||Array.isArray(value)){throw new ZappieError("server_error","Invalid storefront response object")}return value}function text(value){if(typeof value!=="string"){throw new ZappieError("server_error","Invalid storefront response string")}return value}function list(value){if(!Array.isArray(value)){throw new ZappieError("server_error","Invalid storefront response list")}return value}function number(value){if(typeof value!=="number"||!Number.isFinite(value)){throw new ZappieError("server_error","Invalid storefront response number")}return value}function nonnegative(value){const result=number(value);if(result<0){throw new ZappieError("server_error","Negative selection or quantity bound")}return result}function bounds(min,max){const lower=nonnegative(min);if(!max){return{min:lower}}const upper=nonnegative(max);if(upper<lower){throw new UnsupportedValue("a maximum below its minimum")}return{min:lower,max:upper}}var isString=value=>typeof value==="string";var isBoolean=value=>typeof value==="boolean";function opt(key,value,is){return is(value)?{[key]:value}:{}}function mapMoney(value){const v=record(value);return money(number(v.amount_minor),text(v.currency))}function hours(value){return list(value??[]).map(slot=>{const v=record(slot);const day=number(v.day);if(!Number.isInteger(day)||day<0||day>6){throw new ZappieError("server_error","Invalid opening day")}return{day,opens:text(v.open),closes:text(v.close),...opt("disabled",v.disabled,isBoolean)}})}function schedule(v){if(v.hours===void 0&&v.preorder===void 0){return void 0}const preorder=v.preorder===void 0?void 0:record(v.preorder);return{openingTimes:hours(v.hours),...preorder?{preorder:true,preorderNoticeHours:number(preorder.notice_hours),preorderMaxDays:number(preorder.max_days)}:{}}}function mapGroup(value){const g=record(value);const isAttribute=g.kind==="attribute";const kind=text(g.kind);if(!["attribute","choice","text"].includes(kind)){throw new UnsupportedValue(`an option input kind "${kind}"`)}return{id:text(g.id),name:text(g.name),kind:kind==="text"?"text":"select",required:typeof g.required==="boolean"?g.required:number(g.min)>0,selection:bounds(g.min,g.max),isAttribute,choices:list(g.choices??[]).map(raw=>{const c=record(raw);const price=mapMoney(c.price);return{id:text(c.id),name:text(c.name),price:isAttribute?money(0,price.currency):price,...isAttribute&&c.price_hint!==void 0?{priceHint:mapMoney(c.price_hint)}:{},isAvailable:c.available===true,...c.variable_quantity===true?{quantity:bounds(c.min_quantity??1,c.max_quantity)}:{}}}),...opt("helpText",g.help_text,isString),...isString(g.placeholder)?{input:{placeholder:g.placeholder}}:{},...g.conditions?{conditions:list(g.conditions).map(raw=>{const c=record(raw);const count=c.count?record(c.count):void 0;if(count&&!["eq","gte","lte"].includes(text(count.op))){throw new UnsupportedValue(`an option count operator "${text(count.op)}"`)}if(c.match!==void 0&&c.match!=="any"&&c.match!=="all"){throw new UnsupportedValue(`an option match operator "${String(c.match)}"`)}if(c.set_required!=null&&typeof c.set_required!=="boolean"){throw new ZappieError("server_error","Invalid conditional required flag")}return{groupId:text(c.group_id),choiceIds:list(c.choice_ids??[]).map(text),match:c.match==="all"?"all":"any",...count?{count:{op:text(count.op),value:nonnegative(count.value)}}:{},...c.set_required!==void 0?{setRequired:c.set_required}:{},...c.set_min!==void 0?{setMin:c.set_min===null?null:nonnegative(c.set_min)}:{},...c.set_max!==void 0?{setMax:c.set_max===null?null:nonnegative(c.set_max)}:{}}})}:{}}}function mapPromo(value){const p=record(value);return{name:text(p.name)}}function mapItem(value){const v=record(value);const id=text(v.id);let unsupported=false;const tolerate=map=>{try{return map()}catch(error){if(!(error instanceof UnsupportedValue)){throw error}unsupported=true;console.warn(`Zappie item ${id} uses ${error.message} this SDK can't validate; it is shown as unavailable`)}};const optionGroups=list(v.option_groups??[]).flatMap(raw=>tolerate(()=>mapGroup(raw))??[]);const quantity=tolerate(()=>bounds(v.min_quantity??1,v.max_quantity))??{min:1};let unresolved=false;const variants=list(v.variants).map(raw=>{const x=record(raw);const seen=new Set;return{id:text(x.id),attributeChoices:Object.fromEntries(list(x.choice_ids).map(rawId=>{const choiceId=text(rawId);const groups=optionGroups.filter(group=>group.isAttribute&&group.choices.some(choice=>choice.id===choiceId));if(groups.length!==1||seen.has(groups[0].id)){unresolved=true;return["",choiceId]}seen.add(groups[0].id);return[groups[0].id,choiceId]}).filter(([groupId])=>groupId)),price:mapMoney(x.price),...opt("lowStock",x.low_stock,isBoolean),isAvailable:x.available===true,images:list(x.images??[]).map(text)}});if(unresolved){console.warn(`Zappie item ${id} has a variant whose choices don't match its attributes; it is shown as unavailable`)}if(unsupported||unresolved){for(const variant of variants){variant.isAvailable=false}}if(!variants.length){throw new ZappieError("server_error","An item must carry at least one exact variant")}if(new Set(variants.map(variant=>variant.id)).size!==variants.length){throw new ZappieError("server_error","Duplicate variant identity")}return{...v.placements!==void 0?{placements:list(v.placements).map(raw=>{const placement=record(raw);return{menuId:text(placement.menu_id),categoryId:text(placement.category_id)}})}:{},id,name:text(v.name),images:list(v.images??[]).map(text),price:mapMoney(v.price),isAvailable:!unsupported&&!unresolved&&v.available===true,quantity:{...quantity,step:1},variants,optionGroups,tags:list(v.tags??[]).map(text),...v.fulfilment!==void 0?{fulfilment:list(v.fulfilment).map(text)}:{},...opt("stockLabel",v.stock_label,isString),...v.promo!==void 0?{promo:mapPromo(v.promo)}:{},...opt("description",v.description,isString),...opt("descriptionHtml",v.description_html,isString),...v.previous_price?{compareAtPrice:mapMoney(v.previous_price)}:{}}}function mapMenu(value,branchId){const v=record(value);const sources=list(v.menus);if(v.completeness!==void 0&&v.completeness!=="partial"&&v.completeness!=="complete"){throw new ZappieError("server_error","Invalid catalogue completeness")}const categories=new Map;const menus=sources.map(raw=>{const m=record(raw);if(m.placement_count!==void 0&&(!Number.isSafeInteger(m.placement_count)||Number(m.placement_count)<0)||m.paginated!==void 0&&typeof m.paginated!=="boolean"){throw new ZappieError("server_error","Invalid menu loading metadata")}const categoryIds=list(m.categories??[]).map(rawCategory=>{const c=record(rawCategory);const id=text(c.id);const previous=categories.get(id);const itemIds=[...new Set([...previous?.itemIds??[],...list(c.item_ids??[]).map(text)])];categories.set(id,{id,name:text(c.name),itemIds});return id});const s=schedule(m);return{id:text(m.id),name:text(m.name),categoryIds,...m.fulfilment!==void 0?{fulfilment:list(m.fulfilment).map(text)}:{},...m.placement_count!==void 0?{placementCount:m.placement_count}:{},...opt("paginated",m.paginated,isBoolean),...s?{schedule:s}:{},...opt("infoBanner",m.info_banner,isString)}});const items=Object.fromEntries(Object.entries(record(v.items)).flatMap(([id,item])=>{try{const mapped=mapItem(item);if(mapped.id===id){return[[id,mapped]]}}catch{}console.warn(`Zappie item ${id} can't be read; it is left out of the menu`);return[]}));if(v.branch_id!==void 0&&v.branch_id!==branchId){throw new ZappieError("server_error","Menu branch mismatch")}return{id:menus.length===1?menus[0].id:`branch:${branchId}`,branchId,...v.completeness==="partial"?{completeness:"partial"}:{},name:menus.length===1?menus[0].name:"Catalogue",version:text(v.menu_version),categories:[...categories.values()],items,menus,...menus.length===1&&menus[0].schedule?{schedule:menus[0].schedule}:{}}}function mapSeo(value){const seo=record(value);if(typeof seo.hidden!=="boolean"){throw new ZappieError("server_error","Invalid store search visibility")}return{titlePattern:text(seo.title_pattern),description:text(seo.description),shareImageUrl:text(seo.share_image_url),searchConsoleToken:text(seo.search_console_token),hidden:seo.hidden,redirects:list(seo.redirects).map(raw=>{const redirect=record(raw);return{from:text(redirect.from),to:text(redirect.to)}})}}export{hours,isBoolean,isString,list,mapItem,mapMenu,mapMoney,mapSeo,opt,record,text};
|
package/dist/transport/rest.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ZappieError,wireError}from"../errors.js";import{delay,throwIfAborted}from"../internal/abort.js";import{money}from"../money.js";import{hours,isBoolean,isString,list,mapItem,mapMenu,mapMoney,mapSeo,opt,record,text}from"./mappers.js";var MAX_RETRY_WAIT_MS=5e3;var wireFulfilment=value=>value==="dineIn"?"dine_in":value;var presentationError=()=>new ZappieError("server_error","Invalid storefront presentation");var RestTransport=class{constructor(opts={}){const url=new URL(opts.baseUrl??"https://api.zappie.ai/storefront/v1");if(url.username||url.password||url.search||url.hash||url.protocol!=="https:"&&!(url.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(url.hostname))){throw new ZappieError("invalid_request","REST baseUrl requires HTTPS, or HTTP on localhost")}this.baseUrl=url.href.replace(/\/$/,"");this.fetcher=opts.fetch??((input,init)=>globalThis.fetch(input,init))}async request(path,ctx,etag,body){if(typeof window!=="undefined"&&ctx.key.startsWith("sk_")){throw new ZappieError("invalid_request","Secret keys cannot be sent from a browser")}for(let attempt=0;;attempt++){throwIfAborted(ctx.signal);let response;try{response=await this.fetcher(this.baseUrl+path,{method:body?"POST":"GET",...body?{body:JSON.stringify(body)}:{},redirect:"manual",headers:{...body?{"Content-Type":"application/json"}:{},...ctx.idempotencyKey?{"Idempotency-Key":ctx.idempotencyKey}:{},Authorization:`Bearer ${ctx.key}`,"Zappie-Version":ctx.version,...etag?{"If-None-Match":etag}:{}},...ctx.signal?{signal:ctx.signal}:{}})}catch(error){throwIfAborted(ctx.signal);if(attempt>=2){throw new ZappieError("network_error","Could not reach the storefront service",{cause:error})}await delay(100*2**attempt+Math.random()*100,ctx.signal);continue}if(response.ok||response.status===304){return response}const retry=response.headers.get("Retry-After");const seconds=retry!==null?Number(retry):NaN;const wait=retry!==null?Number.isFinite(seconds)?Math.max(0,seconds*1e3):Math.max(0,Date.parse(retry)-Date.now()):NaN;const tooLong=Number.isFinite(wait)&&wait>MAX_RETRY_WAIT_MS;if(attempt<2&&!tooLong&&(response.status===429||response.status>=500)){await response.body?.cancel();await delay(Number.isFinite(wait)?wait:100*2**attempt+Math.random()*100,ctx.signal);continue}const errorBody=await response.json().catch(()=>({}));throw wireError(errorBody,response.status,response.headers.get("Zappie-Request-Id")??void 0)}}async json(response){try{return await response.json()}catch(cause){if(cause instanceof Error&&cause.name==="AbortError"){throw cause}throw new ZappieError("server_error","The storefront service returned invalid JSON",{status:response.status,cause})}}async quote(ctx,body){body=(await import("./quote-body.js")).quoteBody(body);const raw=await this.json(await this.request("/quote",ctx,void 0,body));return raw}async getStore(ctx){const mapper=import("./store.js").catch(cause=>{throw new ZappieError("server_error","Could not load the storefront store mapper",{cause})});const presentation=import("./presentation.js");const response=this.request("/store",ctx).then(value=>this.json(value));const[{mapStore},{presentStore},raw]=await Promise.all([mapper,presentation,response]);const store=mapStore(raw,record,text,list,hours,mapMoney,money,opt,isString,isBoolean,mapSeo);return presentStore(store,raw,presentationError)}async getMenu(ctx){const presentation=import("./presentation.js");let cursor;const seen=new Set;let output;let etag;do{const query=new URLSearchParams({branch:ctx.branchId,...ctx.fulfilment?{fulfilment:wireFulfilment(ctx.fulfilment)}:{},...ctx.metadataOnly?{metadata_only:"true"}:{},...cursor?{cursor}:{}});const response=await this.request(`/menus?${query}`,ctx,cursor?void 0:ctx.ifNoneMatch);if(response.status===304){if(cursor){throw new ZappieError("server_error","Unexpected 304 on a continuation page")}return{notModified:true,...response.headers.get("ETag")?{etag:response.headers.get("ETag")}:{}}}const raw=record(await this.json(response));const page=(await presentation).presentMenu(mapMenu(raw,ctx.branchId),raw,presentationError);if(ctx.metadataOnly){if(Object.keys(page.items).length||raw.next_cursor){throw new ZappieError("server_error","Invalid metadata response")}return{menu:{...page,completeness:"partial"}}}if(!output){output=page;etag=response.headers.get("ETag")??void 0}else{if(page.version!==output.version){throw new ZappieError("server_error","Menu changed while fetching pages; retry the read")}Object.assign(output.items,page.items);for(const category of page.categories){const existing=output.categories.find(c=>c.id===category.id);if(existing){existing.itemIds=[...new Set([...existing.itemIds,...category.itemIds])]}else{output.categories.push(category)}}for(const section of page.menus??[]){const existing=output.menus?.find(m=>m.id===section.id);if(existing){existing.categoryIds=[...new Set([...existing.categoryIds,...section.categoryIds])]}else{output.menus?.push(section)}}}cursor=typeof raw.next_cursor==="string"&&raw.next_cursor?raw.next_cursor:void 0;if(cursor){if(seen.has(cursor)){throw new ZappieError("server_error","Repeated menu pagination cursor")}seen.add(cursor)}}while(cursor);if(output.menus&&output.menus.length>1){output.id=`branch:${ctx.branchId}`;output.name="Catalogue";delete output.schedule}for(const category of output.categories){
|
|
1
|
+
import{ZappieError,wireError}from"../errors.js";import{delay,throwIfAborted}from"../internal/abort.js";import{money}from"../money.js";import{hours,isBoolean,isString,list,mapItem,mapMenu,mapMoney,mapSeo,opt,record,text}from"./mappers.js";var MAX_RETRY_WAIT_MS=5e3;var wireFulfilment=value=>value==="dineIn"?"dine_in":value;var presentationError=()=>new ZappieError("server_error","Invalid storefront presentation");var RestTransport=class{constructor(opts={}){const url=new URL(opts.baseUrl??"https://api.zappie.ai/storefront/v1");if(url.username||url.password||url.search||url.hash||url.protocol!=="https:"&&!(url.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(url.hostname))){throw new ZappieError("invalid_request","REST baseUrl requires HTTPS, or HTTP on localhost")}this.baseUrl=url.href.replace(/\/$/,"");this.fetcher=opts.fetch??((input,init)=>globalThis.fetch(input,init))}async request(path,ctx,etag,body){if(typeof window!=="undefined"&&ctx.key.startsWith("sk_")){throw new ZappieError("invalid_request","Secret keys cannot be sent from a browser")}for(let attempt=0;;attempt++){throwIfAborted(ctx.signal);let response;try{response=await this.fetcher(this.baseUrl+path,{method:body?"POST":"GET",...body?{body:JSON.stringify(body)}:{},redirect:"manual",headers:{...body?{"Content-Type":"application/json"}:{},...ctx.idempotencyKey?{"Idempotency-Key":ctx.idempotencyKey}:{},Authorization:`Bearer ${ctx.key}`,"Zappie-Version":ctx.version,...etag?{"If-None-Match":etag}:{}},...ctx.signal?{signal:ctx.signal}:{}})}catch(error){throwIfAborted(ctx.signal);if(attempt>=2){throw new ZappieError("network_error","Could not reach the storefront service",{cause:error})}await delay(100*2**attempt+Math.random()*100,ctx.signal);continue}if(response.ok||response.status===304){return response}const retry=response.headers.get("Retry-After");const seconds=retry!==null?Number(retry):NaN;const wait=retry!==null?Number.isFinite(seconds)?Math.max(0,seconds*1e3):Math.max(0,Date.parse(retry)-Date.now()):NaN;const tooLong=Number.isFinite(wait)&&wait>MAX_RETRY_WAIT_MS;if(attempt<2&&!tooLong&&(response.status===429||response.status>=500)){await response.body?.cancel();await delay(Number.isFinite(wait)?wait:100*2**attempt+Math.random()*100,ctx.signal);continue}const errorBody=await response.json().catch(()=>({}));throw wireError(errorBody,response.status,response.headers.get("Zappie-Request-Id")??void 0)}}async json(response){try{return await response.json()}catch(cause){if(cause instanceof Error&&cause.name==="AbortError"){throw cause}throw new ZappieError("server_error","The storefront service returned invalid JSON",{status:response.status,cause})}}async quote(ctx,body){body=(await import("./quote-body.js")).quoteBody(body);const raw=await this.json(await this.request("/quote",ctx,void 0,body));return raw}async getStore(ctx){const mapper=import("./store.js").catch(cause=>{throw new ZappieError("server_error","Could not load the storefront store mapper",{cause})});const presentation=import("./presentation.js");const response=this.request("/store",ctx).then(value=>this.json(value));const[{mapStore},{presentStore},raw]=await Promise.all([mapper,presentation,response]);const store=mapStore(raw,record,text,list,hours,mapMoney,money,opt,isString,isBoolean,mapSeo);return presentStore(store,raw,presentationError)}async getMenu(ctx){const presentation=import("./presentation.js");let cursor;const seen=new Set;let output;let etag;do{const query=new URLSearchParams({branch:ctx.branchId,...ctx.fulfilment?{fulfilment:wireFulfilment(ctx.fulfilment)}:{},...ctx.metadataOnly?{metadata_only:"true"}:{},...cursor?{cursor}:{}});const response=await this.request(`/menus?${query}`,ctx,cursor?void 0:ctx.ifNoneMatch);if(response.status===304){if(cursor){throw new ZappieError("server_error","Unexpected 304 on a continuation page")}return{notModified:true,...response.headers.get("ETag")?{etag:response.headers.get("ETag")}:{}}}const raw=record(await this.json(response));const page=(await presentation).presentMenu(mapMenu(raw,ctx.branchId),raw,presentationError);if(ctx.metadataOnly){if(Object.keys(page.items).length||raw.next_cursor){throw new ZappieError("server_error","Invalid metadata response")}return{menu:{...page,completeness:"partial"}}}if(!output){output=page;etag=response.headers.get("ETag")??void 0}else{if(page.version!==output.version){throw new ZappieError("server_error","Menu changed while fetching pages; retry the read")}Object.assign(output.items,page.items);for(const category of page.categories){const existing=output.categories.find(c=>c.id===category.id);if(existing){existing.itemIds=[...new Set([...existing.itemIds,...category.itemIds])]}else{output.categories.push(category)}}for(const section of page.menus??[]){const existing=output.menus?.find(m=>m.id===section.id);if(existing){existing.categoryIds=[...new Set([...existing.categoryIds,...section.categoryIds])]}else{output.menus?.push(section)}}}cursor=typeof raw.next_cursor==="string"&&raw.next_cursor?raw.next_cursor:void 0;if(cursor){if(seen.has(cursor)){throw new ZappieError("server_error","Repeated menu pagination cursor")}seen.add(cursor)}}while(cursor);if(output.menus&&output.menus.length>1){output.id=`branch:${ctx.branchId}`;output.name="Catalogue";delete output.schedule}for(const category of output.categories){category.itemIds=category.itemIds.filter(id=>Object.prototype.hasOwnProperty.call(output.items,id))}if(Object.keys(output.items).length>2e3){console.warn("Zappie menu contains more than 2,000 items")}return{menu:output,...etag?{etag}:{}}}async getSelectedMenu(ctx){return(await import("./selected-menu.js")).selectedMenu(ctx,path=>this.request(path,ctx,ctx.ifNoneMatch),response=>this.json(response),mapMenu,()=>new ZappieError("server_error","Invalid selected menu"))}async search(ctx){return(await import("./search.js")).searchPage(ctx,async path=>this.json(await this.request(path,ctx)),mapMenu,()=>new ZappieError("server_error","Invalid search page"))}async getCategoryPage(ctx){const query=new URLSearchParams({branch:ctx.branchId,...ctx.cursor?{cursor:ctx.cursor}:{}});const raw=await this.json(await this.request(`/menus/${encodeURIComponent(ctx.menuId)}/categories/${encodeURIComponent(ctx.categoryId)}/items?${query}`,ctx));return(await import("./category-page.js")).categoryPage(record(raw),ctx,mapMenu,()=>new ZappieError("server_error","Invalid category page"))}async getMenuVersion(ctx){const value=record(await this.json(await this.request(`/menus/version?${new URLSearchParams({branch:ctx.branchId,...ctx.fulfilment?{fulfilment:wireFulfilment(ctx.fulfilment)}:{}})}`,ctx)));if(typeof value.menu_version!=="string"||typeof value.availability_hash!=="string"){throw new ZappieError("server_error","Invalid menu version response")}return{version:value.menu_version,availabilityHash:value.availability_hash}}async getItem(ctx){const item=mapItem(await this.json(await this.request(`/items/${encodeURIComponent(ctx.itemId)}?${new URLSearchParams({branch:ctx.branchId})}`,ctx)));if(item.id!==ctx.itemId){throw new ZappieError("server_error","Item response identity does not match the request")}return item}};export{RestTransport};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { z as SelectedMenu, i as SelectedMenuRequest, j as SelectedMenuResponse, B as SelectedMenuTransport, D as createSelectedMenuReader, F as selectedMenu, G as selectedMenuKey } from '../client-
|
|
1
|
+
export { z as SelectedMenu, i as SelectedMenuRequest, j as SelectedMenuResponse, B as SelectedMenuTransport, D as createSelectedMenuReader, F as selectedMenu, G as selectedMenuKey } from '../client-CW_OWZ0l.js';
|
|
2
2
|
import '../models-C77LjkK8.js';
|
|
3
3
|
import '../types-CuPaBf6k.js';
|