@zappie/sdk 0.29.1 → 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 +6 -0
- package/dist/debug.js +1 -1
- package/dist/index.js +1 -1
- package/dist/transport/mappers.js +1 -1
- package/dist/transport/rest.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
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
|
+
|
|
3
9
|
## 0.29.1
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
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.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};
|
|
@@ -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};
|