@zappie/sdk 0.29.2 → 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 +6 -0
- package/dist/debug.js +1 -1
- package/dist/index.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,11 @@
|
|
|
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
|
+
|
|
3
9
|
## 0.29.2
|
|
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.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};
|
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};
|