@zappie/sdk 0.29.1 → 0.29.3
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/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/dist/vite/index.d.ts +4 -2
- package/dist/vite/index.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @zappie/sdk
|
|
2
2
|
|
|
3
|
+
## 0.29.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- c1cadf4: On the Studio dev server, `zappieSource` warms the server render at start, so the Worker, `app/entry.server`, `app/root` and the home page's module compile before the first page asks for them. Each marked file's source map now names its file relative to itself and carries the saved code, so the dev server no longer warns that the map points to missing source files.
|
|
8
|
+
|
|
9
|
+
## 0.29.2
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 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.
|
|
14
|
+
|
|
3
15
|
## 0.29.1
|
|
4
16
|
|
|
5
17
|
### Patch Changes
|
package/dist/debug.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var VERSION=true?"0.29.
|
|
1
|
+
var VERSION=true?"0.29.3":"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.3":"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};
|
package/dist/vite/index.d.ts
CHANGED
|
@@ -13,10 +13,11 @@ type ZappieSourceOptions = {
|
|
|
13
13
|
type MarkedSource = {
|
|
14
14
|
/** The file's code with the source and component attributes added. */
|
|
15
15
|
code: string;
|
|
16
|
-
/** A version 3 source map from the marked code back to the saved file. */
|
|
16
|
+
/** A version 3 source map from the marked code back to the saved file, naming that file relative to itself and carrying its code. */
|
|
17
17
|
map: {
|
|
18
18
|
version: 3;
|
|
19
19
|
sources: string[];
|
|
20
|
+
sourcesContent: string[];
|
|
20
21
|
names: string[];
|
|
21
22
|
mappings: string;
|
|
22
23
|
};
|
|
@@ -25,7 +26,8 @@ type MarkedSource = {
|
|
|
25
26
|
* Mark each intrinsic JSX element under `app/` with the file and line that render it, and the component that holds it,
|
|
26
27
|
* so the Studio preview can tell Zee where a region the merchant selected lives. It marks only on the Studio dev
|
|
27
28
|
* server: `vite dev` with `previewHost`, the `ZAPPIE_PREVIEW_HOST` that Studio sets, given. `vite build` never runs it,
|
|
28
|
-
* so no source path reaches a published site.
|
|
29
|
+
* so no source path reaches a published site. There it also compiles the server render's Worker, `app/entry.server`,
|
|
30
|
+
* `app/root` and the home page as the dev server starts, so the first page doesn't wait for them. On every dev server it also pre-bundles each browser entry of the
|
|
29
31
|
* installed `@zappie/sdk` and `@zappie/foundations` up front ({@link zappieDevEntries}), so opening a page that
|
|
30
32
|
* imports one the session hasn't seen never re-bundles and reloads the preview.
|
|
31
33
|
*
|
package/dist/vite/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{randomBytes}from"node:crypto";import{existsSync,readFileSync,realpathSync}from"node:fs";import{createRequire}from"node:module";import path from"node:path";import{parseSync}from"vite";var SOURCE_ATTRIBUTE="data-zappie-source";var COMPONENT_ATTRIBUTE="data-zappie-component";function zappieSource({previewHost}){let root="";return{name:"zappie-source",enforce:"pre",apply:(_config,{command})=>command==="serve",config(config){root=path.resolve(config.root??process.cwd())},configEnvironment(name){if(name!=="client"){return}const include=zappieDevEntries(root);return{optimizeDeps:{entries:["app/**/*.{js,jsx,ts,tsx}"],...include.length?{include}:{}}}},configResolved(config){root=config.root},transform:{filter:{id:/\.[jt]sx$/},handler(code,id){if(!previewHost){return null}if(!id.startsWith(`${root}/`)){return null}const file=id.slice(root.length+1);if(!file.startsWith("app/")||file.includes("node_modules/")){return null}return markSource(code,file)}}}}var SERVER_ONLY_ENTRIES={"@zappie/sdk":["./vite","./server","./testing"],"@zappie/foundations":["./next"],"@zappie/checkout-fields":[]};function zappieDevEntries(root){return Object.entries(SERVER_ONLY_ENTRIES).flatMap(([name,serverOnly])=>{const manifest=installedManifest(root,name);if(!manifest){return[]}const exports=manifest.exports;const subpaths=exports&&typeof exports==="object"&&!Array.isArray(exports)?Object.keys(exports).filter(key=>key.startsWith(".")):["."];return subpaths.filter(subpath=>!serverOnly.includes(subpath)&&!subpath.includes("*")&&!/\.(?:css|json)$/.test(subpath)).map(subpath=>subpath==="."?name:`${name}${subpath.slice(1)}`)})}function installedManifest(root,name){for(let directory=path.resolve(root);;directory=path.dirname(directory)){const file=path.join(directory,"node_modules",name,"package.json");if(existsSync(file)){const real=realpathSync(file);return real.split(path.sep).includes("node_modules")?JSON.parse(readFileSync(real,"utf8")):void 0}if(path.dirname(directory)===directory){return void 0}}}function markSource(code,file){if(!/^[\x21-\x7e]+$/.test(file)){return null}const escaped=file.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<");const parsed=parseSync(file,code);if(parsed.errors.length>0){return null}const lineStarts=[0];for(let index=code.indexOf("\n");index!==-1;index=code.indexOf("\n",index+1)){lineStarts.push(index+1)}const lineOf=offset=>{let low=0;let high=lineStarts.length-1;while(low<high){const middle=low+high+1>>1;if(lineStarts[middle]<=offset){low=middle}else{high=middle-1}}return low};const inserts=[];const visit=(value,component)=>{if(!value||typeof value!=="object"){return}if(Array.isArray(value)){for(const entry of value){visit(entry,component)}return}const node=value;const named=componentName(node)??component;if(node.type==="JSXOpeningElement"){const name=node.name;const attributes=node.attributes;if(name.type==="JSXIdentifier"&&typeof name.name==="string"&&/^[a-z]/.test(name.name)&&!attributes.some(attribute=>attribute.name?.name===SOURCE_ATTRIBUTE)){const component2=named?` ${COMPONENT_ATTRIBUTE}="${named}"`:"";inserts.push([name.end,` ${SOURCE_ATTRIBUTE}="${escaped}:${lineOf(node.start)+1}"${component2}`])}}for(const key in node){if(key!=="type"&&key!=="start"&&key!=="end"){visit(node[key],named)}}};visit(parsed.program,void 0);if(inserts.length===0){return null}inserts.sort((a,b)=>a[0]-b[0]);let output="";let from=0;const lines=lineStarts.map(()=>[[0,0]]);const added=lineStarts.map(()=>0);for(const[offset,text]of inserts){output+=code.slice(from,offset)+text;from=offset;const line=lineOf(offset);const column=offset-lineStarts[line];added[line]+=text.length;lines[line].push([column+added[line],column])}output+=code.slice(from);let previousLine=0;let previousColumn=0;const mappings=lines.map((segments,line)=>{let previousGenerated=0;return segments.map(([generated,original])=>{const encoded=vlq(generated-previousGenerated)+"A"+vlq(line-previousLine)+vlq(original-previousColumn);previousGenerated=generated;previousLine=line;previousColumn=original;return encoded}).join(",")}).join(";");return{code:output,map:{version:3,sources:[file],names:[],mappings}}}var BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function vlq(value){let rest=value<0?-value<<1|1:value<<1;let encoded="";do{let digit=rest&31;rest>>>=5;if(rest>0){digit|=32}encoded+=BASE64[digit]}while(rest>0);return encoded}function componentName(node){const id=node.id??void 0;const capitalised=name=>typeof name==="string"&&/^[A-Z]/.test(name)?name:void 0;if(node.type==="FunctionDeclaration"||node.type==="FunctionExpression"){return capitalised(id?.name)}if(node.type==="VariableDeclarator"&&id?.type==="Identifier"){return capitalised(id.name)}return void 0}function zappieHoistImports(){return{name:"zappie-hoist-imports",apply:"build",applyToEnvironment:environment=>environment.config.consumer==="client",generateBundle(_options,bundle){const importsOf=fileName=>{const chunk=bundle[fileName];return chunk?.type==="chunk"?chunk.imports:[]};for(const chunk of Object.values(bundle)){if(chunk.type!=="chunk"||!chunk.isEntry){continue}const listed=new Set([chunk.fileName,...chunk.imports]);const hoisted=[];const pending=[...chunk.imports];for(let index=0;index<pending.length;index++){for(const next of importsOf(pending[index])){if(!listed.has(next)){listed.add(next);hoisted.push(next);pending.push(next)}}}if(hoisted.length===0){continue}const from=chunk.fileName.split("/").slice(0,-1);chunk.code+=`
|
|
1
|
+
import{randomBytes}from"node:crypto";import{existsSync,readFileSync,realpathSync}from"node:fs";import{createRequire}from"node:module";import path from"node:path";import{parseSync}from"vite";var SOURCE_ATTRIBUTE="data-zappie-source";var COMPONENT_ATTRIBUTE="data-zappie-component";function zappieSource({previewHost}){let root="";return{name:"zappie-source",enforce:"pre",apply:(_config,{command})=>command==="serve",config(config){root=path.resolve(config.root??process.cwd())},configEnvironment(name){if(name==="ssr"){if(!previewHost){return}const warmup=zappieServerWarmup(root);return warmup.length?{dev:{warmup,preTransformRequests:true}}:void 0}if(name!=="client"){return}const include=zappieDevEntries(root);return{optimizeDeps:{entries:["app/**/*.{js,jsx,ts,tsx}"],...include.length?{include}:{}}}},configResolved(config){root=config.root},transform:{filter:{id:/\.[jt]sx$/},handler(code,id){if(!previewHost){return null}if(!id.startsWith(`${root}/`)){return null}const file=id.slice(root.length+1);if(!file.startsWith("app/")||file.includes("node_modules/")){return null}return markSource(code,file)}}}}var SCRIPT_EXTENSIONS=[".tsx",".ts",".jsx",".js"];function zappieServerWarmup(root){const files=[workerEntry(root),withExtension(root,"app/entry.server"),withExtension(root,"app/root"),...homeRoutes(root)];return[...new Set(files.filter(file=>file!==void 0))]}function workerEntry(root){for(const name of["wrangler.jsonc","wrangler.json","wrangler.toml"]){const text=readText(path.join(root,name));if(text===void 0){continue}const main=/"main"\s*:\s*"([^"]+)"|^\s*main\s*=\s*"([^"]+)"/m.exec(text)?.slice(1).find(Boolean);return main?existing(root,main):void 0}return void 0}function homeRoutes(root){const routes=readText(path.join(root,"app","routes.ts"))??readText(path.join(root,"app","routes.js"));if(routes===void 0){return[]}const code=routes.replace(/("(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`)|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g,(_match,literal)=>literal??" ");const modules=code.matchAll(/\b(?:index|layout)\(\s*["'`]([^"'`]+)["'`]|\broute\(\s*["'`]\/?["'`]\s*,\s*["'`]([^"'`]+)["'`]/g);return[...modules].map(match=>existing(root,path.posix.join("app",match[1]??match[2])))}function withExtension(root,file){return SCRIPT_EXTENSIONS.map(extension=>file+extension).find(name=>existsSync(path.join(root,name)))}function existing(root,file){const relative=path.posix.normalize(file.replaceAll("\\","/"));return existsSync(path.join(root,relative))?relative:void 0}function readText(file){try{return readFileSync(file,"utf8")}catch{return void 0}}var SERVER_ONLY_ENTRIES={"@zappie/sdk":["./vite","./server","./testing"],"@zappie/foundations":["./next"],"@zappie/checkout-fields":[]};function zappieDevEntries(root){return Object.entries(SERVER_ONLY_ENTRIES).flatMap(([name,serverOnly])=>{const manifest=installedManifest(root,name);if(!manifest){return[]}const exports=manifest.exports;const subpaths=exports&&typeof exports==="object"&&!Array.isArray(exports)?Object.keys(exports).filter(key=>key.startsWith(".")):["."];return subpaths.filter(subpath=>!serverOnly.includes(subpath)&&!subpath.includes("*")&&!/\.(?:css|json)$/.test(subpath)).map(subpath=>subpath==="."?name:`${name}${subpath.slice(1)}`)})}function installedManifest(root,name){for(let directory=path.resolve(root);;directory=path.dirname(directory)){const file=path.join(directory,"node_modules",name,"package.json");if(existsSync(file)){const real=realpathSync(file);return real.split(path.sep).includes("node_modules")?JSON.parse(readFileSync(real,"utf8")):void 0}if(path.dirname(directory)===directory){return void 0}}}function markSource(code,file){if(!/^[\x21-\x7e]+$/.test(file)){return null}const escaped=file.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<");const parsed=parseSync(file,code);if(parsed.errors.length>0){return null}const lineStarts=[0];for(let index=code.indexOf("\n");index!==-1;index=code.indexOf("\n",index+1)){lineStarts.push(index+1)}const lineOf=offset=>{let low=0;let high=lineStarts.length-1;while(low<high){const middle=low+high+1>>1;if(lineStarts[middle]<=offset){low=middle}else{high=middle-1}}return low};const inserts=[];const visit=(value,component)=>{if(!value||typeof value!=="object"){return}if(Array.isArray(value)){for(const entry of value){visit(entry,component)}return}const node=value;const named=componentName(node)??component;if(node.type==="JSXOpeningElement"){const name=node.name;const attributes=node.attributes;if(name.type==="JSXIdentifier"&&typeof name.name==="string"&&/^[a-z]/.test(name.name)&&!attributes.some(attribute=>attribute.name?.name===SOURCE_ATTRIBUTE)){const component2=named?` ${COMPONENT_ATTRIBUTE}="${named}"`:"";inserts.push([name.end,` ${SOURCE_ATTRIBUTE}="${escaped}:${lineOf(node.start)+1}"${component2}`])}}for(const key in node){if(key!=="type"&&key!=="start"&&key!=="end"){visit(node[key],named)}}};visit(parsed.program,void 0);if(inserts.length===0){return null}inserts.sort((a,b)=>a[0]-b[0]);let output="";let from=0;const lines=lineStarts.map(()=>[[0,0]]);const added=lineStarts.map(()=>0);for(const[offset,text]of inserts){output+=code.slice(from,offset)+text;from=offset;const line=lineOf(offset);const column=offset-lineStarts[line];added[line]+=text.length;lines[line].push([column+added[line],column])}output+=code.slice(from);let previousLine=0;let previousColumn=0;const mappings=lines.map((segments,line)=>{let previousGenerated=0;return segments.map(([generated,original])=>{const encoded=vlq(generated-previousGenerated)+"A"+vlq(line-previousLine)+vlq(original-previousColumn);previousGenerated=generated;previousLine=line;previousColumn=original;return encoded}).join(",")}).join(";");return{code:output,map:{version:3,sources:[path.posix.basename(file)],sourcesContent:[code],names:[],mappings}}}var BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function vlq(value){let rest=value<0?-value<<1|1:value<<1;let encoded="";do{let digit=rest&31;rest>>>=5;if(rest>0){digit|=32}encoded+=BASE64[digit]}while(rest>0);return encoded}function componentName(node){const id=node.id??void 0;const capitalised=name=>typeof name==="string"&&/^[A-Z]/.test(name)?name:void 0;if(node.type==="FunctionDeclaration"||node.type==="FunctionExpression"){return capitalised(id?.name)}if(node.type==="VariableDeclarator"&&id?.type==="Identifier"){return capitalised(id.name)}return void 0}function zappieHoistImports(){return{name:"zappie-hoist-imports",apply:"build",applyToEnvironment:environment=>environment.config.consumer==="client",generateBundle(_options,bundle){const importsOf=fileName=>{const chunk=bundle[fileName];return chunk?.type==="chunk"?chunk.imports:[]};for(const chunk of Object.values(bundle)){if(chunk.type!=="chunk"||!chunk.isEntry){continue}const listed=new Set([chunk.fileName,...chunk.imports]);const hoisted=[];const pending=[...chunk.imports];for(let index=0;index<pending.length;index++){for(const next of importsOf(pending[index])){if(!listed.has(next)){listed.add(next);hoisted.push(next);pending.push(next)}}}if(hoisted.length===0){continue}const from=chunk.fileName.split("/").slice(0,-1);chunk.code+=`
|
|
2
2
|
${hoisted.map(file=>`import ${JSON.stringify(relativeImport(from,file))};`).join("")}
|
|
3
3
|
`;chunk.imports.push(...hoisted)}}}}function relativeImport(from,file){const to=file.split("/");let shared=0;while(shared<from.length&&shared<to.length-1&&from[shared]===to[shared]){shared++}const up=from.length-shared;const rest=to.slice(shared).join("/");return up===0?`./${rest}`:`${"../".repeat(up)}${rest}`}var UPLOADS_PREFIX="/_zappie/assets/";function zappieUploads({host}){const origin=uploadsOrigin(host);return{name:"zappie-uploads",apply:(_config,{command})=>command==="serve"&&Boolean(origin),configureServer(server){server.middlewares.use((request,response,next)=>{const path2=request.url??"";if(!origin||!path2.startsWith(UPLOADS_PREFIX)){next();return}void forwardUpload(origin,path2,request.method,request.headers.accept).then(({status,headers,body})=>{response.writeHead(status,headers);response.end(body)}).catch(()=>{response.writeHead(502,{"cache-control":"no-store"});response.end()})})}}}function uploadsOrigin(host){if(!host){return void 0}try{const url=new URL(host.includes("://")?host:`https://${host}`);return url.protocol==="https:"?url.origin:void 0}catch{return void 0}}async function forwardUpload(origin,path2,method="GET",accept){if(method!=="GET"&&method!=="HEAD"){return{status:405,headers:{allow:"GET, HEAD"},body:Buffer.alloc(0)}}const upstream=await fetch(`${origin}${path2}`,{method,headers:accept?{accept}:{}});const headers={};for(const key of["content-type","cache-control","vary"]){const value=upstream.headers.get(key);if(value){headers[key]=value}}return{status:upstream.status,headers,body:Buffer.from(await upstream.arrayBuffer())}}function zappieWorker(){let root=process.cwd();let building=false;let renderer;return{name:"zappie-worker",enforce:"pre",config(config,{command}){root=path.resolve(config.root??process.cwd());building=command==="build";return{define:{"import.meta.env.ZAPPIE_DEPLOY_ID":JSON.stringify(building?randomBytes(8).toString("hex"):"dev")}}},configEnvironment(name){return building&&name!=="client"?{build:{minify:true}}:void 0},resolveId:{filter:{id:STREAMING_ONLY},handler(source){if(!building||this.environment.config.consumer==="client"||!STREAMING_ONLY.test(source)){return null}renderer??(renderer=streamingRenderer(root)??null);return renderer}}}}var STREAMING_ONLY=/^react-dom\/server(?:\.edge)?$/;function streamingRenderer(root){try{const manifest=createRequire(path.join(root,"package.json")).resolve("react-dom/package.json");const file=path.join(path.dirname(manifest),"cjs","react-dom-server.edge.production.js");return existsSync(file)?file:void 0}catch{return void 0}}export{COMPONENT_ATTRIBUTE,SOURCE_ATTRIBUTE,forwardUpload,markSource,streamingRenderer,uploadsOrigin,zappieDevEntries,zappieHoistImports,zappieSource,zappieUploads,zappieWorker};
|