greatstore 0.2.3 → 0.2.5

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.
Files changed (3) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/cli.js +90 -75
  3. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -3,6 +3,18 @@
3
3
  All notable changes to `@greatstore/cli` are recorded here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/).
5
5
 
6
+ ## 0.2.5 — 2026-10-14
7
+
8
+ ### Changed
9
+ - Pushing new code to a ready-made app that GreatStore keeps up to date makes it
10
+ your own copy: `npx greatstore apps push` says so, and the app stops getting
11
+ those updates. Shoppers keep seeing the previous version until you publish.
12
+
13
+ ## 0.2.4 — 2026-10-13
14
+
15
+ ### Changed
16
+ - Internal improvements.
17
+
6
18
  ## 0.2.3 — 2026-10-07
7
19
 
8
20
  ### Changed
package/dist/cli.js CHANGED
@@ -1,44 +1,44 @@
1
1
  #!/usr/bin/env node
2
- var En={h:"help",v:"version",o:"out"};function qe(e){let t={command:null,positional:[],flags:{}};if(e.length===0)return t;let n=0,r=e[0];for(r&&!r.startsWith("-")&&(t.command=r,n=1);n<e.length;n++){let o=e[n]??"";if(o.startsWith("--")){let s=o.indexOf("="),i,a;if(s!==-1)i=o.slice(2,s),a=o.slice(s+1);else{i=o.slice(2);let l=e[n+1];l===void 0||l.startsWith("--")||l.startsWith("-")?a=!0:(a=l,n++)}i&&(t.flags[i]=a)}else if(o.startsWith("-")&&o.length>1){let s=o.slice(1),i=En[s];if(!i)continue;let a=e[n+1];a===void 0||a.startsWith("-")?t.flags[i]=!0:(t.flags[i]=a,n++)}else t.positional.push(o)}return t}function h(e,t){let n=e[t];return typeof n=="string"?n:void 0}function m(e,t){let n=e[t];return n===!0||n==="true"}import*as Ke from"crypto";import*as We from"http";import{spawn as Ve}from"child_process";var An="/callback",jn='<svg width="40" height="40" viewBox="0 0 82 82" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path transform="scale(0.8) translate(7, 4)" d="M13 70.7522C13 70.7522 1.5 68.7522 1.5 57.7522C1.5 46.7522 23 48.2522 23 48.2522L80 47.2522C80 47.2522 91.5938 45.7522 91 36.2522C90.4062 26.7522 77 26.7522 77 26.7522H51C51 26.7522 44.5 27.6967 40.5 23.2522C36.5 18.8078 39 11.7522 44.5 7.25221C50 2.75222 52.5 0.752227 58 1.75223C63.5 2.75223 67.5 7.25221 65 14.2522C62.5 21.2522 32.5 74.7522 32.5 74.7522C32.5 74.7522 27.5 87.7522 36.5 90.7522C45.5 93.7522 49.5 86.2522 49.5 86.2522C49.5 86.2522 64 61.7522 66 58.7522C68 55.7522 72 52.4522 78 54.2522C84 56.0522 85.5 67.7522 85.5 69.7522C85.5 71.7522 85.5 82.2522 78 83.2522C70.5 84.2522 67.5 79.7522 66.5 78.7522C65.5 77.7522 31 20.7522 30 19.7522C29 18.7522 22 11.7522 16 15.7522C10 19.7522 12.5 27.2522 13 28.7522C13.5 30.2522 28 56.2522 29 58.7522C30 61.2522 31.5 66.7522 27 70.2522C22.5 73.7522 13 70.7522 13 70.7522Z" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/></svg>',Rn=`:root{color-scheme:light}
2
+ var Zn={h:"help",v:"version",o:"out"};function pt(e){let t={command:null,positional:[],flags:{}};if(e.length===0)return t;let n=0,r=e[0];for(r&&!r.startsWith("-")&&(t.command=r,n=1);n<e.length;n++){let o=e[n]??"";if(o.startsWith("--")){let s=o.indexOf("="),i,a;if(s!==-1)i=o.slice(2,s),a=o.slice(s+1);else{i=o.slice(2);let l=e[n+1];l===void 0||l.startsWith("--")||l.startsWith("-")?a=!0:(a=l,n++)}i&&(t.flags[i]=a)}else if(o.startsWith("-")&&o.length>1){let s=o.slice(1),i=Zn[s];if(!i)continue;let a=e[n+1];a===void 0||a.startsWith("-")?t.flags[i]=!0:(t.flags[i]=a,n++)}else t.positional.push(o)}return t}function h(e,t){let n=e[t];return typeof n=="string"?n:void 0}function m(e,t){let n=e[t];return n===!0||n==="true"}import*as mt from"crypto";import*as gt from"http";import{spawn as ft}from"child_process";var er="/callback",tr='<svg width="40" height="40" viewBox="0 0 82 82" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path transform="scale(0.8) translate(7, 4)" d="M13 70.7522C13 70.7522 1.5 68.7522 1.5 57.7522C1.5 46.7522 23 48.2522 23 48.2522L80 47.2522C80 47.2522 91.5938 45.7522 91 36.2522C90.4062 26.7522 77 26.7522 77 26.7522H51C51 26.7522 44.5 27.6967 40.5 23.2522C36.5 18.8078 39 11.7522 44.5 7.25221C50 2.75222 52.5 0.752227 58 1.75223C63.5 2.75223 67.5 7.25221 65 14.2522C62.5 21.2522 32.5 74.7522 32.5 74.7522C32.5 74.7522 27.5 87.7522 36.5 90.7522C45.5 93.7522 49.5 86.2522 49.5 86.2522C49.5 86.2522 64 61.7522 66 58.7522C68 55.7522 72 52.4522 78 54.2522C84 56.0522 85.5 67.7522 85.5 69.7522C85.5 71.7522 85.5 82.2522 78 83.2522C70.5 84.2522 67.5 79.7522 66.5 78.7522C65.5 77.7522 31 20.7522 30 19.7522C29 18.7522 22 11.7522 16 15.7522C10 19.7522 12.5 27.2522 13 28.7522C13.5 30.2522 28 56.2522 29 58.7522C30 61.2522 31.5 66.7522 27 70.2522C22.5 73.7522 13 70.7522 13 70.7522Z" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/></svg>',nr=`:root{color-scheme:light}
3
3
  body{font-family:"Instrument Sans",ui-sans-serif,system-ui,sans-serif;font-size:15px;line-height:1.6;margin:0;padding:4rem 1.5rem;max-width:26rem;margin-inline:auto;color:#091717;background:#fcfaf6;text-align:center}
4
4
  .logo{color:#091717;margin-bottom:1.5rem}
5
5
  h1{font-family:"Instrument Serif",ui-serif,Georgia,serif;font-style:italic;font-weight:400;font-size:1.75rem;margin:0 0 .5rem}
6
- p{color:#2c3a38}`,_n=`<!doctype html>
6
+ p{color:#2c3a38}`,rr=`<!doctype html>
7
7
  <html lang="en"><head><meta charset="utf-8"><title>GreatStore CLI</title>
8
8
  <link rel="preconnect" href="https://fonts.googleapis.com">
9
9
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10
10
  <link href="https://fonts.googleapis.com/css2?family=Instrument+Sans:wght@400;500;600;700&family=Instrument+Serif:ital@1&display=swap" rel="stylesheet">
11
- <style>${Rn}</style></head>
11
+ <style>${nr}</style></head>
12
12
  <body>
13
- <div class="logo">${jn}</div>
13
+ <div class="logo">${tr}</div>
14
14
  <h1>You're signed in.</h1>
15
15
  <p>This window will close automatically. If it doesn't, you can close it and return to your terminal.</p>
16
16
  <script>setTimeout(function(){window.close();},250);</script>
17
- </body></html>`,Je=`<!doctype html>
17
+ </body></html>`,dt=`<!doctype html>
18
18
  <html lang="en"><head><meta charset="utf-8"><title>GreatStore CLI</title>
19
19
  <style>body{font:14px/1.5 system-ui;margin:4rem auto;max-width:32rem;color:#222;text-align:center}
20
20
  h1{font-size:1.4rem;color:#a40000}code{background:#f4f4f4;padding:.1em .3em;border-radius:.2em}</style></head>
21
21
  <body><h1>Sign-in failed.</h1>
22
- <p>Return to your terminal for details.</p></body></html>`,W=class extends Error{constructor(t){super(t),this.name="LoopbackError"}};async function ge(e){let t=(e.generateState??On)(),n=e.timeoutMs??300*1e3,r=e.openBrowser??(s=>Ln(s,e.browserCmdEnv)),o=We.createServer();try{await new Promise(c=>o.listen(0,"127.0.0.1",c));let s=o.address(),i=new URL(`${e.dashboardBaseUrl}/cli/authorize`);i.searchParams.set("port",String(s.port)),i.searchParams.set("state",t),e.requestedStore&&i.searchParams.set("store",e.requestedStore);let a=i.toString(),l=Tn(o,t,n);return r(a),await l}finally{o.close()}}function Tn(e,t,n){return new Promise((r,o)=>{let s=!1,i=l=>{s||(s=!0,l())},a=setTimeout(()=>{i(()=>o(new W("Sign-in timed out. Re-run `npx greatstore login`.")))},n);typeof a.unref=="function"&&a.unref(),e.on("request",(l,c)=>{let p=new URL(l.url??"/","http://127.0.0.1");if(p.pathname!==An){c.writeHead(404,{"content-type":"text/plain"}),c.end("Not found");return}let u=p.searchParams,f=u.get("error"),R=u.get("error_description"),P=u.get("code");if(u.get("state")!==t){c.writeHead(400,{"content-type":"text/html"}),c.end(Je),clearTimeout(a),i(()=>o(new W("Sign-in didn't complete. Please try again.")));return}if(f||!P){c.writeHead(400,{"content-type":"text/html"}),c.end(Je),clearTimeout(a),i(()=>o(new W(R??"Sign-in failed. Please try again.")));return}c.writeHead(200,{"content-type":"text/html"}),c.end(_n),clearTimeout(a);let _=u.get("store")?.trim();i(()=>r(_?{token:P,store:_}:{token:P}))})})}function On(){return Ke.randomBytes(16).toString("hex")}function Ln(e,t){let r=t?.trim()??In();if(r)try{let o;if(r==="start"){let s=`start "" "${e}"`;o=Ve("cmd.exe",["/d","/s","/c",s],{stdio:"ignore",detached:!0,windowsVerbatimArguments:!0})}else o=Ve(r,[e],{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}function In(){switch(process.platform){case"darwin":return"open";case"win32":return"start";case"linux":return"xdg-open";default:return null}}import*as E from"fs";import*as ee from"os";import*as Oe from"path";var Fn=".greatstore",Nn="credentials.json";function he(e=ee.homedir()){return Oe.join(e,Fn)}function Le(e=ee.homedir()){return Oe.join(he(e),Nn)}function T(e=ee.homedir()){let t=Le(e),n;try{let r=E.statSync(t);if(process.platform!=="win32"){let o=r.mode&511;if(o&63)throw new Error(`Refusing to read ${t}: permissions are ${o.toString(8)} (should be 600). Run \`chmod 600 ${t}\`.`)}n=E.readFileSync(t,"utf8")}catch(r){if(Dn(r))return null;throw r}try{let r=JSON.parse(n);return typeof r.access_token!="string"?null:r}catch{return null}}function ye(e,t=ee.homedir()){let n=he(t);if(E.mkdirSync(n,{recursive:!0,mode:448}),process.platform!=="win32")try{E.chmodSync(n,448)}catch{}let r=Le(t);E.writeFileSync(r,`${JSON.stringify(e,null,2)}
23
- `,{mode:384}),process.platform!=="win32"&&E.chmodSync(r,384)}function ze(e=ee.homedir()){E.rmSync(Le(e),{force:!0})}function Xe(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT: expected three dot-separated segments");let n=t[1];if(!n)throw new Error("Invalid JWT: empty payload segment");let o=(n+"=".repeat((4-n.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=Buffer.from(o,"base64").toString("utf8");return JSON.parse(s)}function we(e,t=Math.floor(Date.now()/1e3)){return e.expires_at<=t}function Dn(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}var O="0.2.3";var B=class extends Error{constructor(n,r,o){super(r);this.status=n;this.code=o;this.name="HttpError"}},F=class extends Error{constructor(t="Sign in first. Run `npx greatstore login`."){super(t),this.name="AuthRequiredError"}};function Bn(e){let t;try{t=new URL(e)}catch{return}let n=t.pathname.split("/").filter(Boolean);if(n[1]==="admin"&&n[0])return n[0];let r=t.hostname.split(".")[0],o=new Set(["my","www","app","api","admin","localhost"]);if(t.hostname.includes(".")&&r&&!o.has(r))return r}function Mn(e){let t=Bn(e)??T()?.store;return t?`npx greatstore login --store ${t}`:"npx greatstore login"}async function d(e,t={}){let n=()=>`Run \`${Mn(e)}\`.`,r=T();if(!r)throw new F(`Sign in first. ${n()}`);if(we(r))throw new F(`Session expired. ${n()}`);try{return await Hn(e,t,r.access_token)}catch(o){throw o instanceof B&&o.status===401?new F(`Session expired. ${n()}`):o}}async function Hn(e,t,n){let r={accept:"application/json",authorization:`Bearer ${n}`,"x-gs-cli-version":O,...t.headers??{}},o;if(t.multipart&&t.body!==void 0)throw new Error("request(): pass either `body` or `multipart`, not both");t.multipart?(o=t.multipart,delete r["content-type"]):t.body!==void 0&&(o=JSON.stringify(t.body),r["content-type"]="application/json");let s={method:t.method??"GET",headers:r};o!==void 0&&(s.body=o);let i=await fetch(e,s);if(i.status>=200&&i.status<300)return i.status===204?void 0:(i.headers.get("content-type")??"").includes("application/json")?await i.json():await i.text();let a=await i.text(),l={};try{l=JSON.parse(a)}catch{}let c=l.code??l.error,p=t.validationDetail&&i.status===400&&l.error?l.error:Un(i.status,c,l.detail);throw new B(i.status,p,l.code??l.error)}var Ze=`This version of the GreatStore CLI is no longer supported. Run the latest one:
22
+ <p>Return to your terminal for details.</p></body></html>`,X=class extends Error{constructor(t){super(t),this.name="LoopbackError"}};async function we(e){let t=(e.generateState??sr)(),n=e.timeoutMs??300*1e3,r=e.openBrowser??(s=>ir(s,e.browserCmdEnv)),o=gt.createServer();try{await new Promise(c=>o.listen(0,"127.0.0.1",c));let s=o.address(),i=new URL(`${e.dashboardBaseUrl}/cli/authorize`);i.searchParams.set("port",String(s.port)),i.searchParams.set("state",t),e.requestedStore&&i.searchParams.set("store",e.requestedStore);let a=i.toString(),l=or(o,t,n);return r(a),await l}finally{o.close()}}function or(e,t,n){return new Promise((r,o)=>{let s=!1,i=l=>{s||(s=!0,l())},a=setTimeout(()=>{i(()=>o(new X("Sign-in timed out. Re-run `npx greatstore login`.")))},n);typeof a.unref=="function"&&a.unref(),e.on("request",(l,c)=>{let p=new URL(l.url??"/","http://127.0.0.1");if(p.pathname!==er){c.writeHead(404,{"content-type":"text/plain"}),c.end("Not found");return}let u=p.searchParams,d=u.get("error"),A=u.get("error_description"),y=u.get("code");if(u.get("state")!==t){c.writeHead(400,{"content-type":"text/html"}),c.end(dt),clearTimeout(a),i(()=>o(new X("Sign-in didn't complete. Please try again.")));return}if(d||!y){c.writeHead(400,{"content-type":"text/html"}),c.end(dt),clearTimeout(a),i(()=>o(new X(A??"Sign-in failed. Please try again.")));return}c.writeHead(200,{"content-type":"text/html"}),c.end(rr),clearTimeout(a);let ye=u.get("store")?.trim();i(()=>r(ye?{token:y,store:ye}:{token:y}))})})}function sr(){return mt.randomBytes(16).toString("hex")}function ir(e,t){let r=t?.trim()??ar();if(r)try{let o;if(r==="start"){let s=`start "" "${e}"`;o=ft("cmd.exe",["/d","/s","/c",s],{stdio:"ignore",detached:!0,windowsVerbatimArguments:!0})}else o=ft(r,[e],{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}function ar(){switch(process.platform){case"darwin":return"open";case"win32":return"start";case"linux":return"xdg-open";default:return null}}import*as j from"fs";import*as ne from"os";import*as qe from"path";var cr=".greatstore",lr="credentials.json";function Se(e=ne.homedir()){return qe.join(e,cr)}function Ve(e=ne.homedir()){return qe.join(Se(e),lr)}function _(e=ne.homedir()){let t=Ve(e),n;try{let r=j.statSync(t);if(process.platform!=="win32"){let o=r.mode&511;if(o&63)throw new Error(`Refusing to read ${t}: permissions are ${o.toString(8)} (should be 600). Run \`chmod 600 ${t}\`.`)}n=j.readFileSync(t,"utf8")}catch(r){if(ur(r))return null;throw r}try{let r=JSON.parse(n);return typeof r.access_token!="string"?null:r}catch{return null}}function be(e,t=ne.homedir()){let n=Se(t);if(j.mkdirSync(n,{recursive:!0,mode:448}),process.platform!=="win32")try{j.chmodSync(n,448)}catch{}let r=Ve(t);j.writeFileSync(r,`${JSON.stringify(e,null,2)}
23
+ `,{mode:384}),process.platform!=="win32"&&j.chmodSync(r,384)}function ht(e=ne.homedir()){j.rmSync(Ve(e),{force:!0})}function yt(e){let t=e.split(".");if(t.length!==3)throw new Error("Invalid JWT: expected three dot-separated segments");let n=t[1];if(!n)throw new Error("Invalid JWT: empty payload segment");let o=(n+"=".repeat((4-n.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/"),s=Buffer.from(o,"base64").toString("utf8");return JSON.parse(s)}function xe(e,t=Math.floor(Date.now()/1e3)){return e.expires_at<=t}function ur(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}var O="0.2.5";var L=class extends Error{constructor(n,r,o){super(r);this.status=n;this.code=o;this.name="HttpError"}},N=class extends Error{constructor(t="Sign in first. Run `npx greatstore login`."){super(t),this.name="AuthRequiredError"}};function pr(e){let t;try{t=new URL(e)}catch{return}let n=t.pathname.split("/").filter(Boolean);if(n[1]==="admin"&&n[0])return n[0];let r=t.hostname.split(".")[0],o=new Set(["my","www","app","api","admin","localhost"]);if(t.hostname.includes(".")&&r&&!o.has(r))return r}function fr(e){let t=pr(e)??_()?.store;return t?`npx greatstore login --store ${t}`:"npx greatstore login"}var Je=null;function xt(e){Je=e}async function f(e,t={}){if(Je!==null)return wt(e,t,Je);let n=()=>`Run \`${fr(e)}\`.`,r=_();if(!r)throw new N(`Sign in first. ${n()}`);if(xe(r))throw new N(`Session expired. ${n()}`);try{return await wt(e,t,r.access_token)}catch(o){throw o instanceof L&&o.status===401?new N(`Session expired. ${n()}`):o}}async function wt(e,t,n){let r={accept:"application/json",authorization:`Bearer ${n}`,"x-gs-cli-version":O,...t.headers??{}},o;if(t.multipart&&t.body!==void 0)throw new Error("request(): pass either `body` or `multipart`, not both");t.multipart?(o=t.multipart,delete r["content-type"]):t.body!==void 0&&(o=JSON.stringify(t.body),r["content-type"]="application/json");let s={method:t.method??"GET",headers:r};o!==void 0&&(s.body=o);let i=await fetch(e,s);if(i.status>=200&&i.status<300)return i.status===204?void 0:(i.headers.get("content-type")??"").includes("application/json")?await i.json():await i.text();let a=await i.text(),l={};try{l=JSON.parse(a)}catch{}let c=l.code??l.error,p=t.validationDetail&&i.status===400&&l.error?l.error:dr(i.status,c,l.detail);throw new L(i.status,p,l.code??l.error)}var vt=`This version of the GreatStore CLI is no longer supported. Run the latest one:
24
24
 
25
25
  npx greatstore@latest <command>
26
26
 
27
27
  or, if you installed it, update it:
28
28
 
29
29
  npm install -g greatstore@latest
30
- `,Ye={cli_upgrade_required:{message:Ze},INVALID_NAME:{message:"Invalid component name. Use lowercase letters, digits, and underscores, starting with a letter."},not_found:{message:"Component not found on the server."},concurrent_write:{message:"Another change landed before this one. Run `npx greatstore apps pull` and try again."},stale_base:{message:"The store has moved past the version this copy was taken from. Run `npx greatstore apps pull` first, or push again with --force to overwrite it.",includeDetail:!0},name_taken:{message:"Another component in this store already has that name."},name_mismatch:{message:"Manifest `name` does not match the component folder name.",includeDetail:!0},manifest_invalid:{message:"manifest.json is invalid.",includeDetail:!0},bundle_too_large:{message:"bundle.js is too large."},bundle_not_module:{message:"bundle.js is not a valid ES module."},source_too_large:{message:"component.tsx is too large."}};function Un(e,t,n){if(t&&t in Ye){let r=Ye[t];return r?r.includeDetail&&n?`${r.message} (${n})`:r.message:Qe(e)}return Qe(e)}function Qe(e){return e===401?"Sign-in needed. Run `npx greatstore login`.":e===426?Ze:e===403?"Not authorized for this component or store.":e===404?"Not found.":e===409?"Conflict \u2014 refresh and try again.":e===413?"Upload too large.":e===429?"Too many requests \u2014 wait a moment and retry.":e>=500?"Server error \u2014 try again shortly.":e>=400?"Request rejected.":"Unexpected response."}function be(e,t){let n=Xe(e),r=et(n,"sub");if(!r)throw new Error("Token is missing a `sub` claim.");let o=Gn(n,"exp");return{access_token:e,expires_at:o??Math.floor(Date.now()/1e3)+3600,sub:r,...Se(n,"email","email"),...Se(n,"accountId","accountId"),...Se(n,"name","name"),...Se(n,"surname","surname"),...qn(n,"superUser","superUser"),...t?{store:t}:{}}}function et(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Gn(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Se(e,t,n){let r=et(e,t);return r?{[n]:r}:{}}function qn(e,t,n){let r=e[t];return r===!0?{[n]:!0}:typeof r=="string"&&r.toLowerCase()==="true"?{[n]:!0}:{}}import*as xe from"fs";import*as H from"path";var Vn="https://my.greatstore.ai",M=class extends Error{constructor(t){super(t),this.name="StoreResolutionError"}};function C(e={}){let t=Ie(e.cwd??process.cwd());if(t)return ne(t);throw new M("No .gsrc found in this directory or any ancestor. Run `npx greatstore apps init --store <slug>` first to scaffold a GreatStore project.")}function tt(e=process.cwd()){let t=Ie(e);if(t)return ne(t);let n=ue();if(n)return n;throw new M("No store selected. Run `npx greatstore login`, or run from a project with a .gsrc.")}function ue(){try{return T()?.store??null}catch{return null}}function ne(e){let t=ue();if(t&&t!==e)throw new M(`This targets store "${e}" but you're signed in to "${t}". Run \`npx greatstore switch ${e}\` to change stores.`);return e}function Ie(e){let t=H.resolve(e),n=H.parse(t).root;for(;;){let r=H.join(t,".gsrc");if(xe.existsSync(r))try{let s=xe.readFileSync(r,"utf8"),i=JSON.parse(s);if(typeof i.store=="string"&&i.store.trim())return i.store.trim()}catch{}if(t===n)return null;let o=H.dirname(t);if(o===t)return null;t=o}}function y(e){let t=h(e.flags,"store")?.trim();if(t)return ne(t);let n=Ie(process.cwd());if(n)return ne(n);let r=ue();if(r)return r;throw new M("No store selected. Pass --store <slug>, or run from a project with a .gsrc.")}function k(e,t=process.env){let n=t.GS_API_BASE?.trim();return n?nt(n):`https://${e}.greatstore.ai`}function pe(e=process.env){let t=e.GS_DASHBOARD_BASE?.trim();return t?nt(t):Vn}function S(e,t=process.env){return`${pe(t)}/${e}/admin`}function nt(e){return e.endsWith("/")?e.slice(0,-1):e}async function rt(e){let t=h(e.flags,"store")?.trim();process.stdout.write(`Opening browser for sign-in\u2026
31
- `);let{token:n,store:r}=await ge({dashboardBaseUrl:pe(),...t?{requestedStore:t}:{}}),o=be(n,r);ye(o);let s=o.email??o.sub;o.store?process.stdout.write(`Logged in as ${s}, working on store "${o.store}".
30
+ `,St={cli_upgrade_required:{message:vt},INVALID_NAME:{message:"Invalid component name. Use lowercase letters, digits, and underscores, starting with a letter."},not_found:{message:"Component not found on the server."},concurrent_write:{message:"Another change landed before this one. Run `npx greatstore apps pull` and try again."},stale_base:{message:"The store has moved past the version this copy was taken from. Run `npx greatstore apps pull` first, or push again with --force to overwrite it.",includeDetail:!0},name_taken:{message:"Another component in this store already has that name."},name_mismatch:{message:"Manifest `name` does not match the component folder name.",includeDetail:!0},manifest_invalid:{message:"manifest.json is invalid.",includeDetail:!0},listing_invalid:{message:"listing.json is invalid.",includeDetail:!0},bundle_too_large:{message:"bundle.js is too large."},bundle_not_module:{message:"bundle.js is not a valid ES module."},source_too_large:{message:"component.tsx is too large."}};function dr(e,t,n){if(t&&t in St){let r=St[t];return r?r.includeDetail&&n?`${r.message} (${n})`:r.message:bt(e)}return bt(e)}function bt(e){return e===401?"Sign-in needed. Run `npx greatstore login`.":e===426?vt:e===403?"Not authorized for this component or store.":e===404?"Not found.":e===409?"Conflict \u2014 refresh and try again.":e===413?"Upload too large.":e===429?"Too many requests \u2014 wait a moment and retry.":e>=500?"Server error \u2014 try again shortly.":e>=400?"Request rejected.":"Unexpected response."}function ke(e,t){let n=yt(e),r=kt(n,"sub");if(!r)throw new Error("Token is missing a `sub` claim.");let o=mr(n,"exp");return{access_token:e,expires_at:o??Math.floor(Date.now()/1e3)+3600,sub:r,...ve(n,"email","email"),...ve(n,"accountId","accountId"),...ve(n,"name","name"),...ve(n,"surname","surname"),...gr(n,"superUser","superUser"),...t?{store:t}:{}}}function kt(e,t){let n=e[t];return typeof n=="string"?n:void 0}function mr(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ve(e,t,n){let r=kt(e,t);return r?{[n]:r}:{}}function gr(e,t,n){let r=e[t];return r===!0?{[n]:!0}:typeof r=="string"&&r.toLowerCase()==="true"?{[n]:!0}:{}}import*as $e from"fs";import*as H from"path";var hr="https://my.greatstore.ai",$t="_library";function fe(e){return e===$t}var B=class extends Error{constructor(t){super(t),this.name="StoreResolutionError"}};function x(e={}){let t=Ke(e.cwd??process.cwd());if(t)return oe(t);throw new B("No .gsrc found in this directory or any ancestor. Run `npx greatstore apps init --store <slug>` first to scaffold a GreatStore project.")}function Pt(e=process.cwd()){let t=Ke(e);if(t)return oe(t);let n=de();if(n)return n;throw new B("No store selected. Run `npx greatstore login`, or run from a project with a .gsrc.")}function de(){try{return _()?.store??null}catch{return null}}function oe(e){let t=de();if(t&&t!==e)throw new B(`This targets store "${e}" but you're signed in to "${t}". Run \`npx greatstore switch ${e}\` to change stores.`);return e}function Ke(e){let t=Ct(e);return t?t.library===!0?$t:typeof t.store=="string"?t.store.trim():null:null}function Ct(e){let t=H.resolve(e),n=H.parse(t).root;for(;;){let r=H.join(t,".gsrc");if($e.existsSync(r))try{let s=JSON.parse($e.readFileSync(r,"utf8"));if(s.library===!0||typeof s.store=="string"&&s.store.trim())return s}catch{}if(t===n)return null;let o=H.dirname(t);if(o===t)return null;t=o}}function We(e=process.cwd(),t=process.env){if(t.GS_DASHBOARD_BASE?.trim())return Y(t);let n=Ct(e)?.dashboard;return typeof n=="string"&&n.trim()?ze(n.trim()):Y(t)}function w(e){let t=h(e.flags,"store")?.trim();if(t)return oe(t);let n=Ke(process.cwd());if(n)return oe(n);let r=de();if(r)return r;throw new B("No store selected. Pass --store <slug>, or run from a project with a .gsrc.")}function C(e,t=process.env){let n=t.GS_API_BASE?.trim();return n?ze(n):`https://${e}.greatstore.ai`}function Pe(e,t=process.env){return fe(e)?`${We(process.cwd(),t)}/cli/library`:`${C(e,t)}/api/apps`}function Y(e=process.env){let t=e.GS_DASHBOARD_BASE?.trim();return t?ze(t):hr}function v(e,t=process.env){return`${Y(t)}/${e}/admin`}function ze(e){return e.endsWith("/")?e.slice(0,-1):e}async function Et(e){let t=h(e.flags,"store")?.trim();process.stdout.write(`Opening browser for sign-in\u2026
31
+ `);let{token:n,store:r}=await we({dashboardBaseUrl:Y(),...t?{requestedStore:t}:{}}),o=ke(n,r);be(o);let s=o.email??o.sub;o.store?process.stdout.write(`Logged in as ${s}, working on store "${o.store}".
32
32
  `):process.stdout.write(`Logged in as ${s}.
33
- `)}function ot(){let e=T()!==null;ze(),process.stdout.write(e?`Logged out.
33
+ `)}function At(){let e=_()!==null;ht(),process.stdout.write(e?`Logged out.
34
34
  `:`Not logged in.
35
- `)}function st(){let e=T();if(!e)return process.stderr.write("Not logged in. Run `npx greatstore login`.\n"),1;let t=we(e),n=[`sub: ${e.sub}`,`email: ${e.email??"(none)"}`,`accountId: ${e.accountId??"(none)"}`,`superUser: ${e.superUser??!1}`,`store: ${e.store??"(none \u2014 run `npx greatstore switch`)"}`,`name: ${[e.name,e.surname].filter(Boolean).join(" ")||"(none)"}`,`expires: ${new Date(e.expires_at*1e3).toISOString()}${t?" (EXPIRED)":""}`];return process.stdout.write(n.join(`
35
+ `)}function jt(){let e=_();if(!e)return process.stderr.write("Not logged in. Run `npx greatstore login`.\n"),1;let t=xe(e),n=[`sub: ${e.sub}`,`email: ${e.email??"(none)"}`,`accountId: ${e.accountId??"(none)"}`,`superUser: ${e.superUser??!1}`,`store: ${e.store??"(none \u2014 run `npx greatstore switch`)"}`,`name: ${[e.name,e.surname].filter(Boolean).join(" ")||"(none)"}`,`expires: ${new Date(e.expires_at*1e3).toISOString()}${t?" (EXPIRED)":""}`];return process.stdout.write(n.join(`
36
36
  `)+`
37
- `),t?1:0}async function it(e){if(!T())throw new F;let n=e[0]?.trim();process.stdout.write(`Opening browser to switch stores\u2026
38
- `);let{token:r,store:o}=await ge({dashboardBaseUrl:pe(),...n?{requestedStore:n}:{}}),s=be(r,o);return ye(s),s.store?process.stdout.write(`Now working on store "${s.store}".
37
+ `),t?1:0}async function Rt(e){if(!_())throw new N;let n=e[0]?.trim();process.stdout.write(`Opening browser to switch stores\u2026
38
+ `);let{token:r,store:o}=await we({dashboardBaseUrl:Y(),...n?{requestedStore:n}:{}}),s=ke(r,o);return be(s),s.store?process.stdout.write(`Now working on store "${s.store}".
39
39
  `):process.stdout.write(`Switched.
40
- `),0}import*as b from"fs";import*as ve from"os";import*as z from"path";import{fileURLToPath as Jn}from"url";var re="greatstore",at=".version";function Kn(){for(let e of["./gs-skill/","../../gs-skill/"]){let t=z.resolve(Jn(new URL(e,import.meta.url)));if(b.existsSync(z.join(t,"SKILL.md")))return t}throw new Error("internal: this install of the CLI is missing the agent skill files")}function ct(e=ve.homedir()){return z.join(he(e),"skill",re)}function Fe(e,t=ve.homedir()){let n=ct(t),r=Wn(n);if(r!==null&&zn(r,e)>=0)return n;let o=`${n}.tmp-${process.pid}`,s=`${n}.old-${process.pid}`;return b.rmSync(o,{recursive:!0,force:!0}),b.cpSync(Kn(),o,{recursive:!0}),b.writeFileSync(z.join(o,at),e),b.existsSync(n)&&b.renameSync(n,s),b.renameSync(o,n),b.rmSync(s,{recursive:!0,force:!0}),n}function lt(e,t=ve.homedir()){try{b.existsSync(ct(t))&&Fe(e,t)}catch{}}function Wn(e){try{return b.readFileSync(z.join(e,at),"utf8").trim()}catch{return null}}function zn(e,t){let n=s=>s.split("-")[0].split(".").map(i=>Number(i)||0),[r,o]=[n(e),n(t)];for(let s=0;s<Math.max(r.length,o.length);s++){let i=(r[s]??0)-(o[s]??0);if(i!==0)return i}return 0}function ut(){process.stdout.write(Xn(Fe(O)))}function Xn(e){return["GreatStore agent skill \u2014 installation instructions for an AI coding agent.","","Skill source on this machine:",` ${e}`,"",`Symlink that folder into your skills directory as "${re}":`,""," mkdir -p <SKILLS_DIR>",` ln -sfn "${e}" "<SKILLS_DIR>/${re}"`,"","Symlink it, do not copy it: the CLI refreshes that folder whenever a","newer version runs, and the link picks it up with nothing to re-run.","","<SKILLS_DIR> is wherever you load skills from \u2014 for Claude Code that","is ~/.claude/skills for every project, or ./.claude/skills for this","one. Use your own location if it differs, and create it if missing.",`Then read <SKILLS_DIR>/${re}/SKILL.md to confirm the install.`,"",`On Windows: mklink /D "<SKILLS_DIR>\\${re}" "${e}"`,""].join(`
41
- `)}var U={mode:{kind:"string",values:["auto","light","dark","custom"],help:"Color scheme. `auto` follows the shopper's system preference.",brandVisible:!0},radius:{kind:"string",values:["sharp","default","rounded"],help:"Corner rounding preset applied to every surface.",brandVisible:!0},fontFamily:{kind:"string",help:"Primary font family name.",brandVisible:!0},secondaryFontFamily:{kind:"string",help:"Font family for the agent's chat bubbles.",brandVisible:!0},mobileBottomBarOffset:{kind:"integer",help:"Pixels the mobile bottom bar floats above the screen edge while the chat is closed.",brandVisible:!0},zIndex:{kind:"integer",help:"Stacking order of the chat panel on the host page."},brandColor:{kind:"color",help:"Accent color.",brandVisible:!0},surfaceColor:{kind:"color",help:"Background color.",brandVisible:!0},textColor:{kind:"color",help:"Text color.",brandVisible:!0},surface:{kind:"color",help:"Panel background."},surfaceSecondary:{kind:"color",help:"Secondary background."},surfaceAccent:{kind:"color",help:"Accented background."},surfaceHover:{kind:"color",help:"Hovered background."},foreground:{kind:"color",help:"Body text."},foregroundSecondary:{kind:"color",help:"Secondary text."},foregroundMuted:{kind:"color",help:"Muted text."},foregroundAccent:{kind:"color",help:"Accented text."},border:{kind:"color",help:"Border color."},borderFocus:{kind:"color",help:"Focus-ring color."},primary:{kind:"color",help:"Primary button background."},primaryForeground:{kind:"color",help:"Primary button text."},primaryHover:{kind:"color",help:"Primary button hover."},primaryMuted:{kind:"color",help:"Muted primary background."},primaryMutedForeground:{kind:"color",help:"Muted primary text."},primaryTint:{kind:"color",help:"Primary tint wash."},link:{kind:"color",help:"Link color."}};function pt(e){let t=e.toLowerCase();return Object.keys(U).map(n=>{let r=n.toLowerCase();return{name:n,distance:Qn(t,r),prefix:Yn(t,r)}}).filter(({name:n,distance:r,prefix:o})=>r<=Math.max(2,n.length/3)||o>=4).sort((n,r)=>r.prefix-n.prefix||n.distance-r.distance).slice(0,3).map(({name:n})=>n)}function Yn(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;return n}function Qn(e,t){let n=Array.from({length:t.length+1},(r,o)=>o);for(let r=1;r<=e.length;r++){let o=[r];for(let s=1;s<=t.length;s++)o[s]=Math.min((n[s]??0)+1,(o[s-1]??0)+1,(n[s-1]??0)+(e[r-1]===t[s-1]?0:1));n=o}return n[t.length]??0}var Zn=`npx greatstore configure \u2014 view and edit a store's configuration.
40
+ `),0}import*as k from"fs";import*as Ce from"os";import*as Q from"path";import{fileURLToPath as yr}from"url";var se="greatstore",Tt=".version";function wr(){for(let e of["./gs-skill/","../../gs-skill/"]){let t=Q.resolve(yr(new URL(e,import.meta.url)));if(k.existsSync(Q.join(t,"SKILL.md")))return t}throw new Error("internal: this install of the CLI is missing the agent skill files")}function _t(e=Ce.homedir()){return Q.join(Se(e),"skill",se)}function Xe(e,t=Ce.homedir()){let n=_t(t),r=Sr(n);if(r!==null&&br(r,e)>=0)return n;let o=`${n}.tmp-${process.pid}`,s=`${n}.old-${process.pid}`;return k.rmSync(o,{recursive:!0,force:!0}),k.cpSync(wr(),o,{recursive:!0}),k.writeFileSync(Q.join(o,Tt),e),k.existsSync(n)&&k.renameSync(n,s),k.renameSync(o,n),k.rmSync(s,{recursive:!0,force:!0}),n}function Ot(e,t=Ce.homedir()){try{k.existsSync(_t(t))&&Xe(e,t)}catch{}}function Sr(e){try{return k.readFileSync(Q.join(e,Tt),"utf8").trim()}catch{return null}}function br(e,t){let n=s=>s.split("-")[0].split(".").map(i=>Number(i)||0),[r,o]=[n(e),n(t)];for(let s=0;s<Math.max(r.length,o.length);s++){let i=(r[s]??0)-(o[s]??0);if(i!==0)return i}return 0}function Lt(){process.stdout.write(xr(Xe(O)))}function xr(e){return["GreatStore agent skill \u2014 installation instructions for an AI coding agent.","","Skill source on this machine:",` ${e}`,"",`Symlink that folder into your skills directory as "${se}":`,""," mkdir -p <SKILLS_DIR>",` ln -sfn "${e}" "<SKILLS_DIR>/${se}"`,"","Symlink it, do not copy it: the CLI refreshes that folder whenever a","newer version runs, and the link picks it up with nothing to re-run.","","<SKILLS_DIR> is wherever you load skills from \u2014 for Claude Code that","is ~/.claude/skills for every project, or ./.claude/skills for this","one. Use your own location if it differs, and create it if missing.",`Then read <SKILLS_DIR>/${se}/SKILL.md to confirm the install.`,"",`On Windows: mklink /D "<SKILLS_DIR>\\${se}" "${e}"`,""].join(`
41
+ `)}var M={mode:{kind:"string",values:["auto","light","dark","custom"],help:"Color scheme. `auto` follows the shopper's system preference.",brandVisible:!0},radius:{kind:"string",values:["sharp","default","rounded"],help:"Corner rounding preset applied to every surface.",brandVisible:!0},fontFamily:{kind:"string",help:"Primary font family name.",brandVisible:!0},secondaryFontFamily:{kind:"string",help:"Font family for the agent's chat bubbles.",brandVisible:!0},mobileBottomBarOffset:{kind:"integer",help:"Pixels the mobile bottom bar floats above the screen edge while the chat is closed.",brandVisible:!0},zIndex:{kind:"integer",help:"Stacking order of the chat panel on the host page."},brandColor:{kind:"color",help:"Accent color.",brandVisible:!0},surfaceColor:{kind:"color",help:"Background color.",brandVisible:!0},textColor:{kind:"color",help:"Text color.",brandVisible:!0},surface:{kind:"color",help:"Panel background."},surfaceSecondary:{kind:"color",help:"Secondary background."},surfaceAccent:{kind:"color",help:"Accented background."},surfaceHover:{kind:"color",help:"Hovered background."},foreground:{kind:"color",help:"Body text."},foregroundSecondary:{kind:"color",help:"Secondary text."},foregroundMuted:{kind:"color",help:"Muted text."},foregroundAccent:{kind:"color",help:"Accented text."},border:{kind:"color",help:"Border color."},borderFocus:{kind:"color",help:"Focus-ring color."},primary:{kind:"color",help:"Primary button background."},primaryForeground:{kind:"color",help:"Primary button text."},primaryHover:{kind:"color",help:"Primary button hover."},primaryMuted:{kind:"color",help:"Muted primary background."},primaryMutedForeground:{kind:"color",help:"Muted primary text."},primaryTint:{kind:"color",help:"Primary tint wash."},link:{kind:"color",help:"Link color."}};function It(e){let t=e.toLowerCase();return Object.keys(M).map(n=>{let r=n.toLowerCase();return{name:n,distance:kr(t,r),prefix:vr(t,r)}}).filter(({name:n,distance:r,prefix:o})=>r<=Math.max(2,n.length/3)||o>=4).sort((n,r)=>r.prefix-n.prefix||n.distance-r.distance).slice(0,3).map(({name:n})=>n)}function vr(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;return n}function kr(e,t){let n=Array.from({length:t.length+1},(r,o)=>o);for(let r=1;r<=e.length;r++){let o=[r];for(let s=1;s<=t.length;s++)o[s]=Math.min((n[s]??0)+1,(o[s-1]??0)+1,(n[s-1]??0)+(e[r-1]===t[s-1]?0:1));n=o}return n[t.length]??0}var $r=`npx greatstore configure \u2014 view and edit a store's configuration.
42
42
 
43
43
  Usage:
44
44
  npx greatstore configure Show the current configuration.
@@ -51,8 +51,8 @@ Run \`npx greatstore configure set --help\` for the full field list.
51
51
  Flags:
52
52
  --store <slug> Which store to act on (default: nearest .gsrc).
53
53
  --json Machine-readable output.
54
- `;function er(){let e=Object.entries(U).map(([n,r])=>{let o=r.values?r.values.join(" | "):r.kind==="color"?"<css color>":r.kind==="boolean"?"true | false":r.kind==="integer"?"<integer>":"<name>";return{flag:` --theme.${n} ${o}`,help:r.help}}),t=Math.max(...e.map(n=>n.flag.length))+2;return e.map(n=>`${n.flag.padEnd(t)}${n.help}`).join(`
55
- `)}function tr(){return Object.entries(U).filter(([,e])=>e.brandVisible).map(([e])=>e).join(", ")}function nr(){return`npx greatstore configure set \u2014 save configuration fields.
54
+ `;function Pr(){let e=Object.entries(M).map(([n,r])=>{let o=r.values?r.values.join(" | "):r.kind==="color"?"<css color>":r.kind==="boolean"?"true | false":r.kind==="integer"?"<integer>":"<name>";return{flag:` --theme.${n} ${o}`,help:r.help}}),t=Math.max(...e.map(n=>n.flag.length))+2;return e.map(n=>`${n.flag.padEnd(t)}${n.help}`).join(`
55
+ `)}function Cr(){return Object.entries(M).filter(([,e])=>e.brandVisible).map(([e])=>e).join(", ")}function Er(){return`npx greatstore configure set \u2014 save configuration fields.
56
56
 
57
57
  Only the fields you pass are written; everything else is left alone. Pass an
58
58
  empty value to clear a field (e.g. --displayName "").
@@ -66,7 +66,7 @@ Store fields:
66
66
  --cspConnectHosts <a,b,c> Extra connect hosts to allow.
67
67
 
68
68
  Theme fields (merge into the stored theme):
69
- ${er()}
69
+ ${Pr()}
70
70
 
71
71
  Whole-object theme writes:
72
72
  --theme '<json>' Merge this JSON object into the stored theme.
@@ -75,54 +75,57 @@ Whole-object theme writes:
75
75
  --theme "" Clear the theme entirely.
76
76
 
77
77
  These are shopper-visible, so confirm them with the merchant before writing:
78
- ${tr()}
78
+ ${Cr()}
79
79
 
80
80
  Examples:
81
81
  npx greatstore configure set --theme.fontFamily Manrope --theme.radius sharp
82
82
  npx greatstore configure set --theme.brandColor "#1e1d66"
83
83
  npx greatstore configure set --theme '{"mode":"dark"}' --replace
84
- `}function ft(e){if(e===void 0||e==="show")return Zn;if(e==="set")return nr()}import*as g from"fs";import*as $ from"path";import{readdirSync as Co,readFileSync as Eo}from"fs";import{fileURLToPath as jo}from"url";var ke=null;function mt(){return ke||(ke=JSON.parse('{"component/component.tsx":"import React from \\"react\\";\\n\\n// Add your tool args (matching manifest.json#inputSchema.properties)\\n// alongside the GreatStore-injected lifecycle props. See AGENTS.md for\\n// what each lifecycle prop does.\\ninterface Props {\\n onSendMessage: (text: string) => void;\\n onUpdateModelContext: (context: string) => void;\\n onShowLightbox: (options: { src: string; originRect?: DOMRect }) => void;\\n onClose: () => void;\\n // Ask the store\'s assistant for content matching a JSON Schema (or Zod\\n // schema) \u2014 the app\'s own catalog-grounded generation, for recommended\\n // picks or a personalized summary. Resolves to the generated object.\\n // `fallback` is a required, schema-shaped stand-in rendered in the app\\n // preview (and validated against the schema). See AGENTS.md.\\n onGenerateStructuredContent: <T = unknown>(\\n schema: object,\\n prompt: string,\\n fallback: T,\\n ) => Promise<T>;\\n // Drop-in for <img>: `<Image src=\u2026 alt=\u2026 />`. See AGENTS.md.\\n Image: React.ElementType<React.ComponentProps<\\"img\\">>;\\n}\\n\\n// See AGENTS.md for how an app runs (the assistant picks it by the\\n// manifest\'s name and description, then calls it with these props), the\\n// design rules (em-based sizing, brand CSS variables), and how to write an\\n// async, backend-backed app.\\nexport default function Component(_props: Props): React.ReactElement {\\n return (\\n <div\\n style={{\\n padding: \\"1em\\",\\n border: \\"1px solid var(--color-border-default)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n background: \\"var(--color-surface)\\",\\n color: \\"var(--color-foreground)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n >\\n <strong>__GS_NAME__</strong> \u2014 hello from your app!\\n </div>\\n );\\n}\\n","component/manifest.json":"{\\n \\"name\\": \\"__GS_NAME__\\",\\n \\"displayName\\": \\"__GS_DISPLAY_NAME__\\",\\n \\"description\\": \\"Use when <the shopper situation that should make the assistant open this app \u2014 say when to reach for it and what it reports back, never what it looks like; see AGENTS.md>.\\",\\n \\"displayMode\\": \\"inline\\",\\n \\"async\\": false,\\n \\"inputSchema\\": {\\n \\"type\\": \\"object\\",\\n \\"properties\\": {}\\n }\\n}\\n","root/.gitignore":"node_modules/\\ncomponents/*/bundle.js\\ncomponents/*/.gssync.json\\n*.tsbuildinfo\\n.DS_Store\\n","root/.gsrc":"{\\n \\"store\\": \\"__GS_STORE__\\"\\n}\\n","root/AGENTS.md":"# AGENTS.md\\n\\n> **Do not edit \u2014 auto-generated by the GreatStore CLI v__GS_VERSION__.**\\n> This file is rewritten by `npx greatstore apps init`, so any changes you make here\\n> will be overwritten. If this version trails your installed CLI, re-run\\n> `npx greatstore apps init` to refresh it. Put project-specific notes in another file.\\n\\nGuidance for AI coding agents working on the apps in this project.\\n`CLAUDE.md` and `GEMINI.md` are symlinks to this file.\\n\\nAn app is interactive UI the store\'s assistant renders inside the\\nconversation \u2014 a configurator, a quiz, a size guide, a booking form. You\\nwrite it in React; each app is one folder under `components/`, holding\\n`manifest.json` and `component.tsx`.\\n\\nApps render inside arbitrary publisher websites (the embed widget mounts\\non a host page) as well as the GreatStore storefront. You control neither\\nthe host page\'s base font size nor its color scheme, and the store owner\\ncontrols the look from GreatStore theme settings. The rules below keep\\napps portable across both.\\n\\n## How an app runs\\n\\nAn app is not a page the shopper navigates to. It is a tool the assistant\\ncalls mid-conversation, and once it is on screen it can talk back \u2014 which\\nis the part that makes apps worth building.\\n\\n```\\nShopper Assistant Your app\\n \u2502 \u2502 \u2502\\n \u2502 \\"what size am I?\\" \u2502 \u2502\\n \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502 \u2502\\n \u2502 \u2502 picks the app by its \u2502\\n \u2502 \u2502 name + description \u2502\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 calls it with props \u2502\\n \u2502 \u2502 your inputSchema asked \u2502\\n \u2502 \u2502 for (productName, \u2026) \u2502\\n \u2502 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502\\n \u2502 \u2502 \u251C\u2500\u2500\u2510 onGenerateStructured-\\n \u2502 \u2502 \u2502 \u2502 Content(): its own\\n \u2502 \u2502 \u2502 \u2502 catalog-grounded\\n \u2502 \u2502 \u2502<\u2500\u2518 generation, if wanted\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 \u2502 renders the moment your\\n \u2502 \u2502 \u2502 happy path has what it\\n \u2502 \u2502 \u2502 needs (async: after your\\n \u2502<\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 promise resolves)\\n \u2502 sees the app \u2502 \u2502\\n \u2502 \u2502 \u2502\\n \u2502 picks size M \u2502 \u2502\\n \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 onUpdateModelContext() \u2502 silent: the assistant\\n \u2502 \u2502<\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 now knows the pick\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 onSendMessage() \u2502 visible: a shopper turn\\n \u2502 \u2502<\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 happens right now\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 calls the app again \u2502 same app, new props \u2014\\n \u2502 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502 re-rendered in place\\n \u2502 \u2502 \u2502\\n```\\n\\nFour consequences worth designing around:\\n\\n1. **The assistant chooses the app, so `manifest.json` is the interface it\\n sees** \u2014 see the next section.\\n2. **Control is bidirectional once the app is up.** The app reports what\\n the shopper is doing (`onUpdateModelContext`), can speak for the\\n shopper (`onSendMessage`), and the assistant can call the app again\\n with revised props. Keep the render a function of the props it was\\n given, so a re-call is a re-render rather than a reset.\\n3. **The app can run its own generation, not just receive props.**\\n `onGenerateStructuredContent` returns a catalog-grounded,\\n shopper-personalized object matching your schema \u2014 recommended picks, a\\n personalized summary, a reason per option \u2014 which you render in your\\n own markup.\\n4. **Render on the happy path, not on a shell.** Whatever the app needs to\\n be correct \u2014 props, or awaited data in an async app \u2014 should be there\\n before anything paints; GreatStore owns the loading state.\\n\\n## `manifest.json` \u2014 the name and description decide whether your app runs\\n\\nThe assistant never sees your app. It sees a name and a sentence, next to\\nevery other tool it has, and picks one. Write the description for that\\n*caller*, answering one question: when should I reach for this, and what\\ndo I get back?\\n\\n**Describing the UI is the most common mistake.** Layout, sliders, tabs,\\ncarousels and colors are the shopper\'s concern. To the assistant they are\\nnoise \u2014 they say nothing about when to call the tool.\\n\\n| Don\'t | Do |\\n| --- | --- |\\n| \\"Renders a two-column table of measurements with a unit toggle.\\" | \\"Use when a shopper is unsure which size to buy or asks how an item fits.\\" |\\n| \\"A carousel of product cards with images and prices.\\" | \\"Use to show 2\u20138 specific products you have already chosen, when the shopper wants to see them side by side before deciding.\\" |\\n| \\"Modal with a multi-step form and a progress bar.\\" | \\"Use when the shopper wants a gift but can\'t say what \u2014 collects budget, recipient and occasion, then reports them back so you can recommend.\\" |\\n\\nWhat belongs in a description, in this order:\\n\\n1. **The trigger** \u2014 the shopper situation or intent, in the words a\\n shopper would actually use. Start with `Use when \u2026`.\\n2. **The boundary** \u2014 when *not* to, if another tool overlaps. One clause\\n is enough: \\"Use for in-store appointments; not for delivery scheduling.\\"\\n3. **What the assistant gets back** \u2014 if the app reports state or sends\\n messages, say so: \\"reports the size the shopper settles on back to you.\\"\\n\\nOne or two sentences. If a required `inputSchema` field is subtle, say\\nwhat it means here rather than trusting the schema alone.\\n\\nThe same rule governs the **name** (snake_case, matching the folder under\\n`components/`): name it after the job, not the widget. `size_guide`,\\n`gift_finder`, `book_appointment` read as intents; `size_modal`,\\n`quiz_ui`, `product_grid_v2` read as implementation details and get\\nskipped. `displayName` is the one field written for the shopper.\\n\\nKeep `inputSchema` tight: required fields the assistant can\'t infer from\\nthe conversation cause bad calls.\\n\\n## Design requirements\\n\\n### Never use `rem` for fonts and sizing \u2014 always use `em`\\n\\n`rem` resolves against the host page\'s root font size, which is\\narbitrary and outside our control. A host that sets `html { font-size:\\n8px }` (or 200%) will shrink or blow up every `rem`-based dimension.\\n`em` resolves against the app\'s own font size, so it stays\\nself-consistent wherever the app is mounted.\\n\\nUse `em` for font sizes, padding, margins, gaps, widths, heights,\\nand any other length. Borders may stay in `px` (hairlines should not\\nscale with text).\\n\\n```tsx\\n// Bad \u2014 breaks on hosts with a non-default root font size\\n<div style={{ padding: \\"1rem\\", fontSize: \\"0.875rem\\" }} />\\n\\n// Good\\n<div style={{ padding: \\"1em\\", fontSize: \\"0.875em\\" }} />\\n```\\n\\n### Fullscreen apps must leave a safe-zone at the bottom\\n\\nOn the storefront the chat widget floats over the bottom of the screen, so\\nanything a `fullscreen` app renders there can be covered by it. Reserve a\\nsafe-zone of `6.25em` (100px at the default font size) at the bottom of the\\napp\'s scrolling content \u2014 e.g. `padding-bottom: 6.25em` on the scroll\\ncontainer \u2014 so the last row, button, or link can always be scrolled clear of\\nthe widget. Inline and over-input apps don\'t need it.\\n\\n### Don\'t hardcode colors, fonts, or corner radius \u2014 use GreatStore brand variables\\n\\nThe store owner themes the assistant from GreatStore settings. Hardcoded\\nvalues ignore that and make the app clash with the rest of the store.\\nRead from the CSS variables GreatStore injects on the surface instead, so\\nthe app restyles itself when the theme changes.\\n\\nAvailable variables:\\n\\n| Purpose | Variable |\\n| --- | --- |\\n| Surface background | `--color-surface` |\\n| Secondary surface | `--color-surface-secondary` |\\n| Accent surface | `--color-surface-accent` |\\n| Hover surface | `--color-surface-hover` |\\n| Foreground text | `--color-foreground` |\\n| Secondary text | `--color-foreground-secondary` |\\n| Muted text | `--color-foreground-muted` |\\n| Accent text | `--color-foreground-accent` |\\n| Border | `--color-border-default` |\\n| Focus border | `--color-border-focus` |\\n| Primary / brand | `--color-primary` |\\n| Text on primary | `--color-primary-foreground` |\\n| Primary hover | `--color-primary-hover` |\\n| Primary muted | `--color-primary-muted` |\\n| Text on primary muted | `--color-primary-muted-foreground` |\\n| Primary tint | `--color-primary-tint` |\\n| Link | `--color-link` |\\n| Font family | `--font-primary` |\\n| Secondary font family | `--font-secondary` |\\n| Corner radius (scale) | `--radius-xs` \u2026 `--radius-4xl`, `--radius-pill` |\\n\\nThe store owner can set a secondary font family in their GreatStore\\ntheme settings, exposed as `--font-secondary` (it falls back to\\n`--font-primary` when unset). Reach for it to add a tasteful second\\nlayer of typography \u2014 pair `--font-primary` for body copy with\\n`--font-secondary` for headings, prices, or other accents \u2014 so the app\\nreflects the store\'s full type system instead of a single face.\\n\\n```tsx\\n// Bad \u2014 hardcoded, ignores the store\'s theme\\n<button style={{ background: \\"#4f46e5\\", borderRadius: 8, fontFamily: \\"Inter\\" }} />\\n\\n// Good\\n<button\\n style={{\\n background: \\"var(--color-primary)\\",\\n color: \\"var(--color-primary-foreground)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n/>\\n```\\n\\nProvide a sensible fallback only when a value might be absent, e.g.\\n`var(--color-primary, currentColor)`.\\n\\n## App props\\n\\nEach app receives its tool args (the fields you declare in\\n`manifest.json#inputSchema.properties`) plus these GreatStore-injected\\nlifecycle props, which are always present:\\n\\n| Prop | What it does |\\n| --- | --- |\\n| `onSendMessage(text)` | Send text into the chat as if the shopper typed it. |\\n| `onUpdateModelContext(context)` | Inject invisible background context for the model (selected variant, configured options, current step). Replaces the prior value \u2014 never appends; pass `\\"\\"` to clear. Read on the next chat turn. Use it when the assistant should *know* in-app state without a visible message; use `onSendMessage` when you want a turn to happen now. |\\n| `onShowLightbox({ src, originRect? })` | Expand an image in the chat\'s shared full-screen lightbox \u2014 an on-brand zoom overlay your app can\'t render itself (it\'s boxed inside its own bounds and shadow root). Pass the image `src`; for a smooth zoom, also pass the clicked element\'s `getBoundingClientRect()` as `originRect` (omit it and the image grows from the viewport centre). |\\n| `onGenerateStructuredContent(schema, prompt, fallback)` | Ask the store\'s assistant for content matching a JSON Schema (or a Zod schema); resolves to the generated object. Personalized to the shopper. Works the same in the conversation on the storefront and every embed. Best inside an async app that builds its render from the generated payload \u2014 `await` it, then return the JSX. `fallback` is **required**: a schema-shaped object you supply that the app preview renders (so a generation-driven app previews without a live store). It\'s validated against the schema and throws if the two don\'t line up. |\\n| `onClose()` | Dismiss the host slot. Over-input clears the overlay, fullscreen reverts the pane, inline is a no-op. |\\n| `Image` | A drop-in for `<img>`: render `<Image src=\u2026 alt=\u2026 />` instead of `<img>` and your images are automatically served at the right size for the store. Takes the same props as `<img>` (`src`, `alt`, `style`, `loading`, `onClick`, \u2026). Previewing the app outside the store? Pass `Image={\\"img\\"}` (or your own component) to render a plain image. |\\n\\n## Async apps (backend-backed, render-blocking data)\\n\\nIf an app must load data from a backend/API before it can render\\ncorrectly, make it async \u2014 don\'t render an empty shell and fetch in a\\n`useEffect`. Set `\\"async\\": true` in `manifest.json` and export an async\\ndefault. GreatStore waits for your promise (showing a normal loading\\nstate, so you don\'t render your own placeholder), then renders what it\\nresolves to. Apps that render purely from their props stay synchronous.\\n\\nA thrown error is a **retry signal**: the in-store AI sees it and\\nusually re-calls the tool. So only throw when a *different* call could\\nhelp:\\n\\n1. `await` the backend call, then return the finished JSX.\\n2. Validate the AI-passed props first and throw on bad input \u2014 the AI\\n can fix the args and retry. (Don\'t validate the API\'s *output* and\\n throw: the AI can\'t fix the backend, it\'ll just loop.)\\n3. Broadcast a backend failure ONLY when retrying differently could\\n succeed, and say what to change (e.g. empty search \u2192 \\"try a broader\\n keyword\\"). For idempotent failures (500, timeout, missing record)\\n re-running the same call changes nothing \u2014 render a graceful fallback\\n instead of throwing.\\n\\n```tsx\\nexport default async function Example(props: Props) {\\n if (!props.query?.trim()) throw new Error(\\"missing required prop: query\\");\\n const res = await fetch(`/api/search?q=${encodeURIComponent(props.query)}`);\\n if (res.ok) {\\n const { results } = await res.json();\\n if (results.length === 0)\\n throw new Error(`no results for \\"${props.query}\\" \u2014 try a broader keyword`);\\n return <ul>{/* render results */}</ul>;\\n }\\n return <p>Couldn\'t load results right now.</p>; // idempotent: don\'t throw\\n}\\n```\\n","root/README.md":"# GreatStore apps\\n\\nCustom in-chat apps published to your GreatStore tenant. Each app is a\\nReact component living in its own folder under `components/`.\\n\\n```\\nnpm install\\nnpx greatstore apps init <app_name> # add a new app\\nnpx greatstore apps build # builds every components/<name>/bundle.js\\nnpx greatstore apps push # uploads every changed app as a draft\\nnpx greatstore apps publish <app_name> # promote a specific app to live\\n```\\n\\n- `npx greatstore apps push` (no args) hashes each app and only uploads the ones that\\n have changed since the last sync.\\n- `npx greatstore apps pull` (no args) refreshes every live app into\\n `components/<name>/`. Apps with unsaved local edits are skipped with a\\n warning; pass `--force` to overwrite.\\n\\nSee `AGENTS.md` for how an app runs, how to write a manifest name and\\ndescription the assistant will actually pick, and the design rules every\\napp must follow (em-based sizing, brand CSS variables) \u2014 it doubles as\\nguidance for AI coding agents (`CLAUDE.md` / `GEMINI.md` symlink to it).\\n","root/package.json":"{\\n \\"name\\": \\"greatstore-components\\",\\n \\"version\\": \\"0.0.1\\",\\n \\"private\\": true,\\n \\"type\\": \\"module\\",\\n \\"scripts\\": {\\n \\"build\\": \\"npx greatstore apps build\\",\\n \\"push\\": \\"npx greatstore apps build && npx greatstore apps push\\"\\n },\\n \\"dependencies\\": {\\n \\"react\\": \\"^19.0.0\\",\\n \\"react-dom\\": \\"^19.0.0\\"\\n },\\n \\"devDependencies\\": {\\n \\"@types/react\\": \\"^19.0.0\\",\\n \\"@types/react-dom\\": \\"^19.0.0\\",\\n \\"@vitejs/plugin-react\\": \\"^4.3.0\\",\\n \\"typescript\\": \\"^5.6.0\\",\\n \\"vite\\": \\"^5.4.0\\"\\n }\\n}\\n","root/tsconfig.json":"{\\n \\"compilerOptions\\": {\\n \\"target\\": \\"ES2022\\",\\n \\"module\\": \\"ESNext\\",\\n \\"moduleResolution\\": \\"Bundler\\",\\n \\"jsx\\": \\"react-jsx\\",\\n \\"lib\\": [\\"ES2022\\", \\"DOM\\"],\\n \\"strict\\": true,\\n \\"esModuleInterop\\": true,\\n \\"skipLibCheck\\": true,\\n \\"isolatedModules\\": true,\\n \\"noEmit\\": true\\n },\\n \\"include\\": [\\"components/**/component.tsx\\", \\"vite.config.ts\\"]\\n}\\n","root/vite.config.ts":"import { defineConfig } from \\"vite\\";\\nimport react from \\"@vitejs/plugin-react\\";\\n\\n// Real builds happen in `npx greatstore build` (one Vite invocation per\\n// component, externals + runtime shim paths owned by the CLI). This\\n// file exists only so editors / language servers can resolve the\\n// React plugin when inspecting components/*/component.tsx.\\nexport default defineConfig({\\n plugins: [react()],\\n});\\n"}'),ke)}var dt={name:"__GS_NAME__",displayName:"__GS_DISPLAY_NAME__",store:"__GS_STORE__",version:"__GS_VERSION__"};function gt(e,t){let n=e;for(let o of Object.keys(dt)){let s=t[o];s!==void 0&&(n=n.split(dt[o]).join(s))}let r=n.match(/__GS_[A-Z_]+__/);if(r)throw new Error(`internal: template placeholder ${r[0]} was not provided`);return n}var ht=/^[a-z][a-z0-9_]*$/;function wt(e){let t=e.positional[0];if(t!==void 0&&!ht.test(t))throw new Error(`Invalid component name: "${t}" (must match ${ht}).`);let n=m(e.flags,"force"),r=h(e.flags,"store"),o=h(e.flags,"out")??".",s=$.resolve(o),i=rr(s),a;if(i){if(r!==void 0)throw new Error(`Project at ${s} is already pinned to a store via .gsrc. Drop --store; a project folder ships to exactly one store.`);C({cwd:s})}else if(a=r!==void 0?ne(r):ue()??void 0,a===void 0){let u=t?`npx greatstore apps init ${t} --store <slug>`:"npx greatstore apps init --store <slug>";throw new Error(`--store <slug> is required when scaffolding a new project root. Run \`${u}\`.`)}let l=or(s,i,n,{store:a});if(!t){let u=[];i?(u.push(`Updated GreatStore project root in ${s}.`),l.length>0?u.push("",`Added: ${l.join(", ")}`):u.push("","Already up to date \u2014 nothing to add.")):u.push(`Scaffolded GreatStore project root in ${s}.`),u.push("","Next steps:",` cd ${$.relative(process.cwd(),s)||"."}`," npm install"," npx greatstore apps init <component_name> # add your first component",""),process.stdout.write(u.join(`
85
- `));return}let c=$.join(s,"components",t);ar(c,t,n);let p=$.relative(process.cwd(),s)||".";process.stdout.write([`Added component "${t}" at components/${t}/.`,...i&&l.length>0?["",`Also added to the project root: ${l.join(", ")}`]:[],"","Next steps:",...i?[]:[` cd ${p}`," npm install"],` # edit components/${t}/component.tsx and manifest.json`," npx greatstore apps build"," npx greatstore apps push",""].join(`
86
- `))}function rr(e){return g.existsSync($.join(e,"package.json"))&&g.existsSync($.join(e,".gsrc"))}function or(e,t,n,r){if(g.mkdirSync(e,{recursive:!0}),!t&&!n&&g.readdirSync(e).filter(a=>a!==".gsrc").length>0)throw new Error(`Refusing to scaffold project root into non-empty directory ${e}. Pass --force to override.`);let o=t?lr():cr({store:r.store}),s=ir(e,o,n);return g.mkdirSync($.join(e,"components"),{recursive:!0}),s}var sr=new Set(["AGENTS.md"]);function ir(e,t,n){let r=[];for(let[o,s]of t){let i=$.join(e,o);g.mkdirSync($.dirname(i),{recursive:!0});let a=g.existsSync(i);if(!n&&a&&!sr.has(o))continue;let l=!a||g.readFileSync(i,"utf8")!==s;g.writeFileSync(i,s),l&&r.push(o)}for(let o of["CLAUDE.md","GEMINI.md"]){let s=$.join(e,o);n&&yt(s)&&g.rmSync(s),yt(s)||(g.symlinkSync("AGENTS.md",s),r.push(o))}return r}function yt(e){try{return g.lstatSync(e),!0}catch{return!1}}function ar(e,t,n){if(g.existsSync(e)&&!n&&g.readdirSync(e).length>0)throw new Error(`Refusing to overwrite existing components/${t}/. Pass --force to override.`);g.mkdirSync(e,{recursive:!0});for(let[r,o]of ur(t))g.writeFileSync($.join(e,r),o)}function Ne(e,t,n=new Set){let r=mt();return Object.entries(r).filter(([o])=>o.startsWith(e)).map(([o,s])=>[o.slice(e.length),s]).filter(([o])=>!n.has(o)).map(([o,s])=>[o,gt(s,t)])}function cr(e){if(!e.store)throw new Error("internal: rootFiles called without a store slug");return Ne("root/",{store:e.store,version:O})}function lr(){return Ne("root/",{version:O},new Set([".gsrc"]))}function ur(e){return Ne("component/",{name:e,displayName:pr(e)})}function pr(e){let t=e.split("_").filter(Boolean);if(t.length===0)return e;let n=t[0];return n.charAt(0).toUpperCase()+n.slice(1)+(t.length>1?" "+t.slice(1).join(" "):"")}import*as x from"fs";import*as w from"path";import{createRequire as kr}from"module";import*as Rt from"fs";import*as G from"path";import{createRequire as fr}from"module";import*as $e from"path";function bt(e,t,n){let r=vt(e);if(!r)return{ok:!1,reason:"couldn't check props against the manifest \u2014 `typescript` isn't installed in this project (run `npm install`)"};try{let o=r.createSourceFile(t,n,r.ScriptTarget.Latest,!0,r.ScriptKind.TSX),s=mr(r,o);return s?yr(r,o,s):{ok:!1,reason:"couldn't find a default-exported component function to check props against \u2014 export the component as `export default function \u2026`"}}catch(o){return{ok:!1,reason:`couldn't check props against the manifest \u2014 ${$e.basename(t)} could not be parsed (${o.message})`}}}function xt(e,t,n){let r=vt(e);if(!r)return!1;try{let o=r.createSourceFile(t,n,r.ScriptTarget.Latest,!0,r.ScriptKind.TSX),s=!1,i=a=>{if(!s){if(dr(r,a)){s=!0;return}r.forEachChild(a,i)}};return i(o),s}catch{return!1}}function dr(e,t){if(e.isPropertyAccessExpression(t))return St(e,t.expression)&&t.name.text==="GreatStore";if(e.isElementAccessExpression(t)){let n=t.argumentExpression;return St(e,t.expression)&&e.isStringLiteralLike(n)&&n.text==="GreatStore"}return!1}function St(e,t){return e.isIdentifier(t)&&(t.text==="window"||t.text==="globalThis")}function vt(e){let t=fr($e.join(e,"package.json"));try{return t("typescript")}catch{return null}}function mr(e,t){let n=null;for(let o of t.statements){if(e.isFunctionDeclaration(o)&&gr(e,o))return o;e.isExportAssignment(o)&&!o.isExportEquals&&(n=o.expression)}if(!n)return null;let r=kt(e,n);return e.isArrowFunction(r)||e.isFunctionExpression(r)?r:e.isIdentifier(r)?hr(e,t,r.text):null}function gr(e,t){return t.modifiers?.some(n=>n.kind===e.SyntaxKind.DefaultKeyword)??!1}function kt(e,t){let n=t;for(;e.isParenthesizedExpression(n)||e.isAsExpression(n)||e.isSatisfiesExpression(n);)n=n.expression;return n}function hr(e,t,n){for(let r of t.statements){if(e.isFunctionDeclaration(r)&&r.name?.text===n)return r;if(e.isVariableStatement(r))for(let o of r.declarationList.declarations){if(!e.isIdentifier(o.name)||o.name.text!==n||!o.initializer)continue;let s=kt(e,o.initializer);if(e.isArrowFunction(s)||e.isFunctionExpression(s))return s}}return null}function yr(e,t,n){let r=n.parameters[0];if(!r)return{ok:!0,props:{names:[],open:!1}};if(r.type){let o=De(e,t,r.type,new Set);if(o)return{ok:!0,props:o}}return e.isObjectBindingPattern(r.name)?{ok:!0,props:wr(e,r.name)}:{ok:!1,reason:"couldn't check props against the manifest \u2014 declare the component's props as a local `interface`/`type` or destructure them in the signature"}}function De(e,t,n,r){if(e.isTypeLiteralNode(n))return Pt(e,n.members);if(e.isTypeReferenceNode(n)&&e.isIdentifier(n.typeName))return $t(e,t,n.typeName.text,r);if(e.isIntersectionTypeNode(n)){let o=n.types.map(s=>De(e,t,s,r));return o.every(s=>s===null)?null:Et(o.map(s=>s??{names:[],open:!0}))}return null}function $t(e,t,n,r){if(r.has(n))return{names:[],open:!1};r.add(n);for(let o of t.statements){if(e.isInterfaceDeclaration(o)&&o.name.text===n){let s=Pt(e,o.members),i=(o.heritageClauses??[]).flatMap(a=>a.types.map(l=>e.isIdentifier(l.expression)?$t(e,t,l.expression.text,r)??{names:[],open:!0}:{names:[],open:!0}));return Et([s,...i])}if(e.isTypeAliasDeclaration(o)&&o.name.text===n)return De(e,t,o.type,r)}return null}function Pt(e,t){let n=[],r=!1;for(let o of t){if(e.isIndexSignatureDeclaration(o)){r=!0;continue}if(!e.isPropertySignature(o)&&!e.isMethodSignature(o))continue;let s=Ct(e,o.name);if(s===null){r=!0;continue}n.push(s)}return{names:n,open:r}}function wr(e,t){let n=[],r=!1;for(let o of t.elements){if(o.dotDotDotToken){r=!0;continue}let s=o.propertyName??o.name,i=Ct(e,s);i===null?r=!0:n.push(i)}return{names:n,open:r}}function Ct(e,t){return e.isIdentifier(t)||e.isStringLiteral(t)?t.text:null}function Et(e){let t=[],n=!1;for(let r of e){for(let o of r.names)t.includes(o)||t.push(o);n||=r.open}return{names:t,open:n}}function _t(e){let{root:t,name:n}=e,r=G.join(t,"components",n),o=e.manifestPath??G.join(r,"manifest.json"),s=e.sourcePath??G.join(r,"component.tsx"),i=jt(t,o),a=jt(t,s),l=[],c=null,p=At(o);if(p===null)l.push({severity:"error",rule:"manifest/missing",file:i,message:"manifest not found."});else try{let P=JSON.parse(p);!P||typeof P!="object"||Array.isArray(P)?l.push({severity:"error",rule:"manifest/invalid",file:i,message:"manifest must be a JSON object."}):c=P}catch(P){l.push({severity:"error",rule:"manifest/invalid",file:i,message:`manifest is not valid JSON: ${P.message}`})}let u=At(s),f=u===null?{ok:!1,reason:`couldn't check props against the manifest \u2014 ${a} not found`}:bt(t,s,u),R=u===null?!1:xt(t,s,u);return{ctx:{name:n,manifestFile:i,sourceFile:a,manifest:c,props:f,usesWindowGreatStore:R},diagnostics:l}}function At(e){try{return Rt.readFileSync(e,"utf8")}catch{return null}}function jt(e,t){let n=G.relative(e,t);return n.startsWith("..")?t:n.split(G.sep).join("/")}var Tt=new Set(["onSendMessage","onClose","onUpdateModelContext","onShowLightbox","onGenerateStructuredContent","storeData","Image"]);var Ot=new Map([["onError",'prop `onError` is deprecated and no longer provided \u2014 prefer an async component to report failures. Drop the prop; see the "Async components" section in AGENTS.md for how to signal errors.']]);function It(e){if(!e.manifest)return[];let t=br(e.manifest.inputSchema);if(t===null)return[];if(!e.props.ok)return[{severity:"warning",rule:"props/not-analyzable",file:e.sourceFile,message:`${e.props.reason}.`}];if(e.props.props.open)return[];let n=new Set(e.props.props.names),r=new Set(t),o=[];for(let i of e.props.props.names){if(Tt.has(i))continue;let a=Ot.get(i);if(a){o.push({severity:"warning",rule:"props/retired-lifecycle",file:e.sourceFile,message:a});continue}r.has(i)||o.push({severity:"warning",rule:"props/undeclared",file:e.sourceFile,message:`prop \`${i}\` is not declared in ${e.manifestFile}#inputSchema.properties, so nothing will ever pass it. Declare it in the schema, or drop it from the component.`})}let s=t.filter(i=>!n.has(i));return s.length>0&&o.push({severity:"error",rule:"props/missing",file:e.sourceFile,message:Sr(e.manifestFile,s)}),o}var Lt=8;function Sr(e,t){if(t.length===1){let[s]=t;return`${e} declares inputSchema field \`${s}\`, but the component does not accept a \`${s}\` prop. Add it to the component's props, or remove it from the schema.`}let n=t.slice(0,Lt).map(s=>`\`${s}\``).join(", "),r=t.length-Lt,o=r>0?`${n} (+${r} more)`:n;return`${e} declares ${t.length} inputSchema fields the component does not accept: ${o}. Add them to the component's props, or remove them from the schema.`}function br(e){if(!e||typeof e!="object")return null;let t=e.properties;return!t||typeof t!="object"||Array.isArray(t)?null:Object.keys(t)}var xr=["anyOf","oneOf","allOf","$ref","not"];function Pe(e,t,n){if(Array.isArray(e)){e.forEach((s,i)=>Pe(s,`${t}[${i}]`,n));return}if(!e||typeof e!="object")return;let r=e;for(let s of xr)s in r&&n.unionPaths.push(`${t}.${s}`);let o=r.properties;if(o&&typeof o=="object"&&!Array.isArray(o))for(let[s,i]of Object.entries(o))n.fields+=1,Pe(i,`${t}.${s}`,n);"items"in r&&Pe(r.items,`${t}[]`,n)}function Ft(e){let t=e.manifest?.inputSchema;if(!t||typeof t!="object")return[];let n={bytes:Buffer.byteLength(JSON.stringify(t),"utf8"),fields:0,unionPaths:[]};Pe(t,"inputSchema",n);let r=[];if(n.unionPaths.length>0){let o=n.unionPaths.slice(0,3).join(", "),s=n.unionPaths.length>3?` (+${n.unionPaths.length-3} more)`:"";r.push(`uses ${o}${s} \u2014 declare exactly one type per field; accept alternate shapes in component code instead`)}return n.bytes>8192&&r.push(`is ${(n.bytes/1024).toFixed(1)} KB serialized (limit ${8192/1024} KB)`),n.fields>50&&r.push(`declares ${n.fields} fields (limit 50)`),r.length===0?[]:[{severity:"error",rule:"manifest/input-schema-too-complex",file:e.manifestFile,message:`inputSchema ${r.join("; ")}.
87
- A schema this complex is usually a sign the component is overengineered, and the agent will fill it unreliably or stop calling the tool altogether. Keep it to a small set of flat, single-type fields (one canonical name per concept \u2014 no aliases), and let component code handle formatting, fallbacks, and edge cases.`}]}function Nt(e){let t=e.manifest?.name;return typeof t!="string"||t===e.name?[]:[{severity:"error",rule:"manifest/name-mismatch",file:e.manifestFile,message:`manifest name "${t}" does not match folder name "${e.name}".`}]}function Dt(e){return e.usesWindowGreatStore?[{severity:"warning",rule:"globals/window-greatstore",file:e.sourceFile,message:"this component reads `window.GreatStore`, the host-page embed API. Components should interact with GreatStore through their injected lifecycle props (`onSendMessage`, `onGenerateStructuredContent`, \u2026) instead \u2014 those are wired to the surface the component is mounted in."}]:[]}function fe(e){return e.filter(t=>t.severity==="error")}function Be(e){return e.filter(t=>t.severity==="warning")}function de(e){return`${e.severity==="error"?"error":"warning"} ${e.file}: ${e.message}`}var vr=[Nt,Ft,It,Dt];function Ce(e){let{ctx:t,diagnostics:n}=_t(e);for(let r of vr)n.push(...r(t));return{diagnostics:n,ok:fe(n).length===0}}var X="components";async function Mt(e){let t=process.cwd();if(!x.existsSync(w.join(t,"package.json"))||!x.existsSync(w.join(t,X)))throw new Error(`\`npx greatstore apps build\` must run from a project root (contains \`package.json\` and \`${X}/\`). Current dir: ${t}`);let n=$r(t);if(n.length===0){process.stdout.write(`(no components in ./${X} \u2014 run \`npx greatstore apps init <name>\` to add one)
88
- `);return}let r=e.positional[0],o=r?n.filter(p=>p===r):n;if(r&&o.length===0)throw new Error(`No component named "${r}" in ./${X}`);let s=[],i=[];for(let p of o){let u=Ce({root:t,name:p});for(let f of u.diagnostics)process.stdout.write(` ${de(f)}
89
- `);(u.ok?i:s).push(p)}if(i.length===0){process.stdout.write(`
84
+ `}function Nt(e){if(e===void 0||e==="show")return $r;if(e==="set")return Er()}import*as g from"fs";import*as P from"path";import{readdirSync as rs,readFileSync as os}from"fs";import{fileURLToPath as is}from"url";var Ee=null;function Dt(){return Ee||(Ee=JSON.parse('{"component/component.tsx":"import React from \\"react\\";\\n\\n// Add your tool args (matching manifest.json#inputSchema.properties)\\n// alongside the GreatStore-injected lifecycle props. See AGENTS.md for\\n// what each lifecycle prop does.\\ninterface Props {\\n onSendMessage: (text: string) => void;\\n onUpdateModelContext: (context: string) => void;\\n onShowLightbox: (options: { src: string; originRect?: DOMRect }) => void;\\n onClose: () => void;\\n // Ask the store\'s assistant for content matching a JSON Schema (or Zod\\n // schema) \u2014 the app\'s own catalog-grounded generation, for recommended\\n // picks or a personalized summary. Resolves to the generated object.\\n // `fallback` is a required, schema-shaped stand-in rendered in the app\\n // preview (and validated against the schema). See AGENTS.md.\\n onGenerateStructuredContent: <T = unknown>(\\n schema: object,\\n prompt: string,\\n fallback: T,\\n ) => Promise<T>;\\n // Drop-in for <img>: `<Image src=\u2026 alt=\u2026 />`. See AGENTS.md.\\n Image: React.ElementType<React.ComponentProps<\\"img\\">>;\\n}\\n\\n// See AGENTS.md for how an app runs (the assistant picks it by the\\n// manifest\'s name and description, then calls it with these props), the\\n// design rules (em-based sizing, brand CSS variables), and how to write an\\n// async, backend-backed app.\\nexport default function Component(_props: Props): React.ReactElement {\\n return (\\n <div\\n style={{\\n padding: \\"1em\\",\\n border: \\"1px solid var(--color-border-default)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n background: \\"var(--color-surface)\\",\\n color: \\"var(--color-foreground)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n >\\n <strong>__GS_NAME__</strong> \u2014 hello from your app!\\n </div>\\n );\\n}\\n","component/manifest.json":"{\\n \\"name\\": \\"__GS_NAME__\\",\\n \\"displayName\\": \\"__GS_DISPLAY_NAME__\\",\\n \\"description\\": \\"Use when <the shopper situation that should make the assistant open this app \u2014 say when to reach for it and what it reports back, never what it looks like; see AGENTS.md>.\\",\\n \\"displayMode\\": \\"inline\\",\\n \\"async\\": false,\\n \\"inputSchema\\": {\\n \\"type\\": \\"object\\",\\n \\"properties\\": {}\\n }\\n}\\n","root/.gitignore":"node_modules/\\ncomponents/*/bundle.js\\ncomponents/*/.gssync.json\\n*.tsbuildinfo\\n.DS_Store\\n","root/.gsrc":"{\\n \\"store\\": \\"__GS_STORE__\\"\\n}\\n","root/AGENTS.md":"# AGENTS.md\\n\\n> **Do not edit \u2014 auto-generated by the GreatStore CLI v__GS_VERSION__.**\\n> This file is rewritten by `npx greatstore apps init`, so any changes you make here\\n> will be overwritten. If this version trails your installed CLI, re-run\\n> `npx greatstore apps init` to refresh it. Put project-specific notes in another file.\\n\\nGuidance for AI coding agents working on the apps in this project.\\n`CLAUDE.md` and `GEMINI.md` are symlinks to this file.\\n\\nAn app is interactive UI the store\'s assistant renders inside the\\nconversation \u2014 a configurator, a quiz, a size guide, a booking form. You\\nwrite it in React; each app is one folder under `components/`, holding\\n`manifest.json` and `component.tsx`.\\n\\nApps render inside arbitrary publisher websites (the embed widget mounts\\non a host page) as well as the GreatStore storefront. You control neither\\nthe host page\'s base font size nor its color scheme, and the store owner\\ncontrols the look from GreatStore theme settings. The rules below keep\\napps portable across both.\\n\\n## How an app runs\\n\\nAn app is not a page the shopper navigates to. It is a tool the assistant\\ncalls mid-conversation, and once it is on screen it can talk back \u2014 which\\nis the part that makes apps worth building.\\n\\n```\\nShopper Assistant Your app\\n \u2502 \u2502 \u2502\\n \u2502 \\"what size am I?\\" \u2502 \u2502\\n \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502 \u2502\\n \u2502 \u2502 picks the app by its \u2502\\n \u2502 \u2502 name + description \u2502\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 calls it with props \u2502\\n \u2502 \u2502 your inputSchema asked \u2502\\n \u2502 \u2502 for (productName, \u2026) \u2502\\n \u2502 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502\\n \u2502 \u2502 \u251C\u2500\u2500\u2510 onGenerateStructured-\\n \u2502 \u2502 \u2502 \u2502 Content(): its own\\n \u2502 \u2502 \u2502 \u2502 catalog-grounded\\n \u2502 \u2502 \u2502<\u2500\u2518 generation, if wanted\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 \u2502 renders the moment your\\n \u2502 \u2502 \u2502 happy path has what it\\n \u2502 \u2502 \u2502 needs (async: after your\\n \u2502<\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 promise resolves)\\n \u2502 sees the app \u2502 \u2502\\n \u2502 \u2502 \u2502\\n \u2502 picks size M \u2502 \u2502\\n \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 onUpdateModelContext() \u2502 silent: the assistant\\n \u2502 \u2502<\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 now knows the pick\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 onSendMessage() \u2502 visible: a shopper turn\\n \u2502 \u2502<\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524 happens right now\\n \u2502 \u2502 \u2502\\n \u2502 \u2502 calls the app again \u2502 same app, new props \u2014\\n \u2502 \u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500>\u2502 re-rendered in place\\n \u2502 \u2502 \u2502\\n```\\n\\nFour consequences worth designing around:\\n\\n1. **The assistant chooses the app, so `manifest.json` is the interface it\\n sees** \u2014 see the next section.\\n2. **Control is bidirectional once the app is up.** The app reports what\\n the shopper is doing (`onUpdateModelContext`), can speak for the\\n shopper (`onSendMessage`), and the assistant can call the app again\\n with revised props. Keep the render a function of the props it was\\n given, so a re-call is a re-render rather than a reset.\\n3. **The app can run its own generation, not just receive props.**\\n `onGenerateStructuredContent` returns a catalog-grounded,\\n shopper-personalized object matching your schema \u2014 recommended picks, a\\n personalized summary, a reason per option \u2014 which you render in your\\n own markup.\\n4. **Render on the happy path, not on a shell.** Whatever the app needs to\\n be correct \u2014 props, or awaited data in an async app \u2014 should be there\\n before anything paints; GreatStore owns the loading state.\\n\\n## `manifest.json` \u2014 the name and description decide whether your app runs\\n\\nThe assistant never sees your app. It sees a name and a sentence, next to\\nevery other tool it has, and picks one. Write the description for that\\n*caller*, answering one question: when should I reach for this, and what\\ndo I get back?\\n\\n**Describing the UI is the most common mistake.** Layout, sliders, tabs,\\ncarousels and colors are the shopper\'s concern. To the assistant they are\\nnoise \u2014 they say nothing about when to call the tool.\\n\\n| Don\'t | Do |\\n| --- | --- |\\n| \\"Renders a two-column table of measurements with a unit toggle.\\" | \\"Use when a shopper is unsure which size to buy or asks how an item fits.\\" |\\n| \\"A carousel of product cards with images and prices.\\" | \\"Use to show 2\u20138 specific products you have already chosen, when the shopper wants to see them side by side before deciding.\\" |\\n| \\"Modal with a multi-step form and a progress bar.\\" | \\"Use when the shopper wants a gift but can\'t say what \u2014 collects budget, recipient and occasion, then reports them back so you can recommend.\\" |\\n\\nWhat belongs in a description, in this order:\\n\\n1. **The trigger** \u2014 the shopper situation or intent, in the words a\\n shopper would actually use. Start with `Use when \u2026`.\\n2. **The boundary** \u2014 when *not* to, if another tool overlaps. One clause\\n is enough: \\"Use for in-store appointments; not for delivery scheduling.\\"\\n3. **What the assistant gets back** \u2014 if the app reports state or sends\\n messages, say so: \\"reports the size the shopper settles on back to you.\\"\\n\\nOne or two sentences. If a required `inputSchema` field is subtle, say\\nwhat it means here rather than trusting the schema alone.\\n\\nThe same rule governs the **name** (snake_case, matching the folder under\\n`components/`): name it after the job, not the widget. `size_guide`,\\n`gift_finder`, `book_appointment` read as intents; `size_modal`,\\n`quiz_ui`, `product_grid_v2` read as implementation details and get\\nskipped. `displayName` is the one field written for the shopper.\\n\\nKeep `inputSchema` tight: required fields the assistant can\'t infer from\\nthe conversation cause bad calls.\\n\\n## Design requirements\\n\\n### Never use `rem` for fonts and sizing \u2014 always use `em`\\n\\n`rem` resolves against the host page\'s root font size, which is\\narbitrary and outside our control. A host that sets `html { font-size:\\n8px }` (or 200%) will shrink or blow up every `rem`-based dimension.\\n`em` resolves against the app\'s own font size, so it stays\\nself-consistent wherever the app is mounted.\\n\\nUse `em` for font sizes, padding, margins, gaps, widths, heights,\\nand any other length. Borders may stay in `px` (hairlines should not\\nscale with text).\\n\\n```tsx\\n// Bad \u2014 breaks on hosts with a non-default root font size\\n<div style={{ padding: \\"1rem\\", fontSize: \\"0.875rem\\" }} />\\n\\n// Good\\n<div style={{ padding: \\"1em\\", fontSize: \\"0.875em\\" }} />\\n```\\n\\n### Fullscreen apps must leave a safe-zone at the bottom\\n\\nOn the storefront the chat widget floats over the bottom of the screen, so\\nanything a `fullscreen` app renders there can be covered by it. Reserve a\\nsafe-zone of `6.25em` (100px at the default font size) at the bottom of the\\napp\'s scrolling content \u2014 e.g. `padding-bottom: 6.25em` on the scroll\\ncontainer \u2014 so the last row, button, or link can always be scrolled clear of\\nthe widget. Inline and over-input apps don\'t need it.\\n\\n### Don\'t hardcode colors, fonts, or corner radius \u2014 use GreatStore brand variables\\n\\nThe store owner themes the assistant from GreatStore settings. Hardcoded\\nvalues ignore that and make the app clash with the rest of the store.\\nRead from the CSS variables GreatStore injects on the surface instead, so\\nthe app restyles itself when the theme changes.\\n\\nAvailable variables:\\n\\n| Purpose | Variable |\\n| --- | --- |\\n| Surface background | `--color-surface` |\\n| Secondary surface | `--color-surface-secondary` |\\n| Accent surface | `--color-surface-accent` |\\n| Hover surface | `--color-surface-hover` |\\n| Foreground text | `--color-foreground` |\\n| Secondary text | `--color-foreground-secondary` |\\n| Muted text | `--color-foreground-muted` |\\n| Accent text | `--color-foreground-accent` |\\n| Border | `--color-border-default` |\\n| Focus border | `--color-border-focus` |\\n| Primary / brand | `--color-primary` |\\n| Text on primary | `--color-primary-foreground` |\\n| Primary hover | `--color-primary-hover` |\\n| Primary muted | `--color-primary-muted` |\\n| Text on primary muted | `--color-primary-muted-foreground` |\\n| Primary tint | `--color-primary-tint` |\\n| Link | `--color-link` |\\n| Font family | `--font-primary` |\\n| Secondary font family | `--font-secondary` |\\n| Corner radius (scale) | `--radius-xs` \u2026 `--radius-4xl`, `--radius-pill` |\\n\\nThe store owner can set a secondary font family in their GreatStore\\ntheme settings, exposed as `--font-secondary` (it falls back to\\n`--font-primary` when unset). Reach for it to add a tasteful second\\nlayer of typography \u2014 pair `--font-primary` for body copy with\\n`--font-secondary` for headings, prices, or other accents \u2014 so the app\\nreflects the store\'s full type system instead of a single face.\\n\\n```tsx\\n// Bad \u2014 hardcoded, ignores the store\'s theme\\n<button style={{ background: \\"#4f46e5\\", borderRadius: 8, fontFamily: \\"Inter\\" }} />\\n\\n// Good\\n<button\\n style={{\\n background: \\"var(--color-primary)\\",\\n color: \\"var(--color-primary-foreground)\\",\\n borderRadius: \\"var(--radius-lg)\\",\\n fontFamily: \\"var(--font-primary)\\",\\n }}\\n/>\\n```\\n\\nProvide a sensible fallback only when a value might be absent, e.g.\\n`var(--color-primary, currentColor)`.\\n\\n## App props\\n\\nEach app receives its tool args (the fields you declare in\\n`manifest.json#inputSchema.properties`) plus these GreatStore-injected\\nlifecycle props, which are always present:\\n\\n| Prop | What it does |\\n| --- | --- |\\n| `onSendMessage(text)` | Send text into the chat as if the shopper typed it. |\\n| `onUpdateModelContext(context)` | Inject invisible background context for the model (selected variant, configured options, current step). Replaces the prior value \u2014 never appends; pass `\\"\\"` to clear. Read on the next chat turn. Use it when the assistant should *know* in-app state without a visible message; use `onSendMessage` when you want a turn to happen now. |\\n| `onShowLightbox({ src, originRect? })` | Expand an image in the chat\'s shared full-screen lightbox \u2014 an on-brand zoom overlay your app can\'t render itself (it\'s boxed inside its own bounds and shadow root). Pass the image `src`; for a smooth zoom, also pass the clicked element\'s `getBoundingClientRect()` as `originRect` (omit it and the image grows from the viewport centre). |\\n| `onGenerateStructuredContent(schema, prompt, fallback)` | Ask the store\'s assistant for content matching a JSON Schema (or a Zod schema); resolves to the generated object. Personalized to the shopper. Works the same in the conversation on the storefront and every embed. Best inside an async app that builds its render from the generated payload \u2014 `await` it, then return the JSX. `fallback` is **required**: a schema-shaped object you supply that the app preview renders (so a generation-driven app previews without a live store). It\'s validated against the schema and throws if the two don\'t line up. |\\n| `onClose()` | Dismiss the host slot. Over-input clears the overlay, fullscreen reverts the pane, inline is a no-op. |\\n| `Image` | A drop-in for `<img>`: render `<Image src=\u2026 alt=\u2026 />` instead of `<img>` and your images are automatically served at the right size for the store. Takes the same props as `<img>` (`src`, `alt`, `style`, `loading`, `onClick`, \u2026). Previewing the app outside the store? Pass `Image={\\"img\\"}` (or your own component) to render a plain image. |\\n\\n## Async apps (backend-backed, render-blocking data)\\n\\nIf an app must load data from a backend/API before it can render\\ncorrectly, make it async \u2014 don\'t render an empty shell and fetch in a\\n`useEffect`. Set `\\"async\\": true` in `manifest.json` and export an async\\ndefault. GreatStore waits for your promise (showing a normal loading\\nstate, so you don\'t render your own placeholder), then renders what it\\nresolves to. Apps that render purely from their props stay synchronous.\\n\\nA thrown error is a **retry signal**: the in-store AI sees it and\\nusually re-calls the tool. So only throw when a *different* call could\\nhelp:\\n\\n1. `await` the backend call, then return the finished JSX.\\n2. Validate the AI-passed props first and throw on bad input \u2014 the AI\\n can fix the args and retry. (Don\'t validate the API\'s *output* and\\n throw: the AI can\'t fix the backend, it\'ll just loop.)\\n3. Broadcast a backend failure ONLY when retrying differently could\\n succeed, and say what to change (e.g. empty search \u2192 \\"try a broader\\n keyword\\"). For idempotent failures (500, timeout, missing record)\\n re-running the same call changes nothing \u2014 render a graceful fallback\\n instead of throwing.\\n\\n```tsx\\nexport default async function Example(props: Props) {\\n if (!props.query?.trim()) throw new Error(\\"missing required prop: query\\");\\n const res = await fetch(`/api/search?q=${encodeURIComponent(props.query)}`);\\n if (res.ok) {\\n const { results } = await res.json();\\n if (results.length === 0)\\n throw new Error(`no results for \\"${props.query}\\" \u2014 try a broader keyword`);\\n return <ul>{/* render results */}</ul>;\\n }\\n return <p>Couldn\'t load results right now.</p>; // idempotent: don\'t throw\\n}\\n```\\n","root/README.md":"# GreatStore apps\\n\\nCustom in-chat apps published to your GreatStore tenant. Each app is a\\nReact component living in its own folder under `components/`.\\n\\n```\\nnpm install\\nnpx greatstore apps init <app_name> # add a new app\\nnpx greatstore apps build # builds every components/<name>/bundle.js\\nnpx greatstore apps push # uploads every changed app as a draft\\nnpx greatstore apps publish <app_name> # promote a specific app to live\\n```\\n\\n- `npx greatstore apps push` (no args) hashes each app and only uploads the ones that\\n have changed since the last sync.\\n- `npx greatstore apps pull` (no args) refreshes every live app into\\n `components/<name>/`. Apps with unsaved local edits are skipped with a\\n warning; pass `--force` to overwrite.\\n\\nSee `AGENTS.md` for how an app runs, how to write a manifest name and\\ndescription the assistant will actually pick, and the design rules every\\napp must follow (em-based sizing, brand CSS variables) \u2014 it doubles as\\nguidance for AI coding agents (`CLAUDE.md` / `GEMINI.md` symlink to it).\\n","root/package.json":"{\\n \\"name\\": \\"greatstore-components\\",\\n \\"version\\": \\"0.0.1\\",\\n \\"private\\": true,\\n \\"type\\": \\"module\\",\\n \\"scripts\\": {\\n \\"build\\": \\"npx greatstore apps build\\",\\n \\"push\\": \\"npx greatstore apps build && npx greatstore apps push\\"\\n },\\n \\"dependencies\\": {\\n \\"react\\": \\"^19.0.0\\",\\n \\"react-dom\\": \\"^19.0.0\\"\\n },\\n \\"devDependencies\\": {\\n \\"@types/react\\": \\"^19.0.0\\",\\n \\"@types/react-dom\\": \\"^19.0.0\\",\\n \\"@vitejs/plugin-react\\": \\"^4.3.0\\",\\n \\"typescript\\": \\"^5.6.0\\",\\n \\"vite\\": \\"^5.4.0\\"\\n }\\n}\\n","root/tsconfig.json":"{\\n \\"compilerOptions\\": {\\n \\"target\\": \\"ES2022\\",\\n \\"module\\": \\"ESNext\\",\\n \\"moduleResolution\\": \\"Bundler\\",\\n \\"jsx\\": \\"react-jsx\\",\\n \\"lib\\": [\\"ES2022\\", \\"DOM\\"],\\n \\"strict\\": true,\\n \\"esModuleInterop\\": true,\\n \\"skipLibCheck\\": true,\\n \\"isolatedModules\\": true,\\n \\"noEmit\\": true\\n },\\n \\"include\\": [\\"components/**/component.tsx\\", \\"vite.config.ts\\"]\\n}\\n","root/vite.config.ts":"import { defineConfig } from \\"vite\\";\\nimport react from \\"@vitejs/plugin-react\\";\\n\\n// Real builds happen in `npx greatstore build` (one Vite invocation per\\n// component, externals + runtime shim paths owned by the CLI). This\\n// file exists only so editors / language servers can resolve the\\n// React plugin when inspecting components/*/component.tsx.\\nexport default defineConfig({\\n plugins: [react()],\\n});\\n"}'),Ee)}var Ft={name:"__GS_NAME__",displayName:"__GS_DISPLAY_NAME__",store:"__GS_STORE__",version:"__GS_VERSION__"};function Bt(e,t){let n=e;for(let o of Object.keys(Ft)){let s=t[o];s!==void 0&&(n=n.split(Ft[o]).join(s))}let r=n.match(/__GS_[A-Z_]+__/);if(r)throw new Error(`internal: template placeholder ${r[0]} was not provided`);return n}var Ht=/^[a-z][a-z0-9_]*$/;function Ut(e){let t=e.positional[0];if(t!==void 0&&!Ht.test(t))throw new Error(`Invalid component name: "${t}" (must match ${Ht}).`);let n=m(e.flags,"force"),r=h(e.flags,"store"),o=h(e.flags,"out")??".",s=P.resolve(o),i=Ar(s),a;if(i){if(r!==void 0)throw new Error(`Project at ${s} is already pinned to a store via .gsrc. Drop --store; a project folder ships to exactly one store.`);x({cwd:s})}else if(a=r!==void 0?oe(r):de()??void 0,a===void 0){let u=t?`npx greatstore apps init ${t} --store <slug>`:"npx greatstore apps init --store <slug>";throw new Error(`--store <slug> is required when scaffolding a new project root. Run \`${u}\`.`)}let l=jr(s,i,n,{store:a});if(!t){let u=[];i?(u.push(`Updated GreatStore project root in ${s}.`),l.length>0?u.push("",`Added: ${l.join(", ")}`):u.push("","Already up to date \u2014 nothing to add.")):u.push(`Scaffolded GreatStore project root in ${s}.`),u.push("","Next steps:",` cd ${P.relative(process.cwd(),s)||"."}`," npm install"," npx greatstore apps init <component_name> # add your first component",""),process.stdout.write(u.join(`
85
+ `));return}let c=P.join(s,"components",t);_r(c,t,n);let p=P.relative(process.cwd(),s)||".";process.stdout.write([`Added component "${t}" at components/${t}/.`,...i&&l.length>0?["",`Also added to the project root: ${l.join(", ")}`]:[],"","Next steps:",...i?[]:[` cd ${p}`," npm install"],` # edit components/${t}/component.tsx and manifest.json`," npx greatstore apps build"," npx greatstore apps push",""].join(`
86
+ `))}function Ar(e){return g.existsSync(P.join(e,"package.json"))&&g.existsSync(P.join(e,".gsrc"))}function jr(e,t,n,r){if(g.mkdirSync(e,{recursive:!0}),!t&&!n&&g.readdirSync(e).filter(a=>a!==".gsrc").length>0)throw new Error(`Refusing to scaffold project root into non-empty directory ${e}. Pass --force to override.`);let o=t?Lr():Or({store:r.store}),s=Tr(e,o,n);return g.mkdirSync(P.join(e,"components"),{recursive:!0}),s}var Rr=new Set(["AGENTS.md"]);function Tr(e,t,n){let r=[];for(let[o,s]of t){let i=P.join(e,o);g.mkdirSync(P.dirname(i),{recursive:!0});let a=g.existsSync(i);if(!n&&a&&!Rr.has(o))continue;let l=!a||g.readFileSync(i,"utf8")!==s;g.writeFileSync(i,s),l&&r.push(o)}for(let o of["CLAUDE.md","GEMINI.md"]){let s=P.join(e,o);n&&Mt(s)&&g.rmSync(s),Mt(s)||(g.symlinkSync("AGENTS.md",s),r.push(o))}return r}function Mt(e){try{return g.lstatSync(e),!0}catch{return!1}}function _r(e,t,n){if(g.existsSync(e)&&!n&&g.readdirSync(e).length>0)throw new Error(`Refusing to overwrite existing components/${t}/. Pass --force to override.`);g.mkdirSync(e,{recursive:!0});for(let[r,o]of Ir(t))g.writeFileSync(P.join(e,r),o)}function Ye(e,t,n=new Set){let r=Dt();return Object.entries(r).filter(([o])=>o.startsWith(e)).map(([o,s])=>[o.slice(e.length),s]).filter(([o])=>!n.has(o)).map(([o,s])=>[o,Bt(s,t)])}function Or(e){if(!e.store)throw new Error("internal: rootFiles called without a store slug");return Ye("root/",{store:e.store,version:O})}function Lr(){return Ye("root/",{version:O},new Set([".gsrc"]))}function Ir(e){return Ye("component/",{name:e,displayName:Nr(e)})}function Nr(e){let t=e.split("_").filter(Boolean);if(t.length===0)return e;let n=t[0];return n.charAt(0).toUpperCase()+n.slice(1)+(t.length>1?" "+t.slice(1).join(" "):"")}import*as $ from"fs";import*as b from"path";import{createRequire as Wr}from"module";import*as en from"fs";import*as U from"path";import{createRequire as Fr}from"module";import*as Ae from"path";function qt(e,t,n){let r=Jt(e);if(!r)return{ok:!1,reason:"couldn't check props against the manifest \u2014 `typescript` isn't installed in this project (run `npm install`)"};try{let o=r.createSourceFile(t,n,r.ScriptTarget.Latest,!0,r.ScriptKind.TSX),s=Br(r,o);return s?Ur(r,o,s):{ok:!1,reason:"couldn't find a default-exported component function to check props against \u2014 export the component as `export default function \u2026`"}}catch(o){return{ok:!1,reason:`couldn't check props against the manifest \u2014 ${Ae.basename(t)} could not be parsed (${o.message})`}}}function Vt(e,t,n){let r=Jt(e);if(!r)return!1;try{let o=r.createSourceFile(t,n,r.ScriptTarget.Latest,!0,r.ScriptKind.TSX),s=!1,i=a=>{if(!s){if(Dr(r,a)){s=!0;return}r.forEachChild(a,i)}};return i(o),s}catch{return!1}}function Dr(e,t){if(e.isPropertyAccessExpression(t))return Gt(e,t.expression)&&t.name.text==="GreatStore";if(e.isElementAccessExpression(t)){let n=t.argumentExpression;return Gt(e,t.expression)&&e.isStringLiteralLike(n)&&n.text==="GreatStore"}return!1}function Gt(e,t){return e.isIdentifier(t)&&(t.text==="window"||t.text==="globalThis")}function Jt(e){let t=Fr(Ae.join(e,"package.json"));try{return t("typescript")}catch{return null}}function Br(e,t){let n=null;for(let o of t.statements){if(e.isFunctionDeclaration(o)&&Hr(e,o))return o;e.isExportAssignment(o)&&!o.isExportEquals&&(n=o.expression)}if(!n)return null;let r=Kt(e,n);return e.isArrowFunction(r)||e.isFunctionExpression(r)?r:e.isIdentifier(r)?Mr(e,t,r.text):null}function Hr(e,t){return t.modifiers?.some(n=>n.kind===e.SyntaxKind.DefaultKeyword)??!1}function Kt(e,t){let n=t;for(;e.isParenthesizedExpression(n)||e.isAsExpression(n)||e.isSatisfiesExpression(n);)n=n.expression;return n}function Mr(e,t,n){for(let r of t.statements){if(e.isFunctionDeclaration(r)&&r.name?.text===n)return r;if(e.isVariableStatement(r))for(let o of r.declarationList.declarations){if(!e.isIdentifier(o.name)||o.name.text!==n||!o.initializer)continue;let s=Kt(e,o.initializer);if(e.isArrowFunction(s)||e.isFunctionExpression(s))return s}}return null}function Ur(e,t,n){let r=n.parameters[0];if(!r)return{ok:!0,props:{names:[],open:!1}};if(r.type){let o=Qe(e,t,r.type,new Set);if(o)return{ok:!0,props:o}}return e.isObjectBindingPattern(r.name)?{ok:!0,props:Gr(e,r.name)}:{ok:!1,reason:"couldn't check props against the manifest \u2014 declare the component's props as a local `interface`/`type` or destructure them in the signature"}}function Qe(e,t,n,r){if(e.isTypeLiteralNode(n))return zt(e,n.members);if(e.isTypeReferenceNode(n)&&e.isIdentifier(n.typeName))return Wt(e,t,n.typeName.text,r);if(e.isIntersectionTypeNode(n)){let o=n.types.map(s=>Qe(e,t,s,r));return o.every(s=>s===null)?null:Yt(o.map(s=>s??{names:[],open:!0}))}return null}function Wt(e,t,n,r){if(r.has(n))return{names:[],open:!1};r.add(n);for(let o of t.statements){if(e.isInterfaceDeclaration(o)&&o.name.text===n){let s=zt(e,o.members),i=(o.heritageClauses??[]).flatMap(a=>a.types.map(l=>e.isIdentifier(l.expression)?Wt(e,t,l.expression.text,r)??{names:[],open:!0}:{names:[],open:!0}));return Yt([s,...i])}if(e.isTypeAliasDeclaration(o)&&o.name.text===n)return Qe(e,t,o.type,r)}return null}function zt(e,t){let n=[],r=!1;for(let o of t){if(e.isIndexSignatureDeclaration(o)){r=!0;continue}if(!e.isPropertySignature(o)&&!e.isMethodSignature(o))continue;let s=Xt(e,o.name);if(s===null){r=!0;continue}n.push(s)}return{names:n,open:r}}function Gr(e,t){let n=[],r=!1;for(let o of t.elements){if(o.dotDotDotToken){r=!0;continue}let s=o.propertyName??o.name,i=Xt(e,s);i===null?r=!0:n.push(i)}return{names:n,open:r}}function Xt(e,t){return e.isIdentifier(t)||e.isStringLiteral(t)?t.text:null}function Yt(e){let t=[],n=!1;for(let r of e){for(let o of r.names)t.includes(o)||t.push(o);n||=r.open}return{names:t,open:n}}function tn(e){let{root:t,name:n}=e,r=U.join(t,"components",n),o=e.manifestPath??U.join(r,"manifest.json"),s=e.sourcePath??U.join(r,"component.tsx"),i=Zt(t,o),a=Zt(t,s),l=[],c=null,p=Qt(o);if(p===null)l.push({severity:"error",rule:"manifest/missing",file:i,message:"manifest not found."});else try{let y=JSON.parse(p);!y||typeof y!="object"||Array.isArray(y)?l.push({severity:"error",rule:"manifest/invalid",file:i,message:"manifest must be a JSON object."}):c=y}catch(y){l.push({severity:"error",rule:"manifest/invalid",file:i,message:`manifest is not valid JSON: ${y.message}`})}let u=Qt(s),d=u===null?{ok:!1,reason:`couldn't check props against the manifest \u2014 ${a} not found`}:qt(t,s,u),A=u===null?!1:Vt(t,s,u);return{ctx:{name:n,manifestFile:i,sourceFile:a,manifest:c,props:d,usesWindowGreatStore:A},diagnostics:l}}function Qt(e){try{return en.readFileSync(e,"utf8")}catch{return null}}function Zt(e,t){let n=U.relative(e,t);return n.startsWith("..")?t:n.split(U.sep).join("/")}var nn=new Set(["onSendMessage","onClose","onUpdateModelContext","onShowLightbox","onGenerateStructuredContent","storeData","Image"]);var rn=new Map([["onError",'prop `onError` is deprecated and no longer provided \u2014 prefer an async component to report failures. Drop the prop; see the "Async components" section in AGENTS.md for how to signal errors.']]);function sn(e){if(!e.manifest)return[];let t=Vr(e.manifest.inputSchema);if(t===null)return[];if(!e.props.ok)return[{severity:"warning",rule:"props/not-analyzable",file:e.sourceFile,message:`${e.props.reason}.`}];if(e.props.props.open)return[];let n=new Set(e.props.props.names),r=new Set(t),o=[];for(let i of e.props.props.names){if(nn.has(i))continue;let a=rn.get(i);if(a){o.push({severity:"warning",rule:"props/retired-lifecycle",file:e.sourceFile,message:a});continue}r.has(i)||o.push({severity:"warning",rule:"props/undeclared",file:e.sourceFile,message:`prop \`${i}\` is not declared in ${e.manifestFile}#inputSchema.properties, so nothing will ever pass it. Declare it in the schema, or drop it from the component.`})}let s=t.filter(i=>!n.has(i));return s.length>0&&o.push({severity:"error",rule:"props/missing",file:e.sourceFile,message:qr(e.manifestFile,s)}),o}var on=8;function qr(e,t){if(t.length===1){let[s]=t;return`${e} declares inputSchema field \`${s}\`, but the component does not accept a \`${s}\` prop. Add it to the component's props, or remove it from the schema.`}let n=t.slice(0,on).map(s=>`\`${s}\``).join(", "),r=t.length-on,o=r>0?`${n} (+${r} more)`:n;return`${e} declares ${t.length} inputSchema fields the component does not accept: ${o}. Add them to the component's props, or remove them from the schema.`}function Vr(e){if(!e||typeof e!="object")return null;let t=e.properties;return!t||typeof t!="object"||Array.isArray(t)?null:Object.keys(t)}var Jr=["anyOf","oneOf","allOf","$ref","not"];function je(e,t,n){if(Array.isArray(e)){e.forEach((s,i)=>je(s,`${t}[${i}]`,n));return}if(!e||typeof e!="object")return;let r=e;for(let s of Jr)s in r&&n.unionPaths.push(`${t}.${s}`);let o=r.properties;if(o&&typeof o=="object"&&!Array.isArray(o))for(let[s,i]of Object.entries(o))n.fields+=1,je(i,`${t}.${s}`,n);"items"in r&&je(r.items,`${t}[]`,n)}function an(e){let t=e.manifest?.inputSchema;if(!t||typeof t!="object")return[];let n={bytes:Buffer.byteLength(JSON.stringify(t),"utf8"),fields:0,unionPaths:[]};je(t,"inputSchema",n);let r=[];if(n.unionPaths.length>0){let o=n.unionPaths.slice(0,3).join(", "),s=n.unionPaths.length>3?` (+${n.unionPaths.length-3} more)`:"";r.push(`uses ${o}${s} \u2014 declare exactly one type per field; accept alternate shapes in component code instead`)}return n.bytes>8192&&r.push(`is ${(n.bytes/1024).toFixed(1)} KB serialized (limit ${8192/1024} KB)`),n.fields>50&&r.push(`declares ${n.fields} fields (limit 50)`),r.length===0?[]:[{severity:"error",rule:"manifest/input-schema-too-complex",file:e.manifestFile,message:`inputSchema ${r.join("; ")}.
87
+ A schema this complex is usually a sign the component is overengineered, and the agent will fill it unreliably or stop calling the tool altogether. Keep it to a small set of flat, single-type fields (one canonical name per concept \u2014 no aliases), and let component code handle formatting, fallbacks, and edge cases.`}]}function cn(e){let t=e.manifest?.name;return typeof t!="string"||t===e.name?[]:[{severity:"error",rule:"manifest/name-mismatch",file:e.manifestFile,message:`manifest name "${t}" does not match folder name "${e.name}".`}]}function ln(e){return e.usesWindowGreatStore?[{severity:"warning",rule:"globals/window-greatstore",file:e.sourceFile,message:"this component reads `window.GreatStore`, the host-page embed API. Components should interact with GreatStore through their injected lifecycle props (`onSendMessage`, `onGenerateStructuredContent`, \u2026) instead \u2014 those are wired to the surface the component is mounted in."}]:[]}function me(e){return e.filter(t=>t.severity==="error")}function Ze(e){return e.filter(t=>t.severity==="warning")}function ge(e){return`${e.severity==="error"?"error":"warning"} ${e.file}: ${e.message}`}var Kr=[cn,an,sn,ln];function Re(e){let{ctx:t,diagnostics:n}=tn(e);for(let r of Kr)n.push(...r(t));return{diagnostics:n,ok:me(n).length===0}}var G="components";async function Te(e){let t=process.cwd();if(!$.existsSync(b.join(t,"package.json"))||!$.existsSync(b.join(t,G)))throw new Error(`\`npx greatstore apps build\` must run from a project root (contains \`package.json\` and \`${G}/\`). Current dir: ${t}`);let n=Xr(t);if(n.length===0)return process.stdout.write(`(no components in ./${G} \u2014 run \`npx greatstore apps init <name>\` to add one)
88
+ `),[];let r=e.positional[0],o=r?n.filter(l=>l===r):n;if(r&&o.length===0)throw new Error(`No component named "${r}" in ./${G}`);let s=[],i=[];for(let l of o){let c=Re({root:t,name:l});for(let p of c.diagnostics)process.stdout.write(` ${ge(p)}
89
+ `);(c.ok?i:s).push(l)}if(i.length===0)return process.stdout.write(`
90
90
  Nothing built \u2014 fix the errors above.
91
- `),process.exitCode=1;return}let{build:a,reactPlugin:l,transformWithEsbuild:c}=await Er(t);for(let p of i){let u=w.join(t,X,p),f=w.join(u,"bundle.js");await a({plugins:[l()],logLevel:"warn",build:{lib:{entry:w.join(u,"component.tsx"),formats:["es"],fileName:()=>"bundle.js"},outDir:u,emptyOutDir:!1,rollupOptions:{external:["react","react-dom","react/jsx-runtime"],output:{entryFileNames:"bundle.js",paths:{react:"/assets/remote-components/_runtime.js","react-dom":"/assets/remote-components/_runtime.js","react/jsx-runtime":"/assets/remote-components/_runtime.js"}}},minify:!0,sourcemap:!1}});let R=x.statSync(f).size,P=x.readFileSync(f,"utf8"),{code:Z}=await c(P,f,{minify:!0,legalComments:"none",target:"esnext",loader:"js",sourcemap:!1});x.writeFileSync(f,Z);let _=Buffer.byteLength(Z,"utf8");process.stdout.write(`built ${X}/${p}/bundle.js (${Pr(_)}, ${Cr(R,_)} smaller)
92
- `)}if(s.length>0){process.stdout.write(`
91
+ `),process.exitCode=1,s;let a=await Zr(t);for(let l of i)try{await zr(t,l,a)}catch(c){process.stdout.write(` ${G}/${l}: ${c instanceof Error?c.message:String(c)}
92
+ `),s.push(l)}return s.length>0?(process.stdout.write(`
93
93
  Not built (fix the errors above): ${s.join(", ")}
94
- `),process.exitCode=1;return}process.stdout.write("\nBuilt locally \u2014 nothing uploaded yet. Next: `npx greatstore apps push` to upload, then `npx greatstore apps publish <name>` to ship. If you're an AI assistant: confirm with the user before running these (or just run them if they already asked you to ship end-to-end).\n")}function $r(e){let t=w.join(e,X);return x.readdirSync(t).filter(n=>{let r=w.join(t,n);return x.statSync(r).isDirectory()&&x.existsSync(w.join(r,"component.tsx"))}).sort()}function Pr(e){return e<1024?`${e} B`:`${(e/1024).toFixed(1)} KB`}function Cr(e,t){return e===0?"0%":`${Math.round((1-t/e)*100)}%`}async function Er(e){let t=kr(w.join(e,"package.json")),n=Bt(t,"vite");if(!n)throw new Error("Cannot find `vite` in this project. Run `npm install` first.");let r=Bt(t,"@vitejs/plugin-react");if(!r)throw new Error("Cannot find `@vitejs/plugin-react` in this project. Run `npm install` first.");let o=await import(n),s=o.build??o.default?.build;if(typeof s!="function")throw new Error(`Loaded \`vite\` from ${n} but couldn't find its \`build()\` export. Reinstall vite (>= 5) and retry.`);let i=o.transformWithEsbuild??o.default?.transformWithEsbuild;if(typeof i!="function")throw new Error(`Loaded \`vite\` from ${n} but couldn't find its \`transformWithEsbuild()\` export. Reinstall vite (>= 5) and retry.`);let a=await import(r),l=a.default??a;if(typeof l!="function")throw new Error(`Loaded \`@vitejs/plugin-react\` from ${r} but couldn't find its default export.`);return{build:s,reactPlugin:l,transformWithEsbuild:i}}function Bt(e,t){let n;try{n=e.resolve(t)}catch{return null}let r=Ar(n,t);if(!r)return null;let o=w.dirname(r),s;try{s=JSON.parse(x.readFileSync(r,"utf8"))}catch{return null}let a=jr(s.exports)??(typeof s.module=="string"?s.module:null)??(typeof s.main=="string"?s.main:null);return a?w.resolve(o,a):null}function Ar(e,t){let n=w.dirname(e);for(;;){let r=w.join(n,"package.json");if(x.existsSync(r))try{if(JSON.parse(x.readFileSync(r,"utf8")).name===t)return r}catch{}let o=w.dirname(n);if(o===n)return null;n=o}}function jr(e){if(typeof e!="object"||e===null)return null;let n=e["."]??e;if(typeof n!="object"||n===null)return null;let r=n.import;if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){let o=r.default;if(typeof o=="string")return o}return null}async function Ht(e){let t=tt(),n=`${k(t)}/api/apps/components`,r=await d(n);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(r,null,2)+`
94
+ `),process.exitCode=1,s):(process.stdout.write("\nBuilt locally \u2014 nothing uploaded yet. Next: `npx greatstore apps push` to upload, then `npx greatstore apps publish <name>` to ship. If you're an AI assistant: confirm with the user before running these (or just run them if they already asked you to ship end-to-end).\n"),[])}async function zr(e,t,{build:n,reactPlugin:r,transformWithEsbuild:o}){let s=b.join(e,G,t),i=b.join(s,"bundle.js");await n({plugins:[r()],logLevel:"warn",build:{lib:{entry:b.join(s,"component.tsx"),formats:["es"],fileName:()=>"bundle.js"},outDir:s,emptyOutDir:!1,rollupOptions:{external:["react","react-dom","react/jsx-runtime"],output:{entryFileNames:"bundle.js",paths:{react:"/assets/remote-components/_runtime.js","react-dom":"/assets/remote-components/_runtime.js","react/jsx-runtime":"/assets/remote-components/_runtime.js"}}},minify:!0,sourcemap:!1}});let a=$.statSync(i).size,l=$.readFileSync(i,"utf8"),{code:c}=await o(l,i,{minify:!0,legalComments:"none",target:"esnext",loader:"js",sourcemap:!1});$.writeFileSync(i,c);let p=Buffer.byteLength(c,"utf8");process.stdout.write(`built ${G}/${t}/bundle.js (${Yr(p)}, ${Qr(a,p)} smaller)
95
+ `)}function Xr(e){let t=b.join(e,G);return $.readdirSync(t).filter(n=>{let r=b.join(t,n);return $.statSync(r).isDirectory()&&$.existsSync(b.join(r,"component.tsx"))}).sort()}function Yr(e){return e<1024?`${e} B`:`${(e/1024).toFixed(1)} KB`}function Qr(e,t){return e===0?"0%":`${Math.round((1-t/e)*100)}%`}async function Zr(e){let t=Wr(b.join(e,"package.json")),n=un(t,"vite");if(!n)throw new Error("Cannot find `vite` in this project. Run `npm install` first.");let r=un(t,"@vitejs/plugin-react");if(!r)throw new Error("Cannot find `@vitejs/plugin-react` in this project. Run `npm install` first.");let o=await import(n),s=o.build??o.default?.build;if(typeof s!="function")throw new Error(`Loaded \`vite\` from ${n} but couldn't find its \`build()\` export. Reinstall vite (>= 5) and retry.`);let i=o.transformWithEsbuild??o.default?.transformWithEsbuild;if(typeof i!="function")throw new Error(`Loaded \`vite\` from ${n} but couldn't find its \`transformWithEsbuild()\` export. Reinstall vite (>= 5) and retry.`);let a=await import(r),l=a.default??a;if(typeof l!="function")throw new Error(`Loaded \`@vitejs/plugin-react\` from ${r} but couldn't find its default export.`);return{build:s,reactPlugin:l,transformWithEsbuild:i}}function un(e,t){let n;try{n=e.resolve(t)}catch{return null}let r=eo(n,t);if(!r)return null;let o=b.dirname(r),s;try{s=JSON.parse($.readFileSync(r,"utf8"))}catch{return null}let a=to(s.exports)??(typeof s.module=="string"?s.module:null)??(typeof s.main=="string"?s.main:null);return a?b.resolve(o,a):null}function eo(e,t){let n=b.dirname(e);for(;;){let r=b.join(n,"package.json");if($.existsSync(r))try{if(JSON.parse($.readFileSync(r,"utf8")).name===t)return r}catch{}let o=b.dirname(n);if(o===n)return null;n=o}}function to(e){if(typeof e!="object"||e===null)return null;let n=e["."]??e;if(typeof n!="object"||n===null)return null;let r=n.import;if(typeof r=="string")return r;if(typeof r=="object"&&r!==null){let o=r.default;if(typeof o=="string")return o}return null}async function pn(e){let t=Pt(),n=`${C(t)}/api/apps/components`,r=await f(n);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(r,null,2)+`
95
96
  `);return}if(r.components.length===0){process.stdout.write(`(no components in ${t})
96
97
  `);return}let o=r.components.map(a=>({name:a.name,draft:a.draft?`v${a.draft.version}`:"\u2014",live:a.live?`v${a.live.version}`:"\u2014",updated:a.live?.updatedAt??a.draft?.updatedAt??"",permalink:a.permalink??""})),s={name:Math.max(4,...o.map(a=>a.name.length)),draft:Math.max(5,...o.map(a=>a.draft.length)),live:Math.max(4,...o.map(a=>a.live.length)),updated:Math.max(7,...o.map(a=>a.updated.length))},i=`${q("NAME",s.name)} ${q("DRAFT",s.draft)} ${q("LIVE",s.live)} ${q("UPDATED",s.updated)} LINK`;process.stdout.write(i+`
97
98
  `);for(let a of o)process.stdout.write(`${q(a.name,s.name)} ${q(a.draft,s.draft)} ${q(a.live,s.live)} ${q(a.updated,s.updated)} ${a.permalink}
98
- `)}function q(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}import*as N from"fs";import*as Q from"path";import*as Ut from"crypto";import*as V from"fs";import*as oe from"path";var Gt=".gssync.json";function J(e){return Ut.createHash("sha256").update(e).digest("hex")}function Me(e){return V.existsSync(e)?J(V.readFileSync(e,"utf8")):null}function se(e){let t=Me(oe.join(e,"manifest.json"));if(t===null)throw new Error(`Missing manifest.json in ${e}`);return{manifestHash:t,sourceHash:Me(oe.join(e,"component.tsx")),bundleHash:Me(oe.join(e,"bundle.js"))}}function ie(e){let t=oe.join(e,Gt);if(!V.existsSync(t))return null;try{let n=JSON.parse(V.readFileSync(t,"utf8"));return typeof n.version=="number"&&typeof n.manifestHash=="string"&&typeof n.sourceHash=="string"?{version:n.version,manifestHash:n.manifestHash,sourceHash:n.sourceHash,...typeof n.bundleHash=="string"?{bundleHash:n.bundleHash}:{}}:null}catch{return null}}function Y(e,t){V.writeFileSync(oe.join(e,Gt),JSON.stringify(t,null,2)+`
99
- `)}function qt(e,t){let n=Rr(e);if(!n)return!1;if(t===null||n.manifestHash!==t.manifestHash)return!0;let r=n.sourceHash??"",o=t.sourceHash??"";return r!==o}function Rr(e){try{return se(e)}catch{return null}}async function Vt(e){let t=C(),n=m(e.flags,"force"),r=e.positional,o=process.cwd();if(r.length===0||r.length===1&&r[0]==="*")return _r({slug:t,root:o,args:e,force:n});if(r.length>1&&h(e.flags,"version"))throw new Error("--version is per-component; pass it together with a single `npx greatstore apps pull <name>`.");Wt(o);let s=zt(e),i=[];for(let a of r){let l=await Kt({slug:t,componentDir:Q.join(o,"components",a),name:a,revisionQuery:s,force:n});i.push(l),Xt(l,n)}i.length>1&&Jt(i,t),i.some(a=>a.status==="failed")&&(process.exitCode=1)}async function _r(e){let{slug:t,root:n,args:r,force:o}=e;if(h(r.flags,"version"))throw new Error("--version is per-component; pass it together with `npx greatstore apps pull <name>`.");Wt(n);let s=zt(r),i=`${k(t)}/api/apps/components`,a=await d(i);if(a.components.length===0){process.stdout.write(`(no components in ${t})
100
- `);return}let l=[];for(let c of a.components){let p=Q.join(n,"components",c.name),u=await Kt({slug:t,componentDir:p,name:c.name,revisionQuery:s===""&&c.live===null?"?revision=draft":s,force:o});l.push(u),Xt(u,o)}Jt(l,t),l.some(c=>c.status==="failed")&&(process.exitCode=1)}function Jt(e,t){let n=e.filter(i=>i.status==="pulled").length,r=e.filter(i=>i.status==="skipped").length,o=e.filter(i=>i.status==="failed").length,s=[`${n} pulled`,`${r} skipped`];o>0&&s.push(`${o} failed`),process.stdout.write(`
99
+ `)}function q(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}import*as F from"fs";import*as ee from"path";import*as fn from"crypto";import*as V from"fs";import*as ie from"path";var dn=".gssync.json";function J(e){return fn.createHash("sha256").update(e).digest("hex")}function et(e){return V.existsSync(e)?J(V.readFileSync(e,"utf8")):null}function ae(e){let t=et(ie.join(e,"manifest.json"));if(t===null)throw new Error(`Missing manifest.json in ${e}`);return{manifestHash:t,sourceHash:et(ie.join(e,"component.tsx")),bundleHash:et(ie.join(e,"bundle.js"))}}function ce(e){let t=ie.join(e,dn);if(!V.existsSync(t))return null;try{let n=JSON.parse(V.readFileSync(t,"utf8"));return typeof n.version=="number"&&typeof n.manifestHash=="string"&&typeof n.sourceHash=="string"?{version:n.version,manifestHash:n.manifestHash,sourceHash:n.sourceHash,...typeof n.bundleHash=="string"?{bundleHash:n.bundleHash}:{}}:null}catch{return null}}function Z(e,t){V.writeFileSync(ie.join(e,dn),JSON.stringify(t,null,2)+`
100
+ `)}function mn(e,t){let n=no(e);if(!n)return!1;if(t===null||n.manifestHash!==t.manifestHash)return!0;let r=n.sourceHash??"",o=t.sourceHash??"";return r!==o}function no(e){try{return ae(e)}catch{return null}}async function gn(e){let t=x(),n=m(e.flags,"force"),r=e.positional,o=process.cwd();if(r.length===0||r.length===1&&r[0]==="*")return ro({slug:t,root:o,args:e,force:n});if(r.length>1&&h(e.flags,"version"))throw new Error("--version is per-component; pass it together with a single `npx greatstore apps pull <name>`.");wn(o);let s=Sn(e),i=[];for(let a of r){let l=await yn({slug:t,componentDir:ee.join(o,"components",a),name:a,revisionQuery:s,force:n});i.push(l),bn(l,n)}i.length>1&&hn(i,t),i.some(a=>a.status==="failed")&&(process.exitCode=1)}async function ro(e){let{slug:t,root:n,args:r,force:o}=e;if(h(r.flags,"version"))throw new Error("--version is per-component; pass it together with `npx greatstore apps pull <name>`.");wn(n);let s=Sn(r),i=`${C(t)}/api/apps/components`,a=await f(i);if(a.components.length===0){process.stdout.write(`(no components in ${t})
101
+ `);return}let l=[];for(let c of a.components){let p=ee.join(n,"components",c.name),u=await yn({slug:t,componentDir:p,name:c.name,revisionQuery:s===""&&c.live===null?"?revision=draft":s,force:o});l.push(u),bn(u,o)}hn(l,t),l.some(c=>c.status==="failed")&&(process.exitCode=1)}function hn(e,t){let n=e.filter(i=>i.status==="pulled").length,r=e.filter(i=>i.status==="skipped").length,o=e.filter(i=>i.status==="failed").length,s=[`${n} pulled`,`${r} skipped`];o>0&&s.push(`${o} failed`),process.stdout.write(`
101
102
  ${s.join(", ")} (of ${e.length}) \u2190 ${t}
102
- `)}async function Kt(e){let{slug:t,componentDir:n,name:r,revisionQuery:o,force:s}=e;if(!s&&N.existsSync(n)){let f=ie(n);if(qt(n,f))return{name:r,status:"skipped",message:"local has uncommitted changes; pass --force to overwrite"}}let i=`${k(t)}/api/apps/components/${encodeURIComponent(r)}`,a;try{a=await d(`${i}${o}`)}catch(f){if(o===""&&Tr(f))try{a=await d(`${i}?revision=draft`)}catch(R){return{name:r,status:"failed",message:R instanceof Error?R.message:String(R)}}else return{name:r,status:"failed",message:f instanceof Error?f.message:String(f)}}N.mkdirSync(n,{recursive:!0});let l=JSON.stringify(a.manifest,null,2)+`
103
- `;N.writeFileSync(Q.join(n,"manifest.json"),l),N.writeFileSync(Q.join(n,"bundle.js"),a.bundle);let c=["manifest.json","bundle.js"],p="";a.source!==null&&(N.writeFileSync(Q.join(n,"component.tsx"),a.source),c.push("component.tsx"),p=J(a.source)),Y(n,{version:a.version,manifestHash:J(l),sourceHash:p,bundleHash:J(a.bundle)});let u=se(n);return Y(n,{version:a.version,manifestHash:u.manifestHash,sourceHash:u.sourceHash??"",bundleHash:u.bundleHash??""}),{name:r,status:"pulled",version:a.version,wrote:c}}function Wt(e){N.mkdirSync(Q.join(e,"components"),{recursive:!0})}function Tr(e){return e instanceof B&&e.status===404}function zt(e){let t=h(e.flags,"version");return t?`?version=${encodeURIComponent(t)}`:m(e.flags,"draft")?"?revision=draft":m(e.flags,"live")?"?revision=live":""}function Xt(e,t){switch(e.status){case"pulled":{let n=e.wrote?`{${e.wrote.join(", ")}}`:"";process.stdout.write(` pulled ${e.name} v${e.version} ${n}
103
+ `)}async function yn(e){let{slug:t,componentDir:n,name:r,revisionQuery:o,force:s}=e;if(!s&&F.existsSync(n)){let d=ce(n);if(mn(n,d))return{name:r,status:"skipped",message:"local has uncommitted changes; pass --force to overwrite"}}let i=`${C(t)}/api/apps/components/${encodeURIComponent(r)}`,a;try{a=await f(`${i}${o}`)}catch(d){if(o===""&&oo(d))try{a=await f(`${i}?revision=draft`)}catch(A){return{name:r,status:"failed",message:A instanceof Error?A.message:String(A)}}else return{name:r,status:"failed",message:d instanceof Error?d.message:String(d)}}F.mkdirSync(n,{recursive:!0});let l=JSON.stringify(a.manifest,null,2)+`
104
+ `;F.writeFileSync(ee.join(n,"manifest.json"),l),F.writeFileSync(ee.join(n,"bundle.js"),a.bundle);let c=["manifest.json","bundle.js"],p="";a.source!==null&&(F.writeFileSync(ee.join(n,"component.tsx"),a.source),c.push("component.tsx"),p=J(a.source)),Z(n,{version:a.version,manifestHash:J(l),sourceHash:p,bundleHash:J(a.bundle)});let u=ae(n);return Z(n,{version:a.version,manifestHash:u.manifestHash,sourceHash:u.sourceHash??"",bundleHash:u.bundleHash??""}),{name:r,status:"pulled",version:a.version,wrote:c}}function wn(e){F.mkdirSync(ee.join(e,"components"),{recursive:!0})}function oo(e){return e instanceof L&&e.status===404}function Sn(e){let t=h(e.flags,"version");return t?`?version=${encodeURIComponent(t)}`:m(e.flags,"draft")?"?revision=draft":m(e.flags,"live")?"?revision=live":""}function bn(e,t){switch(e.status){case"pulled":{let n=e.wrote?`{${e.wrote.join(", ")}}`:"";process.stdout.write(` pulled ${e.name} v${e.version} ${n}
104
105
  `);return}case"skipped":process.stdout.write(` skipped ${e.name}: ${e.message}
105
106
  `);return;case"failed":process.stdout.write(` failed ${e.name}: ${e.message??"unknown error"}
106
- `);return}}import*as v from"fs";import*as A from"path";async function en(e){let t=C(),n=process.cwd();Lr(n);let r=A.join(n,"components");if(!v.existsSync(r))throw new Error("No components/ directory here. Run `npx greatstore apps init <name>` to scaffold the project root and your first component.");let o=e.positional,s=h(e.flags,"manifest"),i=h(e.flags,"bundle");if(o.length!==1&&(s||i))throw new Error("--manifest / --bundle can only be used together with a single `npx greatstore apps push <name>`.");if(o.length>0){let c=m(e.flags,"force")||s!==void 0||i!==void 0,p=[];for(let u of o){let f=await Qt({slug:t,root:n,name:u,...s!==void 0?{manifestPath:s}:{},...i!==void 0?{bundlePath:i}:{},force:c});p.push(f),Zt(f)}p.length>1&&Yt(p,t),p.some(u=>u.status==="failed")&&(process.exitCode=1);return}let a=Or(r);if(a.length===0){process.stdout.write("(no components in ./components \u2014 run `npx greatstore apps init <name>` to add one)\n");return}let l=[];for(let c of a){let p=await Qt({slug:t,root:n,name:c,force:!1});l.push(p),Zt(p)}Yt(l,t),l.some(c=>c.status==="failed")&&(process.exitCode=1)}function Yt(e,t){let n=e.filter(i=>i.status==="pushed").length,r=e.filter(i=>i.status==="unchanged").length,o=e.filter(i=>i.status==="failed").length,s=[`${n} pushed`,`${r} unchanged`];o>0&&s.push(`${o} failed`),process.stdout.write(`
107
+ `);return}}import*as S from"fs";import*as E from"path";import*as xn from"crypto";import*as _e from"fs";import*as vn from"path";function Oe(e){let t=e?.screenshots;return Array.isArray(t)?[...new Set(t.filter(n=>typeof n=="string"))]:null}function so(e){return e.subarray(1,4).toString("latin1")==="PNG"?"png":e[0]===255&&e[1]===216?"jpg":e.subarray(0,4).toString("latin1")==="RIFF"&&e.subarray(8,12).toString("latin1")==="WEBP"?"webp":null}function kn(e){let t=so(e);return t?`${xn.createHash("sha256").update(e).digest("hex").slice(0,16)}.${t}`:null}function Le(e,t){let n=vn.join(e,t);return _e.existsSync(n)?_e.readFileSync(n):null}async function Cn(e){let t=x(),n=process.cwd();io(n);let r=E.join(n,"components");if(!S.existsSync(r))throw new Error("No components/ directory here. Run `npx greatstore apps init <name>` to scaffold the project root and your first component.");let o=e.positional,s=h(e.flags,"manifest"),i=h(e.flags,"bundle");if(o.length!==1&&(s||i))throw new Error("--manifest / --bundle can only be used together with a single `npx greatstore apps push <name>`.");if(o.length>0){let c=m(e.flags,"force")||s!==void 0||i!==void 0,p=[];for(let u of o){let d=await Ie({slug:t,root:n,name:u,...s!==void 0?{manifestPath:s}:{},...i!==void 0?{bundlePath:i}:{},force:c});p.push(d),Pn(d)}p.length>1&&$n(p,t),p.some(u=>u.status==="failed")&&(process.exitCode=1);return}let a=nt(r);if(a.length===0){process.stdout.write("(no components in ./components \u2014 run `npx greatstore apps init <name>` to add one)\n");return}let l=[];for(let c of a){let p=await Ie({slug:t,root:n,name:c,force:!1});l.push(p),Pn(p)}$n(l,t),l.some(c=>c.status==="failed")&&(process.exitCode=1)}function $n(e,t){let n=e.filter(i=>i.status==="pushed").length,r=e.filter(i=>i.status==="unchanged").length,o=e.filter(i=>i.status==="failed").length,s=[`${n} pushed`,`${r} unchanged`];o>0&&s.push(`${o} failed`),process.stdout.write(`
107
108
  ${s.join(", ")} (of ${e.length}) \u2192 ${t}
108
- `)}async function Qt(e){let{slug:t,root:n,name:r,force:o}=e,s=A.join(n,"components",r);if(!v.existsSync(s))return{name:r,status:"failed",message:`components/${r}/ does not exist`};let i=e.manifestPath?A.resolve(e.manifestPath):A.join(s,"manifest.json"),a=e.bundlePath?A.resolve(e.bundlePath):A.join(s,"bundle.js"),l=A.join(s,"component.tsx");if(!v.existsSync(a))return{name:r,status:"failed",message:`bundle not found: ${a} (did you run \`npm run build\`?)`};let c=Ce({root:n,name:r,manifestPath:i,sourcePath:l});for(let I of Be(c.diagnostics))process.stdout.write(` ${de(I)}
109
- `);if(!c.ok)return{name:r,status:"failed",message:fe(c.diagnostics).map(I=>`${I.file}: ${I.message}`).join(`
110
- ${tn}`)};let p=v.readFileSync(i,"utf8"),u=se(s),f=ie(s),R=e.bundlePath===void 0&&f?.bundleHash!==void 0&&f.sourceHash!==(u.sourceHash??"")&&f.bundleHash===(u.bundleHash??"");if(!o&&f!==null&&f.manifestHash===u.manifestHash&&f.sourceHash===(u.sourceHash??"")&&f.bundleHash!==void 0&&f.bundleHash===(u.bundleHash??""))return{name:r,status:"unchanged"};let P=v.readFileSync(a,"utf8"),Z=v.existsSync(l)?v.readFileSync(l,"utf8"):null,_=new FormData;_.append("manifest",new Blob([p],{type:"application/json"}),"manifest.json"),_.append("bundle",new Blob([P],{type:"text/javascript"}),"bundle.js"),Z!==null&&_.append("source",new Blob([Z],{type:"text/plain; charset=utf-8"}),"component.tsx"),o||_.append("base_version",String(f?.version??0));let Cn=`${k(t)}/api/apps/components/${encodeURIComponent(r)}`,me;try{me=await d(Cn,{method:"POST",multipart:_})}catch(I){return{name:r,status:"failed",message:I instanceof Error?I.message:String(I)}}let Te=se(s);return Y(s,{version:me.version,manifestHash:Te.manifestHash,sourceHash:Te.sourceHash??"",bundleHash:Te.bundleHash??""}),{name:r,status:"pushed",version:me.version,permalink:me.permalink,...R?{staleBundle:!0}:{}}}function Or(e){return v.readdirSync(e).filter(t=>{let n=A.join(e,t);return v.statSync(n).isDirectory()&&v.existsSync(A.join(n,"manifest.json"))}).sort()}function Lr(e){let t=A.join(e,"manifest.json"),n=A.join(e,"components");if(v.existsSync(t)&&!v.existsSync(n))throw new Error(["Detected the old single-component layout (manifest.json at the project root).","The CLI now uses a multi-component layout: scaffold a fresh dir with","`npx greatstore apps init`, then move your component into `components/<name>/`. Re-run `npx greatstore apps push`","from the new project root."].join(" "))}var tn=" ".repeat(12);function Zt(e){switch(e.status){case"pushed":process.stdout.write(` pushed ${e.name} v${e.version} \u2192 ${e.permalink??""}
111
- `),e.staleBundle&&process.stdout.write(`${tn}component.tsx changed but bundle.js did not \u2014 did you forget to build? Run \`npx greatstore build ${e.name}\` and push again.
109
+ `)}async function Ie(e){let{slug:t,root:n,name:r,force:o}=e,s=E.join(n,"components",r);if(!S.existsSync(s))return{name:r,status:"failed",message:`components/${r}/ does not exist`};let i=e.manifestPath?E.resolve(e.manifestPath):E.join(s,"manifest.json"),a=e.bundlePath?E.resolve(e.bundlePath):E.join(s,"bundle.js"),l=E.join(s,"component.tsx");if(!S.existsSync(a))return{name:r,status:"failed",message:`bundle not found: ${a} (did you run \`npm run build\`?)`};let c=Re({root:n,name:r,manifestPath:i,sourcePath:l});for(let R of Ze(c.diagnostics))process.stdout.write(` ${ge(R)}
110
+ `);if(!c.ok)return{name:r,status:"failed",message:me(c.diagnostics).map(R=>`${R.file}: ${R.message}`).join(`
111
+ ${tt}`)};let p=S.readFileSync(i,"utf8"),u=E.join(s,"listing.json"),d=fe(t);if(d&&!S.existsSync(u))return{name:r,status:"failed",message:`components/${r}/listing.json is required for a library app`};let A=ae(s),y=ce(s),at=e.bundlePath===void 0&&y?.bundleHash!==void 0&&y.sourceHash!==(A.sourceHash??"")&&y.bundleHash===(A.bundleHash??"");if(!o&&y!==null&&y.manifestHash===A.manifestHash&&y.sourceHash===(A.sourceHash??"")&&y.bundleHash!==void 0&&y.bundleHash===(A.bundleHash??""))return{name:r,status:"unchanged"};let ye=S.readFileSync(a,"utf8"),ct=S.existsSync(l)?S.readFileSync(l,"utf8"):null,z=new FormData;if(z.append("manifest",new Blob([p],{type:"application/json"}),"manifest.json"),z.append("bundle",new Blob([ye],{type:"text/javascript"}),"bundle.js"),ct!==null&&z.append("source",new Blob([ct],{type:"text/plain; charset=utf-8"}),"component.tsx"),d){let R=S.readFileSync(u,"utf8");z.append("listing",new Blob([R],{type:"application/json"}),"listing.json");let lt=null;try{lt=Oe(JSON.parse(R))}catch{}for(let Ge of lt??[]){let ut=Le(s,Ge);if(!ut)return{name:r,status:"failed",message:`components/${r}/${Ge} is named in listing.json but doesn't exist`};z.append("screenshot",new Blob([new Uint8Array(ut)]),Ge)}}o||z.append("base_version",String(y?.version??0));let Qn=`${Pe(t)}/components/${encodeURIComponent(r)}`,te;try{te=await f(Qn,{method:"POST",multipart:z})}catch(R){return{name:r,status:"failed",message:R instanceof Error?R.message:String(R)}}let Ue=ae(s);return Z(s,{version:te.version,manifestHash:Ue.manifestHash,sourceHash:Ue.sourceHash??"",bundleHash:Ue.bundleHash??""}),{name:r,status:"pushed",version:te.version,...te.permalink!==void 0&&{permalink:te.permalink},...te.detached&&{detached:!0},...at?{staleBundle:!0}:{}}}function nt(e){return S.readdirSync(e).filter(t=>{let n=E.join(e,t);return S.statSync(n).isDirectory()&&S.existsSync(E.join(n,"manifest.json"))}).sort()}function io(e){let t=E.join(e,"manifest.json"),n=E.join(e,"components");if(S.existsSync(t)&&!S.existsSync(n))throw new Error(["Detected the old single-component layout (manifest.json at the project root).","The CLI now uses a multi-component layout: scaffold a fresh dir with","`npx greatstore apps init`, then move your component into `components/<name>/`. Re-run `npx greatstore apps push`","from the new project root."].join(" "))}var tt=" ".repeat(12);function Pn(e){switch(e.status){case"pushed":process.stdout.write(` pushed ${e.name} v${e.version}${e.permalink?` \u2192 ${e.permalink}`:""}
112
+ `),e.detached&&process.stdout.write(`${tt}This was a ready-made app GreatStore keeps up to date. It's now your own copy and won't get those updates.
113
+ `),e.staleBundle&&process.stdout.write(`${tt}component.tsx changed but bundle.js did not \u2014 did you forget to build? Run \`npx greatstore build ${e.name}\` and push again.
112
114
  `);return;case"unchanged":process.stdout.write(` unchanged ${e.name}
113
115
  `);return;case"failed":process.stdout.write(` failed ${e.name}: ${e.message??"unknown error"}
114
- `);return}}async function rn(e){let t=e.positional;if(t.length===0)throw new Error("Usage: npx greatstore apps publish <name> [<name>...] [--version N]");let n=C(),r=h(e.flags,"version"),o;if(r!==void 0){if(t.length>1)throw new Error("--version is per-component; pass it together with a single `npx greatstore apps publish <name>`.");let c=Number.parseInt(r,10);if(!Number.isInteger(c)||c<1)throw new Error(`Invalid --version: ${r}`);o=c}if(t.length===1){let c=t[0],p=await nn(n,c,o);process.stdout.write(`Published ${c} (v${p.live_version}). ${p.permalink}
115
- `);return}let s=[];for(let c of t){let p;try{let u=await nn(n,c,o);p={name:c,status:"published",version:u.live_version,permalink:u.permalink}}catch(u){p={name:c,status:"failed",message:u instanceof Error?u.message:String(u)}}s.push(p),Ir(p)}let i=s.filter(c=>c.status==="published").length,a=s.filter(c=>c.status==="failed").length,l=[`${i} published`];a>0&&l.push(`${a} failed`),process.stdout.write(`
116
+ `);return}}async function An(e){let t=e.positional;if(t.length===0)throw new Error("Usage: npx greatstore apps publish <name> [<name>...] [--version N]");let n=x(),r=h(e.flags,"version"),o;if(r!==void 0){if(t.length>1)throw new Error("--version is per-component; pass it together with a single `npx greatstore apps publish <name>`.");let c=Number.parseInt(r,10);if(!Number.isInteger(c)||c<1)throw new Error(`Invalid --version: ${r}`);o=c}if(t.length===1){let c=t[0],p=await En(n,c,o);process.stdout.write(`Published ${c} (v${p.live_version}). ${p.permalink}
117
+ `);return}let s=[];for(let c of t){let p;try{let u=await En(n,c,o);p={name:c,status:"published",version:u.live_version,permalink:u.permalink}}catch(u){p={name:c,status:"failed",message:u instanceof Error?u.message:String(u)}}s.push(p),ao(p)}let i=s.filter(c=>c.status==="published").length,a=s.filter(c=>c.status==="failed").length,l=[`${i} published`];a>0&&l.push(`${a} failed`),process.stdout.write(`
116
118
  ${l.join(", ")} (of ${s.length}) \u2192 ${n}
117
- `),a>0&&(process.exitCode=1)}async function nn(e,t,n){let r=`${k(e)}/api/apps/components/${encodeURIComponent(t)}/publish`;return d(r,{method:"POST",body:n!==void 0?{version:n}:{}})}function Ir(e){if(e.status==="published"){process.stdout.write(` published ${e.name} v${e.version} \u2192 ${e.permalink??""}
119
+ `),a>0&&(process.exitCode=1)}async function En(e,t,n){let r=`${C(e)}/api/apps/components/${encodeURIComponent(t)}/publish`;return f(r,{method:"POST",body:n!==void 0?{version:n}:{}})}function ao(e){if(e.status==="published"){process.stdout.write(` published ${e.name} v${e.version} \u2192 ${e.permalink??""}
118
120
  `);return}process.stdout.write(` failed ${e.name}: ${e.message??"unknown error"}
119
- `)}async function on(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore apps unpublish <name>");let n=C(),r=`${k(n)}/api/apps/components/${encodeURIComponent(t)}/unpublish`;await d(r,{method:"POST",body:{}}),process.stdout.write(`Unpublished ${t}.
120
- `)}import*as sn from"readline";async function an(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore apps delete <name> [--yes]");let n=C();if(!m(e.flags,"yes")&&(await Fr(`Soft-delete component "${t}" in store "${n}"? Type "yes" to confirm: `)).trim()!=="yes"){process.stdout.write(`Aborted.
121
- `);return}let r=`${k(n)}/api/apps/components/${encodeURIComponent(t)}`;await d(r,{method:"DELETE"}),process.stdout.write(`Deleted ${t}.
122
- `)}function Fr(e){return new Promise(t=>{let n=sn.createInterface({input:process.stdin,output:process.stdout});n.question(e,r=>{n.close(),t(r)})})}import*as L from"fs";import*as Ee from"path";var Nr=/^[a-z][a-z0-9_]*$/;async function cn(e){let[t,n]=e.positional;if(!t||!n||e.positional.length>2)throw new Error("Usage: npx greatstore apps rename <old-name> <new-name>");if(!Nr.test(n))throw new Error(`Invalid name "${n}": use lowercase letters, digits and underscores, starting with a letter.`);if(t===n)throw new Error(`"${t}" already has that name.`);let r=C(),o=Ee.join(process.cwd(),"components",t),s=Ee.join(process.cwd(),"components",n),i=L.existsSync(o);if(L.existsSync(s))throw new Error(`components/${n}/ already exists; move it aside first.`);let a=`${k(r)}/api/apps/components/${encodeURIComponent(t)}/rename`;if(await d(a,{method:"POST",body:{name:n}}),!i){process.stdout.write(`Renamed ${t} \u2192 ${n}.
123
- `);return}L.renameSync(o,s),Dr(s,n),process.stdout.write(`Renamed ${t} \u2192 ${n}, including components/${n}/.
124
- `)}function Dr(e,t){let n=Ee.join(e,"manifest.json");if(!L.existsSync(n))return;let r=L.readFileSync(n,"utf8"),o=JSON.stringify({...JSON.parse(r),name:t},null,2)+`
125
- `;L.writeFileSync(n,o);let s=ie(e);s&&s.manifestHash===J(r)&&Y(e,{...s,manifestHash:J(o)})}var ln=`npx greatstore apps \u2014 author and ship custom in-chat apps
121
+ `)}async function jn(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore apps unpublish <name>");let n=x(),r=`${C(n)}/api/apps/components/${encodeURIComponent(t)}/unpublish`;await f(r,{method:"POST",body:{}}),process.stdout.write(`Unpublished ${t}.
122
+ `)}import*as Rn from"readline";async function Tn(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore apps delete <name> [--yes]");let n=x();if(!m(e.flags,"yes")&&(await co(`Soft-delete component "${t}" in store "${n}"? Type "yes" to confirm: `)).trim()!=="yes"){process.stdout.write(`Aborted.
123
+ `);return}let r=`${C(n)}/api/apps/components/${encodeURIComponent(t)}`;await f(r,{method:"DELETE"}),process.stdout.write(`Deleted ${t}.
124
+ `)}function co(e){return new Promise(t=>{let n=Rn.createInterface({input:process.stdin,output:process.stdout});n.question(e,r=>{n.close(),t(r)})})}import*as I from"fs";import*as Ne from"path";var lo=/^[a-z][a-z0-9_]*$/;async function _n(e){let[t,n]=e.positional;if(!t||!n||e.positional.length>2)throw new Error("Usage: npx greatstore apps rename <old-name> <new-name>");if(!lo.test(n))throw new Error(`Invalid name "${n}": use lowercase letters, digits and underscores, starting with a letter.`);if(t===n)throw new Error(`"${t}" already has that name.`);let r=x(),o=Ne.join(process.cwd(),"components",t),s=Ne.join(process.cwd(),"components",n),i=I.existsSync(o);if(I.existsSync(s))throw new Error(`components/${n}/ already exists; move it aside first.`);let a=`${C(r)}/api/apps/components/${encodeURIComponent(t)}/rename`;if(await f(a,{method:"POST",body:{name:n}}),!i){process.stdout.write(`Renamed ${t} \u2192 ${n}.
125
+ `);return}I.renameSync(o,s),uo(s,n),process.stdout.write(`Renamed ${t} \u2192 ${n}, including components/${n}/.
126
+ `)}function uo(e,t){let n=Ne.join(e,"manifest.json");if(!I.existsSync(n))return;let r=I.readFileSync(n,"utf8"),o=JSON.stringify({...JSON.parse(r),name:t},null,2)+`
127
+ `;I.writeFileSync(n,o);let s=ce(e);s&&s.manifestHash===J(r)&&Z(e,{...s,manifestHash:J(o)})}import*as K from"fs";import*as he from"path";async function On(e){let t=x();if(!fe(t))throw new Error("`npx greatstore apps release` runs only in the app library's folder.");let n=We();xt(await ho(new URL(n).origin));let r=await Te({command:"build",positional:[],flags:{}});process.exitCode=0;let o=process.cwd(),s=Pe(t),i=he.join(o,"components"),a=nt(i),l=K.readdirSync(i).filter(u=>K.statSync(he.join(i,u)).isDirectory()),c=(await f(`${s}/components`)).components.filter(u=>u.live!==null).map(u=>u.name),p=[];for(let u of a)p.push(r.includes(u)?{name:u,status:"failed",message:"didn't build; see the errors above"}:await po(s,o,t,u));for(let u of l.filter(d=>!a.includes(d)))p.push({name:u,status:"failed",message:`components/${u}/manifest.json is missing`});for(let u of c.filter(d=>!l.includes(d)))try{await f(`${s}/components/${encodeURIComponent(u)}/unpublish`,{method:"POST",body:{}}),p.push({name:u,status:"unpublished"})}catch(d){p.push({name:u,status:"failed",message:Ln(d)})}for(let u of p){let d=u.status==="published"?` v${u.version}`:u.status==="failed"?`: ${u.message}`:"";process.stdout.write(` ${u.status.padEnd(11)} ${u.name}${d}
128
+ `)}p.some(u=>u.status==="failed")&&(process.exitCode=1)}async function po(e,t,n,r){try{let o=await fo(e,r);if(o&&mo(o,he.join(t,"components",r)))return{name:r,status:"unchanged"};let s=await Ie({slug:n,root:t,name:r,force:!0});return s.status!=="pushed"||s.version===void 0?{name:r,status:"failed",message:s.message??"push failed"}:(await f(`${e}/components/${encodeURIComponent(r)}/publish`,{method:"POST",body:{version:s.version},validationDetail:!0}),{name:r,status:"published",version:s.version})}catch(o){return{name:r,status:"failed",message:Ln(o)}}}async function fo(e,t){try{return await f(`${e}/components/${encodeURIComponent(t)}?revision=live`)}catch(n){if(n instanceof L&&n.status===404)return null;throw n}}function mo(e,t){let n=s=>{let i=he.join(t,s);return K.existsSync(i)?K.readFileSync(i,"utf8"):null},r=n("manifest.json"),o=n("listing.json");if(r===null||o===null)return!1;try{return e.bundle===n("bundle.js")&&e.source===n("component.tsx")&&Fe(e.manifest)===Fe(JSON.parse(r))&&Fe(e.listing)===Fe(go(JSON.parse(o),t))}catch{return!1}}function go(e,t){let n=rt(e),r=Oe(n);return r?{...n,screenshots:r.map(o=>{let s=Le(t,o);return(s&&kn(s))??o})}:n}function rt(e){return typeof e=="string"?e.trim():Array.isArray(e)?e.map(rt):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,rt(n)])):e}function Fe(e){return JSON.stringify(e,(t,n)=>n&&typeof n=="object"&&!Array.isArray(n)?Object.fromEntries(Object.entries(n).sort(([r],[o])=>r.localeCompare(o))):n)}async function ho(e){let t=process.env.ACTIONS_ID_TOKEN_REQUEST_URL,n=process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;if(!t||!n)throw new Error("`npx greatstore apps release` isn't available here.");let r=await fetch(`${t}&audience=${encodeURIComponent(e)}`,{headers:{authorization:`Bearer ${n}`}}),o=await r.json().catch(()=>null);if(!r.ok||typeof o?.value!="string")throw new Error("Sign-in needed.");return o.value}function Ln(e){return e instanceof Error?e.message:String(e)}var In=`npx greatstore apps \u2014 author and ship custom in-chat apps
126
129
 
127
130
  Usage:
128
131
  npx greatstore apps <subcommand> [args] [flags]
@@ -137,38 +140,50 @@ Subcommands:
137
140
  unpublish <name> Clear the live pointer.
138
141
  rename <old> <new> Rename a component, keeping its versions and live state.
139
142
  delete <name> Soft-delete the component.
140
- `;async function He(e){let t=e.positional[0],n={...e,positional:e.positional.slice(1)};switch(t){case void 0:case"help":return process.stdout.write(ln),0;case"init":return wt(n),0;case"build":return await Mt(n),0;case"list":return await Ht(n),0;case"pull":return await Vt(n),0;case"push":return await en(n),0;case"publish":return await rn(n),0;case"unpublish":return await on(n),0;case"rename":return await cn(n),0;case"delete":return await an(n),0;default:return process.stderr.write(`Unknown apps subcommand: ${t}
143
+ `;async function ot(e){let t=e.positional[0],n={...e,positional:e.positional.slice(1)};switch(t){case void 0:case"help":return process.stdout.write(In),0;case"init":return Ut(n),0;case"build":return await Te(n),0;case"list":return await pn(n),0;case"pull":return await gn(n),0;case"push":return await Cn(n),0;case"publish":return await An(n),0;case"unpublish":return await jn(n),0;case"rename":return await _n(n),0;case"delete":return await Tn(n),0;case"release":return await On(n),0;default:return process.stderr.write(`Unknown apps subcommand: ${t}
141
144
 
142
- ${ln}`),1}}async function un(e){let t=y(e),n=`${S(t)}/configure/config`,r=await d(n);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(r.brand,null,2)+`
143
- `);return}Br(t,r.brand)}function Br(e,t){let n=[`Configuration for ${e}:`,""];n.push(` displayName ${t.displayName??"\u2014"}`),n.push(` assistantName ${t.assistantName??"\u2014"}`),n.push(` storeLink ${t.storeLink??"\u2014"}`),n.push(` extraOrigins ${Ue(t.extraOrigins)}`),n.push(` icon ${t.icon?.url??"\u2014"}`),n.push(` logoLight ${t.logo?.light?.url??"\u2014"}`),n.push(` logoDark ${t.logo?.dark?.url??"\u2014"}`),n.push(` theme ${t.theme?JSON.stringify(t.theme):"\u2014"}`),n.push(` cspScriptHosts ${Ue(t.cspScriptHosts)}`),n.push(` cspConnectHosts ${Ue(t.cspConnectHosts)}`),process.stdout.write(n.join(`
145
+ ${In}`),1}}async function Nn(e){let t=w(e),n=`${v(t)}/configure/config`,r=await f(n);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(r.brand,null,2)+`
146
+ `);return}yo(t,r.brand)}function yo(e,t){let n=[`Configuration for ${e}:`,""];n.push(` displayName ${t.displayName??"\u2014"}`),n.push(` assistantName ${t.assistantName??"\u2014"}`),n.push(` storeLink ${t.storeLink??"\u2014"}`),n.push(` extraOrigins ${st(t.extraOrigins)}`),n.push(` icon ${t.icon?.url??"\u2014"}`),n.push(` logoLight ${t.logo?.light?.url??"\u2014"}`),n.push(` logoDark ${t.logo?.dark?.url??"\u2014"}`),n.push(` theme ${t.theme?JSON.stringify(t.theme):"\u2014"}`),n.push(` cspScriptHosts ${st(t.cspScriptHosts)}`),n.push(` cspConnectHosts ${st(t.cspConnectHosts)}`),process.stdout.write(n.join(`
144
147
  `)+`
145
- `)}function Ue(e){return!e||e.length===0?"\u2014":e.join(", ")}import*as Ae from"fs";import*as dn from"path";var pn="theme.",Mr=["displayName","assistantName","storeLink"],Hr=["extraOrigins","cspScriptHosts","cspConnectHosts"];async function mn(e){let t=y(e),n={};for(let c of Mr){if(!(c in e.flags))continue;let p=e.flags[c];if(typeof p!="string")throw new Error(`--${c} requires a value (use --${c} "" to clear).`);n[c]=p===""?null:p}for(let c of Hr){if(!(c in e.flags))continue;let p=e.flags[c];if(typeof p!="string")throw new Error(`--${c} requires a comma-separated value (use --${c} "" to clear).`);let u=p.split(",").map(f=>f.trim()).filter(f=>f.length>0);n[c]=u.length===0?null:u}let r=h(e.flags,"themeFile"),o=qr(e.flags),s=m(e.flags,"replace");if("theme"in e.flags&&r!==void 0)throw new Error("Pass either --theme or --themeFile, not both.");if(o!==null&&("theme"in e.flags||r!==void 0))throw new Error("Pass either --theme.<field> flags or a whole --theme/--themeFile object, not both.");let i;if("theme"in e.flags){let c=e.flags.theme;if(typeof c!="string")throw new Error('--theme requires a JSON value (use --theme "" to clear).');i=c===""?null:fn(c,"--theme")}else r!==void 0?i=fn(Ur(r,"--themeFile"),"--themeFile"):o!==null&&(i=o);if(i!==void 0&&(n.theme=i===null||s?i:{...await Gr(t),...i},n.theme!==null)){let c=n.theme;for(let[p,u]of Object.entries(c))u===""&&delete c[p]}if(Object.keys(n).length===0)throw new Error('Nothing to save. Pass at least one field flag, e.g. `npx greatstore configure set --displayName "Acme"`.');let a=`${S(t)}/configure/save`,l=await d(a,{method:"POST",body:n,validationDetail:!0});if(m(e.flags,"json")){process.stdout.write(JSON.stringify(l.config,null,2)+`
148
+ `)}function st(e){return!e||e.length===0?"\u2014":e.join(", ")}import*as De from"fs";import*as Bn from"path";var Fn="theme.",wo=["displayName","assistantName","storeLink"],So=["extraOrigins","cspScriptHosts","cspConnectHosts"];async function Hn(e){let t=w(e),n={};for(let c of wo){if(!(c in e.flags))continue;let p=e.flags[c];if(typeof p!="string")throw new Error(`--${c} requires a value (use --${c} "" to clear).`);n[c]=p===""?null:p}for(let c of So){if(!(c in e.flags))continue;let p=e.flags[c];if(typeof p!="string")throw new Error(`--${c} requires a comma-separated value (use --${c} "" to clear).`);let u=p.split(",").map(d=>d.trim()).filter(d=>d.length>0);n[c]=u.length===0?null:u}let r=h(e.flags,"themeFile"),o=vo(e.flags),s=m(e.flags,"replace");if("theme"in e.flags&&r!==void 0)throw new Error("Pass either --theme or --themeFile, not both.");if(o!==null&&("theme"in e.flags||r!==void 0))throw new Error("Pass either --theme.<field> flags or a whole --theme/--themeFile object, not both.");let i;if("theme"in e.flags){let c=e.flags.theme;if(typeof c!="string")throw new Error('--theme requires a JSON value (use --theme "" to clear).');i=c===""?null:Dn(c,"--theme")}else r!==void 0?i=Dn(bo(r,"--themeFile"),"--themeFile"):o!==null&&(i=o);if(i!==void 0&&(n.theme=i===null||s?i:{...await xo(t),...i},n.theme!==null)){let c=n.theme;for(let[p,u]of Object.entries(c))u===""&&delete c[p]}if(Object.keys(n).length===0)throw new Error('Nothing to save. Pass at least one field flag, e.g. `npx greatstore configure set --displayName "Acme"`.');let a=`${v(t)}/configure/save`,l=await f(a,{method:"POST",body:n,validationDetail:!0});if(m(e.flags,"json")){process.stdout.write(JSON.stringify(l.config,null,2)+`
146
149
  `);return}process.stdout.write(`Saved ${Object.keys(n).join(", ")} \u2192 ${t}
147
- `)}function Ur(e,t){let n=dn.resolve(e);if(!Ae.existsSync(n))throw new Error(`${t}: file not found: ${n}`);return Ae.readFileSync(n,"utf8")}function fn(e,t){let n;try{n=JSON.parse(e)}catch(r){throw new Error(`${t}: not valid JSON: ${r.message}`)}if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`${t}: theme must be a JSON object.`);return n}async function Gr(e){let t=`${S(e)}/configure/config`;return(await d(t)).brand.theme??{}}function qr(e){let t={};for(let[n,r]of Object.entries(e)){if(!n.startsWith(pn))continue;let o=n.slice(pn.length),s=U[o];if(!s){let i=pt(o);throw new Error(`Unknown theme field "${o}".
148
- Valid fields: ${Object.keys(U).join(", ")}.`+(i.length>0?`
149
- Did you mean: ${i.join(", ")}?`:""))}if(typeof r!="string"){if(s.kind==="boolean"){t[o]=!0;continue}throw new Error(`--${n} requires a value (use --${n} "" to clear).`)}t[o]=Vr(n,o,r)}return Object.keys(t).length>0?t:null}function Vr(e,t,n){let r=U[t];if(!r||n==="")return n;if(r.values&&!r.values.includes(n))throw new Error(`--${e} must be one of: ${r.values.join(", ")} (got "${n}").`);if(r.kind==="boolean"){if(n!=="true"&&n!=="false")throw new Error(`--${e} must be true or false (got "${n}").`);return n==="true"}if(r.kind==="integer"){let o=Number.parseInt(n,10);if(!Number.isInteger(o)||String(o)!==n.trim())throw new Error(`--${e} must be an integer (got "${n}").`);return o}return n}import*as _e from"fs";import*as ae from"path";var je=["icon","logoLight","logoDark"];function Re(e){if(e&&je.includes(e))return e;throw new Error(`Asset kind must be one of: ${je.join(", ")}.`)}var Jr={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp"};async function gn(e){let t=y(e),n=Re(e.positional[0]),r=e.positional[1];if(!r)throw new Error(`Usage: npx greatstore configure upload <${je.join("|")}> <file>`);let o=ae.resolve(r);if(!_e.existsSync(o))throw new Error(`File not found: ${o}`);let s=Jr[ae.extname(o).toLowerCase()];if(!s)throw new Error("Unsupported image type. Use .png, .jpg, or .webp.");let i=_e.readFileSync(o),a=new FormData;a.append("file",new Blob([new Uint8Array(i)],{type:s}),ae.basename(o));let l=`${S(t)}/configure/upload/${n}`,c=await d(l,{method:"POST",multipart:a});process.stdout.write(`Uploaded ${n} \u2192 ${c.url}
150
- `)}async function hn(e){let t=y(e),n=Re(e.positional[0]),r=`${S(t)}/configure/delete/${n}`;await d(r,{method:"POST",body:{}}),process.stdout.write(`Cleared ${n} for ${t}
151
- `)}async function yn(e){let t=e.positional[0]??"show",n={...e,positional:e.positional.slice(1)};switch(t){case"show":await un(n);return;case"set":await mn(n);return;case"upload":await gn(n);return;case"clear":await hn(n);return;default:throw new Error(`Unknown configure subcommand: ${t}. Use \`npx greatstore configure [set|upload|clear]\`.`)}}async function j(e){let t=`${S(e)}/connectors/config`;return d(t)}function D(e){return{id:e.id,name:e.name,url:e.url,transport:e.transport,authKind:e.authKind,enabled:e.enabled,profileUrl:e.profileUrl}}async function K(e,t,n,r=t.makerEnabled){let o=`${S(e)}/connectors/save`;return d(o,{method:"POST",body:{makerEnabled:r,makerPriority:Math.min(t.makerPriority,n.length),connectors:n}})}function ce(e,t){let n=e.connectors.find(o=>o.id===t);if(n)return n;let r=e.connectors.filter(o=>o.name===t);if(r.length===1)return r[0];if(r.length>1){let o=r.map(s=>s.id).join(", ");throw new Error(`Multiple connectors are named "${t}". Use an id instead: ${o}`)}throw new Error(`No connector named "${t}". Run \`npx greatstore connectors\` to see them.`)}async function wn(e){let t=y(e),n=await j(t);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(n,null,2)+`
150
+ `)}function bo(e,t){let n=Bn.resolve(e);if(!De.existsSync(n))throw new Error(`${t}: file not found: ${n}`);return De.readFileSync(n,"utf8")}function Dn(e,t){let n;try{n=JSON.parse(e)}catch(r){throw new Error(`${t}: not valid JSON: ${r.message}`)}if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`${t}: theme must be a JSON object.`);return n}async function xo(e){let t=`${v(e)}/configure/config`;return(await f(t)).brand.theme??{}}function vo(e){let t={};for(let[n,r]of Object.entries(e)){if(!n.startsWith(Fn))continue;let o=n.slice(Fn.length),s=M[o];if(!s){let i=It(o);throw new Error(`Unknown theme field "${o}".
151
+ Valid fields: ${Object.keys(M).join(", ")}.`+(i.length>0?`
152
+ Did you mean: ${i.join(", ")}?`:""))}if(typeof r!="string"){if(s.kind==="boolean"){t[o]=!0;continue}throw new Error(`--${n} requires a value (use --${n} "" to clear).`)}t[o]=ko(n,o,r)}return Object.keys(t).length>0?t:null}function ko(e,t,n){let r=M[t];if(!r||n==="")return n;if(r.values&&!r.values.includes(n))throw new Error(`--${e} must be one of: ${r.values.join(", ")} (got "${n}").`);if(r.kind==="boolean"){if(n!=="true"&&n!=="false")throw new Error(`--${e} must be true or false (got "${n}").`);return n==="true"}if(r.kind==="integer"){let o=Number.parseInt(n,10);if(!Number.isInteger(o)||String(o)!==n.trim())throw new Error(`--${e} must be an integer (got "${n}").`);return o}return n}import*as Me from"fs";import*as le from"path";var Be=["icon","logoLight","logoDark"];function He(e){if(e&&Be.includes(e))return e;throw new Error(`Asset kind must be one of: ${Be.join(", ")}.`)}var $o={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp"};async function Mn(e){let t=w(e),n=He(e.positional[0]),r=e.positional[1];if(!r)throw new Error(`Usage: npx greatstore configure upload <${Be.join("|")}> <file>`);let o=le.resolve(r);if(!Me.existsSync(o))throw new Error(`File not found: ${o}`);let s=$o[le.extname(o).toLowerCase()];if(!s)throw new Error("Unsupported image type. Use .png, .jpg, or .webp.");let i=Me.readFileSync(o),a=new FormData;a.append("file",new Blob([new Uint8Array(i)],{type:s}),le.basename(o));let l=`${v(t)}/configure/upload/${n}`,c=await f(l,{method:"POST",multipart:a});process.stdout.write(`Uploaded ${n} \u2192 ${c.url}
153
+ `)}async function Un(e){let t=w(e),n=He(e.positional[0]),r=`${v(t)}/configure/delete/${n}`;await f(r,{method:"POST",body:{}}),process.stdout.write(`Cleared ${n} for ${t}
154
+ `)}async function Gn(e){let t=e.positional[0]??"show",n={...e,positional:e.positional.slice(1)};switch(t){case"show":await Nn(n);return;case"set":await Hn(n);return;case"upload":await Mn(n);return;case"clear":await Un(n);return;default:throw new Error(`Unknown configure subcommand: ${t}. Use \`npx greatstore configure [set|upload|clear]\`.`)}}async function T(e){let t=`${v(e)}/connectors/config`;return f(t)}function D(e){return{id:e.id,name:e.name,url:e.url,transport:e.transport,authKind:e.authKind,enabled:e.enabled,profileUrl:e.profileUrl}}async function W(e,t,n,r=t.makerEnabled){let o=`${v(e)}/connectors/save`;return f(o,{method:"POST",body:{makerEnabled:r,makerPriority:Math.min(t.makerPriority,n.length),connectors:n}})}function ue(e,t){let n=e.connectors.find(o=>o.id===t);if(n)return n;let r=e.connectors.filter(o=>o.name===t);if(r.length===1)return r[0];if(r.length>1){let o=r.map(s=>s.id).join(", ");throw new Error(`Multiple connectors are named "${t}". Use an id instead: ${o}`)}throw new Error(`No connector named "${t}". Run \`npx greatstore connectors\` to see them.`)}async function qn(e){let t=w(e),n=await T(t);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(n,null,2)+`
152
155
  `);return}if(process.stdout.write(`Maker MCP: ${n.makerEnabled?"on":"off"} (position ${n.makerPriority+1})
153
156
  `),n.connectors.length===0){process.stdout.write(`(no custom connectors in ${t})
154
- `);return}let r=n.connectors.map(s=>({name:s.name,enabled:s.enabled?"on":"off",auth:s.authKind==="bearer"?s.hasToken?"bearer":"bearer (no token)":"none",url:s.url})),o={name:Math.max(4,...r.map(s=>s.name.length)),enabled:Math.max(7,...r.map(s=>s.enabled.length)),auth:Math.max(4,...r.map(s=>s.auth.length))};process.stdout.write(`${le("NAME",o.name)} ${le("ENABLED",o.enabled)} ${le("AUTH",o.auth)} URL
155
- `);for(let s of r)process.stdout.write(`${le(s.name,o.name)} ${le(s.enabled,o.enabled)} ${le(s.auth,o.auth)} ${s.url}
156
- `)}function le(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}async function Sn(e){let t=y(e),n=e.positional[0];if(!n)throw new Error("Usage: npx greatstore connectors add <name> --url <url> [--token <token>]");let r=h(e.flags,"url");if(!r)throw new Error("--url is required for `npx greatstore connectors add`.");let o=h(e.flags,"token"),s=h(e.flags,"profileUrl")??null,i=!m(e.flags,"disabled");if(!m(e.flags,"force")){let u=`${S(t)}/connectors/probe`,f=await d(u,{method:"POST",body:{url:r,...o!==void 0?{token:o}:{},...s!==null?{profileUrl:s}:{}}});if(!f.ok)throw new Error(`Connector did not answer tool discovery${f.error?`: ${f.error}`:""}. Fix the URL/token or pass --force to save it anyway.`);process.stdout.write(`Probe ok \u2014 ${f.toolCount??0} tool(s) discovered.
157
- `)}let a=await j(t),l={id:"",name:n,url:r,transport:"http",authKind:o?"bearer":"none",enabled:i,profileUrl:s,...o!==void 0?{token:o}:{}},p=(await K(t,a,[...a.connectors.map(D),l])).connectors.find(u=>u.name===n);process.stdout.write(`Added connector "${n}"${p?` (${p.id})`:""} \u2192 ${t}
158
- `)}async function bn(e){let t=y(e),n=e.positional[0];if(!n)throw new Error("Usage: npx greatstore connectors remove <name|id>");let r=await j(t),o=ce(r,n),s=r.connectors.filter(i=>i.id!==o.id).map(D);await K(t,r,s),process.stdout.write(`Removed connector "${o.name}" from ${t}
159
- `)}async function Ge(e,t){let n=y(e),r=e.positional[0];if(!r)throw new Error(`Usage: npx greatstore connectors ${t?"enable":"disable"} <name|id>`);let o=await j(n),s=ce(o,r),i=o.connectors.map(a=>a.id===s.id?{...D(a),enabled:t}:D(a));await K(n,o,i),process.stdout.write(`Connector "${s.name}" is now ${t?"enabled":"disabled"}
160
- `)}async function xn(e){let t=y(e),n=e.positional[0];if(n!=="on"&&n!=="off")throw new Error("Usage: npx greatstore connectors maker on|off");let r=await j(t);await K(t,r,r.connectors.map(D),n==="on"),process.stdout.write(`Maker MCP is now ${n}
161
- `)}async function vn(e){let t=y(e),n=await j(t),r=null,o=e.positional[0];if(o&&(r=ce(n,o).id),n.connectors.length===0){process.stdout.write(`(no custom connectors in ${t})
162
- `);return}let s=`${S(t)}/connectors/health`,i=await d(s,{method:"POST",body:r?{id:r}:{}});if(m(e.flags,"json")){process.stdout.write(JSON.stringify(i.health,null,2)+`
157
+ `);return}let r=n.connectors.map(s=>({name:s.name,enabled:s.enabled?"on":"off",auth:s.authKind==="bearer"?s.hasToken?"bearer":"bearer (no token)":"none",url:s.url})),o={name:Math.max(4,...r.map(s=>s.name.length)),enabled:Math.max(7,...r.map(s=>s.enabled.length)),auth:Math.max(4,...r.map(s=>s.auth.length))};process.stdout.write(`${pe("NAME",o.name)} ${pe("ENABLED",o.enabled)} ${pe("AUTH",o.auth)} URL
158
+ `);for(let s of r)process.stdout.write(`${pe(s.name,o.name)} ${pe(s.enabled,o.enabled)} ${pe(s.auth,o.auth)} ${s.url}
159
+ `)}function pe(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}async function Vn(e){let t=w(e),n=e.positional[0];if(!n)throw new Error("Usage: npx greatstore connectors add <name> --url <url> [--token <token>]");let r=h(e.flags,"url");if(!r)throw new Error("--url is required for `npx greatstore connectors add`.");let o=h(e.flags,"token"),s=h(e.flags,"profileUrl")??null,i=!m(e.flags,"disabled");if(!m(e.flags,"force")){let u=`${v(t)}/connectors/probe`,d=await f(u,{method:"POST",body:{url:r,...o!==void 0?{token:o}:{},...s!==null?{profileUrl:s}:{}}});if(!d.ok)throw new Error(`Connector did not answer tool discovery${d.error?`: ${d.error}`:""}. Fix the URL/token or pass --force to save it anyway.`);process.stdout.write(`Probe ok \u2014 ${d.toolCount??0} tool(s) discovered.
160
+ `)}let a=await T(t),l={id:"",name:n,url:r,transport:"http",authKind:o?"bearer":"none",enabled:i,profileUrl:s,...o!==void 0?{token:o}:{}},p=(await W(t,a,[...a.connectors.map(D),l])).connectors.find(u=>u.name===n);process.stdout.write(`Added connector "${n}"${p?` (${p.id})`:""} \u2192 ${t}
161
+ `)}async function Jn(e){let t=w(e),n=e.positional[0];if(!n)throw new Error("Usage: npx greatstore connectors remove <name|id>");let r=await T(t),o=ue(r,n),s=r.connectors.filter(i=>i.id!==o.id).map(D);await W(t,r,s),process.stdout.write(`Removed connector "${o.name}" from ${t}
162
+ `)}async function it(e,t){let n=w(e),r=e.positional[0];if(!r)throw new Error(`Usage: npx greatstore connectors ${t?"enable":"disable"} <name|id>`);let o=await T(n),s=ue(o,r),i=o.connectors.map(a=>a.id===s.id?{...D(a),enabled:t}:D(a));await W(n,o,i),process.stdout.write(`Connector "${s.name}" is now ${t?"enabled":"disabled"}
163
+ `)}async function Kn(e){let t=w(e),n=e.positional[0];if(n!=="on"&&n!=="off")throw new Error("Usage: npx greatstore connectors maker on|off");let r=await T(t);await W(t,r,r.connectors.map(D),n==="on"),process.stdout.write(`Maker MCP is now ${n}
164
+ `)}async function Wn(e){let t=w(e),n=await T(t),r=null,o=e.positional[0];if(o&&(r=ue(n,o).id),n.connectors.length===0){process.stdout.write(`(no custom connectors in ${t})
165
+ `);return}let s=`${v(t)}/connectors/health`,i=await f(s,{method:"POST",body:r?{id:r}:{}});if(m(e.flags,"json")){process.stdout.write(JSON.stringify(i.health,null,2)+`
163
166
  `);return}let a=new Map(n.connectors.map(l=>[l.id,l.name]));for(let l of i.health){let c=a.get(l.id)??l.id;l.ok?process.stdout.write(` ok ${c} (${l.toolCount??0} tools)
164
167
  `):(process.stdout.write(` failed ${c}: ${l.error??"discovery failed"}
165
- `),process.exitCode=1)}}async function kn(e){let t=e.positional[0]??"list",n={...e,positional:e.positional.slice(1)};switch(t){case"list":await wn(n);return;case"add":await Sn(n);return;case"remove":await bn(n);return;case"enable":await Ge(n,!0);return;case"disable":await Ge(n,!1);return;case"maker":await xn(n);return;case"health":await vn(n);return;default:throw new Error(`Unknown connectors subcommand: ${t}. Use \`npx greatstore connectors [add|remove|enable|disable|maker|health]\`.`)}}function $n(e,t=15){if(!e.trim())return"";let n=e.split(`
168
+ `),process.exitCode=1)}}async function zn(e){let t=e.positional[0]??"list",n={...e,positional:e.positional.slice(1)};switch(t){case"list":await qn(n);return;case"add":await Vn(n);return;case"remove":await Jn(n);return;case"enable":await it(n,!0);return;case"disable":await it(n,!1);return;case"maker":await Kn(n);return;case"health":await Wn(n);return;default:throw new Error(`Unknown connectors subcommand: ${t}. Use \`npx greatstore connectors [add|remove|enable|disable|maker|health]\`.`)}}function Xn(e,t=15){if(!e.trim())return"";let n=e.split(`
166
169
  `),r=[],o=0,s=!1;for(let i of n){if(i.startsWith("## ")){if(s&&o>=t)break;s=!0}r.push(i),s&&/^\s*[-*+]\s/.test(i)&&o++}return r.join(`
167
- `).trimEnd()}var Kr=`# Changelog
170
+ `).trimEnd()}var Po=`# Changelog
168
171
 
169
172
  All notable changes to \`@greatstore/cli\` are recorded here. The format
170
173
  follows [Keep a Changelog](https://keepachangelog.com/).
171
174
 
175
+ ## 0.2.5 \u2014 2026-10-14
176
+
177
+ ### Changed
178
+ - Pushing new code to a ready-made app that GreatStore keeps up to date makes it
179
+ your own copy: \`npx greatstore apps push\` says so, and the app stops getting
180
+ those updates. Shoppers keep seeing the previous version until you publish.
181
+
182
+ ## 0.2.4 \u2014 2026-10-13
183
+
184
+ ### Changed
185
+ - Internal improvements.
186
+
172
187
  ## 0.2.3 \u2014 2026-10-07
173
188
 
174
189
  ### Changed
@@ -728,7 +743,7 @@ follows [Keep a Changelog](https://keepachangelog.com/).
728
743
 
729
744
  ### Fixed
730
745
  - Sign-in callback parameter handling.
731
- `,Pn=`greatstore \u2014 GreatStore CLI (v${O})
746
+ `,Yn=`greatstore \u2014 GreatStore CLI (v${O})
732
747
 
733
748
  Usage:
734
749
  npx greatstore <command> [args] [flags]
@@ -782,14 +797,14 @@ Environment:
782
797
  GS_API_BASE Override API base (full URL, no trailing slash).
783
798
  GS_DASHBOARD_BASE Override the sign-in/store-picker base URL.
784
799
  GS_BROWSER_CMD Override the browser-open command.
785
- `,Wr=new Set(["init","build","list","pull","push","publish","unpublish","delete"]);async function zr(){let e=process.argv.slice(2),t=qe(e);if(lt(O),m(t.flags,"version")){process.stdout.write(`greatstore v${O}
800
+ `,Co=new Set(["init","build","list","pull","push","publish","unpublish","delete"]);async function Eo(){let e=process.argv.slice(2),t=pt(e);if(Ot(O),m(t.flags,"version")){process.stdout.write(`greatstore v${O}
786
801
 
787
- `);let n=$n(Kr);return n&&process.stdout.write(`${n}
788
- `),0}if(m(t.flags,"help")||t.command==="help"||t.command===null){let n=t.command==="configure"?ft(t.positional[0]):void 0;return process.stdout.write(n??Pn),0}if(t.command!==null&&Wr.has(t.command))return He({...t,positional:[t.command,...t.positional]});switch(t.command){case"login":return await rt(t),0;case"logout":return ot(),0;case"whoami":return st();case"switch":return it(t.positional);case"apps":return He(t);case"configure":return await yn(t),0;case"connectors":return await kn(t),0;case"skill":return ut(),0;default:return process.stderr.write(`Unknown command: ${t.command}
802
+ `);let n=Xn(Po);return n&&process.stdout.write(`${n}
803
+ `),0}if(m(t.flags,"help")||t.command==="help"||t.command===null){let n=t.command==="configure"?Nt(t.positional[0]):void 0;return process.stdout.write(n??Yn),0}if(t.command!==null&&Co.has(t.command))return ot({...t,positional:[t.command,...t.positional]});switch(t.command){case"login":return await Et(t),0;case"logout":return At(),0;case"whoami":return jt();case"switch":return Rt(t.positional);case"apps":return ot(t);case"configure":return await Gn(t),0;case"connectors":return await zn(t),0;case"skill":return Lt(),0;default:return process.stderr.write(`Unknown command: ${t.command}
789
804
 
790
- ${Pn}`),1}}zr().then(e=>process.exit(e)).catch(e=>{e instanceof F?process.stderr.write(`${e.message}
791
- `):e instanceof B?process.stderr.write(`Error: ${e.message}
792
- `):e instanceof M||e instanceof W?process.stderr.write(`Error: ${e.message}
805
+ ${Yn}`),1}}Eo().then(e=>process.exit(e)).catch(e=>{e instanceof N?process.stderr.write(`${e.message}
806
+ `):e instanceof L?process.stderr.write(`Error: ${e.message}
807
+ `):e instanceof B||e instanceof X?process.stderr.write(`Error: ${e.message}
793
808
  `):e instanceof Error?process.stderr.write(`Error: ${e.message}
794
809
  `):process.stderr.write(`Error: ${String(e)}
795
810
  `),process.exit(1)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "greatstore",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "description": "CLI for administering GreatStore stores and authoring custom components.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",