@greatstore/cli 0.2.16 → 0.2.18

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 +6 -0
  2. package/dist/cli.js +102 -88
  3. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -3,6 +3,12 @@
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.18 — 2026-10-30
7
+
8
+ ### Added
9
+ - Every command opens with the CLI's version, except under `--json`. The first run after an update also shows an "Updated!" badge with a pointer to `whats-new`.
10
+ - `whats-new` shows what changed in every release since the version you last ran.
11
+
6
12
  ## 0.2.16 — 2026-10-30
7
13
 
8
14
  ### Added
package/dist/cli.js CHANGED
@@ -1,44 +1,44 @@
1
1
  #!/usr/bin/env node
2
- var Pr={h:"help",v:"version",o:"out"};function Et(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 c=e[n+1];c===void 0||c.startsWith("--")||c.startsWith("-")?a=!0:(a=c,n++)}i&&(t.flags[i]=a)}else if(o.startsWith("-")&&o.length>1){let s=o.slice(1),i=Pr[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 y(e,t){let n=e[t];return typeof n=="string"?n:void 0}function g(e,t){let n=e[t];return n===!0||n==="true"}import*as jt from"crypto";import*as _t from"http";import{spawn as Ct}from"child_process";var Er="/callback",Cr='<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>',Ar=`:root{color-scheme:light}
2
+ var Nr={h:"help",v:"version",o:"out"};function Tt(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=Nr[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 y(e,t){let n=e[t];return typeof n=="string"?n:void 0}function g(e,t){let n=e[t];return n===!0||n==="true"}import*as It from"crypto";import*as Ft from"http";import{spawn as Lt}from"child_process";var Br="/callback",Dr='<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>',Hr=`: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}`,jr=`<!doctype html>
6
+ p{color:#2c3a38}`,Mr=`<!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>${Ar}</style></head>
11
+ <style>${Hr}</style></head>
12
12
  <body>
13
- <div class="logo">${Cr}</div>
13
+ <div class="logo">${Dr}</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>`,At=`<!doctype html>
17
+ </body></html>`,Ot=`<!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>`,ne=class extends Error{constructor(t){super(t),this.name="LoopbackError"}};async function Ce(e){let t=(e.generateState??Tr)(),n=e.timeoutMs??300*1e3,r=e.openBrowser??(s=>Rr(s,e.browserCmdEnv)),o=_t.createServer();try{await new Promise(l=>o.listen(0,"127.0.0.1",l));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(),c=_r(o,t,n);return r(a),await c}finally{o.close()}}function _r(e,t,n){return new Promise((r,o)=>{let s=!1,i=c=>{s||(s=!0,c())},a=setTimeout(()=>{i(()=>o(new ne("Sign-in timed out. Re-run `npx greatstore login`.")))},n);typeof a.unref=="function"&&a.unref(),e.on("request",(c,l)=>{let p=new URL(c.url??"/","http://127.0.0.1");if(p.pathname!==Er){l.writeHead(404,{"content-type":"text/plain"}),l.end("Not found");return}let u=p.searchParams,d=u.get("error"),x=u.get("error_description"),m=u.get("code");if(u.get("state")!==t){l.writeHead(400,{"content-type":"text/html"}),l.end(At),clearTimeout(a),i(()=>o(new ne("Sign-in didn't complete. Please try again.")));return}if(d||!m){l.writeHead(400,{"content-type":"text/html"}),l.end(At),clearTimeout(a),i(()=>o(new ne(x??"Sign-in failed. Please try again.")));return}l.writeHead(200,{"content-type":"text/html"}),l.end(jr),clearTimeout(a);let Ee=u.get("store")?.trim();i(()=>r(Ee?{token:m,store:Ee}:{token:m}))})})}function Tr(){return jt.randomBytes(16).toString("hex")}function Rr(e,t){let r=t?.trim()??Lr();if(r)try{let o;if(r==="start"){let s=`start "" "${e}"`;o=Ct("cmd.exe",["/d","/s","/c",s],{stdio:"ignore",detached:!0,windowsVerbatimArguments:!0})}else o=Ct(r,[e],{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}function Lr(){switch(process.platform){case"darwin":return"open";case"win32":return"start";case"linux":return"xdg-open";default:return null}}import*as L from"fs";import*as le from"os";import*as et from"path";var Or=".greatstore",Ir="credentials.json";function Ae(e=le.homedir()){return et.join(e,Or)}function tt(e=le.homedir()){return et.join(Ae(e),Ir)}function I(e=le.homedir()){let t=tt(e),n;try{let r=L.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=L.readFileSync(t,"utf8")}catch(r){if(Fr(r))return null;throw r}try{let r=JSON.parse(n);return typeof r.access_token!="string"?null:r}catch{return null}}function je(e,t=le.homedir()){let n=Ae(t);if(L.mkdirSync(n,{recursive:!0,mode:448}),process.platform!=="win32")try{L.chmodSync(n,448)}catch{}let r=tt(t);L.writeFileSync(r,`${JSON.stringify(e,null,2)}
23
- `,{mode:384}),process.platform!=="win32"&&L.chmodSync(r,384)}function Tt(e=le.homedir()){L.rmSync(tt(e),{force:!0})}function Rt(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 _e(e,t=Math.floor(Date.now()/1e3)){return e.expires_at<=t}function Fr(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}var F="0.2.16";var D=class extends Error{constructor(n,r,o){super(r);this.status=n;this.code=o;this.name="HttpError"}},M=class extends Error{constructor(t="Sign in first. Run `npx greatstore login`."){super(t),this.name="AuthRequiredError"}};function Nr(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 Br(e){let t=Nr(e)??I()?.store;return t?`npx greatstore login --store ${t}`:"npx greatstore login"}var nt=null;function Ft(e){nt=e}async function f(e,t={}){if(nt!==null)return Lt(e,t,nt);let n=()=>`Run \`${Br(e)}\`.`,r=I();if(!r)throw new M(`Sign in first. ${n()}`);if(_e(r))throw new M(`Session expired. ${n()}`);try{return await Lt(e,t,r.access_token)}catch(o){throw o instanceof D&&o.status===401?new M(`Session expired. ${n()}`):o}}async function Lt(e,t,n){let r={accept:"application/json",authorization:`Bearer ${n}`,"x-gs-cli-version":F,...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(),c={};try{c=JSON.parse(a)}catch{}let l=c.code??c.error,p=t.validationDetail&&i.status===400&&c.error?c.error:Dr(i.status,l,c.detail);throw new D(i.status,p,c.code??c.error)}var Nt=`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>`,ne=class extends Error{constructor(t){super(t),this.name="LoopbackError"}};async function _e(e){let t=(e.generateState??Vr)(),n=e.timeoutMs??300*1e3,r=e.openBrowser??(s=>Gr(s,e.browserCmdEnv)),o=Ft.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=Ur(o,t,n);return r(a),await l}finally{o.close()}}function Ur(e,t,n){return new Promise((r,o)=>{let s=!1,i=l=>{s||(s=!0,l())},a=setTimeout(()=>{i(()=>o(new ne("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!==Br){c.writeHead(404,{"content-type":"text/plain"}),c.end("Not found");return}let u=p.searchParams,d=u.get("error"),x=u.get("error_description"),m=u.get("code");if(u.get("state")!==t){c.writeHead(400,{"content-type":"text/html"}),c.end(Ot),clearTimeout(a),i(()=>o(new ne("Sign-in didn't complete. Please try again.")));return}if(d||!m){c.writeHead(400,{"content-type":"text/html"}),c.end(Ot),clearTimeout(a),i(()=>o(new ne(x??"Sign-in failed. Please try again.")));return}c.writeHead(200,{"content-type":"text/html"}),c.end(Mr),clearTimeout(a);let je=u.get("store")?.trim();i(()=>r(je?{token:m,store:je}:{token:m}))})})}function Vr(){return It.randomBytes(16).toString("hex")}function Gr(e,t){let r=t?.trim()??qr();if(r)try{let o;if(r==="start"){let s=`start "" "${e}"`;o=Lt("cmd.exe",["/d","/s","/c",s],{stdio:"ignore",detached:!0,windowsVerbatimArguments:!0})}else o=Lt(r,[e],{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}function qr(){switch(process.platform){case"darwin":return"open";case"win32":return"start";case"linux":return"xdg-open";default:return null}}import*as L from"fs";import*as le from"os";import*as nt from"path";var Jr=".greatstore",Kr="credentials.json";function re(e=le.homedir()){return nt.join(e,Jr)}function rt(e=le.homedir()){return nt.join(re(e),Kr)}function F(e=le.homedir()){let t=rt(e),n;try{let r=L.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=L.readFileSync(t,"utf8")}catch(r){if(Wr(r))return null;throw r}try{let r=JSON.parse(n);return typeof r.access_token!="string"?null:r}catch{return null}}function Re(e,t=le.homedir()){let n=re(t);if(L.mkdirSync(n,{recursive:!0,mode:448}),process.platform!=="win32")try{L.chmodSync(n,448)}catch{}let r=rt(t);L.writeFileSync(r,`${JSON.stringify(e,null,2)}
23
+ `,{mode:384}),process.platform!=="win32"&&L.chmodSync(r,384)}function Nt(e=le.homedir()){L.rmSync(rt(e),{force:!0})}function Bt(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 Te(e,t=Math.floor(Date.now()/1e3)){return e.expires_at<=t}function Wr(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}var O="0.2.18";function pe(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}var D=class extends Error{constructor(n,r,o){super(r);this.status=n;this.code=o;this.name="HttpError"}},M=class extends Error{constructor(t="Sign in first. Run `npx greatstore login`."){super(t),this.name="AuthRequiredError"}};function Yr(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 zr(e){let t=Yr(e)??F()?.store;return t?`npx greatstore login --store ${t}`:"npx greatstore login"}var ot=null;function Ut(e){ot=e}async function f(e,t={}){if(ot!==null)return Dt(e,t,ot);let n=()=>`Run \`${zr(e)}\`.`,r=F();if(!r)throw new M(`Sign in first. ${n()}`);if(Te(r))throw new M(`Session expired. ${n()}`);try{return await Dt(e,t,r.access_token)}catch(o){throw o instanceof D&&o.status===401?new M(`Session expired. ${n()}`):o}}async function Dt(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:Xr(i.status,c,l.detail);throw new D(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
- `,Ot={cli_upgrade_required:{message:Nt},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},changelog_invalid:{message:"changelog.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."},style_too_large:{message:"style.css is over 256 KB."}};function Dr(e,t,n){if(t&&t in Ot){let r=Ot[t];return r?r.includeDetail&&n?`${r.message} (${n})`:r.message:It(e)}return It(e)}function It(e){return e===401?"Sign-in needed. Run `npx greatstore login`.":e===426?Nt: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 Re(e,t){let n=Rt(e),r=Bt(n,"sub");if(!r)throw new Error("Token is missing a `sub` claim.");let o=Hr(n,"exp");return{access_token:e,expires_at:o??Math.floor(Date.now()/1e3)+3600,sub:r,...Te(n,"email","email"),...Te(n,"accountId","accountId"),...Te(n,"name","name"),...Te(n,"surname","surname"),...Mr(n,"superUser","superUser"),...t?{store:t}:{}}}function Bt(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Hr(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Te(e,t,n){let r=Bt(e,t);return r?{[n]:r}:{}}function Mr(e,t,n){let r=e[t];return r===!0?{[n]:!0}:typeof r=="string"&&r.toLowerCase()==="true"?{[n]:!0}:{}}import*as Le from"fs";import*as W from"path";var Ur="https://my.greatstore.ai",Dt="_library";function be(e){return e===Dt}var K=class extends Error{constructor(t){super(t),this.name="StoreResolutionError"}};function E(e={}){let t=rt(e.cwd??process.cwd());if(t)return ue(t);throw new K("No .gsrc found in this directory or any ancestor. Run `npx greatstore apps init --store <slug>` first to scaffold a GreatStore project.")}function Ht(e=process.cwd()){let t=rt(e);if(t)return ue(t);let n=xe();if(n)return n;throw new K("No store selected. Run `npx greatstore login`, or run from a project with a .gsrc.")}function xe(){try{return I()?.store??null}catch{return null}}function ue(e){let t=xe();if(t&&t!==e)throw new K(`This targets store "${e}" but you're signed in to "${t}". Run \`npx greatstore switch ${e}\` to change stores.`);return e}function rt(e){let t=Mt(e);return t?t.library===!0?Dt:typeof t.store=="string"?t.store.trim():null:null}function Mt(e){let t=W.resolve(e),n=W.parse(t).root;for(;;){let r=W.join(t,".gsrc");if(Le.existsSync(r))try{let s=JSON.parse(Le.readFileSync(r,"utf8"));if(s.library===!0||typeof s.store=="string"&&s.store.trim())return s}catch{}if(t===n)return null;let o=W.dirname(t);if(o===t)return null;t=o}}function ot(e=process.cwd(),t=process.env){if(t.GS_DASHBOARD_BASE?.trim())return re(t);let n=Mt(e)?.dashboard;return typeof n=="string"&&n.trim()?st(n.trim()):re(t)}function w(e){let t=y(e.flags,"store")?.trim();if(t)return ue(t);let n=rt(process.cwd());if(n)return ue(n);let r=xe();if(r)return r;throw new K("No store selected. Pass --store <slug>, or run from a project with a .gsrc.")}function j(e,t=process.env){let n=t.GS_API_BASE?.trim();return n?st(n):`https://${e}.greatstore.ai`}function Oe(e,t=process.env){return be(e)?`${ot(process.cwd(),t)}/cli/library`:`${j(e,t)}/api/apps`}function re(e=process.env){let t=e.GS_DASHBOARD_BASE?.trim();return t?st(t):Ur}function v(e,t=process.env){return`${re(t)}/${e}/admin`}function st(e){return e.endsWith("/")?e.slice(0,-1):e}async function Ut(e){let t=y(e.flags,"store")?.trim();process.stdout.write(`Opening browser for sign-in\u2026
31
- `);let{token:n,store:r}=await Ce({dashboardBaseUrl:re(),...t?{requestedStore:t}:{}}),o=Re(n,r);je(o);let s=o.email??o.sub;o.store?process.stdout.write(`Logged in as ${s}, working on store "${o.store}".
30
+ `,Ht={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},changelog_invalid:{message:"changelog.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."},style_too_large:{message:"style.css is over 256 KB."}};function Xr(e,t,n){if(t&&t in Ht){let r=Ht[t];return r?r.includeDetail&&n?`${r.message} (${n})`:r.message:Mt(e)}return Mt(e)}function Mt(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 Oe(e,t){let n=Bt(e),r=Gt(n,"sub");if(!r)throw new Error("Token is missing a `sub` claim.");let o=Qr(n,"exp");return{access_token:e,expires_at:o??Math.floor(Date.now()/1e3)+3600,sub:r,...Le(n,"email","email"),...Le(n,"accountId","accountId"),...Le(n,"name","name"),...Le(n,"surname","surname"),...Zr(n,"superUser","superUser"),...t?{store:t}:{}}}function Gt(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Qr(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Le(e,t,n){let r=Gt(e,t);return r?{[n]:r}:{}}function Zr(e,t,n){let r=e[t];return r===!0?{[n]:!0}:typeof r=="string"&&r.toLowerCase()==="true"?{[n]:!0}:{}}import*as Ie from"fs";import*as W from"path";var eo="https://my.greatstore.ai",qt="_library";function ve(e){return e===qt}var K=class extends Error{constructor(t){super(t),this.name="StoreResolutionError"}};function E(e={}){let t=st(e.cwd??process.cwd());if(t)return fe(t);throw new K("No .gsrc found in this directory or any ancestor. Run `npx greatstore apps init --store <slug>` first to scaffold a GreatStore project.")}function Jt(e=process.cwd()){let t=st(e);if(t)return fe(t);let n=ke();if(n)return n;throw new K("No store selected. Run `npx greatstore login`, or run from a project with a .gsrc.")}function ke(){try{return F()?.store??null}catch{return null}}function fe(e){let t=ke();if(t&&t!==e)throw new K(`This targets store "${e}" but you're signed in to "${t}". Run \`npx greatstore switch ${e}\` to change stores.`);return e}function st(e){let t=Kt(e);return t?t.library===!0?qt:typeof t.store=="string"?t.store.trim():null:null}function Kt(e){let t=W.resolve(e),n=W.parse(t).root;for(;;){let r=W.join(t,".gsrc");if(Ie.existsSync(r))try{let s=JSON.parse(Ie.readFileSync(r,"utf8"));if(s.library===!0||typeof s.store=="string"&&s.store.trim())return s}catch{}if(t===n)return null;let o=W.dirname(t);if(o===t)return null;t=o}}function it(e=process.cwd(),t=process.env){if(t.GS_DASHBOARD_BASE?.trim())return oe(t);let n=Kt(e)?.dashboard;return typeof n=="string"&&n.trim()?at(n.trim()):oe(t)}function w(e){let t=y(e.flags,"store")?.trim();if(t)return fe(t);let n=st(process.cwd());if(n)return fe(n);let r=ke();if(r)return r;throw new K("No store selected. Pass --store <slug>, or run from a project with a .gsrc.")}function j(e,t=process.env){let n=t.GS_API_BASE?.trim();return n?at(n):`https://${e}.greatstore.ai`}function Fe(e,t=process.env){return ve(e)?`${it(process.cwd(),t)}/cli/library`:`${j(e,t)}/api/apps`}function oe(e=process.env){let t=e.GS_DASHBOARD_BASE?.trim();return t?at(t):eo}function v(e,t=process.env){return`${oe(t)}/${e}/admin`}function at(e){return e.endsWith("/")?e.slice(0,-1):e}async function Wt(e){let t=y(e.flags,"store")?.trim();process.stdout.write(`Opening browser for sign-in\u2026
31
+ `);let{token:n,store:r}=await _e({dashboardBaseUrl:oe(),...t?{requestedStore:t}:{}}),o=Oe(n,r);Re(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 Gt(){let e=I()!==null;Tt(),process.stdout.write(e?`Logged out.
33
+ `)}function Yt(){let e=F()!==null;Nt(),process.stdout.write(e?`Logged out.
34
34
  `:`Not logged in.
35
- `)}function qt(){let e=I();if(!e)return process.stderr.write("Not logged in. Run `npx greatstore login`.\n"),1;let t=_e(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 zt(){let e=F();if(!e)return process.stderr.write("Not logged in. Run `npx greatstore login`.\n"),1;let t=Te(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 Vt(e){if(!I())throw new M;let n=e[0]?.trim();process.stdout.write(`Opening browser to switch stores\u2026
38
- `);let{token:r,store:o}=await Ce({dashboardBaseUrl:re(),...n?{requestedStore:n}:{}}),s=Re(r,o);return je(s),s.store?process.stdout.write(`Now working on store "${s.store}".
37
+ `),t?1:0}async function Xt(e){if(!F())throw new M;let n=e[0]?.trim();process.stdout.write(`Opening browser to switch stores\u2026
38
+ `);let{token:r,store:o}=await _e({dashboardBaseUrl:oe(),...n?{requestedStore:n}:{}}),s=Oe(r,o);return Re(s),s.store?process.stdout.write(`Now working on store "${s.store}".
39
39
  `):process.stdout.write(`Switched.
40
- `),0}import*as C from"fs";import*as Ie from"os";import*as oe from"path";import{fileURLToPath as Gr}from"url";var pe="greatstore",Jt=".version";function qr(){for(let e of["./gs-skill/","../../gs-skill/"]){let t=oe.resolve(Gr(new URL(e,import.meta.url)));if(C.existsSync(oe.join(t,"SKILL.md")))return t}throw new Error("internal: this install of the CLI is missing the agent skill files")}function Kt(e=Ie.homedir()){return oe.join(Ae(e),"skill",pe)}function it(e,t=Ie.homedir()){let n=Kt(t),r=Vr(n);if(r!==null&&Jr(r,e)>=0)return n;let o=`${n}.tmp-${process.pid}`,s=`${n}.old-${process.pid}`;return C.rmSync(o,{recursive:!0,force:!0}),C.cpSync(qr(),o,{recursive:!0}),C.writeFileSync(oe.join(o,Jt),e),C.existsSync(n)&&C.renameSync(n,s),C.renameSync(o,n),C.rmSync(s,{recursive:!0,force:!0}),n}function Wt(e,t=Ie.homedir()){try{C.existsSync(Kt(t))&&it(e,t)}catch{}}function Vr(e){try{return C.readFileSync(oe.join(e,Jt),"utf8").trim()}catch{return null}}function Jr(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 Yt(){process.stdout.write(Kr(it(F)))}function Kr(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 "${pe}":`,""," mkdir -p <SKILLS_DIR>",` ln -sfn "${e}" "<SKILLS_DIR>/${pe}"`,"","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>/${pe}/SKILL.md to confirm the install.`,"",`On Windows: mklink /D "<SKILLS_DIR>\\${pe}" "${e}"`,""].join(`
41
- `)}var Y={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},hiddenUntilOpenedMobile:{kind:"boolean",help:"Keep the chat off the page on mobile until your site opens it.",brandVisible:!0},hiddenUntilOpenedDesktop:{kind:"boolean",help:"Keep the chat off the page on desktop until your site opens it.",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 zt(e){let t=e.toLowerCase();return Object.keys(Y).map(n=>{let r=n.toLowerCase();return{name:n,distance:Yr(t,r),prefix:Wr(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 Wr(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;return n}function Yr(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 zr=`npx greatstore configure \u2014 view and edit a store's configuration.
40
+ `),0}import*as C from"fs";import*as Ne from"os";import*as se from"path";import{fileURLToPath as to}from"url";var de="greatstore",Qt=".version";function no(){for(let e of["./gs-skill/","../../gs-skill/"]){let t=se.resolve(to(new URL(e,import.meta.url)));if(C.existsSync(se.join(t,"SKILL.md")))return t}throw new Error("internal: this install of the CLI is missing the agent skill files")}function Zt(e=Ne.homedir()){return se.join(re(e),"skill",de)}function ct(e,t=Ne.homedir()){let n=Zt(t),r=ro(n);if(r!==null&&pe(r,e)>=0)return n;let o=`${n}.tmp-${process.pid}`,s=`${n}.old-${process.pid}`;return C.rmSync(o,{recursive:!0,force:!0}),C.cpSync(no(),o,{recursive:!0}),C.writeFileSync(se.join(o,Qt),e),C.existsSync(n)&&C.renameSync(n,s),C.renameSync(o,n),C.rmSync(s,{recursive:!0,force:!0}),n}function en(e,t=Ne.homedir()){try{C.existsSync(Zt(t))&&ct(e,t)}catch{}}function ro(e){try{return C.readFileSync(se.join(e,Qt),"utf8").trim()}catch{return null}}function tn(){process.stdout.write(oo(ct(O)))}function oo(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 "${de}":`,""," mkdir -p <SKILLS_DIR>",` ln -sfn "${e}" "<SKILLS_DIR>/${de}"`,"","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>/${de}/SKILL.md to confirm the install.`,"",`On Windows: mklink /D "<SKILLS_DIR>\\${de}" "${e}"`,""].join(`
41
+ `)}var Y={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},hiddenUntilOpenedMobile:{kind:"boolean",help:"Keep the chat off the page on mobile until your site opens it.",brandVisible:!0},hiddenUntilOpenedDesktop:{kind:"boolean",help:"Keep the chat off the page on desktop until your site opens it.",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 nn(e){let t=e.toLowerCase();return Object.keys(Y).map(n=>{let r=n.toLowerCase();return{name:n,distance:io(t,r),prefix:so(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 so(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;return n}function io(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 ao=`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 Xr(){let e=Object.entries(Y).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 Qr(){return Object.entries(Y).filter(([,e])=>e.brandVisible).map(([e])=>e).join(", ")}function Zr(){return`npx greatstore configure set \u2014 save configuration fields.
54
+ `;function co(){let e=Object.entries(Y).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 lo(){return Object.entries(Y).filter(([,e])=>e.brandVisible).map(([e])=>e).join(", ")}function uo(){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
- ${Xr()}
69
+ ${co()}
70
70
 
71
71
  Whole-object theme writes:
72
72
  --theme '<json>' Merge this JSON object into the stored theme.
@@ -75,51 +75,51 @@ 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
- ${Qr()}
78
+ ${lo()}
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 Xt(e){if(e===void 0||e==="show")return zr;if(e==="set")return Zr()}import*as S from"fs";import*as A from"path";import{readdirSync as Ds,readFileSync as Hs}from"fs";import{fileURLToPath as Us}from"url";var Fe=null;function Zt(){return Fe||(Fe=JSON.parse('{"component/component.tsx":"import React from \\"react\\";\\nimport \\"./style.css\\";\\n\\n// Add your tool args (matching manifest.json#inputSchema.properties)\\n// alongside `$`, the GreatStore prop every app receives. See AGENTS.md for\\n// what each `$` member does.\\ninterface Props {\\n $: {\\n sendMessage: (text: string) => void;\\n updateModelContext: (context: string) => void;\\n // Run one of the store\'s read-only connector tools and get its result,\\n // or open one of its full-screen apps by name. See AGENTS.md.\\n callTool: (\\n name: string,\\n args?: Record<string, unknown>,\\n ) => Promise<Record<string, unknown> | undefined>;\\n showLightbox: (options: { src: string; originRect?: DOMRect }) => void;\\n close: () => 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 generateStructuredContent: <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 // A hook for a voice call with the store\'s assistant: call it at the top\\n // of the component. See AGENTS.md.\\n useVoiceCall: () => {\\n status:\\n | \\"started\\"\\n | \\"connecting\\"\\n | \\"connected\\"\\n | \\"speaking\\"\\n | \\"listening\\"\\n | \\"working\\"\\n | \\"disconnected\\"\\n | \\"ended\\"\\n | \\"rejected\\"\\n | null;\\n available: boolean;\\n start: () => Promise<void>;\\n end: () => void;\\n };\\n store: { slug: string };\\n };\\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 (style.css, em-based sizing, brand CSS variables), and how to\\n// write an async, backend-backed app.\\n//\\n// Take what you need from `$` at the top: `const { callTool, Image } = props.$;`\\nexport default function Component(_props: Props): React.ReactElement {\\n return (\\n <div className=\\"app\\">\\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","component/style.css":"/*\\n * Your app\'s styles. Plain CSS, applied inside the app alone: nothing here\\n * reaches the store\'s page, and nothing on the page reaches in.\\n *\\n * Style with the store\'s theme variables rather than fixed values \u2014 write\\n * `color: var(--color-foreground)`, never `color: #111827`. Each store sets\\n * its colours, fonts and corner style (and dark mode) in its GreatStore\\n * dashboard; an app built on these variables follows those settings, and\\n * changes with them.\\n *\\n * Fonts: --font-primary, --font-secondary\\n * Surfaces: --color-surface, --color-surface-secondary, --color-surface-accent,\\n * --color-surface-hover\\n * Text: --color-foreground, --color-foreground-secondary,\\n * --color-foreground-muted, --color-foreground-accent\\n * Borders: --color-border-default, --color-border-focus\\n * Brand: --color-primary, --color-primary-foreground, --color-primary-hover,\\n * --color-primary-muted, --color-primary-muted-foreground,\\n * --color-primary-tint, --color-link\\n * Status: --color-error, --color-error-surface, --color-error-border,\\n * --color-success\\n * Corners: --radius-xs, --radius-sm, --radius-md, --radius-lg, --radius-xl,\\n * --radius-2xl, --radius-3xl, --radius-4xl, --radius-pill\\n */\\n\\n/* Size in em, never rem: an app sits inside other people\'s pages. */\\n.app {\\n padding: 1em;\\n border: 1px solid var(--color-border-default);\\n border-radius: var(--radius-lg);\\n background: var(--color-surface);\\n color: var(--color-foreground);\\n font-family: var(--font-primary);\\n}\\n","root/.gitignore":"node_modules/\\ncomponents/*/bundle.js\\ncomponents/*/bundle.css\\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 $.generateStructured-\\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 $.updateModelContext() \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 $.sendMessage() \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 (`$.updateModelContext`), can speak for the\\n shopper (`$.sendMessage`), 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 `$.generateStructuredContent` 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### Style in `style.css`\\n\\nEach app\'s styles live in `components/<name>/style.css`, imported once at\\nthe top of `component.tsx`:\\n\\n```tsx\\nimport \\"./style.css\\";\\n```\\n\\nWrite ordinary CSS there and use `className` in the component. The sheet\\napplies to your app alone \u2014 it can\'t affect the store\'s page, and the page\\ncan\'t affect your app \u2014 so short class names like `.card` are safe.\\nInline `style={{\u2026}}` still works for values computed at render time.\\n\\nThe rules for `style.css`:\\n\\n- Import only `./style.css`, and only from `component.tsx`. Every other CSS\\n import fails the build.\\n- Keep it self-contained: no `@import`, and `url()` only with `https:` or\\n `data:` URLs \u2014 nothing beside the sheet is uploaded with it.\\n- At most 256 KB.\\n\\n`npx greatstore apps build` minifies the sheet into `bundle.css` beside\\n`bundle.js`; shoppers get that, so comments in `style.css` are for you and\\nnever reach them. Like `bundle.js`, `bundle.css` is generated \u2014 edit\\n`style.css` and build again.\\n\\nThe comment at the top of the scaffolded `style.css` lists the theme\\nvariables below. Style with them rather than fixed values: each store sets\\nits colours, fonts and corner style in its GreatStore dashboard, and an app\\nbuilt on the variables follows those settings.\\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```css\\n/* Bad \u2014 breaks on hosts with a non-default root font size */\\n.card { padding: 1rem; font-size: 0.875rem; }\\n\\n/* Good */\\n.card { padding: 1em; font-size: 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```css\\n/* Bad \u2014 hardcoded, ignores the store\'s theme */\\n.buy { background: #4f46e5; border-radius: 8px; font-family: Inter; }\\n\\n/* Good */\\n.buy {\\n background: var(--color-primary);\\n color: var(--color-primary-foreground);\\n border-radius: var(--radius-lg);\\n font-family: var(--font-primary);\\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 one GreatStore prop, `$`,\\nwhich is always present. Destructure what you need from it at the top of\\nthe component:\\n\\n```tsx\\nexport default function SizeFinder({ category, $ }: Props) {\\n const { callTool, sendMessage, Image } = $;\\n // ...\\n}\\n```\\n\\nNever declare a `$` field in `inputSchema` \u2014 the build refuses it.\\n\\n| `$` member | What it does |\\n| --- | --- |\\n| `$.sendMessage(text)` | Send text into the chat as if the shopper typed it. |\\n| `$.updateModelContext(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 `$.sendMessage` when you want a turn to happen now. |\\n| `$.callTool(name, args?)` | The same call as the page\'s `window.GreatStore.callTool`: run one of the page\'s own WebMCP tools or one of the store\'s read-only connector tools and get its result back, or open one of the store\'s full-screen apps by name. It never touches the conversation \u2014 the assistant doesn\'t learn the call happened (tell it with `$.updateModelContext` if it should). Look up tool names and inputs with `npx greatstore connectors tools` (`webmcp` for page tools). In the app preview, tools run for real and naming a full-screen app only logs what would open. Inside other AI assistants (ChatGPT, \u2026) it always rejects, so handle the rejection. |\\n| `$.showLightbox({ 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| `$.generateStructuredContent(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| `$.close()` | Dismiss the host slot. Over-input clears the overlay, fullscreen reverts the pane, inline is a no-op. |\\n| `$.useVoiceCall()` | A hook \u2014 call it at the top of your component like any other \u2014 returning `{ status, available, start, end }` for a voice call with the store\'s assistant. `start()` starts the call without opening the chat \u2014 it runs in the collapsed chat bar (which stays hidden if the store hides the chat until opened), and the chat opens only when the assistant shows an inline app (call it from a click; it rejects when the store has no voice), `end()` hangs up. `available` says whether the store has voice. `status` is `null` until a call starts, then `started`, `connecting`, `connected`, `listening` / `speaking` / `working` as the conversation goes, `disconnected` while the network drops (the call recovers on its own), and `ended` \u2014 or `rejected` instead of `ended` when the shopper refuses the microphone (calling `start()` again asks again, though a browser where they blocked it refuses without asking). Your app re-renders on every change. |\\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 your own `$` with `Image: \\"img\\"` (or your own component) to render a plain image. |\\n| `$.store` | `{ slug }` \u2014 the store the app is running in. |\\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"}'),Fe)}var Qt={name:"__GS_NAME__",displayName:"__GS_DISPLAY_NAME__",store:"__GS_STORE__",version:"__GS_VERSION__"};function en(e,t){let n=e;for(let o of Object.keys(Qt)){let s=t[o];s!==void 0&&(n=n.split(Qt[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 tn=/^[a-z][a-z0-9_]*$/;function rn(e){let t=e.positional[0];if(t!==void 0&&!tn.test(t))throw new Error(`Invalid component name: "${t}" (must match ${tn}).`);let n=g(e.flags,"force"),r=y(e.flags,"store"),o=y(e.flags,"out")??".",s=A.resolve(o),i=eo(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.`);E({cwd:s})}else if(a=r!==void 0?ue(r):xe()??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 c=to(s,i,n,{store:a});if(!t){let u=[];i?(u.push(`Updated GreatStore project root in ${s}.`),c.length>0?u.push("",`Added: ${c.join(", ")}`):u.push("","Already up to date \u2014 nothing to add.")):u.push(`Scaffolded GreatStore project root in ${s}.`),u.push("","Next steps:",` cd ${A.relative(process.cwd(),s)||"."}`," npm install"," npx greatstore apps init <component_name> # add your first component",""),process.stdout.write(u.join(`
85
- `));return}let l=A.join(s,"components",t);oo(l,t,n);let p=A.relative(process.cwd(),s)||".";process.stdout.write([`Added component "${t}" at components/${t}/.`,...i&&c.length>0?["",`Also added to the project root: ${c.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 eo(e){return S.existsSync(A.join(e,"package.json"))&&S.existsSync(A.join(e,".gsrc"))}function to(e,t,n,r){if(S.mkdirSync(e,{recursive:!0}),!t&&!n&&S.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?io():so({store:r.store}),s=ro(e,o,n);return S.mkdirSync(A.join(e,"components"),{recursive:!0}),s}var no=new Set(["AGENTS.md"]);function ro(e,t,n){let r=[];for(let[o,s]of t){let i=A.join(e,o);S.mkdirSync(A.dirname(i),{recursive:!0});let a=S.existsSync(i);if(!n&&a&&!no.has(o))continue;let c=!a||S.readFileSync(i,"utf8")!==s;S.writeFileSync(i,s),c&&r.push(o)}for(let o of["CLAUDE.md","GEMINI.md"]){let s=A.join(e,o);n&&nn(s)&&S.rmSync(s),nn(s)||(S.symlinkSync("AGENTS.md",s),r.push(o))}return r}function nn(e){try{return S.lstatSync(e),!0}catch{return!1}}function oo(e,t,n){if(S.existsSync(e)&&!n&&S.readdirSync(e).length>0)throw new Error(`Refusing to overwrite existing components/${t}/. Pass --force to override.`);S.mkdirSync(e,{recursive:!0});for(let[r,o]of ao(t))S.writeFileSync(A.join(e,r),o)}function at(e,t,n=new Set){let r=Zt();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,en(s,t)])}function so(e){if(!e.store)throw new Error("internal: rootFiles called without a store slug");return at("root/",{store:e.store,version:F})}function io(){return at("root/",{version:F},new Set([".gsrc"]))}function ao(e){return at("component/",{name:e,displayName:lo(e)})}function lo(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 k from"fs";import*as h from"path";import*as fe from"fs";import*as lt from"path";var $="style.css",_="bundle.css",Ne=`./${$}`,on=256*1024;function co(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,""),n=[],r=/(?:^|[;{}])\s*import\s+(?:[^'";]*?\s+from\s+)?["']([^"']+\.css)(?:\?[^"']*)?["']/gm,o=/\bimport\s*\(\s*["']([^"']+\.css)(?:\?[^"']*)?["']\s*\)/g;for(let s of t.matchAll(r))n.push(s[1]);for(let s of t.matchAll(o))n.push(s[1]);return n}function N(e){let t=lt.join(e,"component.tsx");if(!fe.existsSync(t))return{imported:!1,problems:[]};let n=co(fe.readFileSync(t,"utf8")),r=n.filter(i=>i!==Ne).map(i=>({file:"component.tsx",message:`imports "${i}". A component's styles go in its own ${$}, imported as "${Ne}"; move these rules there.`})),o=n.includes(Ne);if(!o)return{imported:o,problems:r};let s=lt.join(e,$);if(!fe.existsSync(s))return r.push({file:"component.tsx",message:`imports "${Ne}", but there's no ${$} beside it.`}),{imported:o,problems:r};for(let i of uo(fe.readFileSync(s,"utf8")))r.push({file:$,message:i});return{imported:o,problems:r}}function uo(e){let t=[],n=Buffer.byteLength(e,"utf8");n>on&&t.push(`is ${(n/1024).toFixed(1)} KB; the limit is ${on/1024} KB.`);let r=e.replace(/\/\*[\s\S]*?\*\//g,s=>s.replace(/[^\n]/g," ")),o=s=>r.slice(0,s).split(`
87
- `).length;for(let s of r.matchAll(/@import\b/gi))t.push(`line ${o(s.index)} uses @import. A stylesheet ships on its own, so copy the rules in instead.`);for(let s of r.matchAll(/url\(\s*(["']?)([^"')]*)\1\s*\)/gi)){let i=s[2].trim();/^(https:|data:|#)/i.test(i)||t.push(`line ${o(s.index)} refers to "${i}". Only https: and data: URLs work here \u2014 nothing beside the stylesheet is uploaded with it.`)}return t}import{createRequire as vo}from"module";import{pathToFileURL as Cn}from"url";import*as hn from"fs";import*as U from"path";import{createRequire as po}from"module";import*as Be from"path";function an(e,t,n){let r=cn(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=mo(r,o);return s?yo(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 ${Be.basename(t)} could not be parsed (${o.message})`}}}function ln(e,t,n){let r=cn(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(fo(r,a)){s=!0;return}r.forEachChild(a,i)}};return i(o),s}catch{return!1}}function fo(e,t){if(e.isPropertyAccessExpression(t))return sn(e,t.expression)&&t.name.text==="GreatStore";if(e.isElementAccessExpression(t)){let n=t.argumentExpression;return sn(e,t.expression)&&e.isStringLiteralLike(n)&&n.text==="GreatStore"}return!1}function sn(e,t){return e.isIdentifier(t)&&(t.text==="window"||t.text==="globalThis")}function cn(e){let t=po(Be.join(e,"package.json"));try{return t("typescript")}catch{return null}}function mo(e,t){let n=null;for(let o of t.statements){if(e.isFunctionDeclaration(o)&&go(e,o))return o;e.isExportAssignment(o)&&!o.isExportEquals&&(n=o.expression)}if(!n)return null;let r=un(e,n);return e.isArrowFunction(r)||e.isFunctionExpression(r)?r:e.isIdentifier(r)?ho(e,t,r.text):null}function go(e,t){return t.modifiers?.some(n=>n.kind===e.SyntaxKind.DefaultKeyword)??!1}function un(e,t){let n=t;for(;e.isParenthesizedExpression(n)||e.isAsExpression(n)||e.isSatisfiesExpression(n);)n=n.expression;return n}function ho(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=un(e,o.initializer);if(e.isArrowFunction(s)||e.isFunctionExpression(s))return s}}return null}function yo(e,t,n){let r=n.parameters[0];if(!r)return{ok:!0,props:{names:[],open:!1}};if(r.type){let o=ct(e,t,r.type,new Set);if(o)return{ok:!0,props:o}}return e.isObjectBindingPattern(r.name)?{ok:!0,props:wo(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 ct(e,t,n,r){if(e.isTypeLiteralNode(n))return fn(e,n.members);if(e.isTypeReferenceNode(n)&&e.isIdentifier(n.typeName))return pn(e,t,n.typeName.text,r);if(e.isIntersectionTypeNode(n)){let o=n.types.map(s=>ct(e,t,s,r));return o.every(s=>s===null)?null:mn(o.map(s=>s??{names:[],open:!0}))}return null}function pn(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=fn(e,o.members),i=(o.heritageClauses??[]).flatMap(a=>a.types.map(c=>e.isIdentifier(c.expression)?pn(e,t,c.expression.text,r)??{names:[],open:!0}:{names:[],open:!0}));return mn([s,...i])}if(e.isTypeAliasDeclaration(o)&&o.name.text===n)return ct(e,t,o.type,r)}return null}function fn(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=dn(e,o.name);if(s===null){r=!0;continue}n.push(s)}return{names:n,open:r}}function wo(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=dn(e,s);i===null?r=!0:n.push(i)}return{names:n,open:r}}function dn(e,t){return e.isIdentifier(t)||e.isStringLiteral(t)?t.text:null}function mn(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 yn(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=ut(t,o),a=ut(t,s),c=[],l=null,p=gn(o);if(p===null)c.push({severity:"error",rule:"manifest/missing",file:i,message:"manifest not found."});else try{let m=JSON.parse(p);!m||typeof m!="object"||Array.isArray(m)?c.push({severity:"error",rule:"manifest/invalid",file:i,message:"manifest must be a JSON object."}):l=m}catch(m){c.push({severity:"error",rule:"manifest/invalid",file:i,message:`manifest is not valid JSON: ${m.message}`})}let u=gn(s),d=u===null?{ok:!1,reason:`couldn't check props against the manifest \u2014 ${a} not found`}:an(t,s,u),x=u===null?!1:ln(t,s,u);return{ctx:{name:n,manifestFile:i,sourceFile:a,manifest:l,props:d,usesWindowGreatStore:x,styleFile:ut(t,U.join(r,"style.css")),stylesheet:N(r)},diagnostics:c}}function gn(e){try{return hn.readFileSync(e,"utf8")}catch{return null}}function ut(e,t){let n=U.relative(e,t);return n.startsWith("..")?t:n.split(U.sep).join("/")}var wn=new Set(["$"]);var pt=new Map([["onSendMessage","sendMessage"],["onClose","close"],["onUpdateModelContext","updateModelContext"],["onShowLightbox","showLightbox"],["onGenerateStructuredContent","generateStructuredContent"],["storeData","store"],["Image","Image"],["useVoiceCall","useVoiceCall"]]);function Sn(e){let t=e.map(o=>`\`${o}\``).join(", "),n=e.map(o=>pt.get(o)).join(", "),r=e.length===1;return`${t} ${r?"is":"are"} retired \u2014 new apps must use \`const { ${n} } = $\`. Support for the old ${r?"prop":"props"} can end without notice; migrate before your next release.`}var bn=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 $n(e){if(!e.manifest)return[];let t=bo(e.manifest.inputSchema);if(t===null)return[];let n=[];if(t.includes("$")&&n.push({severity:"error",rule:"props/reserved",file:e.manifestFile,message:`${e.manifestFile} declares inputSchema field \`$\`, but GreatStore always passes its own \`$\` prop, so that field can never reach the component. Rename the field.`}),!e.props.ok)return[...n,{severity:"warning",rule:"props/not-analyzable",file:e.sourceFile,message:`${e.props.reason}.`}];if(e.props.props.open)return n;let r=new Set(e.props.props.names),o=new Set(t),s=[];for(let a of e.props.props.names){if(wn.has(a))continue;if(pt.has(a)){s.push(a);continue}let c=bn.get(a);if(c){n.push({severity:"warning",rule:"props/retired-lifecycle",file:e.sourceFile,message:c});continue}o.has(a)||n.push({severity:"warning",rule:"props/undeclared",file:e.sourceFile,message:`prop \`${a}\` 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.`})}s.length>0&&n.push({severity:"warning",rule:"props/retired-app-api",file:e.sourceFile,message:Sn(s)});let i=t.filter(a=>a!=="$"&&!r.has(a));return i.length>0&&n.push({severity:"error",rule:"props/missing",file:e.sourceFile,message:So(e.manifestFile,i)}),n}var xn=8;function So(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,xn).map(s=>`\`${s}\``).join(", "),r=t.length-xn,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 bo(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 xo=["anyOf","oneOf","allOf","$ref","not"];function De(e,t,n){if(Array.isArray(e)){e.forEach((s,i)=>De(s,`${t}[${i}]`,n));return}if(!e||typeof e!="object")return;let r=e;for(let s of xo)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,De(i,`${t}.${s}`,n);"items"in r&&De(r.items,`${t}[]`,n)}function vn(e){let t=e.manifest?.inputSchema;if(!t||typeof t!="object")return[];let n={bytes:Buffer.byteLength(JSON.stringify(t),"utf8"),fields:0,unionPaths:[]};De(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("; ")}.
88
- 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 kn(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 Pn(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 `$` prop (`const { sendMessage, callTool } = $`, \u2026) instead \u2014 those are wired to the surface the component is mounted in."}]:[]}function En(e){return e.stylesheet.problems.map(t=>({severity:"error",rule:"stylesheet/invalid",file:t.file==="component.tsx"?e.sourceFile:e.styleFile,message:t.message}))}function $e(e){return e.filter(t=>t.severity==="error")}function ft(e){return e.filter(t=>t.severity==="warning")}function ve(e){return`${e.severity==="error"?"error":"warning"} ${e.file}: ${e.message}`}var $o=[kn,vn,$n,Pn,En];function He(e){let{ctx:t,diagnostics:n}=yn(e);for(let r of $o)n.push(...r(t));return{diagnostics:n,ok:$e(n).length===0}}var G="components";async function Me(e){let t=process.cwd();if(!k.existsSync(h.join(t,"package.json"))||!k.existsSync(h.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=Eo(t);if(n.length===0)return process.stdout.write(`(no components in ./${G} \u2014 run \`npx greatstore apps init <name>\` to add one)
89
- `),[];let r=e.positional,o=r.filter(l=>!n.includes(l));if(o.length>0)throw new Error(`No component named ${o.map(l=>`"${l}"`).join(", ")} in ./${G}`);let s=r.length>0?n.filter(l=>r.includes(l)):n,i=[],a=[];for(let l of s){let p=He({root:t,name:l});for(let u of p.diagnostics)process.stdout.write(` ${ve(u)}
90
- `);(p.ok?a:i).push(l)}if(a.length===0)return process.stdout.write(`
84
+ `}function rn(e){if(e===void 0||e==="show")return ao;if(e==="set")return uo()}import*as S from"fs";import*as A from"path";import{readdirSync as Zs,readFileSync as ei}from"fs";import{fileURLToPath as ni}from"url";var Be=null;function sn(){return Be||(Be=JSON.parse('{"component/component.tsx":"import React from \\"react\\";\\nimport \\"./style.css\\";\\n\\n// Add your tool args (matching manifest.json#inputSchema.properties)\\n// alongside `$`, the GreatStore prop every app receives. See AGENTS.md for\\n// what each `$` member does.\\ninterface Props {\\n $: {\\n sendMessage: (text: string) => void;\\n updateModelContext: (context: string) => void;\\n // Run one of the store\'s read-only connector tools and get its result,\\n // or open one of its full-screen apps by name. See AGENTS.md.\\n callTool: (\\n name: string,\\n args?: Record<string, unknown>,\\n ) => Promise<Record<string, unknown> | undefined>;\\n showLightbox: (options: { src: string; originRect?: DOMRect }) => void;\\n close: () => 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 generateStructuredContent: <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 // A hook for a voice call with the store\'s assistant: call it at the top\\n // of the component. See AGENTS.md.\\n useVoiceCall: () => {\\n status:\\n | \\"started\\"\\n | \\"connecting\\"\\n | \\"connected\\"\\n | \\"speaking\\"\\n | \\"listening\\"\\n | \\"working\\"\\n | \\"disconnected\\"\\n | \\"ended\\"\\n | \\"rejected\\"\\n | null;\\n available: boolean;\\n start: () => Promise<void>;\\n end: () => void;\\n };\\n store: { slug: string };\\n };\\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 (style.css, em-based sizing, brand CSS variables), and how to\\n// write an async, backend-backed app.\\n//\\n// Take what you need from `$` at the top: `const { callTool, Image } = props.$;`\\nexport default function Component(_props: Props): React.ReactElement {\\n return (\\n <div className=\\"app\\">\\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","component/style.css":"/*\\n * Your app\'s styles. Plain CSS, applied inside the app alone: nothing here\\n * reaches the store\'s page, and nothing on the page reaches in.\\n *\\n * Style with the store\'s theme variables rather than fixed values \u2014 write\\n * `color: var(--color-foreground)`, never `color: #111827`. Each store sets\\n * its colours, fonts and corner style (and dark mode) in its GreatStore\\n * dashboard; an app built on these variables follows those settings, and\\n * changes with them.\\n *\\n * Fonts: --font-primary, --font-secondary\\n * Surfaces: --color-surface, --color-surface-secondary, --color-surface-accent,\\n * --color-surface-hover\\n * Text: --color-foreground, --color-foreground-secondary,\\n * --color-foreground-muted, --color-foreground-accent\\n * Borders: --color-border-default, --color-border-focus\\n * Brand: --color-primary, --color-primary-foreground, --color-primary-hover,\\n * --color-primary-muted, --color-primary-muted-foreground,\\n * --color-primary-tint, --color-link\\n * Status: --color-error, --color-error-surface, --color-error-border,\\n * --color-success\\n * Corners: --radius-xs, --radius-sm, --radius-md, --radius-lg, --radius-xl,\\n * --radius-2xl, --radius-3xl, --radius-4xl, --radius-pill\\n */\\n\\n/* Size in em, never rem: an app sits inside other people\'s pages. */\\n.app {\\n padding: 1em;\\n border: 1px solid var(--color-border-default);\\n border-radius: var(--radius-lg);\\n background: var(--color-surface);\\n color: var(--color-foreground);\\n font-family: var(--font-primary);\\n}\\n","root/.gitignore":"node_modules/\\ncomponents/*/bundle.js\\ncomponents/*/bundle.css\\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 $.generateStructured-\\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 $.updateModelContext() \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 $.sendMessage() \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 (`$.updateModelContext`), can speak for the\\n shopper (`$.sendMessage`), 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 `$.generateStructuredContent` 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### Style in `style.css`\\n\\nEach app\'s styles live in `components/<name>/style.css`, imported once at\\nthe top of `component.tsx`:\\n\\n```tsx\\nimport \\"./style.css\\";\\n```\\n\\nWrite ordinary CSS there and use `className` in the component. The sheet\\napplies to your app alone \u2014 it can\'t affect the store\'s page, and the page\\ncan\'t affect your app \u2014 so short class names like `.card` are safe.\\nInline `style={{\u2026}}` still works for values computed at render time.\\n\\nThe rules for `style.css`:\\n\\n- Import only `./style.css`, and only from `component.tsx`. Every other CSS\\n import fails the build.\\n- Keep it self-contained: no `@import`, and `url()` only with `https:` or\\n `data:` URLs \u2014 nothing beside the sheet is uploaded with it.\\n- At most 256 KB.\\n\\n`npx greatstore apps build` minifies the sheet into `bundle.css` beside\\n`bundle.js`; shoppers get that, so comments in `style.css` are for you and\\nnever reach them. Like `bundle.js`, `bundle.css` is generated \u2014 edit\\n`style.css` and build again.\\n\\nThe comment at the top of the scaffolded `style.css` lists the theme\\nvariables below. Style with them rather than fixed values: each store sets\\nits colours, fonts and corner style in its GreatStore dashboard, and an app\\nbuilt on the variables follows those settings.\\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```css\\n/* Bad \u2014 breaks on hosts with a non-default root font size */\\n.card { padding: 1rem; font-size: 0.875rem; }\\n\\n/* Good */\\n.card { padding: 1em; font-size: 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```css\\n/* Bad \u2014 hardcoded, ignores the store\'s theme */\\n.buy { background: #4f46e5; border-radius: 8px; font-family: Inter; }\\n\\n/* Good */\\n.buy {\\n background: var(--color-primary);\\n color: var(--color-primary-foreground);\\n border-radius: var(--radius-lg);\\n font-family: var(--font-primary);\\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 one GreatStore prop, `$`,\\nwhich is always present. Destructure what you need from it at the top of\\nthe component:\\n\\n```tsx\\nexport default function SizeFinder({ category, $ }: Props) {\\n const { callTool, sendMessage, Image } = $;\\n // ...\\n}\\n```\\n\\nNever declare a `$` field in `inputSchema` \u2014 the build refuses it.\\n\\n| `$` member | What it does |\\n| --- | --- |\\n| `$.sendMessage(text)` | Send text into the chat as if the shopper typed it. |\\n| `$.updateModelContext(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 `$.sendMessage` when you want a turn to happen now. |\\n| `$.callTool(name, args?)` | The same call as the page\'s `window.GreatStore.callTool`: run one of the page\'s own WebMCP tools or one of the store\'s read-only connector tools and get its result back, or open one of the store\'s full-screen apps by name. It never touches the conversation \u2014 the assistant doesn\'t learn the call happened (tell it with `$.updateModelContext` if it should). Look up tool names and inputs with `npx greatstore connectors tools` (`webmcp` for page tools). In the app preview, tools run for real and naming a full-screen app only logs what would open. Inside other AI assistants (ChatGPT, \u2026) it always rejects, so handle the rejection. |\\n| `$.showLightbox({ 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| `$.generateStructuredContent(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| `$.close()` | Dismiss the host slot. Over-input clears the overlay, fullscreen reverts the pane, inline is a no-op. |\\n| `$.useVoiceCall()` | A hook \u2014 call it at the top of your component like any other \u2014 returning `{ status, available, start, end }` for a voice call with the store\'s assistant. `start()` starts the call without opening the chat \u2014 it runs in the collapsed chat bar (which stays hidden if the store hides the chat until opened), and the chat opens only when the assistant shows an inline app (call it from a click; it rejects when the store has no voice), `end()` hangs up. `available` says whether the store has voice. `status` is `null` until a call starts, then `started`, `connecting`, `connected`, `listening` / `speaking` / `working` as the conversation goes, `disconnected` while the network drops (the call recovers on its own), and `ended` \u2014 or `rejected` instead of `ended` when the shopper refuses the microphone (calling `start()` again asks again, though a browser where they blocked it refuses without asking). Your app re-renders on every change. |\\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 your own `$` with `Image: \\"img\\"` (or your own component) to render a plain image. |\\n| `$.store` | `{ slug }` \u2014 the store the app is running in. |\\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"}'),Be)}var on={name:"__GS_NAME__",displayName:"__GS_DISPLAY_NAME__",store:"__GS_STORE__",version:"__GS_VERSION__"};function an(e,t){let n=e;for(let o of Object.keys(on)){let s=t[o];s!==void 0&&(n=n.split(on[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 cn=/^[a-z][a-z0-9_]*$/;function un(e){let t=e.positional[0];if(t!==void 0&&!cn.test(t))throw new Error(`Invalid component name: "${t}" (must match ${cn}).`);let n=g(e.flags,"force"),r=y(e.flags,"store"),o=y(e.flags,"out")??".",s=A.resolve(o),i=po(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.`);E({cwd:s})}else if(a=r!==void 0?fe(r):ke()??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=fo(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 ${A.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=A.join(s,"components",t);ho(c,t,n);let p=A.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 po(e){return S.existsSync(A.join(e,"package.json"))&&S.existsSync(A.join(e,".gsrc"))}function fo(e,t,n,r){if(S.mkdirSync(e,{recursive:!0}),!t&&!n&&S.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?wo():yo({store:r.store}),s=go(e,o,n);return S.mkdirSync(A.join(e,"components"),{recursive:!0}),s}var mo=new Set(["AGENTS.md"]);function go(e,t,n){let r=[];for(let[o,s]of t){let i=A.join(e,o);S.mkdirSync(A.dirname(i),{recursive:!0});let a=S.existsSync(i);if(!n&&a&&!mo.has(o))continue;let l=!a||S.readFileSync(i,"utf8")!==s;S.writeFileSync(i,s),l&&r.push(o)}for(let o of["CLAUDE.md","GEMINI.md"]){let s=A.join(e,o);n&&ln(s)&&S.rmSync(s),ln(s)||(S.symlinkSync("AGENTS.md",s),r.push(o))}return r}function ln(e){try{return S.lstatSync(e),!0}catch{return!1}}function ho(e,t,n){if(S.existsSync(e)&&!n&&S.readdirSync(e).length>0)throw new Error(`Refusing to overwrite existing components/${t}/. Pass --force to override.`);S.mkdirSync(e,{recursive:!0});for(let[r,o]of So(t))S.writeFileSync(A.join(e,r),o)}function lt(e,t,n=new Set){let r=sn();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,an(s,t)])}function yo(e){if(!e.store)throw new Error("internal: rootFiles called without a store slug");return lt("root/",{store:e.store,version:O})}function wo(){return lt("root/",{version:O},new Set([".gsrc"]))}function So(e){return lt("component/",{name:e,displayName:bo(e)})}function bo(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 k from"fs";import*as h from"path";import*as me from"fs";import*as ut from"path";var $="style.css",_="bundle.css",De=`./${$}`,pn=256*1024;function xo(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,""),n=[],r=/(?:^|[;{}])\s*import\s+(?:[^'";]*?\s+from\s+)?["']([^"']+\.css)(?:\?[^"']*)?["']/gm,o=/\bimport\s*\(\s*["']([^"']+\.css)(?:\?[^"']*)?["']\s*\)/g;for(let s of t.matchAll(r))n.push(s[1]);for(let s of t.matchAll(o))n.push(s[1]);return n}function N(e){let t=ut.join(e,"component.tsx");if(!me.existsSync(t))return{imported:!1,problems:[]};let n=xo(me.readFileSync(t,"utf8")),r=n.filter(i=>i!==De).map(i=>({file:"component.tsx",message:`imports "${i}". A component's styles go in its own ${$}, imported as "${De}"; move these rules there.`})),o=n.includes(De);if(!o)return{imported:o,problems:r};let s=ut.join(e,$);if(!me.existsSync(s))return r.push({file:"component.tsx",message:`imports "${De}", but there's no ${$} beside it.`}),{imported:o,problems:r};for(let i of $o(me.readFileSync(s,"utf8")))r.push({file:$,message:i});return{imported:o,problems:r}}function $o(e){let t=[],n=Buffer.byteLength(e,"utf8");n>pn&&t.push(`is ${(n/1024).toFixed(1)} KB; the limit is ${pn/1024} KB.`);let r=e.replace(/\/\*[\s\S]*?\*\//g,s=>s.replace(/[^\n]/g," ")),o=s=>r.slice(0,s).split(`
87
+ `).length;for(let s of r.matchAll(/@import\b/gi))t.push(`line ${o(s.index)} uses @import. A stylesheet ships on its own, so copy the rules in instead.`);for(let s of r.matchAll(/url\(\s*(["']?)([^"')]*)\1\s*\)/gi)){let i=s[2].trim();/^(https:|data:|#)/i.test(i)||t.push(`line ${o(s.index)} refers to "${i}". Only https: and data: URLs work here \u2014 nothing beside the stylesheet is uploaded with it.`)}return t}import{createRequire as Oo}from"module";import{pathToFileURL as Ln}from"url";import*as $n from"fs";import*as U from"path";import{createRequire as vo}from"module";import*as He from"path";function dn(e,t,n){let r=gn(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=Po(r,o);return s?Ao(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 ${He.basename(t)} could not be parsed (${o.message})`}}}function mn(e,t,n){let r=gn(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(ko(r,a)){s=!0;return}r.forEachChild(a,i)}};return i(o),s}catch{return!1}}function ko(e,t){if(e.isPropertyAccessExpression(t))return fn(e,t.expression)&&t.name.text==="GreatStore";if(e.isElementAccessExpression(t)){let n=t.argumentExpression;return fn(e,t.expression)&&e.isStringLiteralLike(n)&&n.text==="GreatStore"}return!1}function fn(e,t){return e.isIdentifier(t)&&(t.text==="window"||t.text==="globalThis")}function gn(e){let t=vo(He.join(e,"package.json"));try{return t("typescript")}catch{return null}}function Po(e,t){let n=null;for(let o of t.statements){if(e.isFunctionDeclaration(o)&&Eo(e,o))return o;e.isExportAssignment(o)&&!o.isExportEquals&&(n=o.expression)}if(!n)return null;let r=hn(e,n);return e.isArrowFunction(r)||e.isFunctionExpression(r)?r:e.isIdentifier(r)?Co(e,t,r.text):null}function Eo(e,t){return t.modifiers?.some(n=>n.kind===e.SyntaxKind.DefaultKeyword)??!1}function hn(e,t){let n=t;for(;e.isParenthesizedExpression(n)||e.isAsExpression(n)||e.isSatisfiesExpression(n);)n=n.expression;return n}function Co(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=hn(e,o.initializer);if(e.isArrowFunction(s)||e.isFunctionExpression(s))return s}}return null}function Ao(e,t,n){let r=n.parameters[0];if(!r)return{ok:!0,props:{names:[],open:!1}};if(r.type){let o=pt(e,t,r.type,new Set);if(o)return{ok:!0,props:o}}return e.isObjectBindingPattern(r.name)?{ok:!0,props:jo(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 pt(e,t,n,r){if(e.isTypeLiteralNode(n))return wn(e,n.members);if(e.isTypeReferenceNode(n)&&e.isIdentifier(n.typeName))return yn(e,t,n.typeName.text,r);if(e.isIntersectionTypeNode(n)){let o=n.types.map(s=>pt(e,t,s,r));return o.every(s=>s===null)?null:bn(o.map(s=>s??{names:[],open:!0}))}return null}function yn(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=wn(e,o.members),i=(o.heritageClauses??[]).flatMap(a=>a.types.map(l=>e.isIdentifier(l.expression)?yn(e,t,l.expression.text,r)??{names:[],open:!0}:{names:[],open:!0}));return bn([s,...i])}if(e.isTypeAliasDeclaration(o)&&o.name.text===n)return pt(e,t,o.type,r)}return null}function wn(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=Sn(e,o.name);if(s===null){r=!0;continue}n.push(s)}return{names:n,open:r}}function jo(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=Sn(e,s);i===null?r=!0:n.push(i)}return{names:n,open:r}}function Sn(e,t){return e.isIdentifier(t)||e.isStringLiteral(t)?t.text:null}function bn(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 vn(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=ft(t,o),a=ft(t,s),l=[],c=null,p=xn(o);if(p===null)l.push({severity:"error",rule:"manifest/missing",file:i,message:"manifest not found."});else try{let m=JSON.parse(p);!m||typeof m!="object"||Array.isArray(m)?l.push({severity:"error",rule:"manifest/invalid",file:i,message:"manifest must be a JSON object."}):c=m}catch(m){l.push({severity:"error",rule:"manifest/invalid",file:i,message:`manifest is not valid JSON: ${m.message}`})}let u=xn(s),d=u===null?{ok:!1,reason:`couldn't check props against the manifest \u2014 ${a} not found`}:dn(t,s,u),x=u===null?!1:mn(t,s,u);return{ctx:{name:n,manifestFile:i,sourceFile:a,manifest:c,props:d,usesWindowGreatStore:x,styleFile:ft(t,U.join(r,"style.css")),stylesheet:N(r)},diagnostics:l}}function xn(e){try{return $n.readFileSync(e,"utf8")}catch{return null}}function ft(e,t){let n=U.relative(e,t);return n.startsWith("..")?t:n.split(U.sep).join("/")}var kn=new Set(["$"]);var dt=new Map([["onSendMessage","sendMessage"],["onClose","close"],["onUpdateModelContext","updateModelContext"],["onShowLightbox","showLightbox"],["onGenerateStructuredContent","generateStructuredContent"],["storeData","store"],["Image","Image"],["useVoiceCall","useVoiceCall"]]);function Pn(e){let t=e.map(o=>`\`${o}\``).join(", "),n=e.map(o=>dt.get(o)).join(", "),r=e.length===1;return`${t} ${r?"is":"are"} retired \u2014 new apps must use \`const { ${n} } = $\`. Support for the old ${r?"prop":"props"} can end without notice; migrate before your next release.`}var En=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 An(e){if(!e.manifest)return[];let t=Ro(e.manifest.inputSchema);if(t===null)return[];let n=[];if(t.includes("$")&&n.push({severity:"error",rule:"props/reserved",file:e.manifestFile,message:`${e.manifestFile} declares inputSchema field \`$\`, but GreatStore always passes its own \`$\` prop, so that field can never reach the component. Rename the field.`}),!e.props.ok)return[...n,{severity:"warning",rule:"props/not-analyzable",file:e.sourceFile,message:`${e.props.reason}.`}];if(e.props.props.open)return n;let r=new Set(e.props.props.names),o=new Set(t),s=[];for(let a of e.props.props.names){if(kn.has(a))continue;if(dt.has(a)){s.push(a);continue}let l=En.get(a);if(l){n.push({severity:"warning",rule:"props/retired-lifecycle",file:e.sourceFile,message:l});continue}o.has(a)||n.push({severity:"warning",rule:"props/undeclared",file:e.sourceFile,message:`prop \`${a}\` 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.`})}s.length>0&&n.push({severity:"warning",rule:"props/retired-app-api",file:e.sourceFile,message:Pn(s)});let i=t.filter(a=>a!=="$"&&!r.has(a));return i.length>0&&n.push({severity:"error",rule:"props/missing",file:e.sourceFile,message:_o(e.manifestFile,i)}),n}var Cn=8;function _o(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,Cn).map(s=>`\`${s}\``).join(", "),r=t.length-Cn,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 Ro(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 To=["anyOf","oneOf","allOf","$ref","not"];function Me(e,t,n){if(Array.isArray(e)){e.forEach((s,i)=>Me(s,`${t}[${i}]`,n));return}if(!e||typeof e!="object")return;let r=e;for(let s of To)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,Me(i,`${t}.${s}`,n);"items"in r&&Me(r.items,`${t}[]`,n)}function jn(e){let t=e.manifest?.inputSchema;if(!t||typeof t!="object")return[];let n={bytes:Buffer.byteLength(JSON.stringify(t),"utf8"),fields:0,unionPaths:[]};Me(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("; ")}.
88
+ 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 _n(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 Rn(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 `$` prop (`const { sendMessage, callTool } = $`, \u2026) instead \u2014 those are wired to the surface the component is mounted in."}]:[]}function Tn(e){return e.stylesheet.problems.map(t=>({severity:"error",rule:"stylesheet/invalid",file:t.file==="component.tsx"?e.sourceFile:e.styleFile,message:t.message}))}function Pe(e){return e.filter(t=>t.severity==="error")}function mt(e){return e.filter(t=>t.severity==="warning")}function Ee(e){return`${e.severity==="error"?"error":"warning"} ${e.file}: ${e.message}`}var Lo=[_n,jn,An,Rn,Tn];function Ue(e){let{ctx:t,diagnostics:n}=vn(e);for(let r of Lo)n.push(...r(t));return{diagnostics:n,ok:Pe(n).length===0}}var V="components";async function Ve(e){let t=process.cwd();if(!k.existsSync(h.join(t,"package.json"))||!k.existsSync(h.join(t,V)))throw new Error(`\`npx greatstore apps build\` must run from a project root (contains \`package.json\` and \`${V}/\`). Current dir: ${t}`);let n=No(t);if(n.length===0)return process.stdout.write(`(no components in ./${V} \u2014 run \`npx greatstore apps init <name>\` to add one)
89
+ `),[];let r=e.positional,o=r.filter(c=>!n.includes(c));if(o.length>0)throw new Error(`No component named ${o.map(c=>`"${c}"`).join(", ")} in ./${V}`);let s=r.length>0?n.filter(c=>r.includes(c)):n,i=[],a=[];for(let c of s){let p=Ue({root:t,name:c});for(let u of p.diagnostics)process.stdout.write(` ${Ee(u)}
90
+ `);(p.ok?a:i).push(c)}if(a.length===0)return process.stdout.write(`
91
91
  Nothing built \u2014 fix the errors above.
92
- `),process.exitCode=1,i;let c=await Co(t);for(let l of a)try{await ko(t,l,c)}catch(p){process.stdout.write(` ${G}/${l}: ${p instanceof Error?p.message:String(p)}
93
- `),i.push(l)}return i.length>0?(process.stdout.write(`
92
+ `),process.exitCode=1,i;let l=await Bo(t);for(let c of a)try{await Io(t,c,l)}catch(p){process.stdout.write(` ${V}/${c}: ${p instanceof Error?p.message:String(p)}
93
+ `),i.push(c)}return i.length>0?(process.stdout.write(`
94
94
  Not built (fix the errors above): ${i.join(", ")}
95
- `),process.exitCode=1,i):(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 ko(e,t,{build:n,reactPlugin:r,transformWithEsbuild:o}){let s=h.join(e,G,t),i=h.join(s,"bundle.js");await n({plugins:[Po(s),r()],logLevel:"warn",build:{lib:{entry:h.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=k.statSync(i).size,c=k.readFileSync(i,"utf8"),{code:l}=await o(c,i,{minify:!0,legalComments:"none",target:"esnext",loader:"js",sourcemap:!1});k.writeFileSync(i,l);let p=Buffer.byteLength(l,"utf8");process.stdout.write(`built ${G}/${t}/bundle.js (${An(p)}, ${jn(a,p)} smaller)
96
- `);let u=h.join(s,_);if(!N(s).imported){k.rmSync(u,{force:!0});return}let d=k.readFileSync(h.join(s,$),"utf8"),x=await o(d,h.join(s,$),{minify:!0,legalComments:"none",loader:"css",sourcemap:!1});k.writeFileSync(u,x.code);let m=Buffer.byteLength(x.code,"utf8");process.stdout.write(`built ${G}/${t}/${_} (${An(m)}, ${jn(Buffer.byteLength(d,"utf8"),m)} smaller)
97
- `)}function Po(e){let t=h.join(e,$),n=h.join(e,"component.tsx"),r="\0greatstore-stylesheet";return{name:"greatstore-stylesheet",enforce:"pre",resolveId(o,s){if(!/\.css(\?.*)?$/.test(o))return null;let i=h.resolve(s??n);if(h.resolve(h.dirname(i),o.replace(/\?.*$/,""))===t&&i===n)return r;throw new Error(`${h.relative(e,i)} imports "${o}". A component's styles go in its own ${$}, imported from component.tsx as "./${$}".`)},load(o){return o===r?"export {};":null}}}function Eo(e){let t=h.join(e,G);return k.readdirSync(t).filter(n=>{let r=h.join(t,n);return k.statSync(r).isDirectory()&&k.existsSync(h.join(r,"component.tsx"))}).sort()}function An(e){return e<1024?`${e} B`:`${(e/1024).toFixed(1)} KB`}function jn(e,t){return e===0?"0%":`${Math.round((1-t/e)*100)}%`}async function Co(e){let t=vo(h.join(e,"package.json")),n=_n(t,"vite");if(!n)throw new Error("Cannot find `vite` in this project. Run `npm install` first.");let r=_n(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(Cn(n).href),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(Cn(r).href),c=a.default??a;if(typeof c!="function")throw new Error(`Loaded \`@vitejs/plugin-react\` from ${r} but couldn't find its default export.`);return{build:s,reactPlugin:c,transformWithEsbuild:i}}function _n(e,t){let n;try{n=e.resolve(t)}catch{return null}let r=Ao(n,t);if(!r)return null;let o=h.dirname(r),s;try{s=JSON.parse(k.readFileSync(r,"utf8"))}catch{return null}let a=jo(s.exports)??(typeof s.module=="string"?s.module:null)??(typeof s.main=="string"?s.main:null);return a?h.resolve(o,a):null}function Ao(e,t){let n=h.dirname(e);for(;;){let r=h.join(n,"package.json");if(k.existsSync(r))try{if(JSON.parse(k.readFileSync(r,"utf8")).name===t)return r}catch{}let o=h.dirname(n);if(o===n)return null;n=o}}function jo(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 Tn(e){let t=Ht(),n=`${j(t)}/api/apps/components`,r=await f(n);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(r,null,2)+`
95
+ `),process.exitCode=1,i):(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 Io(e,t,{build:n,reactPlugin:r,transformWithEsbuild:o}){let s=h.join(e,V,t),i=h.join(s,"bundle.js");await n({plugins:[Fo(s),r()],logLevel:"warn",build:{lib:{entry:h.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=k.statSync(i).size,l=k.readFileSync(i,"utf8"),{code:c}=await o(l,i,{minify:!0,legalComments:"none",target:"esnext",loader:"js",sourcemap:!1});k.writeFileSync(i,c);let p=Buffer.byteLength(c,"utf8");process.stdout.write(`built ${V}/${t}/bundle.js (${On(p)}, ${In(a,p)} smaller)
96
+ `);let u=h.join(s,_);if(!N(s).imported){k.rmSync(u,{force:!0});return}let d=k.readFileSync(h.join(s,$),"utf8"),x=await o(d,h.join(s,$),{minify:!0,legalComments:"none",loader:"css",sourcemap:!1});k.writeFileSync(u,x.code);let m=Buffer.byteLength(x.code,"utf8");process.stdout.write(`built ${V}/${t}/${_} (${On(m)}, ${In(Buffer.byteLength(d,"utf8"),m)} smaller)
97
+ `)}function Fo(e){let t=h.join(e,$),n=h.join(e,"component.tsx"),r="\0greatstore-stylesheet";return{name:"greatstore-stylesheet",enforce:"pre",resolveId(o,s){if(!/\.css(\?.*)?$/.test(o))return null;let i=h.resolve(s??n);if(h.resolve(h.dirname(i),o.replace(/\?.*$/,""))===t&&i===n)return r;throw new Error(`${h.relative(e,i)} imports "${o}". A component's styles go in its own ${$}, imported from component.tsx as "./${$}".`)},load(o){return o===r?"export {};":null}}}function No(e){let t=h.join(e,V);return k.readdirSync(t).filter(n=>{let r=h.join(t,n);return k.statSync(r).isDirectory()&&k.existsSync(h.join(r,"component.tsx"))}).sort()}function On(e){return e<1024?`${e} B`:`${(e/1024).toFixed(1)} KB`}function In(e,t){return e===0?"0%":`${Math.round((1-t/e)*100)}%`}async function Bo(e){let t=Oo(h.join(e,"package.json")),n=Fn(t,"vite");if(!n)throw new Error("Cannot find `vite` in this project. Run `npm install` first.");let r=Fn(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(Ln(n).href),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(Ln(r).href),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 Fn(e,t){let n;try{n=e.resolve(t)}catch{return null}let r=Do(n,t);if(!r)return null;let o=h.dirname(r),s;try{s=JSON.parse(k.readFileSync(r,"utf8"))}catch{return null}let a=Ho(s.exports)??(typeof s.module=="string"?s.module:null)??(typeof s.main=="string"?s.main:null);return a?h.resolve(o,a):null}function Do(e,t){let n=h.dirname(e);for(;;){let r=h.join(n,"package.json");if(k.existsSync(r))try{if(JSON.parse(k.readFileSync(r,"utf8")).name===t)return r}catch{}let o=h.dirname(n);if(o===n)return null;n=o}}function Ho(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 Nn(e){let t=Jt(),n=`${j(t)}/api/apps/components`,r=await f(n);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(r,null,2)+`
98
98
  `);return}if(r.components.length===0){process.stdout.write(`(no components in ${t})
99
99
  `);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=`${z("NAME",s.name)} ${z("DRAFT",s.draft)} ${z("LIVE",s.live)} ${z("UPDATED",s.updated)} LINK`;process.stdout.write(i+`
100
100
  `);for(let a of o)process.stdout.write(`${z(a.name,s.name)} ${z(a.draft,s.draft)} ${z(a.live,s.live)} ${z(a.updated,s.updated)} ${a.permalink}
101
- `)}function z(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}import*as T from"fs";import*as V from"path";import*as Rn from"crypto";import*as X from"fs";import*as q from"path";var Ln=".gssync.json";function Q(e){return Rn.createHash("sha256").update(e).digest("hex")}function de(e){return X.existsSync(e)?Q(X.readFileSync(e,"utf8")):null}function me(e){let t=de(q.join(e,"manifest.json"));if(t===null)throw new Error(`Missing manifest.json in ${e}`);return{manifestHash:t,sourceHash:de(q.join(e,"component.tsx")),bundleHash:de(q.join(e,"bundle.js")),...N(e).imported?{styleHash:de(q.join(e,$)),styleBundleHash:de(q.join(e,_))}:{styleHash:null,styleBundleHash:null}}}function ge(e){let t=q.join(e,Ln);if(!X.existsSync(t))return null;try{let n=JSON.parse(X.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}:{},...typeof n.styleHash=="string"?{styleHash:n.styleHash}:{},...typeof n.styleBundleHash=="string"?{styleBundleHash:n.styleBundleHash}:{}}:null}catch{return null}}function se(e,t){X.writeFileSync(q.join(e,Ln),JSON.stringify(t,null,2)+`
102
- `)}function On(e,t){let n=_o(e);if(!n)return!1;if(t===null||n.manifestHash!==t.manifestHash)return!0;let r=n.sourceHash??"",o=t.sourceHash??"";return r!==o?!0:(de(q.join(e,$))??"")!==(t.styleHash??"")}function _o(e){try{return me(e)}catch{return null}}async function In(e){let t=E(),n=g(e.flags,"force"),r=e.positional,o=process.cwd();if(r.length===0||r.length===1&&r[0]==="*")return To({slug:t,root:o,args:e,force:n});if(r.length>1&&y(e.flags,"version"))throw new Error("--version is per-component; pass it together with a single `npx greatstore apps pull <name>`.");Bn(o);let s=Dn(e),i=[];for(let a of r){let c=await Nn({slug:t,componentDir:V.join(o,"components",a),name:a,revisionQuery:s,force:n});i.push(c),Hn(c,n)}i.length>1&&Fn(i,t),i.some(a=>a.status==="failed")&&(process.exitCode=1)}async function To(e){let{slug:t,root:n,args:r,force:o}=e;if(y(r.flags,"version"))throw new Error("--version is per-component; pass it together with `npx greatstore apps pull <name>`.");Bn(n);let s=Dn(r),i=`${j(t)}/api/apps/components`,a=await f(i);if(a.components.length===0){process.stdout.write(`(no components in ${t})
103
- `);return}let c=[];for(let l of a.components){let p=V.join(n,"components",l.name),u=await Nn({slug:t,componentDir:p,name:l.name,revisionQuery:s===""&&l.live===null?"?revision=draft":s,force:o});c.push(u),Hn(u,o)}Fn(c,t),c.some(l=>l.status==="failed")&&(process.exitCode=1)}function Fn(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
+ `)}function z(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}import*as R from"fs";import*as q from"path";import*as Bn from"crypto";import*as X from"fs";import*as G from"path";var Dn=".gssync.json";function Q(e){return Bn.createHash("sha256").update(e).digest("hex")}function ge(e){return X.existsSync(e)?Q(X.readFileSync(e,"utf8")):null}function he(e){let t=ge(G.join(e,"manifest.json"));if(t===null)throw new Error(`Missing manifest.json in ${e}`);return{manifestHash:t,sourceHash:ge(G.join(e,"component.tsx")),bundleHash:ge(G.join(e,"bundle.js")),...N(e).imported?{styleHash:ge(G.join(e,$)),styleBundleHash:ge(G.join(e,_))}:{styleHash:null,styleBundleHash:null}}}function ye(e){let t=G.join(e,Dn);if(!X.existsSync(t))return null;try{let n=JSON.parse(X.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}:{},...typeof n.styleHash=="string"?{styleHash:n.styleHash}:{},...typeof n.styleBundleHash=="string"?{styleBundleHash:n.styleBundleHash}:{}}:null}catch{return null}}function ie(e,t){X.writeFileSync(G.join(e,Dn),JSON.stringify(t,null,2)+`
102
+ `)}function Hn(e,t){let n=Mo(e);if(!n)return!1;if(t===null||n.manifestHash!==t.manifestHash)return!0;let r=n.sourceHash??"",o=t.sourceHash??"";return r!==o?!0:(ge(G.join(e,$))??"")!==(t.styleHash??"")}function Mo(e){try{return he(e)}catch{return null}}async function Mn(e){let t=E(),n=g(e.flags,"force"),r=e.positional,o=process.cwd();if(r.length===0||r.length===1&&r[0]==="*")return Uo({slug:t,root:o,args:e,force:n});if(r.length>1&&y(e.flags,"version"))throw new Error("--version is per-component; pass it together with a single `npx greatstore apps pull <name>`.");Gn(o);let s=qn(e),i=[];for(let a of r){let l=await Vn({slug:t,componentDir:q.join(o,"components",a),name:a,revisionQuery:s,force:n});i.push(l),Jn(l,n)}i.length>1&&Un(i,t),i.some(a=>a.status==="failed")&&(process.exitCode=1)}async function Uo(e){let{slug:t,root:n,args:r,force:o}=e;if(y(r.flags,"version"))throw new Error("--version is per-component; pass it together with `npx greatstore apps pull <name>`.");Gn(n);let s=qn(r),i=`${j(t)}/api/apps/components`,a=await f(i);if(a.components.length===0){process.stdout.write(`(no components in ${t})
103
+ `);return}let l=[];for(let c of a.components){let p=q.join(n,"components",c.name),u=await Vn({slug:t,componentDir:p,name:c.name,revisionQuery:s===""&&c.live===null?"?revision=draft":s,force:o});l.push(u),Jn(u,o)}Un(l,t),l.some(c=>c.status==="failed")&&(process.exitCode=1)}function Un(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(`
104
104
  ${s.join(", ")} (of ${e.length}) \u2190 ${t}
105
- `)}async function Nn(e){let{slug:t,componentDir:n,name:r,revisionQuery:o,force:s}=e;if(!s&&T.existsSync(n)){let m=ge(n);if(On(n,m))return{name:r,status:"skipped",message:"local has uncommitted changes; pass --force to overwrite"}}let i=`${j(t)}/api/apps/components/${encodeURIComponent(r)}`,a;try{a=await f(`${i}${o}`)}catch(m){if(o===""&&Ro(m))try{a=await f(`${i}?revision=draft`)}catch(ie){return{name:r,status:"failed",message:ie instanceof Error?ie.message:String(ie)}}else return{name:r,status:"failed",message:m instanceof Error?m.message:String(m)}}T.mkdirSync(n,{recursive:!0});let c=JSON.stringify(a.manifest,null,2)+`
106
- `;T.writeFileSync(V.join(n,"manifest.json"),c),T.writeFileSync(V.join(n,"bundle.js"),a.bundle);let l=["manifest.json","bundle.js"],p="";a.source!==null&&(T.writeFileSync(V.join(n,"component.tsx"),a.source),l.push("component.tsx"),p=Q(a.source));let u=V.join(n,$),d=V.join(n,_);typeof a.style=="string"?(T.writeFileSync(u,a.style),T.writeFileSync(d,a.style_bundle??a.style),l.push($,_)):(T.rmSync(u,{force:!0}),T.rmSync(d,{force:!0})),se(n,{version:a.version,manifestHash:Q(c),sourceHash:p,bundleHash:Q(a.bundle)});let x=me(n);return se(n,{version:a.version,manifestHash:x.manifestHash,sourceHash:x.sourceHash??"",bundleHash:x.bundleHash??"",styleHash:x.styleHash??"",styleBundleHash:x.styleBundleHash??""}),{name:r,status:"pulled",version:a.version,wrote:l}}function Bn(e){T.mkdirSync(V.join(e,"components"),{recursive:!0})}function Ro(e){return e instanceof D&&e.status===404}function Dn(e){let t=y(e.flags,"version");return t?`?version=${encodeURIComponent(t)}`:g(e.flags,"draft")?"?revision=draft":g(e.flags,"live")?"?revision=live":""}function Hn(e,t){switch(e.status){case"pulled":{let n=e.wrote?`{${e.wrote.join(", ")}}`:"";process.stdout.write(` pulled ${e.name} v${e.version} ${n}
105
+ `)}async function Vn(e){let{slug:t,componentDir:n,name:r,revisionQuery:o,force:s}=e;if(!s&&R.existsSync(n)){let m=ye(n);if(Hn(n,m))return{name:r,status:"skipped",message:"local has uncommitted changes; pass --force to overwrite"}}let i=`${j(t)}/api/apps/components/${encodeURIComponent(r)}`,a;try{a=await f(`${i}${o}`)}catch(m){if(o===""&&Vo(m))try{a=await f(`${i}?revision=draft`)}catch(ae){return{name:r,status:"failed",message:ae instanceof Error?ae.message:String(ae)}}else return{name:r,status:"failed",message:m instanceof Error?m.message:String(m)}}R.mkdirSync(n,{recursive:!0});let l=JSON.stringify(a.manifest,null,2)+`
106
+ `;R.writeFileSync(q.join(n,"manifest.json"),l),R.writeFileSync(q.join(n,"bundle.js"),a.bundle);let c=["manifest.json","bundle.js"],p="";a.source!==null&&(R.writeFileSync(q.join(n,"component.tsx"),a.source),c.push("component.tsx"),p=Q(a.source));let u=q.join(n,$),d=q.join(n,_);typeof a.style=="string"?(R.writeFileSync(u,a.style),R.writeFileSync(d,a.style_bundle??a.style),c.push($,_)):(R.rmSync(u,{force:!0}),R.rmSync(d,{force:!0})),ie(n,{version:a.version,manifestHash:Q(l),sourceHash:p,bundleHash:Q(a.bundle)});let x=he(n);return ie(n,{version:a.version,manifestHash:x.manifestHash,sourceHash:x.sourceHash??"",bundleHash:x.bundleHash??"",styleHash:x.styleHash??"",styleBundleHash:x.styleBundleHash??""}),{name:r,status:"pulled",version:a.version,wrote:c}}function Gn(e){R.mkdirSync(q.join(e,"components"),{recursive:!0})}function Vo(e){return e instanceof D&&e.status===404}function qn(e){let t=y(e.flags,"version");return t?`?version=${encodeURIComponent(t)}`:g(e.flags,"draft")?"?revision=draft":g(e.flags,"live")?"?revision=live":""}function Jn(e,t){switch(e.status){case"pulled":{let n=e.wrote?`{${e.wrote.join(", ")}}`:"";process.stdout.write(` pulled ${e.name} v${e.version} ${n}
107
107
  `);return}case"skipped":process.stdout.write(` skipped ${e.name}: ${e.message}
108
108
  `);return;case"failed":process.stdout.write(` failed ${e.name}: ${e.message??"unknown error"}
109
- `);return}}import*as b from"fs";import*as P from"path";import*as Mn from"crypto";import*as Ue from"fs";import*as Un from"path";function Ge(e){let t=e?.screenshots;return Array.isArray(t)?[...new Set(t.filter(n=>typeof n=="string"))]:null}function Lo(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 Gn(e){let t=Lo(e);return t?`${Mn.createHash("sha256").update(e).digest("hex").slice(0,16)}.${t}`:null}function qe(e,t){let n=Un.join(e,t);return Ue.existsSync(n)?Ue.readFileSync(n):null}async function Jn(e){let t=E(),n=process.cwd();Oo(n);let r=P.join(n,"components");if(!b.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=y(e.flags,"manifest"),i=y(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 l=g(e.flags,"force")||s!==void 0||i!==void 0,p=[];for(let u of o){let d=await Je({slug:t,root:n,name:u,...s!==void 0?{manifestPath:s}:{},...i!==void 0?{bundlePath:i}:{},force:l});p.push(d),Vn(d)}p.length>1&&qn(p,t),p.some(u=>u.status==="failed")&&(process.exitCode=1);return}let a=dt(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 c=[];for(let l of a){let p=await Je({slug:t,root:n,name:l,force:!1});c.push(p),Vn(p)}qn(c,t),c.some(l=>l.status==="failed")&&(process.exitCode=1)}function qn(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(`
109
+ `);return}}import*as b from"fs";import*as P from"path";import*as Kn from"crypto";import*as Ge from"fs";import*as Wn from"path";function qe(e){let t=e?.screenshots;return Array.isArray(t)?[...new Set(t.filter(n=>typeof n=="string"))]:null}function Go(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 Yn(e){let t=Go(e);return t?`${Kn.createHash("sha256").update(e).digest("hex").slice(0,16)}.${t}`:null}function Je(e,t){let n=Wn.join(e,t);return Ge.existsSync(n)?Ge.readFileSync(n):null}async function Qn(e){let t=E(),n=process.cwd();qo(n);let r=P.join(n,"components");if(!b.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=y(e.flags,"manifest"),i=y(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=g(e.flags,"force")||s!==void 0||i!==void 0,p=[];for(let u of o){let d=await We({slug:t,root:n,name:u,...s!==void 0?{manifestPath:s}:{},...i!==void 0?{bundlePath:i}:{},force:c});p.push(d),Xn(d)}p.length>1&&zn(p,t),p.some(u=>u.status==="failed")&&(process.exitCode=1);return}let a=gt(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 We({slug:t,root:n,name:c,force:!1});l.push(p),Xn(p)}zn(l,t),l.some(c=>c.status==="failed")&&(process.exitCode=1)}function zn(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(`
110
110
  ${s.join(", ")} (of ${e.length}) \u2192 ${t}
111
- `)}async function Je(e){let{slug:t,root:n,name:r,force:o}=e,s=P.join(n,"components",r);if(!b.existsSync(s))return{name:r,status:"failed",message:`components/${r}/ does not exist`};let i=e.manifestPath?P.resolve(e.manifestPath):P.join(s,"manifest.json"),a=e.bundlePath?P.resolve(e.bundlePath):P.join(s,"bundle.js"),c=P.join(s,"component.tsx");if(!b.existsSync(a))return{name:r,status:"failed",message:`bundle not found: ${a} (did you run \`npm run build\`?)`};let l=He({root:n,name:r,manifestPath:i,sourcePath:c});for(let O of ft(l.diagnostics))process.stdout.write(` ${ve(O)}
112
- `);if(!l.ok)return{name:r,status:"failed",message:$e(l.diagnostics).map(O=>`${O.file}: ${O.message}`).join(`
113
- ${Ve}`)};let p=b.readFileSync(i,"utf8"),u=P.join(s,"listing.json"),d=be(t);if(d&&!b.existsSync(u))return{name:r,status:"failed",message:`components/${r}/listing.json is required for a library app`};let x=me(s),m=ge(s),ie=e.bundlePath===void 0&&m?.bundleHash!==void 0&&m.sourceHash!==(x.sourceHash??"")&&m.bundleHash===(x.bundleHash??""),Ee=m?.styleBundleHash!==void 0&&(m.styleHash??"")!==(x.styleHash??"")&&m.styleBundleHash===(x.styleBundleHash??""),bt=N(s).imported,xt=P.join(s,_);if(bt&&!b.existsSync(xt))return{name:r,status:"failed",message:`components/${r}/${_} is missing \u2014 run \`npx greatstore build ${r}\` first`};if(!o&&m!==null&&m.manifestHash===x.manifestHash&&m.sourceHash===(x.sourceHash??"")&&m.bundleHash!==void 0&&m.bundleHash===(x.bundleHash??"")&&(m.styleHash??"")===(x.styleHash??"")&&(m.styleBundleHash??"")===(x.styleBundleHash??""))return{name:r,status:"unchanged"};let vr=b.readFileSync(a,"utf8"),$t=b.existsSync(c)?b.readFileSync(c,"utf8"):null,B=new FormData;if(B.append("manifest",new Blob([p],{type:"application/json"}),"manifest.json"),B.append("bundle",new Blob([vr],{type:"text/javascript"}),"bundle.js"),$t!==null&&B.append("source",new Blob([$t],{type:"text/plain; charset=utf-8"}),"component.tsx"),bt&&(B.append("style",new Blob([b.readFileSync(xt,"utf8")],{type:"text/css; charset=utf-8"}),_),B.append("style_source",new Blob([b.readFileSync(P.join(s,$),"utf8")],{type:"text/css; charset=utf-8"}),$)),d){let O=b.readFileSync(u,"utf8");B.append("listing",new Blob([O],{type:"application/json"}),"listing.json");let vt=P.join(s,"changelog.json");b.existsSync(vt)&&B.append("changelog",new Blob([b.readFileSync(vt,"utf8")],{type:"application/json"}),"changelog.json");let kt=null;try{kt=Ge(JSON.parse(O))}catch{}for(let Ze of kt??[]){let Pt=qe(s,Ze);if(!Pt)return{name:r,status:"failed",message:`components/${r}/${Ze} is named in listing.json but doesn't exist`};B.append("screenshot",new Blob([new Uint8Array(Pt)]),Ze)}}o||B.append("base_version",String(m?.version??0));let kr=`${Oe(t)}/components/${encodeURIComponent(r)}`,ae;try{ae=await f(kr,{method:"POST",multipart:B})}catch(O){return{name:r,status:"failed",message:O instanceof Error?O.message:String(O)}}let Se=me(s);return se(s,{version:ae.version,manifestHash:Se.manifestHash,sourceHash:Se.sourceHash??"",bundleHash:Se.bundleHash??"",styleHash:Se.styleHash??"",styleBundleHash:Se.styleBundleHash??""}),{name:r,status:"pushed",version:ae.version,...ae.permalink!==void 0&&{permalink:ae.permalink},...ae.detached&&{detached:!0},...ie?{staleBundle:!0}:{},...Ee?{staleStyle:!0}:{}}}function dt(e){return b.readdirSync(e).filter(t=>{let n=P.join(e,t);return b.statSync(n).isDirectory()&&b.existsSync(P.join(n,"manifest.json"))}).sort()}function Oo(e){let t=P.join(e,"manifest.json"),n=P.join(e,"components");if(b.existsSync(t)&&!b.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 Ve=" ".repeat(12);function Vn(e){switch(e.status){case"pushed":process.stdout.write(` pushed ${e.name} v${e.version}${e.permalink?` \u2192 ${e.permalink}`:""}
114
- `),e.detached&&process.stdout.write(`${Ve}This was a ready-made app GreatStore keeps up to date. It's now your own copy and won't get those updates.
115
- `),e.staleBundle&&process.stdout.write(`${Ve}component.tsx changed but bundle.js did not \u2014 did you forget to build? Run \`npx greatstore build ${e.name}\` and push again.
116
- `),e.staleStyle&&process.stdout.write(`${Ve}style.css changed but bundle.css did not \u2014 did you forget to build? Run \`npx greatstore build ${e.name}\` and push again.
111
+ `)}async function We(e){let{slug:t,root:n,name:r,force:o}=e,s=P.join(n,"components",r);if(!b.existsSync(s))return{name:r,status:"failed",message:`components/${r}/ does not exist`};let i=e.manifestPath?P.resolve(e.manifestPath):P.join(s,"manifest.json"),a=e.bundlePath?P.resolve(e.bundlePath):P.join(s,"bundle.js"),l=P.join(s,"component.tsx");if(!b.existsSync(a))return{name:r,status:"failed",message:`bundle not found: ${a} (did you run \`npm run build\`?)`};let c=Ue({root:n,name:r,manifestPath:i,sourcePath:l});for(let I of mt(c.diagnostics))process.stdout.write(` ${Ee(I)}
112
+ `);if(!c.ok)return{name:r,status:"failed",message:Pe(c.diagnostics).map(I=>`${I.file}: ${I.message}`).join(`
113
+ ${Ke}`)};let p=b.readFileSync(i,"utf8"),u=P.join(s,"listing.json"),d=ve(t);if(d&&!b.existsSync(u))return{name:r,status:"failed",message:`components/${r}/listing.json is required for a library app`};let x=he(s),m=ye(s),ae=e.bundlePath===void 0&&m?.bundleHash!==void 0&&m.sourceHash!==(x.sourceHash??"")&&m.bundleHash===(x.bundleHash??""),je=m?.styleBundleHash!==void 0&&(m.styleHash??"")!==(x.styleHash??"")&&m.styleBundleHash===(x.styleBundleHash??""),Et=N(s).imported,Ct=P.join(s,_);if(Et&&!b.existsSync(Ct))return{name:r,status:"failed",message:`components/${r}/${_} is missing \u2014 run \`npx greatstore build ${r}\` first`};if(!o&&m!==null&&m.manifestHash===x.manifestHash&&m.sourceHash===(x.sourceHash??"")&&m.bundleHash!==void 0&&m.bundleHash===(x.bundleHash??"")&&(m.styleHash??"")===(x.styleHash??"")&&(m.styleBundleHash??"")===(x.styleBundleHash??""))return{name:r,status:"unchanged"};let Ir=b.readFileSync(a,"utf8"),At=b.existsSync(l)?b.readFileSync(l,"utf8"):null,B=new FormData;if(B.append("manifest",new Blob([p],{type:"application/json"}),"manifest.json"),B.append("bundle",new Blob([Ir],{type:"text/javascript"}),"bundle.js"),At!==null&&B.append("source",new Blob([At],{type:"text/plain; charset=utf-8"}),"component.tsx"),Et&&(B.append("style",new Blob([b.readFileSync(Ct,"utf8")],{type:"text/css; charset=utf-8"}),_),B.append("style_source",new Blob([b.readFileSync(P.join(s,$),"utf8")],{type:"text/css; charset=utf-8"}),$)),d){let I=b.readFileSync(u,"utf8");B.append("listing",new Blob([I],{type:"application/json"}),"listing.json");let jt=P.join(s,"changelog.json");b.existsSync(jt)&&B.append("changelog",new Blob([b.readFileSync(jt,"utf8")],{type:"application/json"}),"changelog.json");let _t=null;try{_t=qe(JSON.parse(I))}catch{}for(let tt of _t??[]){let Rt=Je(s,tt);if(!Rt)return{name:r,status:"failed",message:`components/${r}/${tt} is named in listing.json but doesn't exist`};B.append("screenshot",new Blob([new Uint8Array(Rt)]),tt)}}o||B.append("base_version",String(m?.version??0));let Fr=`${Fe(t)}/components/${encodeURIComponent(r)}`,ce;try{ce=await f(Fr,{method:"POST",multipart:B})}catch(I){return{name:r,status:"failed",message:I instanceof Error?I.message:String(I)}}let $e=he(s);return ie(s,{version:ce.version,manifestHash:$e.manifestHash,sourceHash:$e.sourceHash??"",bundleHash:$e.bundleHash??"",styleHash:$e.styleHash??"",styleBundleHash:$e.styleBundleHash??""}),{name:r,status:"pushed",version:ce.version,...ce.permalink!==void 0&&{permalink:ce.permalink},...ce.detached&&{detached:!0},...ae?{staleBundle:!0}:{},...je?{staleStyle:!0}:{}}}function gt(e){return b.readdirSync(e).filter(t=>{let n=P.join(e,t);return b.statSync(n).isDirectory()&&b.existsSync(P.join(n,"manifest.json"))}).sort()}function qo(e){let t=P.join(e,"manifest.json"),n=P.join(e,"components");if(b.existsSync(t)&&!b.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 Ke=" ".repeat(12);function Xn(e){switch(e.status){case"pushed":process.stdout.write(` pushed ${e.name} v${e.version}${e.permalink?` \u2192 ${e.permalink}`:""}
114
+ `),e.detached&&process.stdout.write(`${Ke}This was a ready-made app GreatStore keeps up to date. It's now your own copy and won't get those updates.
115
+ `),e.staleBundle&&process.stdout.write(`${Ke}component.tsx changed but bundle.js did not \u2014 did you forget to build? Run \`npx greatstore build ${e.name}\` and push again.
116
+ `),e.staleStyle&&process.stdout.write(`${Ke}style.css changed but bundle.css did not \u2014 did you forget to build? Run \`npx greatstore build ${e.name}\` and push again.
117
117
  `);return;case"unchanged":process.stdout.write(` unchanged ${e.name}
118
118
  `);return;case"failed":process.stdout.write(` failed ${e.name}: ${e.message??"unknown error"}
119
- `);return}}async function Yn(e){let t=e.positional;if(t.length===0)throw new Error("Usage: npx greatstore apps publish <name> [<name>...] [--version N]");let n=E(),r=y(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 l=Number.parseInt(r,10);if(!Number.isInteger(l)||l<1)throw new Error(`Invalid --version: ${r}`);o=l}if(t.length===1){let l=t[0],p=await Kn(n,l,o);process.stdout.write(`Published ${l} (v${p.live_version}). ${p.permalink}
120
- `),p.embed_snippet&&Wn(l,p.embed_snippet);return}let s=[];for(let l of t){let p;try{let u=await Kn(n,l,o);p={name:l,status:"published",version:u.live_version,permalink:u.permalink,...u.embed_snippet?{snippet:u.embed_snippet}:{}}}catch(u){p={name:l,status:"failed",message:u instanceof Error?u.message:String(u)}}s.push(p),Io(p)}for(let l of s)l.snippet&&Wn(l.name,l.snippet);let i=s.filter(l=>l.status==="published").length,a=s.filter(l=>l.status==="failed").length,c=[`${i} published`];a>0&&c.push(`${a} failed`),process.stdout.write(`
121
- ${c.join(", ")} (of ${s.length}) \u2192 ${n}
122
- `),a>0&&(process.exitCode=1)}async function Kn(e,t,n){let r=`${j(e)}/api/apps/components/${encodeURIComponent(t)}/publish`;return f(r,{method:"POST",body:n!==void 0?{version:n}:{}})}function Wn(e,t){process.stdout.write(`
119
+ `);return}}async function tr(e){let t=e.positional;if(t.length===0)throw new Error("Usage: npx greatstore apps publish <name> [<name>...] [--version N]");let n=E(),r=y(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 Zn(n,c,o);process.stdout.write(`Published ${c} (v${p.live_version}). ${p.permalink}
120
+ `),p.embed_snippet&&er(c,p.embed_snippet);return}let s=[];for(let c of t){let p;try{let u=await Zn(n,c,o);p={name:c,status:"published",version:u.live_version,permalink:u.permalink,...u.embed_snippet?{snippet:u.embed_snippet}:{}}}catch(u){p={name:c,status:"failed",message:u instanceof Error?u.message:String(u)}}s.push(p),Jo(p)}for(let c of s)c.snippet&&er(c.name,c.snippet);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(`
121
+ ${l.join(", ")} (of ${s.length}) \u2192 ${n}
122
+ `),a>0&&(process.exitCode=1)}async function Zn(e,t,n){let r=`${j(e)}/api/apps/components/${encodeURIComponent(t)}/publish`;return f(r,{method:"POST",body:n!==void 0?{version:n}:{}})}function er(e,t){process.stdout.write(`
123
123
  Put ${e} on your site by pasting this where you want it:
124
124
 
125
125
  ${t.split(`
@@ -127,16 +127,16 @@ ${t.split(`
127
127
  `)}
128
128
 
129
129
  If the GreatStore script is already on the page, the second line is enough.
130
- `)}function Io(e){if(e.status==="published"){process.stdout.write(` published ${e.name} v${e.version} \u2192 ${e.permalink??""}
130
+ `)}function Jo(e){if(e.status==="published"){process.stdout.write(` published ${e.name} v${e.version} \u2192 ${e.permalink??""}
131
131
  `);return}process.stdout.write(` failed ${e.name}: ${e.message??"unknown error"}
132
- `)}async function zn(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore apps unpublish <name>");let n=E(),r=`${j(n)}/api/apps/components/${encodeURIComponent(t)}/unpublish`;await f(r,{method:"POST",body:{}}),process.stdout.write(`Unpublished ${t}.
133
- `)}import*as Xn from"readline";async function Qn(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore apps delete <name> [--yes]");let n=E();if(!g(e.flags,"yes")&&(await Fo(`Soft-delete component "${t}" in store "${n}"? Type "yes" to confirm: `)).trim()!=="yes"){process.stdout.write(`Aborted.
132
+ `)}async function nr(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore apps unpublish <name>");let n=E(),r=`${j(n)}/api/apps/components/${encodeURIComponent(t)}/unpublish`;await f(r,{method:"POST",body:{}}),process.stdout.write(`Unpublished ${t}.
133
+ `)}import*as rr from"readline";async function or(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore apps delete <name> [--yes]");let n=E();if(!g(e.flags,"yes")&&(await Ko(`Soft-delete component "${t}" in store "${n}"? Type "yes" to confirm: `)).trim()!=="yes"){process.stdout.write(`Aborted.
134
134
  `);return}let r=`${j(n)}/api/apps/components/${encodeURIComponent(t)}`;await f(r,{method:"DELETE"}),process.stdout.write(`Deleted ${t}.
135
- `)}function Fo(e){return new Promise(t=>{let n=Xn.createInterface({input:process.stdin,output:process.stdout});n.question(e,r=>{n.close(),t(r)})})}import*as H from"fs";import*as Ke from"path";var No=/^[a-z][a-z0-9_]*$/;async function Zn(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(!No.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=E(),o=Ke.join(process.cwd(),"components",t),s=Ke.join(process.cwd(),"components",n),i=H.existsSync(o);if(H.existsSync(s))throw new Error(`components/${n}/ already exists; move it aside first.`);let a=`${j(r)}/api/apps/components/${encodeURIComponent(t)}/rename`;if(await f(a,{method:"POST",body:{name:n}}),!i){process.stdout.write(`Renamed ${t} \u2192 ${n}.
136
- `);return}H.renameSync(o,s),Bo(s,n),process.stdout.write(`Renamed ${t} \u2192 ${n}, including components/${n}/.
137
- `)}function Bo(e,t){let n=Ke.join(e,"manifest.json");if(!H.existsSync(n))return;let r=H.readFileSync(n,"utf8"),o=JSON.stringify({...JSON.parse(r),name:t},null,2)+`
138
- `;H.writeFileSync(n,o);let s=ge(e);s&&s.manifestHash===Q(r)&&se(e,{...s,manifestHash:Q(o)})}import*as Z from"fs";import*as ke from"path";async function er(e){let t=E();if(!be(t))throw new Error("`npx greatstore apps release` runs only in the app library's folder.");let n=ot();Ft(await Go(new URL(n).origin));let r=await Me({command:"build",positional:[],flags:{}});process.exitCode=0;let o=process.cwd(),s=Oe(t),i=ke.join(o,"components"),a=dt(i),c=Z.readdirSync(i).filter(u=>Z.statSync(ke.join(i,u)).isDirectory()),l=(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 Do(s,o,t,u));for(let u of c.filter(d=>!a.includes(d)))p.push({name:u,status:"failed",message:`components/${u}/manifest.json is missing`});for(let u of l.filter(d=>!c.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:tr(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}
139
- `)}p.some(u=>u.status==="failed")&&(process.exitCode=1)}async function Do(e,t,n,r){try{let o=await Ho(e,r);if(o&&Mo(o,ke.join(t,"components",r)))return{name:r,status:"unchanged"};let s=await Je({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:tr(o)}}}async function Ho(e,t){try{return await f(`${e}/components/${encodeURIComponent(t)}?revision=live`)}catch(n){if(n instanceof D&&n.status===404)return null;throw n}}function Mo(e,t){let n=i=>{let a=ke.join(t,i);return Z.existsSync(a)?Z.readFileSync(a,"utf8"):null},r=n("manifest.json"),o=n("listing.json"),s=n("changelog.json");if(r===null||o===null)return!1;try{return e.bundle===n("bundle.js")&&e.source===n("component.tsx")&&(e.style??null)===(N(t).imported?n($):null)&&(e.style_bundle??e.style??null)===(N(t).imported?n(_):null)&&he(e.manifest)===he(JSON.parse(r))&&he(e.listing)===he(Uo(JSON.parse(o),t))&&he(e.changelog??null)===he(s===null?null:We(JSON.parse(s)))}catch{return!1}}function Uo(e,t){let n=We(e),r=Ge(n);return r?{...n,screenshots:r.map(o=>{let s=qe(t,o);return(s&&Gn(s))??o})}:n}function We(e){return typeof e=="string"?e.trim():Array.isArray(e)?e.map(We):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,We(n)])):e}function he(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 Go(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 tr(e){return e instanceof Error?e.message:String(e)}var nr=`npx greatstore apps \u2014 author and ship custom in-chat apps
135
+ `)}function Ko(e){return new Promise(t=>{let n=rr.createInterface({input:process.stdin,output:process.stdout});n.question(e,r=>{n.close(),t(r)})})}import*as H from"fs";import*as Ye from"path";var Wo=/^[a-z][a-z0-9_]*$/;async function sr(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(!Wo.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=E(),o=Ye.join(process.cwd(),"components",t),s=Ye.join(process.cwd(),"components",n),i=H.existsSync(o);if(H.existsSync(s))throw new Error(`components/${n}/ already exists; move it aside first.`);let a=`${j(r)}/api/apps/components/${encodeURIComponent(t)}/rename`;if(await f(a,{method:"POST",body:{name:n}}),!i){process.stdout.write(`Renamed ${t} \u2192 ${n}.
136
+ `);return}H.renameSync(o,s),Yo(s,n),process.stdout.write(`Renamed ${t} \u2192 ${n}, including components/${n}/.
137
+ `)}function Yo(e,t){let n=Ye.join(e,"manifest.json");if(!H.existsSync(n))return;let r=H.readFileSync(n,"utf8"),o=JSON.stringify({...JSON.parse(r),name:t},null,2)+`
138
+ `;H.writeFileSync(n,o);let s=ye(e);s&&s.manifestHash===Q(r)&&ie(e,{...s,manifestHash:Q(o)})}import*as Z from"fs";import*as Ce from"path";async function ir(e){let t=E();if(!ve(t))throw new Error("`npx greatstore apps release` runs only in the app library's folder.");let n=it();Ut(await es(new URL(n).origin));let r=await Ve({command:"build",positional:[],flags:{}});process.exitCode=0;let o=process.cwd(),s=Fe(t),i=Ce.join(o,"components"),a=gt(i),l=Z.readdirSync(i).filter(u=>Z.statSync(Ce.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 zo(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:ar(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}
139
+ `)}p.some(u=>u.status==="failed")&&(process.exitCode=1)}async function zo(e,t,n,r){try{let o=await Xo(e,r);if(o&&Qo(o,Ce.join(t,"components",r)))return{name:r,status:"unchanged"};let s=await We({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:ar(o)}}}async function Xo(e,t){try{return await f(`${e}/components/${encodeURIComponent(t)}?revision=live`)}catch(n){if(n instanceof D&&n.status===404)return null;throw n}}function Qo(e,t){let n=i=>{let a=Ce.join(t,i);return Z.existsSync(a)?Z.readFileSync(a,"utf8"):null},r=n("manifest.json"),o=n("listing.json"),s=n("changelog.json");if(r===null||o===null)return!1;try{return e.bundle===n("bundle.js")&&e.source===n("component.tsx")&&(e.style??null)===(N(t).imported?n($):null)&&(e.style_bundle??e.style??null)===(N(t).imported?n(_):null)&&we(e.manifest)===we(JSON.parse(r))&&we(e.listing)===we(Zo(JSON.parse(o),t))&&we(e.changelog??null)===we(s===null?null:ze(JSON.parse(s)))}catch{return!1}}function Zo(e,t){let n=ze(e),r=qe(n);return r?{...n,screenshots:r.map(o=>{let s=Je(t,o);return(s&&Yn(s))??o})}:n}function ze(e){return typeof e=="string"?e.trim():Array.isArray(e)?e.map(ze):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,ze(n)])):e}function we(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 es(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 ar(e){return e instanceof Error?e.message:String(e)}var cr=`npx greatstore apps \u2014 author and ship custom in-chat apps
140
140
 
141
141
  Usage:
142
142
  npx greatstore apps <subcommand> [args] [flags]
@@ -151,53 +151,63 @@ Subcommands:
151
151
  unpublish <name> Clear the live pointer.
152
152
  rename <old> <new> Rename a component, keeping its versions and live state.
153
153
  delete <name> Soft-delete the component.
154
- `;async function mt(e){let t=e.positional[0],n={...e,positional:e.positional.slice(1)};switch(t){case void 0:case"help":return process.stdout.write(nr),0;case"init":return rn(n),0;case"build":return await Me(n),0;case"list":return await Tn(n),0;case"pull":return await In(n),0;case"push":return await Jn(n),0;case"publish":return await Yn(n),0;case"unpublish":return await zn(n),0;case"rename":return await Zn(n),0;case"delete":return await Qn(n),0;case"release":return await er(n),0;default:return process.stderr.write(`Unknown apps subcommand: ${t}
154
+ `;async function ht(e){let t=e.positional[0],n={...e,positional:e.positional.slice(1)};switch(t){case void 0:case"help":return process.stdout.write(cr),0;case"init":return un(n),0;case"build":return await Ve(n),0;case"list":return await Nn(n),0;case"pull":return await Mn(n),0;case"push":return await Qn(n),0;case"publish":return await tr(n),0;case"unpublish":return await nr(n),0;case"rename":return await sr(n),0;case"delete":return await or(n),0;case"release":return await ir(n),0;default:return process.stderr.write(`Unknown apps subcommand: ${t}
155
155
 
156
- ${nr}`),1}}async function rr(e){let t=w(e),n=`${v(t)}/configure/config`,r=await f(n);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(r.brand,null,2)+`
157
- `);return}qo(t,r.brand)}function qo(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 ${gt(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 ${gt(t.cspScriptHosts)}`),n.push(` cspConnectHosts ${gt(t.cspConnectHosts)}`),process.stdout.write(n.join(`
156
+ ${cr}`),1}}async function lr(e){let t=w(e),n=`${v(t)}/configure/config`,r=await f(n);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(r.brand,null,2)+`
157
+ `);return}ts(t,r.brand)}function ts(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 ${yt(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 ${yt(t.cspScriptHosts)}`),n.push(` cspConnectHosts ${yt(t.cspConnectHosts)}`),process.stdout.write(n.join(`
158
158
  `)+`
159
- `)}function gt(e){return!e||e.length===0?"\u2014":e.join(", ")}import*as Ye from"fs";import*as ir from"path";var or="theme.",Vo=["displayName","assistantName","storeLink"],Jo=["extraOrigins","cspScriptHosts","cspConnectHosts"];async function ar(e){let t=w(e),n={};for(let l of Vo){if(!(l in e.flags))continue;let p=e.flags[l];if(typeof p!="string")throw new Error(`--${l} requires a value (use --${l} "" to clear).`);n[l]=p===""?null:p}for(let l of Jo){if(!(l in e.flags))continue;let p=e.flags[l];if(typeof p!="string")throw new Error(`--${l} requires a comma-separated value (use --${l} "" to clear).`);let u=p.split(",").map(d=>d.trim()).filter(d=>d.length>0);n[l]=u.length===0?null:u}let r=y(e.flags,"themeFile"),o=Yo(e.flags),s=g(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 l=e.flags.theme;if(typeof l!="string")throw new Error('--theme requires a JSON value (use --theme "" to clear).');i=l===""?null:sr(l,"--theme")}else r!==void 0?i=sr(Ko(r,"--themeFile"),"--themeFile"):o!==null&&(i=o);if(i!==void 0&&(n.theme=i===null||s?i:{...await Wo(t),...i},n.theme!==null)){let l=n.theme;for(let[p,u]of Object.entries(l))u===""&&delete l[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`,c=await f(a,{method:"POST",body:n,validationDetail:!0});if(g(e.flags,"json")){process.stdout.write(JSON.stringify(c.config,null,2)+`
159
+ `)}function yt(e){return!e||e.length===0?"\u2014":e.join(", ")}import*as Xe from"fs";import*as fr from"path";var ur="theme.",ns=["displayName","assistantName","storeLink"],rs=["extraOrigins","cspScriptHosts","cspConnectHosts"];async function dr(e){let t=w(e),n={};for(let c of ns){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 rs){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=y(e.flags,"themeFile"),o=is(e.flags),s=g(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:pr(c,"--theme")}else r!==void 0?i=pr(os(r,"--themeFile"),"--themeFile"):o!==null&&(i=o);if(i!==void 0&&(n.theme=i===null||s?i:{...await ss(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(g(e.flags,"json")){process.stdout.write(JSON.stringify(l.config,null,2)+`
160
160
  `);return}process.stdout.write(`Saved ${Object.keys(n).join(", ")} \u2192 ${t}
161
- `)}function Ko(e,t){let n=ir.resolve(e);if(!Ye.existsSync(n))throw new Error(`${t}: file not found: ${n}`);return Ye.readFileSync(n,"utf8")}function sr(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 Wo(e){let t=`${v(e)}/configure/config`;return(await f(t)).brand.theme??{}}function Yo(e){let t={};for(let[n,r]of Object.entries(e)){if(!n.startsWith(or))continue;let o=n.slice(or.length),s=Y[o];if(!s){let i=zt(o);throw new Error(`Unknown theme field "${o}".
161
+ `)}function os(e,t){let n=fr.resolve(e);if(!Xe.existsSync(n))throw new Error(`${t}: file not found: ${n}`);return Xe.readFileSync(n,"utf8")}function pr(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 ss(e){let t=`${v(e)}/configure/config`;return(await f(t)).brand.theme??{}}function is(e){let t={};for(let[n,r]of Object.entries(e)){if(!n.startsWith(ur))continue;let o=n.slice(ur.length),s=Y[o];if(!s){let i=nn(o);throw new Error(`Unknown theme field "${o}".
162
162
  Valid fields: ${Object.keys(Y).join(", ")}.`+(i.length>0?`
163
- 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]=zo(n,o,r)}return Object.keys(t).length>0?t:null}function zo(e,t,n){let r=Y[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 Qe from"fs";import*as ye from"path";var ze=["icon","logoLight","logoDark"];function Xe(e){if(e&&ze.includes(e))return e;throw new Error(`Asset kind must be one of: ${ze.join(", ")}.`)}var Xo={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp"};async function lr(e){let t=w(e),n=Xe(e.positional[0]),r=e.positional[1];if(!r)throw new Error(`Usage: npx greatstore configure upload <${ze.join("|")}> <file>`);let o=ye.resolve(r);if(!Qe.existsSync(o))throw new Error(`File not found: ${o}`);let s=Xo[ye.extname(o).toLowerCase()];if(!s)throw new Error("Unsupported image type. Use .png, .jpg, or .webp.");let i=Qe.readFileSync(o),a=new FormData;a.append("file",new Blob([new Uint8Array(i)],{type:s}),ye.basename(o));let c=`${v(t)}/configure/upload/${n}`,l=await f(c,{method:"POST",multipart:a});process.stdout.write(`Uploaded ${n} \u2192 ${l.url}
164
- `)}async function cr(e){let t=w(e),n=Xe(e.positional[0]),r=`${v(t)}/configure/delete/${n}`;await f(r,{method:"POST",body:{}}),process.stdout.write(`Cleared ${n} for ${t}
165
- `)}async function ur(e){let t=e.positional[0]??"show",n={...e,positional:e.positional.slice(1)};switch(t){case"show":await rr(n);return;case"set":await ar(n);return;case"upload":await lr(n);return;case"clear":await cr(n);return;default:throw new Error(`Unknown configure subcommand: ${t}. Use \`npx greatstore configure [set|upload|clear]\`.`)}}async function R(e){let t=`${v(e)}/connectors/config`;return f(t)}function J(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 ee(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 te(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 pr(e){let t=w(e),n=await R(t);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(n,null,2)+`
163
+ 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]=as(n,o,r)}return Object.keys(t).length>0?t:null}function as(e,t,n){let r=Y[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 et from"fs";import*as Se from"path";var Qe=["icon","logoLight","logoDark"];function Ze(e){if(e&&Qe.includes(e))return e;throw new Error(`Asset kind must be one of: ${Qe.join(", ")}.`)}var cs={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp"};async function mr(e){let t=w(e),n=Ze(e.positional[0]),r=e.positional[1];if(!r)throw new Error(`Usage: npx greatstore configure upload <${Qe.join("|")}> <file>`);let o=Se.resolve(r);if(!et.existsSync(o))throw new Error(`File not found: ${o}`);let s=cs[Se.extname(o).toLowerCase()];if(!s)throw new Error("Unsupported image type. Use .png, .jpg, or .webp.");let i=et.readFileSync(o),a=new FormData;a.append("file",new Blob([new Uint8Array(i)],{type:s}),Se.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}
164
+ `)}async function gr(e){let t=w(e),n=Ze(e.positional[0]),r=`${v(t)}/configure/delete/${n}`;await f(r,{method:"POST",body:{}}),process.stdout.write(`Cleared ${n} for ${t}
165
+ `)}async function hr(e){let t=e.positional[0]??"show",n={...e,positional:e.positional.slice(1)};switch(t){case"show":await lr(n);return;case"set":await dr(n);return;case"upload":await mr(n);return;case"clear":await gr(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 J(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 ee(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 te(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 yr(e){let t=w(e),n=await T(t);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(n,null,2)+`
166
166
  `);return}if(process.stdout.write(`Maker MCP: ${n.makerEnabled?"on":"off"} (position ${n.makerPriority+1})
167
167
  `),n.connectors.length===0){process.stdout.write(`(no custom connectors in ${t})
168
- `);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(`${we("NAME",o.name)} ${we("ENABLED",o.enabled)} ${we("AUTH",o.auth)} URL
169
- `);for(let s of r)process.stdout.write(`${we(s.name,o.name)} ${we(s.enabled,o.enabled)} ${we(s.auth,o.auth)} ${s.url}
170
- `)}function we(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}async function fr(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=y(e.flags,"url");if(!r)throw new Error("--url is required for `npx greatstore connectors add`.");let o=y(e.flags,"token"),s=y(e.flags,"profileUrl")??null,i=!g(e.flags,"disabled");if(!g(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.
171
- `)}let a=await R(t),c={id:"",name:n,url:r,transport:"http",authKind:o?"bearer":"none",enabled:i,profileUrl:s,...o!==void 0?{token:o}:{}},p=(await ee(t,a,[...a.connectors.map(J),c])).connectors.find(u=>u.name===n);process.stdout.write(`Added connector "${n}"${p?` (${p.id})`:""} \u2192 ${t}
172
- `)}async function dr(e){let t=w(e),n=e.positional[0];if(!n)throw new Error("Usage: npx greatstore connectors remove <name|id>");let r=await R(t),o=te(r,n),s=r.connectors.filter(i=>i.id!==o.id).map(J);await ee(t,r,s),process.stdout.write(`Removed connector "${o.name}" from ${t}
173
- `)}async function ht(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 R(n),s=te(o,r),i=o.connectors.map(a=>a.id===s.id?{...J(a),enabled:t}:J(a));await ee(n,o,i),process.stdout.write(`Connector "${s.name}" is now ${t?"enabled":"disabled"}
174
- `)}async function mr(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 R(t);await ee(t,r,r.connectors.map(J),n==="on"),process.stdout.write(`Maker MCP is now ${n}
175
- `)}async function gr(e){let t=w(e),n=await R(t),r=null,o=e.positional[0];if(o&&(r=te(n,o).id),n.connectors.length===0){process.stdout.write(`(no custom connectors in ${t})
168
+ `);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(`${be("NAME",o.name)} ${be("ENABLED",o.enabled)} ${be("AUTH",o.auth)} URL
169
+ `);for(let s of r)process.stdout.write(`${be(s.name,o.name)} ${be(s.enabled,o.enabled)} ${be(s.auth,o.auth)} ${s.url}
170
+ `)}function be(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}async function wr(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=y(e.flags,"url");if(!r)throw new Error("--url is required for `npx greatstore connectors add`.");let o=y(e.flags,"token"),s=y(e.flags,"profileUrl")??null,i=!g(e.flags,"disabled");if(!g(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.
171
+ `)}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 ee(t,a,[...a.connectors.map(J),l])).connectors.find(u=>u.name===n);process.stdout.write(`Added connector "${n}"${p?` (${p.id})`:""} \u2192 ${t}
172
+ `)}async function Sr(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=te(r,n),s=r.connectors.filter(i=>i.id!==o.id).map(J);await ee(t,r,s),process.stdout.write(`Removed connector "${o.name}" from ${t}
173
+ `)}async function wt(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=te(o,r),i=o.connectors.map(a=>a.id===s.id?{...J(a),enabled:t}:J(a));await ee(n,o,i),process.stdout.write(`Connector "${s.name}" is now ${t?"enabled":"disabled"}
174
+ `)}async function br(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 ee(t,r,r.connectors.map(J),n==="on"),process.stdout.write(`Maker MCP is now ${n}
175
+ `)}async function xr(e){let t=w(e),n=await T(t),r=null,o=e.positional[0];if(o&&(r=te(n,o).id),n.connectors.length===0){process.stdout.write(`(no custom connectors in ${t})
176
176
  `);return}let s=`${v(t)}/connectors/health`,i=await f(s,{method:"POST",body:r?{id:r}:{}});if(g(e.flags,"json")){process.stdout.write(JSON.stringify(i.health,null,2)+`
177
- `);return}let a=new Map(n.connectors.map(c=>[c.id,c.name]));for(let c of i.health){let l=a.get(c.id)??c.id;c.ok?process.stdout.write(` ok ${l} (${c.toolCount??0} tools)
178
- `):(process.stdout.write(` failed ${l}: ${c.error??"discovery failed"}
179
- `),process.exitCode=1)}}var Qo={readOnly:"read-only",write:"write",other:"other"};async function yr(e){let t=w(e),n=e.positional[0];if(!n)throw new Error("Usage: npx greatstore connectors tools <name|id|maker|webmcp> [<tool>] [--json]");let r=n==="maker"||n==="webmcp"?n:te(await R(t),n).id,o=await f(`${v(t)}/connectors/tools`,{method:"POST",body:{id:r}});if(!o.ok||!o.tools)throw new Error(`Couldn't list the tools of ${n}: ${o.error??"discovery failed"}`);let s=e.positional[1],i=s?o.tools.filter(a=>a.name===s):o.tools;if(s&&i.length===0)throw new Error(`${n} has no tool named "${s}". Run \`npx greatstore connectors tools ${n}\` to see them.`);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(s?i[0]:i,null,2)+`
177
+ `);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)
178
+ `):(process.stdout.write(` failed ${c}: ${l.error??"discovery failed"}
179
+ `),process.exitCode=1)}}var ls={readOnly:"read-only",write:"write",other:"other"};async function vr(e){let t=w(e),n=e.positional[0];if(!n)throw new Error("Usage: npx greatstore connectors tools <name|id|maker|webmcp> [<tool>] [--json]");let r=n==="maker"||n==="webmcp"?n:te(await T(t),n).id,o=await f(`${v(t)}/connectors/tools`,{method:"POST",body:{id:r}});if(!o.ok||!o.tools)throw new Error(`Couldn't list the tools of ${n}: ${o.error??"discovery failed"}`);let s=e.positional[1],i=s?o.tools.filter(a=>a.name===s):o.tools;if(s&&i.length===0)throw new Error(`${n} has no tool named "${s}". Run \`npx greatstore connectors tools ${n}\` to see them.`);if(g(e.flags,"json")){process.stdout.write(JSON.stringify(s?i[0]:i,null,2)+`
180
180
  `);return}if(r==="webmcp"&&i.length===0){process.stdout.write(`No page tools yet. A tool shows up here after a chat on a page that registers it once GreatStore is ready.
181
- `);return}process.stdout.write(i.map(es).join(`
181
+ `);return}process.stdout.write(i.map(ps).join(`
182
182
 
183
183
  `)+`
184
- `)}function Zo(e){if(e.callable)return"callable from the page with GreatStore.callTool";switch(e.reason){case"not_read_only":return"not callable from the page: it changes state";case"shadowed":return`not callable from the page: the name reaches ${e.shadowedBy==="app"?"a store app":e.shadowedBy} instead`;case"unavailable":return"not callable from the page: its connector is off, the tool is disallowed, or it was added in the last few minutes"}}function es(e){let t=[`## ${e.name}`,`${Qo[e.group]}, ${e.allowed?"allowed":"disallowed"} \u2014 ${Zo(e.page)}`];if(e.notSeenRecently&&t.push("not registered by your pages in the last 30 days"),e.description&&t.push("",e.description.trim()),!e.inputSchema)return t.push("","Input: as declared in the page's own registerTool call"),t.join(`
185
- `);t.push("","Input:");let n=yt(e.inputSchema,1);return t.push(...n.length>0?n:[" (none)"]),t.join(`
186
- `)}function yt(e,t){let n=Pe(e.properties);if(!n)return[];let r=new Set(Array.isArray(e.required)?e.required:[]),o=[];for(let[s,i]of Object.entries(n)){let a=Pe(i)??{};o.push(...wt(s,a,r.has(s),t))}return e.additionalProperties===!1&&o.push(`${St(t)}(no other fields accepted)`),o}function wt(e,t,n,r){let o=[ts(t),n?"required":"optional",...hr(t)],s=typeof t.description=="string"?` \u2014 ${t.description.trim()}`:"",i=[`${St(r)}${e} (${o.join(", ")})${s}`];i.push(...yt(t,r+1));let a=Pe(t.items);if(a){let c=yt(a,r+2);c.length>0?i.push(`${St(r+1)}each item:`,...c):(hr(a).length>0||a.description)&&i.push(...wt("each item",a,!0,r+1))}for(let c of["anyOf","oneOf","allOf"])(Array.isArray(t[c])?t[c]:[]).forEach((p,u)=>{let d=Pe(p);d&&i.push(...wt(`${c}[${u}]`,d,!0,r+1))});return i}function ts(e){let t=e.type,n=Array.isArray(t)?t.join(" | "):typeof t=="string"?t:"any",r=Pe(e.items);return n==="array"&&r&&typeof r.type=="string"?`array of ${r.type}`:n}var ns=[["minimum","min"],["maximum","max"],["exclusiveMinimum","greater than"],["exclusiveMaximum","less than"],["minLength","min length"],["maxLength","max length"],["minItems","min items"],["maxItems","max items"],["pattern","pattern"],["format","format"]];function hr(e){let t=[];Array.isArray(e.enum)&&t.push(`one of ${e.enum.map(n=>JSON.stringify(n)).join(", ")}`),"const"in e&&t.push(`always ${JSON.stringify(e.const)}`);for(let[n,r]of ns)e[n]!==void 0&&t.push(`${r} ${String(e[n])}`);return e.uniqueItems===!0&&t.push("unique items"),"default"in e&&t.push(`default ${JSON.stringify(e.default)}`),t}function Pe(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function St(e){return" ".repeat(e)}var rs=7,wr=120,os=864e5,ss={mcp:"connector",local:"custom app",browser:"browser"};async function Sr(e){let t=w(e),n=is(y(e.flags,"days")),r=y(e.flags,"tool"),o=new Date,s=new Date(o.getTime()-n*os),i=await f(`${v(t)}/usage/report`,{method:"POST",body:{from:s.toISOString(),to:o.toISOString(),bucket:"day"}}),a=i.data.tools.toolFailures??[],c=r?a.filter(u=>u.tool_name===r):a,l=i.data.tools.toolFailuresTruncated===!0;if(g(e.flags,"json")){process.stdout.write(JSON.stringify({days:n,errors:c,truncated:l},null,2)+`
187
- `);return}let p=r?`${r} in ${t}`:t;if(c.length===0){process.stdout.write(`(no tool errors in ${p} in the last ${n} days)
184
+ `)}function us(e){if(e.callable)return"callable from the page with GreatStore.callTool";switch(e.reason){case"not_read_only":return"not callable from the page: it changes state";case"shadowed":return`not callable from the page: the name reaches ${e.shadowedBy==="app"?"a store app":e.shadowedBy} instead`;case"unavailable":return"not callable from the page: its connector is off, the tool is disallowed, or it was added in the last few minutes"}}function ps(e){let t=[`## ${e.name}`,`${ls[e.group]}, ${e.allowed?"allowed":"disallowed"} \u2014 ${us(e.page)}`];if(e.notSeenRecently&&t.push("not registered by your pages in the last 30 days"),e.description&&t.push("",e.description.trim()),!e.inputSchema)return t.push("","Input: as declared in the page's own registerTool call"),t.join(`
185
+ `);t.push("","Input:");let n=St(e.inputSchema,1);return t.push(...n.length>0?n:[" (none)"]),t.join(`
186
+ `)}function St(e,t){let n=Ae(e.properties);if(!n)return[];let r=new Set(Array.isArray(e.required)?e.required:[]),o=[];for(let[s,i]of Object.entries(n)){let a=Ae(i)??{};o.push(...bt(s,a,r.has(s),t))}return e.additionalProperties===!1&&o.push(`${xt(t)}(no other fields accepted)`),o}function bt(e,t,n,r){let o=[fs(t),n?"required":"optional",...$r(t)],s=typeof t.description=="string"?` \u2014 ${t.description.trim()}`:"",i=[`${xt(r)}${e} (${o.join(", ")})${s}`];i.push(...St(t,r+1));let a=Ae(t.items);if(a){let l=St(a,r+2);l.length>0?i.push(`${xt(r+1)}each item:`,...l):($r(a).length>0||a.description)&&i.push(...bt("each item",a,!0,r+1))}for(let l of["anyOf","oneOf","allOf"])(Array.isArray(t[l])?t[l]:[]).forEach((p,u)=>{let d=Ae(p);d&&i.push(...bt(`${l}[${u}]`,d,!0,r+1))});return i}function fs(e){let t=e.type,n=Array.isArray(t)?t.join(" | "):typeof t=="string"?t:"any",r=Ae(e.items);return n==="array"&&r&&typeof r.type=="string"?`array of ${r.type}`:n}var ds=[["minimum","min"],["maximum","max"],["exclusiveMinimum","greater than"],["exclusiveMaximum","less than"],["minLength","min length"],["maxLength","max length"],["minItems","min items"],["maxItems","max items"],["pattern","pattern"],["format","format"]];function $r(e){let t=[];Array.isArray(e.enum)&&t.push(`one of ${e.enum.map(n=>JSON.stringify(n)).join(", ")}`),"const"in e&&t.push(`always ${JSON.stringify(e.const)}`);for(let[n,r]of ds)e[n]!==void 0&&t.push(`${r} ${String(e[n])}`);return e.uniqueItems===!0&&t.push("unique items"),"default"in e&&t.push(`default ${JSON.stringify(e.default)}`),t}function Ae(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function xt(e){return" ".repeat(e)}var ms=7,kr=120,gs=864e5,hs={mcp:"connector",local:"custom app",browser:"browser"};async function Pr(e){let t=w(e),n=ys(y(e.flags,"days")),r=y(e.flags,"tool"),o=new Date,s=new Date(o.getTime()-n*gs),i=await f(`${v(t)}/usage/report`,{method:"POST",body:{from:s.toISOString(),to:o.toISOString(),bucket:"day"}}),a=i.data.tools.toolFailures??[],l=r?a.filter(u=>u.tool_name===r):a,c=i.data.tools.toolFailuresTruncated===!0;if(g(e.flags,"json")){process.stdout.write(JSON.stringify({days:n,errors:l,truncated:c},null,2)+`
187
+ `);return}let p=r?`${r} in ${t}`:t;if(l.length===0){process.stdout.write(`(no tool errors in ${p} in the last ${n} days)
188
188
  `);return}process.stdout.write(`Tool errors in ${p}, last ${n} days (most frequent first):
189
189
 
190
- `);for(let u of c){let d=ss[u.tool_backend]??u.tool_backend;process.stdout.write(` ${String(u.occurrences).padStart(5)}\xD7 ${u.tool_name} (${d}), last ${u.last_at}
190
+ `);for(let u of l){let d=hs[u.tool_backend]??u.tool_backend;process.stdout.write(` ${String(u.occurrences).padStart(5)}\xD7 ${u.tool_name} (${d}), last ${u.last_at}
191
191
  ${u.error}
192
- `)}l&&process.stdout.write(`
192
+ `)}c&&process.stdout.write(`
193
193
  The rarest errors are left out of this list.
194
- `)}function is(e){if(e===void 0)return rs;let t=Number(e);if(!Number.isInteger(t)||t<1||t>wr)throw new Error(`--days must be a whole number from 1 to ${wr}.`);return t}async function br(e){let t=e.positional[0]??"list",n={...e,positional:e.positional.slice(1)};switch(t){case"list":await pr(n);return;case"add":await fr(n);return;case"remove":await dr(n);return;case"enable":await ht(n,!0);return;case"disable":await ht(n,!1);return;case"maker":await mr(n);return;case"health":await gr(n);return;case"tools":await yr(n);return;case"errors":await Sr(n);return;default:throw new Error(`Unknown connectors subcommand: ${t}. Use \`npx greatstore connectors [add|remove|enable|disable|maker|health|tools|errors]\`.`)}}function xr(e,t=15){if(!e.trim())return"";let n=e.split(`
194
+ `)}function ys(e){if(e===void 0)return ms;let t=Number(e);if(!Number.isInteger(t)||t<1||t>kr)throw new Error(`--days must be a whole number from 1 to ${kr}.`);return t}async function Er(e){let t=e.positional[0]??"list",n={...e,positional:e.positional.slice(1)};switch(t){case"list":await yr(n);return;case"add":await wr(n);return;case"remove":await Sr(n);return;case"enable":await wt(n,!0);return;case"disable":await wt(n,!1);return;case"maker":await br(n);return;case"health":await xr(n);return;case"tools":await vr(n);return;case"errors":await Pr(n);return;default:throw new Error(`Unknown connectors subcommand: ${t}. Use \`npx greatstore connectors [add|remove|enable|disable|maker|health|tools|errors]\`.`)}}function $t(e,t=15){if(!e.trim())return"";let n=e.split(`
195
195
  `),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(`
196
- `).trimEnd()}var as=`# Changelog
196
+ `).trimEnd()}function Cr(e,t){let n=[],r=!1;for(let o of e.split(/\r?\n/)){if(o.startsWith("## ")){let s=/^##\s+v?(\d+(?:\.\d+)*)/.exec(o)?.[1];r=s!==void 0&&pe(s,t)>0}r&&n.push(o)}return n.join(`
197
+ `).trimEnd()}import*as xe from"fs";import*as vt from"os";import*as _r from"path";var ws="version-check.json",Ss="0.0.0-dev";function Rr(e){return _r.join(re(e),ws)}function kt(e=vt.homedir()){try{let t=JSON.parse(xe.readFileSync(Rr(e),"utf8"));if(!t||typeof t!="object")return null;let{version:n,previous:r}=t;return typeof n!="string"?null:typeof r=="string"?{version:n,previous:r}:{version:n}}catch{return null}}function Tr(e,t=vt.homedir()){if(e===Ss)return!1;let n=kt(t);if(n?.version===e)return!1;let r=n!==null&&pe(e,n.version)>0;try{xe.mkdirSync(re(t),{recursive:!0,mode:448});let o=n?{version:e,previous:n.version}:{version:e};xe.writeFileSync(Rr(t),JSON.stringify(o)+`
198
+ `)}catch{return!1}return r}var Ar="\x1B[34m",bs="\x1B[30;42m",jr="\x1B[0m";function Lr(e,t,n=process.stderr.hasColors?.()===!0){let r="(run to learn more: npx greatstore whats-new)";if(!n)return`greatstore v${e}${t?` [Updated!] ${r}`:""}
199
+ `;let o=t?` ${bs} Updated! ${jr}${Ar} ${r}`:"";return`${Ar}greatstore v${e}${o}${jr}
200
+ `}var Pt=`# Changelog
197
201
 
198
202
  All notable changes to \`@greatstore/cli\` are recorded here. The format
199
203
  follows [Keep a Changelog](https://keepachangelog.com/).
200
204
 
205
+ ## 0.2.18 \u2014 2026-10-30
206
+
207
+ ### Added
208
+ - Every command opens with the CLI's version, except under \`--json\`. The first run after an update also shows an "Updated!" badge with a pointer to \`whats-new\`.
209
+ - \`whats-new\` shows what changed in every release since the version you last ran.
210
+
201
211
  ## 0.2.16 \u2014 2026-10-30
202
212
 
203
213
  ### Added
@@ -846,7 +856,7 @@ follows [Keep a Changelog](https://keepachangelog.com/).
846
856
 
847
857
  ### Fixed
848
858
  - Sign-in callback parameter handling.
849
- `,$r=`greatstore \u2014 GreatStore CLI (v${F})
859
+ `,Or=`greatstore \u2014 GreatStore CLI (v${O})
850
860
 
851
861
  Usage:
852
862
  npx greatstore <command> [args] [flags]
@@ -886,6 +896,9 @@ Agent tooling:
886
896
  skill Print how to install the GreatStore agent skill,
887
897
  for the AI coding agent that runs it.
888
898
 
899
+ About the CLI:
900
+ whats-new What changed since the version you last ran.
901
+
889
902
  Common flags:
890
903
  --store <slug> Target store for admin commands (default: nearest .gsrc,
891
904
  else the store chosen at sign-in). Must match the
@@ -906,12 +919,13 @@ Environment:
906
919
  GS_API_BASE Override API base (full URL, no trailing slash).
907
920
  GS_DASHBOARD_BASE Override the sign-in/store-picker base URL.
908
921
  GS_BROWSER_CMD Override the browser-open command.
909
- `,ls=new Set(["init","build","list","pull","push","publish","unpublish","delete"]);async function cs(){let e=process.argv.slice(2),t=Et(e);if(Wt(F),g(t.flags,"version")){process.stdout.write(`greatstore v${F}
922
+ `,xs=new Set(["init","build","list","pull","push","publish","unpublish","delete"]);async function $s(){let e=process.argv.slice(2),t=Tt(e);if(en(O),g(t.flags,"version")){process.stdout.write(`greatstore v${O}
910
923
 
911
- `);let n=xr(as);return n&&process.stdout.write(`${n}
912
- `),0}if(g(t.flags,"help")||t.command==="help"||t.command===null){let n=t.command==="configure"?Xt(t.positional[0]):void 0;return process.stdout.write(n??$r),0}if(t.command!==null&&ls.has(t.command))return mt({...t,positional:[t.command,...t.positional]});switch(t.command){case"login":return await Ut(t),0;case"logout":return Gt(),0;case"whoami":return qt();case"switch":return Vt(t.positional);case"apps":return mt(t);case"configure":return await ur(t),0;case"connectors":return await br(t),0;case"skill":return Yt(),0;default:return process.stderr.write(`Unknown command: ${t.command}
924
+ `);let n=$t(Pt);return n&&process.stdout.write(`${n}
925
+ `),0}if(g(t.flags,"help")||t.command==="help"||t.command===null){let n=t.command==="configure"?rn(t.positional[0]):void 0;return process.stdout.write(n??Or),0}if(g(t.flags,"json")||process.stderr.write(Lr(O,Tr(O))),t.command!==null&&xs.has(t.command))return ht({...t,positional:[t.command,...t.positional]});switch(t.command){case"login":return await Wt(t),0;case"logout":return Yt(),0;case"whoami":return zt();case"switch":return Xt(t.positional);case"apps":return ht(t);case"configure":return await hr(t),0;case"connectors":return await Er(t),0;case"skill":return tn(),0;case"whats-new":{let n=kt()?.previous,r=n?Cr(Pt,n):$t(Pt);return process.stdout.write(`${r||"No release notes in this build."}
926
+ `),0}default:return process.stderr.write(`Unknown command: ${t.command}
913
927
 
914
- ${$r}`),1}}cs().then(e=>process.exit(e||Number(process.exitCode??0))).catch(e=>{e instanceof M?process.stderr.write(`${e.message}
928
+ ${Or}`),1}}$s().then(e=>process.exit(e||Number(process.exitCode??0))).catch(e=>{e instanceof M?process.stderr.write(`${e.message}
915
929
  `):e instanceof D?process.stderr.write(`Error: ${e.message}
916
930
  `):e instanceof K||e instanceof ne?process.stderr.write(`Error: ${e.message}
917
931
  `):e instanceof Error?process.stderr.write(`Error: ${e.message}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@greatstore/cli",
3
- "version": "0.2.16",
3
+ "version": "0.2.18",
4
4
  "description": "CLI for administering GreatStore stores and authoring custom components.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",