@zappie/sdk 0.23.0 → 0.23.1

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 CHANGED
@@ -1,5 +1,15 @@
1
1
  # @zappie/sdk
2
2
 
3
+ ## 0.23.1
4
+
5
+ ### Patch Changes
6
+
7
+ - b7848ed: `@zappie/checkout-fields` is the behaviour of a checkout's fields above `useCheckoutFlow`, with no markup beyond the map: `useAddressPicker` and `useAddressSuggestions` for the address search, `DeliveryAddressMap` for the live or static map of the address, `useContactDraft` and `contactProblemText` for the contact details, `useScheduleStrip` and `scheduledLabel` for the schedule's days, `useRegionSearch`, `useEscapeClose` and `orderTimeChoice`.
8
+
9
+ The kit's address picker uses it, so `address-utils.ts` and `use-address-picker.ts` are no longer copied into a project, and `zappie add address-picker` installs the package. The SDK's Vite plugin pre-bundles the package in development. The starter picks its address and words its phone problem with it.
10
+
11
+ `zappie diff --apply` names the packages a new item version needs that the project doesn't have. `zappie doctor` accepts a later 0.x minor of a Zappie package for an item's requirement, so an item that asks for `^0.1.0` is met by 0.21.0.
12
+
3
13
  ## 0.23.0
4
14
 
5
15
  ### Minor Changes
package/dist/debug.js CHANGED
@@ -1,2 +1,2 @@
1
- var VERSION=true?"0.23.0":"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};
1
+ var VERSION=true?"0.23.1":"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};
2
2
  //# sourceMappingURL=debug.js.map
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
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}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.23.0":"0.0.0-development";export{API_VERSION,RestTransport,VERSION,ZappieCartError,ZappieError,createZappie,estimateUnitPrice,format,holdsForLater,isHeldQuote,isZappieError,money,previewItem,resolveSourceMenu,validateLine};
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}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.23.1":"0.0.0-development";export{API_VERSION,RestTransport,VERSION,ZappieCartError,ZappieError,createZappie,estimateUnitPrice,format,holdsForLater,isHeldQuote,isZappieError,money,previewItem,resolveSourceMenu,validateLine};
2
2
  //# sourceMappingURL=index.js.map
@@ -38,7 +38,7 @@ type MarkedSource = {
38
38
  */
39
39
  declare function zappieSource({ previewHost }: ZappieSourceOptions): Plugin;
40
40
  /**
41
- * Every browser entry of the `@zappie/sdk` and `@zappie/foundations` installed under `root`, such as
41
+ * Every browser entry of the `@zappie/sdk`, `@zappie/foundations` and `@zappie/checkout-fields` installed under `root`, such as
42
42
  * `@zappie/sdk/customer`, for Vite's `optimizeDeps.include`. A package that isn't installed, or that is linked from a
43
43
  * workspace rather than installed, which Vite serves from source, adds none.
44
44
  *
@@ -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"]};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("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;");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!=="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("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;");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+=`
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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zappie/sdk",
3
- "version": "0.23.0",
3
+ "version": "0.23.1",
4
4
  "description": "Typed, framework-agnostic client for Zappie menus, carts, checkout, auth and events.",
5
5
  "type": "module",
6
6
  "sideEffects": [