@greatstore/cli 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,49 +1,49 @@
1
1
  #!/usr/bin/env node
2
- var Ao=new Set(["old","new","text"]),Co={h:"help",v:"version",o:"out"};function nn(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||!Ao.has(i)&&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=Co[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 w(e,t){let n=e[t];return typeof n=="string"?n:void 0}function m(e,t){let n=e[t];return n===!0||n==="true"}import*as sn from"crypto";import*as an from"http";import{spawn as rn}from"child_process";var To="/callback",jo='<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>',_o=`:root{color-scheme:light}
2
+ var Mo=new Set(["old","new","text"]),Uo={h:"help",v:"version",o:"out"};function an(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||!Mo.has(i)&&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=Uo[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 w(e,t){let n=e[t];return typeof n=="string"?n:void 0}function m(e,t){let n=e[t];return n===!0||n==="true"}import*as un from"crypto";import*as pn from"http";import{spawn as ln}from"child_process";var Ho="/callback",qo='<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>',Go=`: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}`,ln='<script>history.replaceState(null,"",location.pathname);</script>',Ro=`<!doctype html>
6
+ p{color:#2c3a38}`,dn='<script>history.replaceState(null,"",location.pathname);</script>',Vo=`<!doctype html>
7
7
  <html lang="en"><head><meta charset="utf-8"><title>GreatStore CLI</title>
8
- ${ln}
8
+ ${dn}
9
9
  <link rel="preconnect" href="https://fonts.googleapis.com">
10
10
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
11
11
  <link href="https://fonts.googleapis.com/css2?family=Instrument+Sans:wght@400;500;600;700&family=Instrument+Serif:ital@1&display=swap" rel="stylesheet">
12
- <style>${_o}</style></head>
12
+ <style>${Go}</style></head>
13
13
  <body>
14
- <div class="logo">${jo}</div>
14
+ <div class="logo">${qo}</div>
15
15
  <h1>You're signed in.</h1>
16
16
  <p>This window will close automatically. If it doesn't, you can close it and return to your terminal.</p>
17
17
  <script>setTimeout(function(){window.close();},250);</script>
18
- </body></html>`,on=`<!doctype html>
18
+ </body></html>`,cn=`<!doctype html>
19
19
  <html lang="en"><head><meta charset="utf-8"><title>GreatStore CLI</title>
20
- ${ln}
20
+ ${dn}
21
21
  <style>body{font:14px/1.5 system-ui;margin:4rem auto;max-width:32rem;color:#222;text-align:center}
22
22
  h1{font-size:1.4rem;color:#a40000}code{background:#f4f4f4;padding:.1em .3em;border-radius:.2em}</style></head>
23
23
  <body><h1>Sign-in failed.</h1>
24
- <p>Return to your terminal for details.</p></body></html>`,ue=class extends Error{constructor(t){super(t),this.name="LoopbackError"}};async function qe(e){let t=(e.generateState??Io)(),n=e.timeoutMs??300*1e3,r=e.openBrowser??(s=>No(s,e.browserCmdEnv)),o=an.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=Lo(o,t,n);return r(a),process.stderr.write(`If your browser didn't open, visit:
24
+ <p>Return to your terminal for details.</p></body></html>`,ue=class extends Error{constructor(t){super(t),this.name="LoopbackError"}};async function Ge(e){let t=(e.generateState??Jo)(),n=e.timeoutMs??300*1e3,r=e.openBrowser??(s=>Wo(s,e.browserCmdEnv)),o=pn.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=Ko(o,t,n);return r(a),process.stderr.write(`If your browser didn't open, visit:
25
25
  ${a}
26
- `),await l}finally{o.close()}}function Lo(e,t,n){return new Promise((r,o)=>{let s=!1,i=l=>{s||(s=!0,l())},a=setTimeout(()=>{i(()=>o(new ue("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!==To){c.writeHead(404,{"content-type":"text/plain"}),c.end("Not found");return}let u=p.searchParams,f=u.get("error"),y=u.get("error_description"),g=u.get("code");if(u.get("state")!==t){c.writeHead(400,{"content-type":"text/html"}),c.end(on),clearTimeout(a),i(()=>o(new ue("Sign-in didn't complete. Please try again.")));return}if(f||!g){c.writeHead(400,{"content-type":"text/html"}),c.end(on),clearTimeout(a),i(()=>o(new ue(y??"Sign-in failed. Please try again.")));return}c.writeHead(200,{"content-type":"text/html"}),c.end(Ro),clearTimeout(a);let Ge=u.get("store")?.trim();i(()=>r(Ge?{token:g,store:Ge}:{token:g}))})})}function Io(){return sn.randomBytes(16).toString("hex")}function No(e,t){let n=t?.trim();cn(e,n?[n]:Oo(process.platform,process.env))}function cn(e,t){let[n,...r]=t;if(n===void 0)return;let o=()=>cn(e,r);try{let s;if(n==="start"){let l=`start "" "${e}"`;s=rn("cmd.exe",["/d","/s","/c",l],{stdio:"ignore",detached:!0,windowsVerbatimArguments:!0})}else s=rn(n,[e],{stdio:"ignore",detached:!0});let i=!1,a=()=>{i||(i=!0,o())};s.on("error",a),s.on("exit",l=>{l!==0?a():i=!0}),s.unref()}catch{o()}}function Oo(e,t){if(e==="android"||t.TERMUX_VERSION!==void 0||(t.PREFIX??"").includes("/com.termux/"))return["termux-open-url","termux-open","xdg-open"];switch(e){case"darwin":return["open"];case"win32":return["start"];case"linux":return["xdg-open"];default:return[]}}import*as I from"fs";import*as Se from"os";import*as $t from"path";var Fo=".greatstore",Do="credentials.json";function pe(e=Se.homedir()){return $t.join(e,Fo)}function kt(e=Se.homedir()){return $t.join(pe(e),Do)}function B(e=Se.homedir()){let t=kt(e),n;try{let r=I.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=I.readFileSync(t,"utf8")}catch(r){if(Bo(r))return null;throw r}try{let r=JSON.parse(n);return typeof r.access_token!="string"?null:r}catch{return null}}function Ve(e,t=Se.homedir()){let n=pe(t);if(I.mkdirSync(n,{recursive:!0,mode:448}),process.platform!=="win32")try{I.chmodSync(n,448)}catch{}let r=kt(t);I.writeFileSync(r,`${JSON.stringify(e,null,2)}
27
- `,{mode:384}),process.platform!=="win32"&&I.chmodSync(r,384)}function un(e=Se.homedir()){I.rmSync(kt(e),{force:!0})}function pn(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 Ke(e,t=Math.floor(Date.now()/1e3)){return e.expires_at<=t}function Bo(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}var N="0.3.1";function xe(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 M=class extends Error{constructor(n,r,o){super(r);this.status=n;this.code=o;this.name="HttpError"}},q=class extends Error{constructor(t="Sign in first. Run `npx greatstore login`."){super(t),this.name="AuthRequiredError"}};function Uo(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 Ho(e){let t=Uo(e)??B()?.store;return t?`npx greatstore login --store ${t}`:"npx greatstore login"}var vt=null;function gn(e){vt=e}async function d(e,t={}){return Mo(await Le(e,t))}async function Le(e,t={}){if(vt!==null)return dn(e,t,vt);let n=()=>`Run \`${Ho(e)}\`.`,r=B();if(!r)throw new q(`Sign in first. ${n()}`);if(Ke(r))throw new q(`Session expired. ${n()}`);try{return await dn(e,t,r.access_token)}catch(o){throw o instanceof M&&o.status===401?new q(`Session expired. ${n()}`):o}}async function Mo(e){return e.status===204?void 0:(e.headers.get("content-type")??"").includes("application/json")?await e.json():await e.text()}async function dn(e,t,n){let r={accept:"application/json",authorization:`Bearer ${n}`,"x-gs-cli-version":N,...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;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:Go(i.status,c,l.detail);throw new M(i.status,p,l.code??l.error)}var hn=`This version of the GreatStore CLI is no longer supported. Run the latest one:
26
+ `),await l}finally{o.close()}}function Ko(e,t,n){return new Promise((r,o)=>{let s=!1,i=l=>{s||(s=!0,l())},a=setTimeout(()=>{i(()=>o(new ue("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!==Ho){c.writeHead(404,{"content-type":"text/plain"}),c.end("Not found");return}let u=p.searchParams,f=u.get("error"),y=u.get("error_description"),g=u.get("code");if(u.get("state")!==t){c.writeHead(400,{"content-type":"text/html"}),c.end(cn),clearTimeout(a),i(()=>o(new ue("Sign-in didn't complete. Please try again.")));return}if(f||!g){c.writeHead(400,{"content-type":"text/html"}),c.end(cn),clearTimeout(a),i(()=>o(new ue(y??"Sign-in failed. Please try again.")));return}c.writeHead(200,{"content-type":"text/html"}),c.end(Vo),clearTimeout(a);let qe=u.get("store")?.trim();i(()=>r(qe?{token:g,store:qe}:{token:g}))})})}function Jo(){return un.randomBytes(16).toString("hex")}function Wo(e,t){let n=t?.trim();fn(e,n?[n]:Yo(process.platform,process.env))}function fn(e,t){let[n,...r]=t;if(n===void 0)return;let o=()=>fn(e,r);try{let s;if(n==="start"){let l=`start "" "${e}"`;s=ln("cmd.exe",["/d","/s","/c",l],{stdio:"ignore",detached:!0,windowsVerbatimArguments:!0})}else s=ln(n,[e],{stdio:"ignore",detached:!0});let i=!1,a=()=>{i||(i=!0,o())};s.on("error",a),s.on("exit",l=>{l!==0?a():i=!0}),s.unref()}catch{o()}}function Yo(e,t){if(e==="android"||t.TERMUX_VERSION!==void 0||(t.PREFIX??"").includes("/com.termux/"))return["termux-open-url","termux-open","xdg-open"];switch(e){case"darwin":return["open"];case"win32":return["start"];case"linux":return["xdg-open"];default:return[]}}import*as L from"fs";import*as Se from"os";import*as vt from"path";var zo=".greatstore",Xo="credentials.json";function pe(e=Se.homedir()){return vt.join(e,zo)}function kt(e=Se.homedir()){return vt.join(pe(e),Xo)}function M(e=Se.homedir()){let t=kt(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(Qo(r))return null;throw r}try{let r=JSON.parse(n);return typeof r.access_token!="string"?null:r}catch{return null}}function Ve(e,t=Se.homedir()){let n=pe(t);if(L.mkdirSync(n,{recursive:!0,mode:448}),process.platform!=="win32")try{L.chmodSync(n,448)}catch{}let r=kt(t);L.writeFileSync(r,`${JSON.stringify(e,null,2)}
27
+ `,{mode:384}),process.platform!=="win32"&&L.chmodSync(r,384)}function mn(e=Se.homedir()){L.rmSync(kt(e),{force:!0})}function gn(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 Ke(e,t=Math.floor(Date.now()/1e3)){return e.expires_at<=t}function Qo(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}var N="0.4.0";function xe(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"}},G=class extends Error{constructor(t="Sign in first. Run `npx greatstore login`."){super(t),this.name="AuthRequiredError"}};function Zo(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 es(e){let t=Zo(e)??M()?.store;return t?`npx greatstore login --store ${t}`:"npx greatstore login"}var Et=null;function Sn(e){Et=e}async function d(e,t={}){return ts(await Ie(e,t))}async function Ie(e,t={}){if(Et!==null)return hn(e,t,Et);let n=()=>`Run \`${es(e)}\`.`,r=M();if(!r)throw new G(`Sign in first. ${n()}`);if(Ke(r))throw new G(`Session expired. ${n()}`);try{return await hn(e,t,r.access_token)}catch(o){throw o instanceof D&&o.status===401?new G(`Session expired. ${n()}`):o}}async function ts(e){return e.status===204?void 0:(e.headers.get("content-type")??"").includes("application/json")?await e.json():await e.text()}async function hn(e,t,n){let r={accept:"application/json",authorization:`Bearer ${n}`,"x-gs-cli-version":N,...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;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:ns(i.status,c,l.detail);throw new D(i.status,p,l.code??l.error)}var bn=`This version of the GreatStore CLI is no longer supported. Run the latest one:
28
28
 
29
29
  npx greatstore@latest <command>
30
30
 
31
31
  or, if you installed it, update it:
32
32
 
33
33
  npm install -g greatstore@latest
34
- `,fn={cli_upgrade_required:{message:hn},INVALID_NAME:{message:"Invalid app name. Use lowercase letters, digits, and underscores, starting with a letter."},not_found:{message:"App not found in the store."},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 app in this store already has that name."},name_mismatch:{message:"Manifest `name` does not match the app's 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."},SESSION_EXPIRED:{message:"That conversation has ended. Start a new one by leaving out --conversation."},SESSION_TERMINATED:{message:"That conversation was replaced by a newer one. Start a new one by leaving out --conversation."},STORE_PAUSED:{message:"The store is paused, so its assistant can't reply."},SPEND_LIMIT_REACHED:{message:"The store has reached its spending limit."},STORE_PLAN_INACTIVE:{message:"The store's plan isn't active."},CREDIT_BALANCE_EXHAUSTED:{message:"The store is out of credits."},CREDIT_BALANCE_TOO_LOW:{message:"The store's credit balance is too low."},TEST_ALLOWANCE_REACHED:{message:"Test chats have used their allowance for now. Try again later.",includeDetail:!0},STALE_EDIT:{message:"The text changed since you read it, or your edit doesn't match it.",includeDetail:!0}};function Go(e,t,n){if(t&&t in fn){let r=fn[t];return r?r.includeDetail&&n?`${r.message} (${n})`:r.message:mn(e)}return mn(e)}function mn(e){return e===401?"Sign-in needed. Run `npx greatstore login`.":e===426?hn:e===403?"Not authorized for this app 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 We(e,t){let n=pn(e),r=wn(n,"sub");if(!r)throw new Error("Token is missing a `sub` claim.");let o=qo(n,"exp");return{access_token:e,expires_at:o??Math.floor(Date.now()/1e3)+3600,sub:r,...Je(n,"email","email"),...Je(n,"accountId","accountId"),...Je(n,"name","name"),...Je(n,"surname","surname"),...Vo(n,"superUser","superUser"),...t?{store:t}:{}}}function wn(e,t){let n=e[t];return typeof n=="string"?n:void 0}function qo(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Je(e,t,n){let r=wn(e,t);return r?{[n]:r}:{}}function Vo(e,t,n){let r=e[t];return r===!0?{[n]:!0}:typeof r=="string"&&r.toLowerCase()==="true"?{[n]:!0}:{}}import*as Ye from"fs";import*as te from"path";var Ko="https://my.greatstore.ai",yn="_library";function Ie(e){return e===yn}var ee=class extends Error{constructor(t){super(t),this.name="StoreResolutionError"}};function E(e={}){let t=Et(e.cwd??process.cwd());if(t)return $e(t);throw new ee("No .gsrc found in this directory or any ancestor. Run `npx greatstore apps init --store <slug>` first to scaffold a GreatStore project.")}function Sn(e=process.cwd()){let t=Et(e);if(t)return $e(t);let n=Ne();if(n)return n;throw new ee("No store selected. Run `npx greatstore login`, or run from a project with a .gsrc.")}function Ne(){try{return B()?.store??null}catch{return null}}function $e(e){let t=Ne();if(t&&t!==e)throw new ee(`This targets store "${e}" but you're signed in to "${t}". Run \`npx greatstore switch ${e}\` to change stores.`);return e}function Et(e){let t=bn(e);return t?t.library===!0?yn:typeof t.store=="string"?t.store.trim():null:null}function bn(e){let t=te.resolve(e),n=te.parse(t).root;for(;;){let r=te.join(t,".gsrc");if(Ye.existsSync(r))try{let s=JSON.parse(Ye.readFileSync(r,"utf8"));if(s.library===!0||typeof s.store=="string"&&s.store.trim())return s}catch{}if(t===n)return null;let o=te.dirname(t);if(o===t)return null;t=o}}function Pt(e=process.cwd(),t=process.env){if(t.GS_DASHBOARD_BASE?.trim())return de(t);let n=bn(e)?.dashboard;return typeof n=="string"&&n.trim()?At(n.trim()):de(t)}function h(e){let t=w(e.flags,"store")?.trim();if(t)return $e(t);let n=Et(process.cwd());if(n)return $e(n);let r=Ne();if(r)return r;throw new ee("No store selected. Pass --store <slug>, or run from a project with a .gsrc.")}function C(e,t=process.env){let n=t.GS_API_BASE?.trim();return n?At(n):`https://${e}.greatstore.ai`}function ze(e,t=process.env){return Ie(e)?`${Pt(process.cwd(),t)}/cli/library`:`${C(e,t)}/api/apps`}function de(e=process.env){let t=e.GS_DASHBOARD_BASE?.trim();return t?At(t):Ko}function b(e,t=process.env){return`${de(t)}/${e}/admin`}function At(e){return e.endsWith("/")?e.slice(0,-1):e}import*as P from"fs";import*as Xe from"os";import*as fe from"path";import{fileURLToPath as Jo}from"url";var ke="greatstore",xn=".version";function Wo(){for(let e of["./gs-skill/","../../gs-skill/"]){let t=fe.resolve(Jo(new URL(e,import.meta.url)));if(P.existsSync(fe.join(t,"SKILL.md")))return t}throw new Error("internal: this install of the CLI is missing the agent skill files")}function Qe(e=Xe.homedir()){return fe.join(pe(e),"skill",ke)}function Ct(e,t=Xe.homedir()){let n=Qe(t),r=Yo(n);if(r!==null&&xe(r,e)>=0)return n;let o=`${n}.tmp-${process.pid}`,s=`${n}.old-${process.pid}`;return P.rmSync(o,{recursive:!0,force:!0}),P.cpSync(Wo(),o,{recursive:!0}),P.writeFileSync(fe.join(o,xn),e),P.existsSync(n)&&P.renameSync(n,s),P.renameSync(o,n),P.rmSync(s,{recursive:!0,force:!0}),n}function $n(e,t=Xe.homedir()){try{P.existsSync(Qe(t))&&Ct(e,t)}catch{}}function Yo(e){try{return P.readFileSync(fe.join(e,xn),"utf8").trim()}catch{return null}}import*as kn from"fs";async function vn(e){let t=w(e.flags,"store")?.trim();process.stdout.write(`Opening browser for sign-in\u2026
35
- `);let{token:n,store:r}=await qe({dashboardBaseUrl:de(),...t?{requestedStore:t}:{}}),o=We(n,r);Ve(o);let s=o.email??o.sub;o.store?process.stdout.write(`Logged in as ${s}, working on store "${o.store}".
34
+ `,wn={cli_upgrade_required:{message:bn},INVALID_NAME:{message:"Invalid app name. Use lowercase letters, digits, and underscores, starting with a letter."},not_found:{message:"App not found in the store."},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 app in this store already has that name."},name_mismatch:{message:"Manifest `name` does not match the app's 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."},SESSION_EXPIRED:{message:"That conversation has ended. Start a new one by leaving out --conversation."},SESSION_TERMINATED:{message:"That conversation was replaced by a newer one. Start a new one by leaving out --conversation."},STORE_PAUSED:{message:"The store is paused, so its assistant can't reply."},SPEND_LIMIT_REACHED:{message:"The store has reached its spending limit."},STORE_PLAN_INACTIVE:{message:"The store's plan isn't active."},CREDIT_BALANCE_EXHAUSTED:{message:"The store is out of credits."},CREDIT_BALANCE_TOO_LOW:{message:"The store's credit balance is too low."},TEST_ALLOWANCE_REACHED:{message:"Test chats have used their allowance for now. Try again later.",includeDetail:!0},STALE_EDIT:{message:"The text changed since you read it, or your edit doesn't match it.",includeDetail:!0}};function ns(e,t,n){if(t&&t in wn){let r=wn[t];return r?r.includeDetail&&n?`${r.message} (${n})`:r.message:yn(e)}return yn(e)}function yn(e){return e===401?"Sign-in needed. Run `npx greatstore login`.":e===426?bn:e===403?"Not authorized for this app 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 We(e,t){let n=gn(e),r=xn(n,"sub");if(!r)throw new Error("Token is missing a `sub` claim.");let o=rs(n,"exp");return{access_token:e,expires_at:o??Math.floor(Date.now()/1e3)+3600,sub:r,...Je(n,"email","email"),...Je(n,"accountId","accountId"),...Je(n,"name","name"),...Je(n,"surname","surname"),...os(n,"superUser","superUser"),...t?{store:t}:{}}}function xn(e,t){let n=e[t];return typeof n=="string"?n:void 0}function rs(e,t){let n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Je(e,t,n){let r=xn(e,t);return r?{[n]:r}:{}}function os(e,t,n){let r=e[t];return r===!0?{[n]:!0}:typeof r=="string"&&r.toLowerCase()==="true"?{[n]:!0}:{}}import*as Ye from"fs";import*as te from"path";var ss="https://my.greatstore.ai",$n="_library";function Le(e){return e===$n}var ee=class extends Error{constructor(t){super(t),this.name="StoreResolutionError"}};function E(e={}){let t=Pt(e.cwd??process.cwd());if(t)return $e(t);throw new ee("No .gsrc found in this directory or any ancestor. Run `npx greatstore apps init --store <slug>` first to scaffold a GreatStore project.")}function vn(e=process.cwd()){let t=Pt(e);if(t)return $e(t);let n=Ne();if(n)return n;throw new ee("No store selected. Run `npx greatstore login`, or run from a project with a .gsrc.")}function Ne(){try{return M()?.store??null}catch{return null}}function $e(e){let t=Ne();if(t&&t!==e)throw new ee(`This targets store "${e}" but you're signed in to "${t}". Run \`npx greatstore switch ${e}\` to change stores.`);return e}function Pt(e){let t=kn(e);return t?t.library===!0?$n:typeof t.store=="string"?t.store.trim():null:null}function kn(e){let t=te.resolve(e),n=te.parse(t).root;for(;;){let r=te.join(t,".gsrc");if(Ye.existsSync(r))try{let s=JSON.parse(Ye.readFileSync(r,"utf8"));if(s.library===!0||typeof s.store=="string"&&s.store.trim())return s}catch{}if(t===n)return null;let o=te.dirname(t);if(o===t)return null;t=o}}function At(e=process.cwd(),t=process.env){if(t.GS_DASHBOARD_BASE?.trim())return de(t);let n=kn(e)?.dashboard;return typeof n=="string"&&n.trim()?Ct(n.trim()):de(t)}function h(e){let t=w(e.flags,"store")?.trim();if(t)return $e(t);let n=Pt(process.cwd());if(n)return $e(n);let r=Ne();if(r)return r;throw new ee("No store selected. Pass --store <slug>, or run from a project with a .gsrc.")}function C(e,t=process.env){let n=t.GS_API_BASE?.trim();return n?Ct(n):`https://${e}.greatstore.ai`}function ze(e,t=process.env){return Le(e)?`${At(process.cwd(),t)}/cli/library`:`${C(e,t)}/api/apps`}function de(e=process.env){let t=e.GS_DASHBOARD_BASE?.trim();return t?Ct(t):ss}function S(e,t=process.env){return`${de(t)}/${e}/admin`}function Ct(e){return e.endsWith("/")?e.slice(0,-1):e}import*as P from"fs";import*as Xe from"os";import*as fe from"path";import{fileURLToPath as is}from"url";var ve="greatstore",En=".version";function as(){for(let e of["./gs-skill/","../../gs-skill/"]){let t=fe.resolve(is(new URL(e,import.meta.url)));if(P.existsSync(fe.join(t,"SKILL.md")))return t}throw new Error("internal: this install of the CLI is missing the agent skill files")}function Qe(e=Xe.homedir()){return fe.join(pe(e),"skill",ve)}function Tt(e,t=Xe.homedir()){let n=Qe(t),r=ls(n);if(r!==null&&xe(r,e)>=0)return n;let o=`${n}.tmp-${process.pid}`,s=`${n}.old-${process.pid}`;return P.rmSync(o,{recursive:!0,force:!0}),P.cpSync(as(),o,{recursive:!0}),P.writeFileSync(fe.join(o,En),e),P.existsSync(n)&&P.renameSync(n,s),P.renameSync(o,n),P.rmSync(s,{recursive:!0,force:!0}),n}function Pn(e,t=Xe.homedir()){try{P.existsSync(Qe(t))&&Tt(e,t)}catch{}}function ls(e){try{return P.readFileSync(fe.join(e,En),"utf8").trim()}catch{return null}}import*as An from"fs";async function Cn(e){let t=w(e.flags,"store")?.trim();process.stdout.write(`Opening browser for sign-in\u2026
35
+ `);let{token:n,store:r}=await Ge({dashboardBaseUrl:de(),...t?{requestedStore:t}:{}}),o=We(n,r);Ve(o);let s=o.email??o.sub;o.store?process.stdout.write(`Logged in as ${s}, working on store "${o.store}".
36
36
  `):process.stdout.write(`Logged in as ${s}.
37
- `),process.stdout.write(zo())}function zo(e){return kn.existsSync(Qe(e))?"":["","AI coding agent? Run `npx greatstore skill` and follow its steps to install the","GreatStore skill, which teaches you how to work with this store. (Using one","yourself? Ask it to run that command.)",""].join(`
38
- `)}function En(){let e=B()!==null;un(),process.stdout.write(e?`Logged out.
37
+ `),process.stdout.write(cs())}function cs(e){return An.existsSync(Qe(e))?"":["","AI coding agent? Run `npx greatstore skill` and follow its steps to install the","GreatStore skill, which teaches you how to work with this store. (Using one","yourself? Ask it to run that command.)",""].join(`
38
+ `)}function Tn(){let e=M()!==null;mn(),process.stdout.write(e?`Logged out.
39
39
  `:`Not logged in.
40
- `)}function Pn(){let e=B();if(!e)return process.stderr.write("Not logged in. Run `npx greatstore login`.\n"),1;let t=Ke(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(`
40
+ `)}function Rn(){let e=M();if(!e)return process.stderr.write("Not logged in. Run `npx greatstore login`.\n"),1;let t=Ke(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(`
41
41
  `)+`
42
- `),t?1:0}async function An(e){if(!B())throw new q;let n=e[0]?.trim();process.stdout.write(`Opening browser to switch stores\u2026
43
- `);let{token:r,store:o}=await qe({dashboardBaseUrl:de(),...n?{requestedStore:n}:{}}),s=We(r,o);return Ve(s),s.store?process.stdout.write(`Now working on store "${s.store}".
42
+ `),t?1:0}async function _n(e){if(!M())throw new G;let n=e[0]?.trim();process.stdout.write(`Opening browser to switch stores\u2026
43
+ `);let{token:r,store:o}=await Ge({dashboardBaseUrl:de(),...n?{requestedStore:n}:{}}),s=We(r,o);return Ve(s),s.store?process.stdout.write(`Now working on store "${s.store}".
44
44
  `):process.stdout.write(`Switched.
45
- `),0}function Cn(){process.stdout.write(Xo(Ct(N)))}function Xo(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 "${ke}":`,""," mkdir -p <SKILLS_DIR>",` ln -sfn "${e}" "<SKILLS_DIR>/${ke}"`,"","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>/${ke}/SKILL.md to confirm the install.`,"",`On Windows: mklink /D "<SKILLS_DIR>\\${ke}" "${e}"`,""].join(`
46
- `)}var ne={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},barLook:{kind:"string",values:["glass","lifted","outlined","bold"],help:"How the chat bar looks on the page.",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 Tn(e){let t=e.toLowerCase();return Object.keys(ne).map(n=>{let r=n.toLowerCase();return{name:n,distance:Zo(t,r),prefix:Qo(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 Qo(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;return n}function Zo(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 es=`npx greatstore configure \u2014 view and edit a store's configuration.
45
+ `),0}function jn(){process.stdout.write(us(Tt(N)))}function us(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 "${ve}":`,""," mkdir -p <SKILLS_DIR>",` ln -sfn "${e}" "<SKILLS_DIR>/${ve}"`,"","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>/${ve}/SKILL.md to confirm the install.`,"",`On Windows: mklink /D "<SKILLS_DIR>\\${ve}" "${e}"`,""].join(`
46
+ `)}var ne={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},barLook:{kind:"string",values:["glass","lifted","outlined","bold"],help:"How the chat bar looks on the page.",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 In(e){let t=e.toLowerCase();return Object.keys(ne).map(n=>{let r=n.toLowerCase();return{name:n,distance:ds(t,r),prefix:ps(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 ps(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;return n}function ds(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 fs=`npx greatstore configure \u2014 view and edit a store's configuration.
47
47
 
48
48
  Usage:
49
49
  npx greatstore configure Show the current configuration.
@@ -56,8 +56,8 @@ Run \`npx greatstore configure set --help\` for the full field list.
56
56
  Flags:
57
57
  --store <slug> Which store to act on (default: nearest .gsrc).
58
58
  --json Machine-readable output.
59
- `;function ts(){let e=Object.entries(ne).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(`
60
- `)}function ns(){return Object.entries(ne).filter(([,e])=>e.brandVisible).map(([e])=>e).join(", ")}function rs(){return`npx greatstore configure set \u2014 save configuration fields.
59
+ `;function ms(){let e=Object.entries(ne).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(`
60
+ `)}function gs(){return Object.entries(ne).filter(([,e])=>e.brandVisible).map(([e])=>e).join(", ")}function hs(){return`npx greatstore configure set \u2014 save configuration fields.
61
61
 
62
62
  Only the fields you pass are written; everything else is left alone. Pass an
63
63
  empty value to clear a field (e.g. --displayName "").
@@ -71,7 +71,7 @@ Store fields:
71
71
  --cspConnectHosts <a,b,c> Extra connect hosts to allow.
72
72
 
73
73
  Theme fields (merge into the stored theme):
74
- ${ts()}
74
+ ${ms()}
75
75
 
76
76
  Whole-object theme writes:
77
77
  --theme '<json>' Merge this JSON object into the stored theme.
@@ -80,54 +80,54 @@ Whole-object theme writes:
80
80
  --theme "" Clear the theme entirely.
81
81
 
82
82
  These are shopper-visible, so confirm them with the merchant before writing:
83
- ${ns()}
83
+ ${gs()}
84
84
 
85
85
  Examples:
86
86
  npx greatstore configure set --theme.fontFamily Manrope --theme.radius sharp
87
87
  npx greatstore configure set --theme.brandColor "#1e1d66"
88
88
  npx greatstore configure set --theme '{"mode":"dark"}' --replace
89
- `}function jn(e){if(e===void 0||e==="show")return es;if(e==="set")return rs()}import*as A from"fs";import*as T from"path";import{readdirSync as aa,readFileSync as la}from"fs";import{fileURLToPath as ua}from"url";var Ze=null;function et(){return Ze||(Ze=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 // Report a meaningful click (not scrolling or closing) to the store\'s\\n // analytics, e.g. `track({ action: \\"open_product\\", product_id })`.\\n // See AGENTS.md.\\n track: (details?: Record<string, string | number | boolean>) => 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); `prefetch` names lookups\\n // the content needs, so it\'s ready sooner. See AGENTS.md.\\n generateStructuredContent: <T = unknown>(\\n schema: object,\\n prompt: string,\\n options: {\\n fallback: T;\\n prefetch?: { name: string; args?: Record<string, unknown> }[];\\n },\\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> Every CLI command that writes to this project rewrites this file to match the\\n> CLI running it, so any changes you make here will be overwritten. Put\\n> 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 \u251C\u2500\u2500\u2510 $.track(): the click\\n \u2502 \u2502 \u2502 \u2502 counts in the store\'s\\n \u2502 \u2502 \u2502<\u2500\u2518 Google Analytics\\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/`): it always starts with a verb, then names the job, not\\nthe widget. `show_size_guide`, `find_gift`, `book_appointment` read as\\nintents; `size_guide` and `gift_finder` read as nouns with no action, and\\n`size_modal`, `quiz_ui`, `product_grid_v2` as implementation details \u2014\\nall get skipped. Prefer a plain verb that says what happens: `show_` to\\npresent something, `find_`/`compare_` for helping choose, `book_`/`start_`\\nfor a flow the shopper completes. `displayName` is the one field written\\nfor 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| `$.track(details?)` | Report a meaningful click to the store\'s Google Analytics, as a `greatstore_app_click` event that counts toward the shopper having used the store\'s agent. Call it when the shopper does something in your app \u2014 opens a product, copies a code, submits a form \u2014 never for scrolling, paging, zooming or closing. `details` is a flat object of strings, numbers and booleans; by convention pass an `action` verb plus `product_id` when a product is involved: `$.track({ action: \\"open_product\\", product_id })`. Each event also carries `app_name` and `app_open_seconds` (how long the app had been on screen), which your keys can\'t overwrite. Strings are cut to 100 characters, nested values and names Google Analytics rejects are dropped, and an identical call within about a second counts once. Where the page has no Google Analytics, and in the app preview, it does nothing. |\\n| `$.generateStructuredContent(schema, prompt, { fallback, prefetch })` | 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. `prefetch` is optional: when the app already knows the lookups the content needs (say, its product\'s details by ID), list them as `{ name, args }` \u2014 the read-only connector tools `$.callTool` runs, up to 5 \u2014 and the content is ready sooner. They are then the content\'s only data. |\\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"}'),Ze)}var _n={name:"__GS_NAME__",displayName:"__GS_DISPLAY_NAME__",store:"__GS_STORE__",version:"__GS_VERSION__"};function tt(e,t){let n=e;for(let o of Object.keys(_n)){let s=t[o];s!==void 0&&(n=n.split(_n[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}import*as O from"fs";import*as nt from"path";var re="AGENTS.md",os=["CLAUDE.md","GEMINI.md"];function ss(){let e=et()[`root/${re}`];if(e===void 0)throw new Error(`internal: template is missing root/${re}`);return tt(e,{version:N})}function Tt(e,t={}){let n=[],r=ss(),o=nt.join(e,re);(O.existsSync(o)?O.readFileSync(o,"utf8"):null)!==r&&(O.writeFileSync(o,r),n.push(re));for(let i of os){let a=nt.join(e,i);t.force&&Rn(a)&&O.rmSync(a),Rn(a)||(O.symlinkSync(re,a),n.push(i))}return n}function V(e){try{if(!O.existsSync(nt.join(e,"components")))return;let t=Tt(e);t.length>0&&process.stdout.write(is(t))}catch{}}function is(e){return`Refreshed ${e.join(", ")} to match GreatStore CLI v${N}.
89
+ `}function Ln(e){if(e===void 0||e==="show")return fs;if(e==="set")return hs()}import*as A from"fs";import*as T from"path";import{readdirSync as Pa,readFileSync as Aa}from"fs";import{fileURLToPath as Ta}from"url";var Ze=null;function et(){return Ze||(Ze=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 // Report a meaningful click (not scrolling or closing) to the store\'s\\n // analytics, e.g. `track({ action: \\"open_product\\", product_id })`.\\n // See AGENTS.md.\\n track: (details?: Record<string, string | number | boolean>) => 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); `prefetch` names lookups\\n // the content needs, so it\'s ready sooner. See AGENTS.md.\\n generateStructuredContent: <T = unknown>(\\n schema: object,\\n prompt: string,\\n options: {\\n fallback: T;\\n prefetch?: { name: string; args?: Record<string, unknown> }[];\\n },\\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> Every CLI command that writes to this project rewrites this file to match the\\n> CLI running it, so any changes you make here will be overwritten. Put\\n> 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 \u251C\u2500\u2500\u2510 $.track(): the click\\n \u2502 \u2502 \u2502 \u2502 counts in the store\'s\\n \u2502 \u2502 \u2502<\u2500\u2518 Google Analytics\\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/`): it always starts with a verb, then names the job, not\\nthe widget. `show_size_guide`, `find_gift`, `book_appointment` read as\\nintents; `size_guide` and `gift_finder` read as nouns with no action, and\\n`size_modal`, `quiz_ui`, `product_grid_v2` as implementation details \u2014\\nall get skipped. Prefer a plain verb that says what happens: `show_` to\\npresent something, `find_`/`compare_` for helping choose, `book_`/`start_`\\nfor a flow the shopper completes. `displayName` is the one field written\\nfor 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| `$.track(details?)` | Report a meaningful click to the store\'s Google Analytics, as a `greatstore_app_click` event that counts toward the shopper having used the store\'s agent. Call it when the shopper does something in your app \u2014 opens a product, copies a code, submits a form \u2014 never for scrolling, paging, zooming or closing. `details` is a flat object of strings, numbers and booleans; by convention pass an `action` verb plus `product_id` when a product is involved: `$.track({ action: \\"open_product\\", product_id })`. Each event also carries `app_name` and `app_open_seconds` (how long the app had been on screen), which your keys can\'t overwrite. Strings are cut to 100 characters, nested values and names Google Analytics rejects are dropped, and an identical call within about a second counts once. Where the page has no Google Analytics, and in the app preview, it does nothing. |\\n| `$.generateStructuredContent(schema, prompt, { fallback, prefetch })` | 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. `prefetch` is optional: when the app already knows the lookups the content needs (say, its product\'s details by ID), list them as `{ name, args }` \u2014 the read-only connector tools `$.callTool` runs, up to 5 \u2014 and the content is ready sooner. They are then the content\'s only data. |\\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"}'),Ze)}var Nn={name:"__GS_NAME__",displayName:"__GS_DISPLAY_NAME__",store:"__GS_STORE__",version:"__GS_VERSION__"};function tt(e,t){let n=e;for(let o of Object.keys(Nn)){let s=t[o];s!==void 0&&(n=n.split(Nn[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}import*as O from"fs";import*as nt from"path";var re="AGENTS.md",ws=["CLAUDE.md","GEMINI.md"];function ys(){let e=et()[`root/${re}`];if(e===void 0)throw new Error(`internal: template is missing root/${re}`);return tt(e,{version:N})}function Rt(e,t={}){let n=[],r=ys(),o=nt.join(e,re);(O.existsSync(o)?O.readFileSync(o,"utf8"):null)!==r&&(O.writeFileSync(o,r),n.push(re));for(let i of ws){let a=nt.join(e,i);t.force&&On(a)&&O.rmSync(a),On(a)||(O.symlinkSync(re,a),n.push(i))}return n}function V(e){try{if(!O.existsSync(nt.join(e,"components")))return;let t=Rt(e);t.length>0&&process.stdout.write(Ss(t))}catch{}}function Ss(e){return`Refreshed ${e.join(", ")} to match GreatStore CLI v${N}.
90
90
  This is a routine, expected update, like a lockfile. Commit it together with your
91
91
  own changes, even though you didn't make it.
92
- `}function Rn(e){try{return O.lstatSync(e),!0}catch{return!1}}var Ln=/^[a-z][a-z0-9_]*$/;function In(e){let t=e.positional[0];if(t!==void 0&&!Ln.test(t))throw new Error(`Invalid app name: "${t}" (must match ${Ln}).`);let n=m(e.flags,"force"),r=w(e.flags,"store"),o=w(e.flags,"out")??".",s=T.resolve(o),i=as(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?$e(r):Ne()??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=ls(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 ${T.relative(process.cwd(),s)||"."}`," npm install"," npx greatstore apps init <app_name> # add your first app",""),process.stdout.write(u.join(`
93
- `));return}let c=T.join(s,"components",t);us(c,t,n);let p=T.relative(process.cwd(),s)||".";process.stdout.write([`Added app "${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(`
94
- `))}function as(e){return A.existsSync(T.join(e,"package.json"))&&A.existsSync(T.join(e,".gsrc"))}function ls(e,t,n,r){if(A.mkdirSync(e,{recursive:!0}),!t&&!n&&A.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?ds():ps({store:r.store}),s=cs(e,o,n);return A.mkdirSync(T.join(e,"components"),{recursive:!0}),s}function cs(e,t,n){let r=[];for(let[o,s]of t){let i=T.join(e,o);A.mkdirSync(T.dirname(i),{recursive:!0}),!(!n&&A.existsSync(i))&&(A.writeFileSync(i,s),r.push(o))}return r.push(...Tt(e,{force:n})),r}function us(e,t,n){if(A.existsSync(e)&&!n&&A.readdirSync(e).length>0)throw new Error(`Refusing to overwrite existing components/${t}/. Pass --force to override.`);A.mkdirSync(e,{recursive:!0});for(let[r,o]of fs(t))A.writeFileSync(T.join(e,r),o)}function jt(e,t,n=new Set){let r=et();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,tt(s,t)])}function ps(e){if(!e.store)throw new Error("internal: rootFiles called without a store slug");return jt("root/",{store:e.store},new Set([re]))}function ds(){return jt("root/",{},new Set([".gsrc",re]))}function fs(e){return jt("component/",{name:e,displayName:ms(e)})}function ms(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 S from"path";import*as ve from"fs";import*as _t from"path";var $="style.css",j="bundle.css",rt=`./${$}`,Nn=256*1024;function gs(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 U(e){let t=_t.join(e,"component.tsx");if(!ve.existsSync(t))return{imported:!1,problems:[]};let n=gs(ve.readFileSync(t,"utf8")),r=n.filter(i=>i!==rt).map(i=>({file:"component.tsx",message:`imports "${i}". A component's styles go in its own ${$}, imported as "${rt}"; move these rules there.`})),o=n.includes(rt);if(!o)return{imported:o,problems:r};let s=_t.join(e,$);if(!ve.existsSync(s))return r.push({file:"component.tsx",message:`imports "${rt}", but there's no ${$} beside it.`}),{imported:o,problems:r};for(let i of hs(ve.readFileSync(s,"utf8")))r.push({file:$,message:i});return{imported:o,problems:r}}function hs(e){let t=[],n=Buffer.byteLength(e,"utf8");n>Nn&&t.push(`is ${(n/1024).toFixed(1)} KB; the limit is ${Nn/1024} KB.`);let r=e.replace(/\/\*[\s\S]*?\*\//g,s=>s.replace(/[^\n]/g," ")),o=s=>r.slice(0,s).split(`
95
- `).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 Cs}from"module";import{pathToFileURL as rr}from"url";import*as Kn from"fs";import*as K from"path";import{createRequire as ws}from"module";import*as ot from"path";function Fn(e,t,n){let r=Bn(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=Ss(r,o);return s?$s(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 ${ot.basename(t)} could not be parsed (${o.message})`}}}function Dn(e,t,n){let r=Bn(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(ys(r,a)){s=!0;return}r.forEachChild(a,i)}};return i(o),s}catch{return!1}}function ys(e,t){if(e.isPropertyAccessExpression(t))return On(e,t.expression)&&t.name.text==="GreatStore";if(e.isElementAccessExpression(t)){let n=t.argumentExpression;return On(e,t.expression)&&e.isStringLiteralLike(n)&&n.text==="GreatStore"}return!1}function On(e,t){return e.isIdentifier(t)&&(t.text==="window"||t.text==="globalThis")}function Bn(e){let t=ws(ot.join(e,"package.json"));try{return t("typescript")}catch{return null}}function Ss(e,t){let n=null;for(let o of t.statements){if(e.isFunctionDeclaration(o)&&bs(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)?xs(e,t,r.text):null}function bs(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 xs(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 $s(e,t,n){let r=n.parameters[0];if(!r)return{ok:!0,props:{names:[],open:!1}};if(r.type){let o=Rt(e,t,r.type,new Set);if(o)return{ok:!0,props:o}}return e.isObjectBindingPattern(r.name)?{ok:!0,props:ks(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 Rt(e,t,n,r){if(e.isTypeLiteralNode(n))return Mn(e,n.members);if(e.isTypeReferenceNode(n)&&e.isIdentifier(n.typeName))return Hn(e,t,n.typeName.text,r);if(e.isIntersectionTypeNode(n)){let o=n.types.map(s=>Rt(e,t,s,r));return o.every(s=>s===null)?null:qn(o.map(s=>s??{names:[],open:!0}))}return null}function Hn(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=Mn(e,o.members),i=(o.heritageClauses??[]).flatMap(a=>a.types.map(l=>e.isIdentifier(l.expression)?Hn(e,t,l.expression.text,r)??{names:[],open:!0}:{names:[],open:!0}));return qn([s,...i])}if(e.isTypeAliasDeclaration(o)&&o.name.text===n)return Rt(e,t,o.type,r)}return null}function Mn(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=Gn(e,o.name);if(s===null){r=!0;continue}n.push(s)}return{names:n,open:r}}function ks(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=Gn(e,s);i===null?r=!0:n.push(i)}return{names:n,open:r}}function Gn(e,t){return e.isIdentifier(t)||e.isStringLiteral(t)?t.text:null}function qn(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 Jn(e){let{root:t,name:n}=e,r=K.join(t,"components",n),o=e.manifestPath??K.join(r,"manifest.json"),s=e.sourcePath??K.join(r,"component.tsx"),i=Lt(t,o),a=Lt(t,s),l=[],c=null,p=Vn(o);if(p===null)l.push({severity:"error",rule:"manifest/missing",file:i,message:"manifest not found."});else try{let g=JSON.parse(p);!g||typeof g!="object"||Array.isArray(g)?l.push({severity:"error",rule:"manifest/invalid",file:i,message:"manifest must be a JSON object."}):c=g}catch(g){l.push({severity:"error",rule:"manifest/invalid",file:i,message:`manifest is not valid JSON: ${g.message}`})}let u=Vn(s),f=u===null?{ok:!1,reason:`couldn't check props against the manifest \u2014 ${a} not found`}:Fn(t,s,u),y=u===null?!1:Dn(t,s,u);return{ctx:{name:n,manifestFile:i,sourceFile:a,manifest:c,props:f,usesWindowGreatStore:y,styleFile:Lt(t,K.join(r,"style.css")),stylesheet:U(r)},diagnostics:l}}function Vn(e){try{return Kn.readFileSync(e,"utf8")}catch{return null}}function Lt(e,t){let n=K.relative(e,t);return n.startsWith("..")?t:n.split(K.sep).join("/")}var Wn=new Set(["$"]);var It=new Map([["onSendMessage","sendMessage"],["onClose","close"],["onUpdateModelContext","updateModelContext"],["onShowLightbox","showLightbox"],["onGenerateStructuredContent","generateStructuredContent"],["storeData","store"],["Image","Image"],["useVoiceCall","useVoiceCall"]]);function Yn(e){let t=e.map(o=>`\`${o}\``).join(", "),n=e.map(o=>It.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 zn=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 apps" section in AGENTS.md for how to signal errors.']]);function Qn(e){if(!e.manifest)return[];let t=Es(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(It.has(a)){s.push(a);continue}let l=zn.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:Yn(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:vs(e.manifestFile,i)}),n}var Xn=8;function vs(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 Es(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 Ps=["anyOf","oneOf","allOf","$ref","not"];function st(e,t,n){if(Array.isArray(e)){e.forEach((s,i)=>st(s,`${t}[${i}]`,n));return}if(!e||typeof e!="object")return;let r=e;for(let s of Ps)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,st(i,`${t}.${s}`,n);"items"in r&&st(r.items,`${t}[]`,n)}function Zn(e){let t=e.manifest?.inputSchema;if(!t||typeof t!="object")return[];let n={bytes:Buffer.byteLength(JSON.stringify(t),"utf8"),fields:0,unionPaths:[]};st(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("; ")}.
96
- 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 er(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 tr(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 nr(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 Oe(e){return e.filter(t=>t.severity==="error")}function Nt(e){return e.filter(t=>t.severity==="warning")}function Fe(e){return`${e.severity==="error"?"error":"warning"} ${e.file}: ${e.message}`}var As=[er,Zn,Qn,tr,nr];function it(e){let{ctx:t,diagnostics:n}=Jn(e);for(let r of As)n.push(...r(t));return{diagnostics:n,ok:Oe(n).length===0}}var J="components";async function at(e){let t=process.cwd();if(!k.existsSync(S.join(t,"package.json"))||!k.existsSync(S.join(t,J)))throw new Error(`\`npx greatstore apps build\` must run from a project root (contains \`package.json\` and \`${J}/\`). Current dir: ${t}`);V(t);let n=_s(t);if(n.length===0)return process.stdout.write(`(no apps in ./${J} \u2014 run \`npx greatstore apps init <name>\` to add one)
92
+ `}function On(e){try{return O.lstatSync(e),!0}catch{return!1}}var Fn=/^[a-z][a-z0-9_]*$/;function Dn(e){let t=e.positional[0];if(t!==void 0&&!Fn.test(t))throw new Error(`Invalid app name: "${t}" (must match ${Fn}).`);let n=m(e.flags,"force"),r=w(e.flags,"store"),o=w(e.flags,"out")??".",s=T.resolve(o),i=bs(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?$e(r):Ne()??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=xs(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 ${T.relative(process.cwd(),s)||"."}`," npm install"," npx greatstore apps init <app_name> # add your first app",""),process.stdout.write(u.join(`
93
+ `));return}let c=T.join(s,"components",t);vs(c,t,n);let p=T.relative(process.cwd(),s)||".";process.stdout.write([`Added app "${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(`
94
+ `))}function bs(e){return A.existsSync(T.join(e,"package.json"))&&A.existsSync(T.join(e,".gsrc"))}function xs(e,t,n,r){if(A.mkdirSync(e,{recursive:!0}),!t&&!n&&A.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?Es():ks({store:r.store}),s=$s(e,o,n);return A.mkdirSync(T.join(e,"components"),{recursive:!0}),s}function $s(e,t,n){let r=[];for(let[o,s]of t){let i=T.join(e,o);A.mkdirSync(T.dirname(i),{recursive:!0}),!(!n&&A.existsSync(i))&&(A.writeFileSync(i,s),r.push(o))}return r.push(...Rt(e,{force:n})),r}function vs(e,t,n){if(A.existsSync(e)&&!n&&A.readdirSync(e).length>0)throw new Error(`Refusing to overwrite existing components/${t}/. Pass --force to override.`);A.mkdirSync(e,{recursive:!0});for(let[r,o]of Ps(t))A.writeFileSync(T.join(e,r),o)}function _t(e,t,n=new Set){let r=et();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,tt(s,t)])}function ks(e){if(!e.store)throw new Error("internal: rootFiles called without a store slug");return _t("root/",{store:e.store},new Set([re]))}function Es(){return _t("root/",{},new Set([".gsrc",re]))}function Ps(e){return _t("component/",{name:e,displayName:As(e)})}function As(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 v from"fs";import*as b from"path";import*as ke from"fs";import*as jt from"path";var $="style.css",R="bundle.css",rt=`./${$}`,Bn=256*1024;function Cs(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 U(e){let t=jt.join(e,"component.tsx");if(!ke.existsSync(t))return{imported:!1,problems:[]};let n=Cs(ke.readFileSync(t,"utf8")),r=n.filter(i=>i!==rt).map(i=>({file:"component.tsx",message:`imports "${i}". A component's styles go in its own ${$}, imported as "${rt}"; move these rules there.`})),o=n.includes(rt);if(!o)return{imported:o,problems:r};let s=jt.join(e,$);if(!ke.existsSync(s))return r.push({file:"component.tsx",message:`imports "${rt}", but there's no ${$} beside it.`}),{imported:o,problems:r};for(let i of Ts(ke.readFileSync(s,"utf8")))r.push({file:$,message:i});return{imported:o,problems:r}}function Ts(e){let t=[],n=Buffer.byteLength(e,"utf8");n>Bn&&t.push(`is ${(n/1024).toFixed(1)} KB; the limit is ${Bn/1024} KB.`);let r=e.replace(/\/\*[\s\S]*?\*\//g,s=>s.replace(/[^\n]/g," ")),o=s=>r.slice(0,s).split(`
95
+ `).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 Us}from"module";import{pathToFileURL as ar}from"url";import*as zn from"fs";import*as K from"path";import{createRequire as Rs}from"module";import*as ot from"path";function Un(e,t,n){let r=qn(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=js(r,o);return s?Ns(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 ${ot.basename(t)} could not be parsed (${o.message})`}}}function Hn(e,t,n){let r=qn(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(_s(r,a)){s=!0;return}r.forEachChild(a,i)}};return i(o),s}catch{return!1}}function _s(e,t){if(e.isPropertyAccessExpression(t))return Mn(e,t.expression)&&t.name.text==="GreatStore";if(e.isElementAccessExpression(t)){let n=t.argumentExpression;return Mn(e,t.expression)&&e.isStringLiteralLike(n)&&n.text==="GreatStore"}return!1}function Mn(e,t){return e.isIdentifier(t)&&(t.text==="window"||t.text==="globalThis")}function qn(e){let t=Rs(ot.join(e,"package.json"));try{return t("typescript")}catch{return null}}function js(e,t){let n=null;for(let o of t.statements){if(e.isFunctionDeclaration(o)&&Is(e,o))return o;e.isExportAssignment(o)&&!o.isExportEquals&&(n=o.expression)}if(!n)return null;let r=Gn(e,n);return e.isArrowFunction(r)||e.isFunctionExpression(r)?r:e.isIdentifier(r)?Ls(e,t,r.text):null}function Is(e,t){return t.modifiers?.some(n=>n.kind===e.SyntaxKind.DefaultKeyword)??!1}function Gn(e,t){let n=t;for(;e.isParenthesizedExpression(n)||e.isAsExpression(n)||e.isSatisfiesExpression(n);)n=n.expression;return n}function Ls(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=Gn(e,o.initializer);if(e.isArrowFunction(s)||e.isFunctionExpression(s))return s}}return null}function Ns(e,t,n){let r=n.parameters[0];if(!r)return{ok:!0,props:{names:[],open:!1}};if(r.type){let o=It(e,t,r.type,new Set);if(o)return{ok:!0,props:o}}return e.isObjectBindingPattern(r.name)?{ok:!0,props:Os(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 It(e,t,n,r){if(e.isTypeLiteralNode(n))return Kn(e,n.members);if(e.isTypeReferenceNode(n)&&e.isIdentifier(n.typeName))return Vn(e,t,n.typeName.text,r);if(e.isIntersectionTypeNode(n)){let o=n.types.map(s=>It(e,t,s,r));return o.every(s=>s===null)?null:Wn(o.map(s=>s??{names:[],open:!0}))}return null}function Vn(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=Kn(e,o.members),i=(o.heritageClauses??[]).flatMap(a=>a.types.map(l=>e.isIdentifier(l.expression)?Vn(e,t,l.expression.text,r)??{names:[],open:!0}:{names:[],open:!0}));return Wn([s,...i])}if(e.isTypeAliasDeclaration(o)&&o.name.text===n)return It(e,t,o.type,r)}return null}function Kn(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=Jn(e,o.name);if(s===null){r=!0;continue}n.push(s)}return{names:n,open:r}}function Os(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=Jn(e,s);i===null?r=!0:n.push(i)}return{names:n,open:r}}function Jn(e,t){return e.isIdentifier(t)||e.isStringLiteral(t)?t.text:null}function Wn(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 Xn(e){let{root:t,name:n}=e,r=K.join(t,"components",n),o=e.manifestPath??K.join(r,"manifest.json"),s=e.sourcePath??K.join(r,"component.tsx"),i=Lt(t,o),a=Lt(t,s),l=[],c=null,p=Yn(o);if(p===null)l.push({severity:"error",rule:"manifest/missing",file:i,message:"manifest not found."});else try{let g=JSON.parse(p);!g||typeof g!="object"||Array.isArray(g)?l.push({severity:"error",rule:"manifest/invalid",file:i,message:"manifest must be a JSON object."}):c=g}catch(g){l.push({severity:"error",rule:"manifest/invalid",file:i,message:`manifest is not valid JSON: ${g.message}`})}let u=Yn(s),f=u===null?{ok:!1,reason:`couldn't check props against the manifest \u2014 ${a} not found`}:Un(t,s,u),y=u===null?!1:Hn(t,s,u);return{ctx:{name:n,manifestFile:i,sourceFile:a,manifest:c,props:f,usesWindowGreatStore:y,styleFile:Lt(t,K.join(r,"style.css")),stylesheet:U(r)},diagnostics:l}}function Yn(e){try{return zn.readFileSync(e,"utf8")}catch{return null}}function Lt(e,t){let n=K.relative(e,t);return n.startsWith("..")?t:n.split(K.sep).join("/")}var Qn=new Set(["$"]);var Nt=new Map([["onSendMessage","sendMessage"],["onClose","close"],["onUpdateModelContext","updateModelContext"],["onShowLightbox","showLightbox"],["onGenerateStructuredContent","generateStructuredContent"],["storeData","store"],["Image","Image"],["useVoiceCall","useVoiceCall"]]);function Zn(e){let t=e.map(o=>`\`${o}\``).join(", "),n=e.map(o=>Nt.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 er=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 apps" section in AGENTS.md for how to signal errors.']]);function nr(e){if(!e.manifest)return[];let t=Ds(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(Qn.has(a))continue;if(Nt.has(a)){s.push(a);continue}let l=er.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:Zn(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:Fs(e.manifestFile,i)}),n}var tr=8;function Fs(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,tr).map(s=>`\`${s}\``).join(", "),r=t.length-tr,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 Ds(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 Bs=["anyOf","oneOf","allOf","$ref","not"];function st(e,t,n){if(Array.isArray(e)){e.forEach((s,i)=>st(s,`${t}[${i}]`,n));return}if(!e||typeof e!="object")return;let r=e;for(let s of Bs)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,st(i,`${t}.${s}`,n);"items"in r&&st(r.items,`${t}[]`,n)}function rr(e){let t=e.manifest?.inputSchema;if(!t||typeof t!="object")return[];let n={bytes:Buffer.byteLength(JSON.stringify(t),"utf8"),fields:0,unionPaths:[]};st(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("; ")}.
96
+ 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 or(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 sr(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 ir(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 Oe(e){return e.filter(t=>t.severity==="error")}function Ot(e){return e.filter(t=>t.severity==="warning")}function Fe(e){return`${e.severity==="error"?"error":"warning"} ${e.file}: ${e.message}`}var Ms=[or,rr,nr,sr,ir];function it(e){let{ctx:t,diagnostics:n}=Xn(e);for(let r of Ms)n.push(...r(t));return{diagnostics:n,ok:Oe(n).length===0}}var J="components";async function at(e){let t=process.cwd();if(!v.existsSync(b.join(t,"package.json"))||!v.existsSync(b.join(t,J)))throw new Error(`\`npx greatstore apps build\` must run from a project root (contains \`package.json\` and \`${J}/\`). Current dir: ${t}`);V(t);let n=Gs(t);if(n.length===0)return process.stdout.write(`(no apps in ./${J} \u2014 run \`npx greatstore apps init <name>\` to add one)
97
97
  `),[];let r=e.positional,o=r.filter(c=>!n.includes(c));if(o.length>0)throw new Error(`No app named ${o.map(c=>`"${c}"`).join(", ")} in ./${J}`);let s=r.length>0?n.filter(c=>r.includes(c)):n,i=[],a=[];for(let c of s){let p=it({root:t,name:c});for(let u of p.diagnostics)process.stdout.write(` ${Fe(u)}
98
98
  `);(p.ok?a:i).push(c)}if(a.length===0)return process.stdout.write(`
99
99
  Nothing built \u2014 fix the errors above.
100
- `),process.exitCode=1,i;let l=await Rs(t);for(let c of a)try{await Ts(t,c,l)}catch(p){process.stdout.write(` ${J}/${c}: ${p instanceof Error?p.message:String(p)}
100
+ `),process.exitCode=1,i;let l=await Vs(t);for(let c of a)try{await Hs(t,c,l)}catch(p){process.stdout.write(` ${J}/${c}: ${p instanceof Error?p.message:String(p)}
101
101
  `),i.push(c)}return i.length>0?(process.stdout.write(`
102
102
  Not built (fix the errors above): ${i.join(", ")}
103
- `),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 Ts(e,t,{build:n,reactPlugin:r,transformWithEsbuild:o}){let s=S.join(e,J,t),i=S.join(s,"bundle.js");await n({plugins:[js(s),r()],logLevel:"warn",build:{lib:{entry:S.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 ${J}/${t}/bundle.js (${or(p)}, ${sr(a,p)} smaller)
104
- `);let u=S.join(s,j);if(!U(s).imported){k.rmSync(u,{force:!0});return}let f=k.readFileSync(S.join(s,$),"utf8"),y=await o(f,S.join(s,$),{minify:!0,legalComments:"none",loader:"css",sourcemap:!1});k.writeFileSync(u,y.code);let g=Buffer.byteLength(y.code,"utf8");process.stdout.write(`built ${J}/${t}/${j} (${or(g)}, ${sr(Buffer.byteLength(f,"utf8"),g)} smaller)
105
- `)}function js(e){let t=S.join(e,$),n=S.join(e,"component.tsx"),r="\0greatstore-stylesheet";return{name:"greatstore-stylesheet",enforce:"pre",resolveId(o,s){if(!/\.css(\?.*)?$/.test(o))return null;let i=S.resolve(s??n);if(S.resolve(S.dirname(i),o.replace(/\?.*$/,""))===t&&i===n)return r;throw new Error(`${S.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 _s(e){let t=S.join(e,J);return k.readdirSync(t).filter(n=>{let r=S.join(t,n);return k.statSync(r).isDirectory()&&k.existsSync(S.join(r,"component.tsx"))}).sort()}function or(e){return e<1024?`${e} B`:`${(e/1024).toFixed(1)} KB`}function sr(e,t){return e===0?"0%":`${Math.round((1-t/e)*100)}%`}async function Rs(e){let t=Cs(S.join(e,"package.json")),n=ir(t,"vite");if(!n)throw new Error("Cannot find `vite` in this project. Run `npm install` first.");let r=ir(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(rr(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(rr(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 ir(e,t){let n;try{n=e.resolve(t)}catch{return null}let r=Ls(n,t);if(!r)return null;let o=S.dirname(r),s;try{s=JSON.parse(k.readFileSync(r,"utf8"))}catch{return null}let a=Is(s.exports)??(typeof s.module=="string"?s.module:null)??(typeof s.main=="string"?s.main:null);return a?S.resolve(o,a):null}function Ls(e,t){let n=S.dirname(e);for(;;){let r=S.join(n,"package.json");if(k.existsSync(r))try{if(JSON.parse(k.readFileSync(r,"utf8")).name===t)return r}catch{}let o=S.dirname(n);if(o===n)return null;n=o}}function Is(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 ar(e){let t=Sn(),n=`${C(t)}/api/apps/components`,r=await d(n);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(r,null,2)+`
103
+ `),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 Hs(e,t,{build:n,reactPlugin:r,transformWithEsbuild:o}){let s=b.join(e,J,t),i=b.join(s,"bundle.js");await n({plugins:[qs(s),r()],logLevel:"warn",build:{lib:{entry:b.join(s,"component.tsx"),formats:["es"],fileName:()=>"bundle.js"},outDir:s,emptyOutDir:!1,rollupOptions:{external:["react","react-dom","react/jsx-runtime"],output:{entryFileNames:"bundle.js",paths:{react:"/assets/remote-components/_runtime.js","react-dom":"/assets/remote-components/_runtime.js","react/jsx-runtime":"/assets/remote-components/_runtime.js"}}},minify:!0,sourcemap:!1}});let a=v.statSync(i).size,l=v.readFileSync(i,"utf8"),{code:c}=await o(l,i,{minify:!0,legalComments:"none",target:"esnext",loader:"js",sourcemap:!1});v.writeFileSync(i,c);let p=Buffer.byteLength(c,"utf8");process.stdout.write(`built ${J}/${t}/bundle.js (${lr(p)}, ${cr(a,p)} smaller)
104
+ `);let u=b.join(s,R);if(!U(s).imported){v.rmSync(u,{force:!0});return}let f=v.readFileSync(b.join(s,$),"utf8"),y=await o(f,b.join(s,$),{minify:!0,legalComments:"none",loader:"css",sourcemap:!1});v.writeFileSync(u,y.code);let g=Buffer.byteLength(y.code,"utf8");process.stdout.write(`built ${J}/${t}/${R} (${lr(g)}, ${cr(Buffer.byteLength(f,"utf8"),g)} smaller)
105
+ `)}function qs(e){let t=b.join(e,$),n=b.join(e,"component.tsx"),r="\0greatstore-stylesheet";return{name:"greatstore-stylesheet",enforce:"pre",resolveId(o,s){if(!/\.css(\?.*)?$/.test(o))return null;let i=b.resolve(s??n);if(b.resolve(b.dirname(i),o.replace(/\?.*$/,""))===t&&i===n)return r;throw new Error(`${b.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 Gs(e){let t=b.join(e,J);return v.readdirSync(t).filter(n=>{let r=b.join(t,n);return v.statSync(r).isDirectory()&&v.existsSync(b.join(r,"component.tsx"))}).sort()}function lr(e){return e<1024?`${e} B`:`${(e/1024).toFixed(1)} KB`}function cr(e,t){return e===0?"0%":`${Math.round((1-t/e)*100)}%`}async function Vs(e){let t=Us(b.join(e,"package.json")),n=ur(t,"vite");if(!n)throw new Error("Cannot find `vite` in this project. Run `npm install` first.");let r=ur(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(ar(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(ar(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 ur(e,t){let n;try{n=e.resolve(t)}catch{return null}let r=Ks(n,t);if(!r)return null;let o=b.dirname(r),s;try{s=JSON.parse(v.readFileSync(r,"utf8"))}catch{return null}let a=Js(s.exports)??(typeof s.module=="string"?s.module:null)??(typeof s.main=="string"?s.main:null);return a?b.resolve(o,a):null}function Ks(e,t){let n=b.dirname(e);for(;;){let r=b.join(n,"package.json");if(v.existsSync(r))try{if(JSON.parse(v.readFileSync(r,"utf8")).name===t)return r}catch{}let o=b.dirname(n);if(o===n)return null;n=o}}function Js(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 pr(e){let t=vn(),n=`${C(t)}/api/apps/components`,r=await d(n);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(r,null,2)+`
106
106
  `);return}if(r.components.length===0){process.stdout.write(`(no apps in ${t})
107
107
  `);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=`${oe("NAME",s.name)} ${oe("DRAFT",s.draft)} ${oe("LIVE",s.live)} ${oe("UPDATED",s.updated)} LINK`;process.stdout.write(i+`
108
108
  `);for(let a of o)process.stdout.write(`${oe(a.name,s.name)} ${oe(a.draft,s.draft)} ${oe(a.live,s.live)} ${oe(a.updated,s.updated)} ${a.permalink}
109
- `)}function oe(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}import*as _ from"fs";import*as Y from"path";import*as lr from"crypto";import*as se from"fs";import*as W from"path";var cr=".gssync.json";function ie(e){return lr.createHash("sha256").update(e).digest("hex")}function Ee(e){return se.existsSync(e)?ie(se.readFileSync(e,"utf8")):null}function Pe(e){let t=Ee(W.join(e,"manifest.json"));if(t===null)throw new Error(`Missing manifest.json in ${e}`);return{manifestHash:t,sourceHash:Ee(W.join(e,"component.tsx")),bundleHash:Ee(W.join(e,"bundle.js")),...U(e).imported?{styleHash:Ee(W.join(e,$)),styleBundleHash:Ee(W.join(e,j))}:{styleHash:null,styleBundleHash:null}}}function Ae(e){let t=W.join(e,cr);if(!se.existsSync(t))return null;try{let n=JSON.parse(se.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 me(e,t){se.writeFileSync(W.join(e,cr),JSON.stringify(t,null,2)+`
110
- `)}function ur(e,t){let n=Ns(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:(Ee(W.join(e,$))??"")!==(t.styleHash??"")}function Ns(e){try{return Pe(e)}catch{return null}}async function pr(e){let t=E(),n=m(e.flags,"force"),r=e.positional,o=process.cwd();if(r.length===0||r.length===1&&r[0]==="*")return Os({slug:t,root:o,args:e,force:n});if(r.length>1&&w(e.flags,"version"))throw new Error("--version is per-app; pass it together with a single `npx greatstore apps pull <name>`.");mr(o),V(o);let s=gr(e),i=[];for(let a of r){let l=await fr({slug:t,componentDir:Y.join(o,"components",a),name:a,revisionQuery:s,force:n});i.push(l),hr(l,n)}i.length>1&&dr(i,t),i.some(a=>a.status==="failed")&&(process.exitCode=1)}async function Os(e){let{slug:t,root:n,args:r,force:o}=e;if(w(r.flags,"version"))throw new Error("--version is per-app; pass it together with `npx greatstore apps pull <name>`.");mr(n),V(n);let s=gr(r),i=`${C(t)}/api/apps/components`,a=await d(i);if(a.components.length===0){process.stdout.write(`(no apps in ${t})
111
- `);return}let l=[];for(let c of a.components){let p=Y.join(n,"components",c.name),u=await fr({slug:t,componentDir:p,name:c.name,revisionQuery:s===""&&c.live===null?"?revision=draft":s,force:o});l.push(u),hr(u,o)}dr(l,t),l.some(c=>c.status==="failed")&&(process.exitCode=1)}function dr(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(`
109
+ `)}function oe(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}import*as _ from"fs";import*as Y from"path";import*as dr from"crypto";import*as se from"fs";import*as W from"path";var fr=".gssync.json";function ie(e){return dr.createHash("sha256").update(e).digest("hex")}function Ee(e){return se.existsSync(e)?ie(se.readFileSync(e,"utf8")):null}function Pe(e){let t=Ee(W.join(e,"manifest.json"));if(t===null)throw new Error(`Missing manifest.json in ${e}`);return{manifestHash:t,sourceHash:Ee(W.join(e,"component.tsx")),bundleHash:Ee(W.join(e,"bundle.js")),...U(e).imported?{styleHash:Ee(W.join(e,$)),styleBundleHash:Ee(W.join(e,R))}:{styleHash:null,styleBundleHash:null}}}function Ae(e){let t=W.join(e,fr);if(!se.existsSync(t))return null;try{let n=JSON.parse(se.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 me(e,t){se.writeFileSync(W.join(e,fr),JSON.stringify(t,null,2)+`
110
+ `)}function mr(e,t){let n=Ws(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:(Ee(W.join(e,$))??"")!==(t.styleHash??"")}function Ws(e){try{return Pe(e)}catch{return null}}async function gr(e){let t=E(),n=m(e.flags,"force"),r=e.positional,o=process.cwd();if(r.length===0||r.length===1&&r[0]==="*")return Ys({slug:t,root:o,args:e,force:n});if(r.length>1&&w(e.flags,"version"))throw new Error("--version is per-app; pass it together with a single `npx greatstore apps pull <name>`.");yr(o),V(o);let s=Sr(e),i=[];for(let a of r){let l=await wr({slug:t,componentDir:Y.join(o,"components",a),name:a,revisionQuery:s,force:n});i.push(l),br(l,n)}i.length>1&&hr(i,t),i.some(a=>a.status==="failed")&&(process.exitCode=1)}async function Ys(e){let{slug:t,root:n,args:r,force:o}=e;if(w(r.flags,"version"))throw new Error("--version is per-app; pass it together with `npx greatstore apps pull <name>`.");yr(n),V(n);let s=Sr(r),i=`${C(t)}/api/apps/components`,a=await d(i);if(a.components.length===0){process.stdout.write(`(no apps in ${t})
111
+ `);return}let l=[];for(let c of a.components){let p=Y.join(n,"components",c.name),u=await wr({slug:t,componentDir:p,name:c.name,revisionQuery:s===""&&c.live===null?"?revision=draft":s,force:o});l.push(u),br(u,o)}hr(l,t),l.some(c=>c.status==="failed")&&(process.exitCode=1)}function hr(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(`
112
112
  ${s.join(", ")} (of ${e.length}) \u2190 ${t}
113
- `)}async function fr(e){let{slug:t,componentDir:n,name:r,revisionQuery:o,force:s}=e;if(!s&&_.existsSync(n)){let g=Ae(n);if(ur(n,g))return{name:r,status:"skipped",message:"local has uncommitted changes; pass --force to overwrite"}}let i=`${C(t)}/api/apps/components/${encodeURIComponent(r)}`,a;try{a=await d(`${i}${o}`)}catch(g){if(o===""&&Fs(g))try{a=await d(`${i}?revision=draft`)}catch(L){return{name:r,status:"failed",message:L instanceof Error?L.message:String(L)}}else return{name:r,status:"failed",message:g instanceof Error?g.message:String(g)}}_.mkdirSync(n,{recursive:!0});let l=JSON.stringify(a.manifest,null,2)+`
114
- `;_.writeFileSync(Y.join(n,"manifest.json"),l),_.writeFileSync(Y.join(n,"bundle.js"),a.bundle);let c=["manifest.json","bundle.js"],p="";a.source!==null&&(_.writeFileSync(Y.join(n,"component.tsx"),a.source),c.push("component.tsx"),p=ie(a.source));let u=Y.join(n,$),f=Y.join(n,j);typeof a.style=="string"?(_.writeFileSync(u,a.style),_.writeFileSync(f,a.style_bundle??a.style),c.push($,j)):(_.rmSync(u,{force:!0}),_.rmSync(f,{force:!0})),me(n,{version:a.version,manifestHash:ie(l),sourceHash:p,bundleHash:ie(a.bundle)});let y=Pe(n);return me(n,{version:a.version,manifestHash:y.manifestHash,sourceHash:y.sourceHash??"",bundleHash:y.bundleHash??"",styleHash:y.styleHash??"",styleBundleHash:y.styleBundleHash??""}),{name:r,status:"pulled",version:a.version,wrote:c}}function mr(e){_.mkdirSync(Y.join(e,"components"),{recursive:!0})}function Fs(e){return e instanceof M&&e.status===404}function gr(e){let t=w(e.flags,"version");return t?`?version=${encodeURIComponent(t)}`:m(e.flags,"draft")?"?revision=draft":m(e.flags,"live")?"?revision=live":""}function hr(e,t){switch(e.status){case"pulled":{let n=e.wrote?`{${e.wrote.join(", ")}}`:"";process.stdout.write(` pulled ${e.name} v${e.version} ${n}
113
+ `)}async function wr(e){let{slug:t,componentDir:n,name:r,revisionQuery:o,force:s}=e;if(!s&&_.existsSync(n)){let g=Ae(n);if(mr(n,g))return{name:r,status:"skipped",message:"local has uncommitted changes; pass --force to overwrite"}}let i=`${C(t)}/api/apps/components/${encodeURIComponent(r)}`,a;try{a=await d(`${i}${o}`)}catch(g){if(o===""&&zs(g))try{a=await d(`${i}?revision=draft`)}catch(I){return{name:r,status:"failed",message:I instanceof Error?I.message:String(I)}}else return{name:r,status:"failed",message:g instanceof Error?g.message:String(g)}}_.mkdirSync(n,{recursive:!0});let l=JSON.stringify(a.manifest,null,2)+`
114
+ `;_.writeFileSync(Y.join(n,"manifest.json"),l),_.writeFileSync(Y.join(n,"bundle.js"),a.bundle);let c=["manifest.json","bundle.js"],p="";a.source!==null&&(_.writeFileSync(Y.join(n,"component.tsx"),a.source),c.push("component.tsx"),p=ie(a.source));let u=Y.join(n,$),f=Y.join(n,R);typeof a.style=="string"?(_.writeFileSync(u,a.style),_.writeFileSync(f,a.style_bundle??a.style),c.push($,R)):(_.rmSync(u,{force:!0}),_.rmSync(f,{force:!0})),me(n,{version:a.version,manifestHash:ie(l),sourceHash:p,bundleHash:ie(a.bundle)});let y=Pe(n);return me(n,{version:a.version,manifestHash:y.manifestHash,sourceHash:y.sourceHash??"",bundleHash:y.bundleHash??"",styleHash:y.styleHash??"",styleBundleHash:y.styleBundleHash??""}),{name:r,status:"pulled",version:a.version,wrote:c}}function yr(e){_.mkdirSync(Y.join(e,"components"),{recursive:!0})}function zs(e){return e instanceof D&&e.status===404}function Sr(e){let t=w(e.flags,"version");return t?`?version=${encodeURIComponent(t)}`:m(e.flags,"draft")?"?revision=draft":m(e.flags,"live")?"?revision=live":""}function br(e,t){switch(e.status){case"pulled":{let n=e.wrote?`{${e.wrote.join(", ")}}`:"";process.stdout.write(` pulled ${e.name} v${e.version} ${n}
115
115
  `);return}case"skipped":process.stdout.write(` skipped ${e.name}: ${e.message}
116
116
  `);return;case"failed":process.stdout.write(` failed ${e.name}: ${e.message??"unknown error"}
117
- `);return}}import*as x from"fs";import*as v from"path";import*as wr from"crypto";import*as lt from"fs";import*as yr from"path";function ct(e){let t=e?.screenshots;return Array.isArray(t)?[...new Set(t.filter(n=>typeof n=="string"))]:null}function Ds(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 Sr(e){let t=Ds(e);return t?`${wr.createHash("sha256").update(e).digest("hex").slice(0,16)}.${t}`:null}function ut(e,t){let n=yr.join(e,t);return lt.existsSync(n)?lt.readFileSync(n):null}async function $r(e){let t=E(),n=process.cwd();Bs(n);let r=v.join(n,"components");if(!x.existsSync(r))throw new Error("No components/ directory here. Run `npx greatstore apps init <name>` to scaffold the project root and your first app.");V(n);let o=e.positional,s=w(e.flags,"manifest"),i=w(e.flags,"bundle");if(o.length!==1&&(s||i))throw new Error("--manifest / --bundle can only be used together with a single `npx greatstore apps push <name>`.");if(o.length>0){let c=m(e.flags,"force")||s!==void 0||i!==void 0,p=[];for(let u of o){let f=await dt({slug:t,root:n,name:u,...s!==void 0?{manifestPath:s}:{},...i!==void 0?{bundlePath:i}:{},force:c});p.push(f),xr(f)}p.length>1&&br(p,t),p.some(u=>u.status==="failed")&&(process.exitCode=1);return}let a=Ot(r);if(a.length===0){process.stdout.write("(no apps in ./components \u2014 run `npx greatstore apps init <name>` to add one)\n");return}let l=[];for(let c of a){let p=await dt({slug:t,root:n,name:c,force:!1});l.push(p),xr(p)}br(l,t),l.some(c=>c.status==="failed")&&(process.exitCode=1)}function br(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(`
117
+ `);return}}import*as x from"fs";import*as k from"path";import*as xr from"crypto";import*as lt from"fs";import*as $r from"path";function ct(e){let t=e?.screenshots;return Array.isArray(t)?[...new Set(t.filter(n=>typeof n=="string"))]:null}function Xs(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 vr(e){let t=Xs(e);return t?`${xr.createHash("sha256").update(e).digest("hex").slice(0,16)}.${t}`:null}function ut(e,t){let n=$r.join(e,t);return lt.existsSync(n)?lt.readFileSync(n):null}async function Pr(e){let t=E(),n=process.cwd();Qs(n);let r=k.join(n,"components");if(!x.existsSync(r))throw new Error("No components/ directory here. Run `npx greatstore apps init <name>` to scaffold the project root and your first app.");V(n);let o=e.positional,s=w(e.flags,"manifest"),i=w(e.flags,"bundle");if(o.length!==1&&(s||i))throw new Error("--manifest / --bundle can only be used together with a single `npx greatstore apps push <name>`.");if(o.length>0){let c=m(e.flags,"force")||s!==void 0||i!==void 0,p=[];for(let u of o){let f=await dt({slug:t,root:n,name:u,...s!==void 0?{manifestPath:s}:{},...i!==void 0?{bundlePath:i}:{},force:c});p.push(f),Er(f)}p.length>1&&kr(p,t),p.some(u=>u.status==="failed")&&(process.exitCode=1);return}let a=Ft(r);if(a.length===0){process.stdout.write("(no apps in ./components \u2014 run `npx greatstore apps init <name>` to add one)\n");return}let l=[];for(let c of a){let p=await dt({slug:t,root:n,name:c,force:!1});l.push(p),Er(p)}kr(l,t),l.some(c=>c.status==="failed")&&(process.exitCode=1)}function kr(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(`
118
118
  ${s.join(", ")} (of ${e.length}) \u2192 ${t}
119
- `)}async function dt(e){let{slug:t,root:n,name:r,force:o}=e,s=v.join(n,"components",r);if(!x.existsSync(s))return{name:r,status:"failed",message:`components/${r}/ does not exist`};let i=e.manifestPath?v.resolve(e.manifestPath):v.join(s,"manifest.json"),a=e.bundlePath?v.resolve(e.bundlePath):v.join(s,"bundle.js"),l=v.join(s,"component.tsx");if(!x.existsSync(a))return{name:r,status:"failed",message:`bundle not found: ${a} (did you run \`npm run build\`?)`};let c=it({root:n,name:r,manifestPath:i,sourcePath:l});for(let F of Nt(c.diagnostics))process.stdout.write(` ${Fe(F)}
119
+ `)}async function dt(e){let{slug:t,root:n,name:r,force:o}=e,s=k.join(n,"components",r);if(!x.existsSync(s))return{name:r,status:"failed",message:`components/${r}/ does not exist`};let i=e.manifestPath?k.resolve(e.manifestPath):k.join(s,"manifest.json"),a=e.bundlePath?k.resolve(e.bundlePath):k.join(s,"bundle.js"),l=k.join(s,"component.tsx");if(!x.existsSync(a))return{name:r,status:"failed",message:`bundle not found: ${a} (did you run \`npm run build\`?)`};let c=it({root:n,name:r,manifestPath:i,sourcePath:l});for(let F of Ot(c.diagnostics))process.stdout.write(` ${Fe(F)}
120
120
  `);if(!c.ok)return{name:r,status:"failed",message:Oe(c.diagnostics).map(F=>`${F.file}: ${F.message}`).join(`
121
- ${pt}`)};let p=x.readFileSync(i,"utf8"),u=v.join(s,"listing.json"),f=Ie(t);if(f&&!x.existsSync(u))return{name:r,status:"failed",message:`components/${r}/listing.json is required for a library app`};let y=Pe(s),g=Ae(s),L=e.bundlePath===void 0&&g?.bundleHash!==void 0&&g.sourceHash!==(y.sourceHash??"")&&g.bundleHash===(y.bundleHash??""),Ge=g?.styleBundleHash!==void 0&&(g.styleHash??"")!==(y.styleHash??"")&&g.styleBundleHash===(y.styleBundleHash??""),zt=U(s).imported,Xt=v.join(s,j);if(zt&&!x.existsSync(Xt))return{name:r,status:"failed",message:`components/${r}/${j} is missing \u2014 run \`npx greatstore build ${r}\` first`};if(!o&&g!==null&&g.manifestHash===y.manifestHash&&g.sourceHash===(y.sourceHash??"")&&g.bundleHash!==void 0&&g.bundleHash===(y.bundleHash??"")&&(g.styleHash??"")===(y.styleHash??"")&&(g.styleBundleHash??"")===(y.styleBundleHash??""))return{name:r,status:"unchanged"};let Eo=x.readFileSync(a,"utf8"),Qt=x.existsSync(l)?x.readFileSync(l,"utf8"):null,H=new FormData;if(H.append("manifest",new Blob([p],{type:"application/json"}),"manifest.json"),H.append("bundle",new Blob([Eo],{type:"text/javascript"}),"bundle.js"),Qt!==null&&H.append("source",new Blob([Qt],{type:"text/plain; charset=utf-8"}),"component.tsx"),zt&&(H.append("style",new Blob([x.readFileSync(Xt,"utf8")],{type:"text/css; charset=utf-8"}),j),H.append("style_source",new Blob([x.readFileSync(v.join(s,$),"utf8")],{type:"text/css; charset=utf-8"}),$)),f){let F=x.readFileSync(u,"utf8");H.append("listing",new Blob([F],{type:"application/json"}),"listing.json");let Zt=v.join(s,"changelog.json");x.existsSync(Zt)&&H.append("changelog",new Blob([x.readFileSync(Zt,"utf8")],{type:"application/json"}),"changelog.json");let en=null;try{en=ct(JSON.parse(F))}catch{}for(let xt of en??[]){let tn=ut(s,xt);if(!tn)return{name:r,status:"failed",message:`components/${r}/${xt} is named in listing.json but doesn't exist`};H.append("screenshot",new Blob([new Uint8Array(tn)]),xt)}}o||H.append("base_version",String(g?.version??0));let Po=`${ze(t)}/components/${encodeURIComponent(r)}`,ye;try{ye=await d(Po,{method:"POST",multipart:H})}catch(F){return{name:r,status:"failed",message:F instanceof Error?F.message:String(F)}}let Re=Pe(s);return me(s,{version:ye.version,manifestHash:Re.manifestHash,sourceHash:Re.sourceHash??"",bundleHash:Re.bundleHash??"",styleHash:Re.styleHash??"",styleBundleHash:Re.styleBundleHash??""}),{name:r,status:"pushed",version:ye.version,...ye.permalink!==void 0&&{permalink:ye.permalink},...ye.detached&&{detached:!0},...L?{staleBundle:!0}:{},...Ge?{staleStyle:!0}:{}}}function Ot(e){return x.readdirSync(e).filter(t=>{let n=v.join(e,t);return x.statSync(n).isDirectory()&&x.existsSync(v.join(n,"manifest.json"))}).sort()}function Bs(e){let t=v.join(e,"manifest.json"),n=v.join(e,"components");if(x.existsSync(t)&&!x.existsSync(n))throw new Error(["Detected the old single-app layout (manifest.json at the project root).","The CLI now uses a multi-app layout: scaffold a fresh dir with","`npx greatstore apps init`, then move your app into `components/<name>/`. Re-run `npx greatstore apps push`","from the new project root."].join(" "))}var pt=" ".repeat(12);function xr(e){switch(e.status){case"pushed":process.stdout.write(` pushed ${e.name} v${e.version}${e.permalink?` \u2192 ${e.permalink}`:""}
121
+ ${pt}`)};let p=x.readFileSync(i,"utf8"),u=k.join(s,"listing.json"),f=Le(t);if(f&&!x.existsSync(u))return{name:r,status:"failed",message:`components/${r}/listing.json is required for a library app`};let y=Pe(s),g=Ae(s),I=e.bundlePath===void 0&&g?.bundleHash!==void 0&&g.sourceHash!==(y.sourceHash??"")&&g.bundleHash===(y.bundleHash??""),qe=g?.styleBundleHash!==void 0&&(g.styleHash??"")!==(y.styleHash??"")&&g.styleBundleHash===(y.styleBundleHash??""),en=U(s).imported,tn=k.join(s,R);if(en&&!x.existsSync(tn))return{name:r,status:"failed",message:`components/${r}/${R} is missing \u2014 run \`npx greatstore build ${r}\` first`};if(!o&&g!==null&&g.manifestHash===y.manifestHash&&g.sourceHash===(y.sourceHash??"")&&g.bundleHash!==void 0&&g.bundleHash===(y.bundleHash??"")&&(g.styleHash??"")===(y.styleHash??"")&&(g.styleBundleHash??"")===(y.styleBundleHash??""))return{name:r,status:"unchanged"};let Do=x.readFileSync(a,"utf8"),nn=x.existsSync(l)?x.readFileSync(l,"utf8"):null,H=new FormData;if(H.append("manifest",new Blob([p],{type:"application/json"}),"manifest.json"),H.append("bundle",new Blob([Do],{type:"text/javascript"}),"bundle.js"),nn!==null&&H.append("source",new Blob([nn],{type:"text/plain; charset=utf-8"}),"component.tsx"),en&&(H.append("style",new Blob([x.readFileSync(tn,"utf8")],{type:"text/css; charset=utf-8"}),R),H.append("style_source",new Blob([x.readFileSync(k.join(s,$),"utf8")],{type:"text/css; charset=utf-8"}),$)),f){let F=x.readFileSync(u,"utf8");H.append("listing",new Blob([F],{type:"application/json"}),"listing.json");let rn=k.join(s,"changelog.json");x.existsSync(rn)&&H.append("changelog",new Blob([x.readFileSync(rn,"utf8")],{type:"application/json"}),"changelog.json");let on=null;try{on=ct(JSON.parse(F))}catch{}for(let $t of on??[]){let sn=ut(s,$t);if(!sn)return{name:r,status:"failed",message:`components/${r}/${$t} is named in listing.json but doesn't exist`};H.append("screenshot",new Blob([new Uint8Array(sn)]),$t)}}o||H.append("base_version",String(g?.version??0));let Bo=`${ze(t)}/components/${encodeURIComponent(r)}`,ye;try{ye=await d(Bo,{method:"POST",multipart:H})}catch(F){return{name:r,status:"failed",message:F instanceof Error?F.message:String(F)}}let je=Pe(s);return me(s,{version:ye.version,manifestHash:je.manifestHash,sourceHash:je.sourceHash??"",bundleHash:je.bundleHash??"",styleHash:je.styleHash??"",styleBundleHash:je.styleBundleHash??""}),{name:r,status:"pushed",version:ye.version,...ye.permalink!==void 0&&{permalink:ye.permalink},...ye.detached&&{detached:!0},...I?{staleBundle:!0}:{},...qe?{staleStyle:!0}:{}}}function Ft(e){return x.readdirSync(e).filter(t=>{let n=k.join(e,t);return x.statSync(n).isDirectory()&&x.existsSync(k.join(n,"manifest.json"))}).sort()}function Qs(e){let t=k.join(e,"manifest.json"),n=k.join(e,"components");if(x.existsSync(t)&&!x.existsSync(n))throw new Error(["Detected the old single-app layout (manifest.json at the project root).","The CLI now uses a multi-app layout: scaffold a fresh dir with","`npx greatstore apps init`, then move your app into `components/<name>/`. Re-run `npx greatstore apps push`","from the new project root."].join(" "))}var pt=" ".repeat(12);function Er(e){switch(e.status){case"pushed":process.stdout.write(` pushed ${e.name} v${e.version}${e.permalink?` \u2192 ${e.permalink}`:""}
122
122
  `),e.detached&&process.stdout.write(`${pt}This was a ready-made app GreatStore keeps up to date. It's now your own copy and won't get those updates.
123
123
  `),e.staleBundle&&process.stdout.write(`${pt}component.tsx changed but bundle.js did not \u2014 did you forget to build? Run \`npx greatstore build ${e.name}\` and push again.
124
124
  `),e.staleStyle&&process.stdout.write(`${pt}style.css changed but bundle.css did not \u2014 did you forget to build? Run \`npx greatstore build ${e.name}\` and push again.
125
125
  `);return;case"unchanged":process.stdout.write(` unchanged ${e.name}
126
126
  `);return;case"failed":process.stdout.write(` failed ${e.name}: ${e.message??"unknown error"}
127
- `);return}}async function Er(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=w(e.flags,"version"),o;if(r!==void 0){if(t.length>1)throw new Error("--version is per-app; 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 kr(n,c,o);process.stdout.write(`Published ${c} (v${p.live_version}). ${p.permalink}
128
- `),p.embed_snippet&&vr(c,p.embed_snippet);return}let s=[];for(let c of t){let p;try{let u=await kr(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),Us(p)}for(let c of s)c.snippet&&vr(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(`
127
+ `);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=w(e.flags,"version"),o;if(r!==void 0){if(t.length>1)throw new Error("--version is per-app; 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 Ar(n,c,o);process.stdout.write(`Published ${c} (v${p.live_version}). ${p.permalink}
128
+ `),p.embed_snippet&&Cr(c,p.embed_snippet);return}let s=[];for(let c of t){let p;try{let u=await Ar(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),Zs(p)}for(let c of s)c.snippet&&Cr(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(`
129
129
  ${l.join(", ")} (of ${s.length}) \u2192 ${n}
130
- `),a>0&&(process.exitCode=1)}async function kr(e,t,n){let r=`${C(e)}/api/apps/components/${encodeURIComponent(t)}/publish`;return d(r,{method:"POST",body:n!==void 0?{version:n}:{}})}function vr(e,t){process.stdout.write(`
130
+ `),a>0&&(process.exitCode=1)}async function Ar(e,t,n){let r=`${C(e)}/api/apps/components/${encodeURIComponent(t)}/publish`;return d(r,{method:"POST",body:n!==void 0?{version:n}:{}})}function Cr(e,t){process.stdout.write(`
131
131
  Put ${e} on your site by pasting this where you want it:
132
132
 
133
133
  ${t.split(`
@@ -135,16 +135,16 @@ ${t.split(`
135
135
  `)}
136
136
 
137
137
  If the GreatStore script is already on the page, the second line is enough.
138
- `)}function Us(e){if(e.status==="published"){process.stdout.write(` published ${e.name} v${e.version} \u2192 ${e.permalink??""}
138
+ `)}function Zs(e){if(e.status==="published"){process.stdout.write(` published ${e.name} v${e.version} \u2192 ${e.permalink??""}
139
139
  `);return}process.stdout.write(` failed ${e.name}: ${e.message??"unknown error"}
140
- `)}async function Pr(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore apps unpublish <name>");let n=E(),r=`${C(n)}/api/apps/components/${encodeURIComponent(t)}/unpublish`;await d(r,{method:"POST",body:{}}),process.stdout.write(`Unpublished ${t}.
141
- `)}import*as Ar from"readline";async function Cr(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore apps delete <name> [--yes]");let n=E();if(!m(e.flags,"yes")&&(await Hs(`Soft-delete app "${t}" in store "${n}"? Type "yes" to confirm: `)).trim()!=="yes"){process.stdout.write(`Aborted.
140
+ `)}async function Rr(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore apps unpublish <name>");let n=E(),r=`${C(n)}/api/apps/components/${encodeURIComponent(t)}/unpublish`;await d(r,{method:"POST",body:{}}),process.stdout.write(`Unpublished ${t}.
141
+ `)}import*as _r from"readline";async function jr(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore apps delete <name> [--yes]");let n=E();if(!m(e.flags,"yes")&&(await ei(`Soft-delete app "${t}" in store "${n}"? Type "yes" to confirm: `)).trim()!=="yes"){process.stdout.write(`Aborted.
142
142
  `);return}let r=`${C(n)}/api/apps/components/${encodeURIComponent(t)}`;await d(r,{method:"DELETE"}),process.stdout.write(`Deleted ${t}.
143
- `)}function Hs(e){return new Promise(t=>{let n=Ar.createInterface({input:process.stdin,output:process.stdout});n.question(e,r=>{n.close(),t(r)})})}import*as G from"fs";import*as ft from"path";var Ms=/^[a-z][a-z0-9_]*$/;async function Tr(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(!Ms.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=ft.join(process.cwd(),"components",t),s=ft.join(process.cwd(),"components",n),i=G.existsSync(o);if(G.existsSync(s))throw new Error(`components/${n}/ already exists; move it aside first.`);let a=`${C(r)}/api/apps/components/${encodeURIComponent(t)}/rename`;if(await d(a,{method:"POST",body:{name:n}}),!i){process.stdout.write(`Renamed ${t} \u2192 ${n}.
144
- `);return}G.renameSync(o,s),Gs(s,n),V(process.cwd()),process.stdout.write(`Renamed ${t} \u2192 ${n}, including components/${n}/.
145
- `)}function Gs(e,t){let n=ft.join(e,"manifest.json");if(!G.existsSync(n))return;let r=G.readFileSync(n,"utf8"),o=JSON.stringify({...JSON.parse(r),name:t},null,2)+`
146
- `;G.writeFileSync(n,o);let s=Ae(e);s&&s.manifestHash===ie(r)&&me(e,{...s,manifestHash:ie(o)})}import*as ae from"fs";import*as De from"path";async function jr(e){let t=E();if(!Ie(t))throw new Error("`npx greatstore apps release` runs only in the app library's folder.");let n=Pt();gn(await Ws(new URL(n).origin));let r=await at({command:"build",positional:[],flags:{}});process.exitCode=0;let o=process.cwd(),s=ze(t),i=De.join(o,"components"),a=Ot(i),l=ae.readdirSync(i).filter(u=>ae.statSync(De.join(i,u)).isDirectory()),c=(await d(`${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 qs(s,o,t,u));for(let u of l.filter(f=>!a.includes(f)))p.push({name:u,status:"failed",message:`components/${u}/manifest.json is missing`});for(let u of c.filter(f=>!l.includes(f)))try{await d(`${s}/components/${encodeURIComponent(u)}/unpublish`,{method:"POST",body:{}}),p.push({name:u,status:"unpublished"})}catch(f){p.push({name:u,status:"failed",message:_r(f)})}for(let u of p){let f=u.status==="published"?` v${u.version}`:u.status==="failed"?`: ${u.message}`:"";process.stdout.write(` ${u.status.padEnd(11)} ${u.name}${f}
147
- `)}p.some(u=>u.status==="failed")&&(process.exitCode=1)}async function qs(e,t,n,r){try{let o=await Vs(e,r);if(o&&Ks(o,De.join(t,"components",r)))return{name:r,status:"unchanged"};let s=await dt({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 d(`${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:_r(o)}}}async function Vs(e,t){try{return await d(`${e}/components/${encodeURIComponent(t)}?revision=live`)}catch(n){if(n instanceof M&&n.status===404)return null;throw n}}function Ks(e,t){let n=i=>{let a=De.join(t,i);return ae.existsSync(a)?ae.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)===(U(t).imported?n($):null)&&(e.style_bundle??e.style??null)===(U(t).imported?n(j):null)&&Ce(e.manifest)===Ce(JSON.parse(r))&&Ce(e.listing)===Ce(Js(JSON.parse(o),t))&&Ce(e.changelog??null)===Ce(s===null?null:mt(JSON.parse(s)))}catch{return!1}}function Js(e,t){let n=mt(e),r=ct(n);return r?{...n,screenshots:r.map(o=>{let s=ut(t,o);return(s&&Sr(s))??o})}:n}function mt(e){return typeof e=="string"?e.trim():Array.isArray(e)?e.map(mt):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,mt(n)])):e}function Ce(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 Ws(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 _r(e){return e instanceof Error?e.message:String(e)}var Rr=`npx greatstore apps \u2014 author and ship custom in-chat apps
143
+ `)}function ei(e){return new Promise(t=>{let n=_r.createInterface({input:process.stdin,output:process.stdout});n.question(e,r=>{n.close(),t(r)})})}import*as q from"fs";import*as ft from"path";var ti=/^[a-z][a-z0-9_]*$/;async function Ir(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(!ti.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=ft.join(process.cwd(),"components",t),s=ft.join(process.cwd(),"components",n),i=q.existsSync(o);if(q.existsSync(s))throw new Error(`components/${n}/ already exists; move it aside first.`);let a=`${C(r)}/api/apps/components/${encodeURIComponent(t)}/rename`;if(await d(a,{method:"POST",body:{name:n}}),!i){process.stdout.write(`Renamed ${t} \u2192 ${n}.
144
+ `);return}q.renameSync(o,s),ni(s,n),V(process.cwd()),process.stdout.write(`Renamed ${t} \u2192 ${n}, including components/${n}/.
145
+ `)}function ni(e,t){let n=ft.join(e,"manifest.json");if(!q.existsSync(n))return;let r=q.readFileSync(n,"utf8"),o=JSON.stringify({...JSON.parse(r),name:t},null,2)+`
146
+ `;q.writeFileSync(n,o);let s=Ae(e);s&&s.manifestHash===ie(r)&&me(e,{...s,manifestHash:ie(o)})}import*as ae from"fs";import*as De from"path";async function Lr(e){let t=E();if(!Le(t))throw new Error("`npx greatstore apps release` runs only in the app library's folder.");let n=At();Sn(await ai(new URL(n).origin));let r=await at({command:"build",positional:[],flags:{}});process.exitCode=0;let o=process.cwd(),s=ze(t),i=De.join(o,"components"),a=Ft(i),l=ae.readdirSync(i).filter(u=>ae.statSync(De.join(i,u)).isDirectory()),c=(await d(`${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 ri(s,o,t,u));for(let u of l.filter(f=>!a.includes(f)))p.push({name:u,status:"failed",message:`components/${u}/manifest.json is missing`});for(let u of c.filter(f=>!l.includes(f)))try{await d(`${s}/components/${encodeURIComponent(u)}/unpublish`,{method:"POST",body:{}}),p.push({name:u,status:"unpublished"})}catch(f){p.push({name:u,status:"failed",message:Nr(f)})}for(let u of p){let f=u.status==="published"?` v${u.version}`:u.status==="failed"?`: ${u.message}`:"";process.stdout.write(` ${u.status.padEnd(11)} ${u.name}${f}
147
+ `)}p.some(u=>u.status==="failed")&&(process.exitCode=1)}async function ri(e,t,n,r){try{let o=await oi(e,r);if(o&&si(o,De.join(t,"components",r)))return{name:r,status:"unchanged"};let s=await dt({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 d(`${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:Nr(o)}}}async function oi(e,t){try{return await d(`${e}/components/${encodeURIComponent(t)}?revision=live`)}catch(n){if(n instanceof D&&n.status===404)return null;throw n}}function si(e,t){let n=i=>{let a=De.join(t,i);return ae.existsSync(a)?ae.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)===(U(t).imported?n($):null)&&(e.style_bundle??e.style??null)===(U(t).imported?n(R):null)&&Ce(e.manifest)===Ce(JSON.parse(r))&&Ce(e.listing)===Ce(ii(JSON.parse(o),t))&&Ce(e.changelog??null)===Ce(s===null?null:mt(JSON.parse(s)))}catch{return!1}}function ii(e,t){let n=mt(e),r=ct(n);return r?{...n,screenshots:r.map(o=>{let s=ut(t,o);return(s&&vr(s))??o})}:n}function mt(e){return typeof e=="string"?e.trim():Array.isArray(e)?e.map(mt):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,mt(n)])):e}function Ce(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 ai(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 Nr(e){return e instanceof Error?e.message:String(e)}var Or=`npx greatstore apps \u2014 author and ship custom in-chat apps
148
148
 
149
149
  Usage:
150
150
  npx greatstore apps <subcommand> [args] [flags]
@@ -159,111 +159,111 @@ Subcommands:
159
159
  unpublish <name> Take a published app down; its draft is kept.
160
160
  rename <old> <new> Rename an app, keeping its versions and whether it's live.
161
161
  delete <name> Delete the app from the store.
162
- `;async function Ft(e){let t=e.positional[0],n={...e,positional:e.positional.slice(1)};switch(t){case void 0:case"help":return process.stdout.write(Rr),0;case"init":return In(n),0;case"build":return await at(n),0;case"list":return await ar(n),0;case"pull":return await pr(n),0;case"push":return await $r(n),0;case"publish":return await Er(n),0;case"unpublish":return await Pr(n),0;case"rename":return await Tr(n),0;case"delete":return await Cr(n),0;case"release":return await jr(n),0;default:return process.stderr.write(`Unknown apps subcommand: ${t}
162
+ `;async function Dt(e){let t=e.positional[0],n={...e,positional:e.positional.slice(1)};switch(t){case void 0:case"help":return process.stdout.write(Or),0;case"init":return Dn(n),0;case"build":return await at(n),0;case"list":return await pr(n),0;case"pull":return await gr(n),0;case"push":return await Pr(n),0;case"publish":return await Tr(n),0;case"unpublish":return await Rr(n),0;case"rename":return await Ir(n),0;case"delete":return await jr(n),0;case"release":return await Lr(n),0;default:return process.stderr.write(`Unknown apps subcommand: ${t}
163
163
 
164
- ${Rr}`),1}}async function Lr(e){let t=h(e),n=`${b(t)}/configure/config`,r=await d(n);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(r.brand,null,2)+`
165
- `);return}Ys(t,r.brand)}function Ys(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 ${Dt(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 ${Dt(t.cspScriptHosts)}`),n.push(` cspConnectHosts ${Dt(t.cspConnectHosts)}`),process.stdout.write(n.join(`
164
+ ${Or}`),1}}async function Fr(e){let t=h(e),n=`${S(t)}/configure/config`,r=await d(n);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(r.brand,null,2)+`
165
+ `);return}li(t,r.brand)}function li(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 ${Bt(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 ${Bt(t.cspScriptHosts)}`),n.push(` cspConnectHosts ${Bt(t.cspConnectHosts)}`),process.stdout.write(n.join(`
166
166
  `)+`
167
- `)}function Dt(e){return!e||e.length===0?"\u2014":e.join(", ")}import*as gt from"fs";import*as Or from"path";var Ir="theme.",zs=["displayName","assistantName","storeLink"],Xs=["extraOrigins","cspScriptHosts","cspConnectHosts"];async function Fr(e){let t=h(e),n={};for(let c of zs){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 Xs){if(!(c in e.flags))continue;let p=e.flags[c];if(typeof p!="string")throw new Error(`--${c} requires a comma-separated value (use --${c} "" to clear).`);let u=p.split(",").map(f=>f.trim()).filter(f=>f.length>0);n[c]=u.length===0?null:u}let r=w(e.flags,"themeFile"),o=ei(e.flags),s=m(e.flags,"replace");if("theme"in e.flags&&r!==void 0)throw new Error("Pass either --theme or --themeFile, not both.");if(o!==null&&("theme"in e.flags||r!==void 0))throw new Error("Pass either --theme.<field> flags or a whole --theme/--themeFile object, not both.");let i;if("theme"in e.flags){let c=e.flags.theme;if(typeof c!="string")throw new Error('--theme requires a JSON value (use --theme "" to clear).');i=c===""?null:Nr(c,"--theme")}else r!==void 0?i=Nr(Qs(r,"--themeFile"),"--themeFile"):o!==null&&(i=o);if(i!==void 0&&(n.theme=i===null||s?i:{...await Zs(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=`${b(t)}/configure/save`,l=await d(a,{method:"POST",body:n,validationDetail:!0});if(m(e.flags,"json")){process.stdout.write(JSON.stringify(l.config,null,2)+`
167
+ `)}function Bt(e){return!e||e.length===0?"\u2014":e.join(", ")}import*as gt from"fs";import*as Mr from"path";var Dr="theme.",ci=["displayName","assistantName","storeLink"],ui=["extraOrigins","cspScriptHosts","cspConnectHosts"];async function Ur(e){let t=h(e),n={};for(let c of ci){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 ui){if(!(c in e.flags))continue;let p=e.flags[c];if(typeof p!="string")throw new Error(`--${c} requires a comma-separated value (use --${c} "" to clear).`);let u=p.split(",").map(f=>f.trim()).filter(f=>f.length>0);n[c]=u.length===0?null:u}let r=w(e.flags,"themeFile"),o=fi(e.flags),s=m(e.flags,"replace");if("theme"in e.flags&&r!==void 0)throw new Error("Pass either --theme or --themeFile, not both.");if(o!==null&&("theme"in e.flags||r!==void 0))throw new Error("Pass either --theme.<field> flags or a whole --theme/--themeFile object, not both.");let i;if("theme"in e.flags){let c=e.flags.theme;if(typeof c!="string")throw new Error('--theme requires a JSON value (use --theme "" to clear).');i=c===""?null:Br(c,"--theme")}else r!==void 0?i=Br(pi(r,"--themeFile"),"--themeFile"):o!==null&&(i=o);if(i!==void 0&&(n.theme=i===null||s?i:{...await di(t),...i},n.theme!==null)){let c=n.theme;for(let[p,u]of Object.entries(c))u===""&&delete c[p]}if(Object.keys(n).length===0)throw new Error('Nothing to save. Pass at least one field flag, e.g. `npx greatstore configure set --displayName "Acme"`.');let a=`${S(t)}/configure/save`,l=await d(a,{method:"POST",body:n,validationDetail:!0});if(m(e.flags,"json")){process.stdout.write(JSON.stringify(l.config,null,2)+`
168
168
  `);return}process.stdout.write(`Saved ${Object.keys(n).join(", ")} \u2192 ${t}
169
- `)}function Qs(e,t){let n=Or.resolve(e);if(!gt.existsSync(n))throw new Error(`${t}: file not found: ${n}`);return gt.readFileSync(n,"utf8")}function Nr(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 Zs(e){let t=`${b(e)}/configure/config`;return(await d(t)).brand.theme??{}}function ei(e){let t={};for(let[n,r]of Object.entries(e)){if(!n.startsWith(Ir))continue;let o=n.slice(Ir.length),s=ne[o];if(!s){let i=Tn(o);throw new Error(`Unknown theme field "${o}".
169
+ `)}function pi(e,t){let n=Mr.resolve(e);if(!gt.existsSync(n))throw new Error(`${t}: file not found: ${n}`);return gt.readFileSync(n,"utf8")}function Br(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 di(e){let t=`${S(e)}/configure/config`;return(await d(t)).brand.theme??{}}function fi(e){let t={};for(let[n,r]of Object.entries(e)){if(!n.startsWith(Dr))continue;let o=n.slice(Dr.length),s=ne[o];if(!s){let i=In(o);throw new Error(`Unknown theme field "${o}".
170
170
  Valid fields: ${Object.keys(ne).join(", ")}.`+(i.length>0?`
171
- 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]=ti(n,o,r)}return Object.keys(t).length>0?t:null}function ti(e,t,n){let r=ne[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 yt from"fs";import*as Te from"path";var ht=["icon","logoLight","logoDark"];function wt(e){if(e&&ht.includes(e))return e;throw new Error(`Asset kind must be one of: ${ht.join(", ")}.`)}var ni={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp"};async function Dr(e){let t=h(e),n=wt(e.positional[0]),r=e.positional[1];if(!r)throw new Error(`Usage: npx greatstore configure upload <${ht.join("|")}> <file>`);let o=Te.resolve(r);if(!yt.existsSync(o))throw new Error(`File not found: ${o}`);let s=ni[Te.extname(o).toLowerCase()];if(!s)throw new Error("Unsupported image type. Use .png, .jpg, or .webp.");let i=yt.readFileSync(o),a=new FormData;a.append("file",new Blob([new Uint8Array(i)],{type:s}),Te.basename(o));let l=`${b(t)}/configure/upload/${n}`,c=await d(l,{method:"POST",multipart:a});process.stdout.write(`Uploaded ${n} \u2192 ${c.url}
172
- `)}async function Br(e){let t=h(e),n=wt(e.positional[0]),r=`${b(t)}/configure/delete/${n}`;await d(r,{method:"POST",body:{}}),process.stdout.write(`Cleared ${n} for ${t}
173
- `)}async function Ur(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 Fr(n);return;case"upload":await Dr(n);return;case"clear":await Br(n);return;default:throw new Error(`Unknown configure subcommand: ${t}. Use \`npx greatstore configure [set|upload|clear]\`.`)}}async function R(e){let t=`${b(e)}/connectors/config`;return d(t)}function z(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 le(e,t,n,r=t.makerEnabled){let o=`${b(e)}/connectors/save`;return d(o,{method:"POST",body:{makerEnabled:r,makerPriority:Math.min(t.makerPriority,n.length),connectors:n}})}function ce(e,t){let n=e.connectors.find(o=>o.id===t);if(n)return n;let r=e.connectors.filter(o=>o.name===t);if(r.length===1)return r[0];if(r.length>1){let o=r.map(s=>s.id).join(", ");throw new Error(`Multiple connectors are named "${t}". Use an id instead: ${o}`)}throw new Error(`No connector named "${t}". Run \`npx greatstore connectors\` to see them.`)}async function Hr(e){let t=h(e),n=await R(t);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(n,null,2)+`
171
+ 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]=mi(n,o,r)}return Object.keys(t).length>0?t:null}function mi(e,t,n){let r=ne[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 yt from"fs";import*as Te from"path";var ht=["icon","logoLight","logoDark"];function wt(e){if(e&&ht.includes(e))return e;throw new Error(`Asset kind must be one of: ${ht.join(", ")}.`)}var gi={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp"};async function Hr(e){let t=h(e),n=wt(e.positional[0]),r=e.positional[1];if(!r)throw new Error(`Usage: npx greatstore configure upload <${ht.join("|")}> <file>`);let o=Te.resolve(r);if(!yt.existsSync(o))throw new Error(`File not found: ${o}`);let s=gi[Te.extname(o).toLowerCase()];if(!s)throw new Error("Unsupported image type. Use .png, .jpg, or .webp.");let i=yt.readFileSync(o),a=new FormData;a.append("file",new Blob([new Uint8Array(i)],{type:s}),Te.basename(o));let l=`${S(t)}/configure/upload/${n}`,c=await d(l,{method:"POST",multipart:a});process.stdout.write(`Uploaded ${n} \u2192 ${c.url}
172
+ `)}async function qr(e){let t=h(e),n=wt(e.positional[0]),r=`${S(t)}/configure/delete/${n}`;await d(r,{method:"POST",body:{}}),process.stdout.write(`Cleared ${n} for ${t}
173
+ `)}async function Gr(e){let t=e.positional[0]??"show",n={...e,positional:e.positional.slice(1)};switch(t){case"show":await Fr(n);return;case"set":await Ur(n);return;case"upload":await Hr(n);return;case"clear":await qr(n);return;default:throw new Error(`Unknown configure subcommand: ${t}. Use \`npx greatstore configure [set|upload|clear]\`.`)}}async function j(e){let t=`${S(e)}/connectors/config`;return d(t)}function z(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 le(e,t,n,r=t.makerEnabled){let o=`${S(e)}/connectors/save`;return d(o,{method:"POST",body:{makerEnabled:r,makerPriority:Math.min(t.makerPriority,n.length),connectors:n}})}function ce(e,t){let n=e.connectors.find(o=>o.id===t);if(n)return n;let r=e.connectors.filter(o=>o.name===t);if(r.length===1)return r[0];if(r.length>1){let o=r.map(s=>s.id).join(", ");throw new Error(`Multiple connectors are named "${t}". Use an id instead: ${o}`)}throw new Error(`No connector named "${t}". Run \`npx greatstore connectors\` to see them.`)}async function Vr(e){let t=h(e),n=await j(t);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(n,null,2)+`
174
174
  `);return}if(process.stdout.write(`Maker MCP: ${n.makerEnabled?"on":"off"} (position ${n.makerPriority+1})
175
175
  `),n.connectors.length===0){process.stdout.write(`(no custom connectors in ${t})
176
- `);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(`${je("NAME",o.name)} ${je("ENABLED",o.enabled)} ${je("AUTH",o.auth)} URL
177
- `);for(let s of r)process.stdout.write(`${je(s.name,o.name)} ${je(s.enabled,o.enabled)} ${je(s.auth,o.auth)} ${s.url}
178
- `)}function je(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}async function Mr(e){let t=h(e),n=e.positional[0];if(!n)throw new Error("Usage: npx greatstore connectors add <name> --url <url> [--token <token>]");let r=w(e.flags,"url");if(!r)throw new Error("--url is required for `npx greatstore connectors add`.");let o=w(e.flags,"token"),s=w(e.flags,"profileUrl")??null,i=!m(e.flags,"disabled");if(!m(e.flags,"force")){let u=`${b(t)}/connectors/probe`,f=await d(u,{method:"POST",body:{url:r,...o!==void 0?{token:o}:{},...s!==null?{profileUrl:s}:{}}});if(!f.ok)throw new Error(`Connector did not answer tool discovery${f.error?`: ${f.error}`:""}. Fix the URL/token or pass --force to save it anyway.`);process.stdout.write(`Probe ok \u2014 ${f.toolCount??0} tool(s) discovered.
179
- `)}let a=await R(t),l={id:"",name:n,url:r,transport:"http",authKind:o?"bearer":"none",enabled:i,profileUrl:s,...o!==void 0?{token:o}:{}},p=(await le(t,a,[...a.connectors.map(z),l])).connectors.find(u=>u.name===n);process.stdout.write(`Added connector "${n}"${p?` (${p.id})`:""} \u2192 ${t}
180
- `)}async function Gr(e){let t=h(e),n=e.positional[0];if(!n)throw new Error("Usage: npx greatstore connectors remove <name|id>");let r=await R(t),o=ce(r,n),s=r.connectors.filter(i=>i.id!==o.id).map(z);await le(t,r,s),process.stdout.write(`Removed connector "${o.name}" from ${t}
181
- `)}async function Bt(e,t){let n=h(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=ce(o,r),i=o.connectors.map(a=>a.id===s.id?{...z(a),enabled:t}:z(a));await le(n,o,i),process.stdout.write(`Connector "${s.name}" is now ${t?"enabled":"disabled"}
182
- `)}async function qr(e){let t=h(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 le(t,r,r.connectors.map(z),n==="on"),process.stdout.write(`Maker MCP is now ${n}
183
- `)}async function Vr(e){let t=h(e),n=await R(t),r=null,o=e.positional[0];if(o&&(r=ce(n,o).id),n.connectors.length===0){process.stdout.write(`(no custom connectors in ${t})
184
- `);return}let s=`${b(t)}/connectors/health`,i=await d(s,{method:"POST",body:r?{id:r}:{}});if(m(e.flags,"json")){process.stdout.write(JSON.stringify(i.health,null,2)+`
176
+ `);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(`${Re("NAME",o.name)} ${Re("ENABLED",o.enabled)} ${Re("AUTH",o.auth)} URL
177
+ `);for(let s of r)process.stdout.write(`${Re(s.name,o.name)} ${Re(s.enabled,o.enabled)} ${Re(s.auth,o.auth)} ${s.url}
178
+ `)}function Re(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}async function Kr(e){let t=h(e),n=e.positional[0];if(!n)throw new Error("Usage: npx greatstore connectors add <name> --url <url> [--token <token>]");let r=w(e.flags,"url");if(!r)throw new Error("--url is required for `npx greatstore connectors add`.");let o=w(e.flags,"token"),s=w(e.flags,"profileUrl")??null,i=!m(e.flags,"disabled");if(!m(e.flags,"force")){let u=`${S(t)}/connectors/probe`,f=await d(u,{method:"POST",body:{url:r,...o!==void 0?{token:o}:{},...s!==null?{profileUrl:s}:{}}});if(!f.ok)throw new Error(`Connector did not answer tool discovery${f.error?`: ${f.error}`:""}. Fix the URL/token or pass --force to save it anyway.`);process.stdout.write(`Probe ok \u2014 ${f.toolCount??0} tool(s) discovered.
179
+ `)}let a=await j(t),l={id:"",name:n,url:r,transport:"http",authKind:o?"bearer":"none",enabled:i,profileUrl:s,...o!==void 0?{token:o}:{}},p=(await le(t,a,[...a.connectors.map(z),l])).connectors.find(u=>u.name===n);process.stdout.write(`Added connector "${n}"${p?` (${p.id})`:""} \u2192 ${t}
180
+ `)}async function Jr(e){let t=h(e),n=e.positional[0];if(!n)throw new Error("Usage: npx greatstore connectors remove <name|id>");let r=await j(t),o=ce(r,n),s=r.connectors.filter(i=>i.id!==o.id).map(z);await le(t,r,s),process.stdout.write(`Removed connector "${o.name}" from ${t}
181
+ `)}async function Mt(e,t){let n=h(e),r=e.positional[0];if(!r)throw new Error(`Usage: npx greatstore connectors ${t?"enable":"disable"} <name|id>`);let o=await j(n),s=ce(o,r),i=o.connectors.map(a=>a.id===s.id?{...z(a),enabled:t}:z(a));await le(n,o,i),process.stdout.write(`Connector "${s.name}" is now ${t?"enabled":"disabled"}
182
+ `)}async function Wr(e){let t=h(e),n=e.positional[0];if(n!=="on"&&n!=="off")throw new Error("Usage: npx greatstore connectors maker on|off");let r=await j(t);await le(t,r,r.connectors.map(z),n==="on"),process.stdout.write(`Maker MCP is now ${n}
183
+ `)}async function Yr(e){let t=h(e),n=await j(t),r=null,o=e.positional[0];if(o&&(r=ce(n,o).id),n.connectors.length===0){process.stdout.write(`(no custom connectors in ${t})
184
+ `);return}let s=`${S(t)}/connectors/health`,i=await d(s,{method:"POST",body:r?{id:r}:{}});if(m(e.flags,"json")){process.stdout.write(JSON.stringify(i.health,null,2)+`
185
185
  `);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)
186
186
  `):(process.stdout.write(` failed ${c}: ${l.error??"discovery failed"}
187
- `),process.exitCode=1)}}var ri={readOnly:"read-only",write:"write",other:"other"};async function Jr(e){let t=h(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:ce(await R(t),n).id,o=await d(`${b(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(m(e.flags,"json")){process.stdout.write(JSON.stringify(s?i[0]:i,null,2)+`
187
+ `),process.exitCode=1)}}var hi={readOnly:"read-only",write:"write",other:"other"};async function Xr(e){let t=h(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:ce(await j(t),n).id,o=await d(`${S(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(m(e.flags,"json")){process.stdout.write(JSON.stringify(s?i[0]:i,null,2)+`
188
188
  `);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.
189
- `);return}process.stdout.write(i.map(si).join(`
189
+ `);return}process.stdout.write(i.map(yi).join(`
190
190
 
191
191
  `)+`
192
- `)}function oi(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 si(e){let t=[`## ${e.name}`,`${ri[e.group]}, ${e.allowed?"allowed":"disallowed"} \u2014 ${oi(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: not recorded yet; it appears after a chat on a page that registers this tool"),t.join(`
192
+ `)}function wi(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 yi(e){let t=[`## ${e.name}`,`${hi[e.group]}, ${e.allowed?"allowed":"disallowed"} \u2014 ${wi(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: not recorded yet; it appears after a chat on a page that registers this tool"),t.join(`
193
193
  `);t.push("","Input:");let n=Ut(e.inputSchema,1);return t.push(...n.length>0?n:[" (none)"]),t.join(`
194
- `)}function Ut(e,t){let n=Be(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=Be(i)??{};o.push(...Ht(s,a,r.has(s),t))}return e.additionalProperties===!1&&o.push(`${Mt(t)}(no other fields accepted)`),o}function Ht(e,t,n,r){let o=[ii(t),n?"required":"optional",...Kr(t)],s=typeof t.description=="string"?` \u2014 ${t.description.trim()}`:"",i=[`${Mt(r)}${e} (${o.join(", ")})${s}`];i.push(...Ut(t,r+1));let a=Be(t.items);if(a){let l=Ut(a,r+2);l.length>0?i.push(`${Mt(r+1)}each item:`,...l):(Kr(a).length>0||a.description)&&i.push(...Ht("each item",a,!0,r+1))}for(let l of["anyOf","oneOf","allOf"])(Array.isArray(t[l])?t[l]:[]).forEach((p,u)=>{let f=Be(p);f&&i.push(...Ht(`${l}[${u}]`,f,!0,r+1))});return i}function ii(e){let t=e.type,n=Array.isArray(t)?t.join(" | "):typeof t=="string"?t:"any",r=Be(e.items);return n==="array"&&r&&typeof r.type=="string"?`array of ${r.type}`:n}var ai=[["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 Kr(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 ai)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 Be(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Mt(e){return" ".repeat(e)}var li=7,Wr=120,ci=864e5,ui={mcp:"connector",local:"custom app",browser:"browser"};async function Yr(e){let t=h(e),n=pi(w(e.flags,"days")),r=w(e.flags,"tool"),o=new Date,s=new Date(o.getTime()-n*ci),i=await d(`${b(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(m(e.flags,"json")){process.stdout.write(JSON.stringify({days:n,errors:l,truncated:c},null,2)+`
194
+ `)}function Ut(e,t){let n=Be(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=Be(i)??{};o.push(...Ht(s,a,r.has(s),t))}return e.additionalProperties===!1&&o.push(`${qt(t)}(no other fields accepted)`),o}function Ht(e,t,n,r){let o=[Si(t),n?"required":"optional",...zr(t)],s=typeof t.description=="string"?` \u2014 ${t.description.trim()}`:"",i=[`${qt(r)}${e} (${o.join(", ")})${s}`];i.push(...Ut(t,r+1));let a=Be(t.items);if(a){let l=Ut(a,r+2);l.length>0?i.push(`${qt(r+1)}each item:`,...l):(zr(a).length>0||a.description)&&i.push(...Ht("each item",a,!0,r+1))}for(let l of["anyOf","oneOf","allOf"])(Array.isArray(t[l])?t[l]:[]).forEach((p,u)=>{let f=Be(p);f&&i.push(...Ht(`${l}[${u}]`,f,!0,r+1))});return i}function Si(e){let t=e.type,n=Array.isArray(t)?t.join(" | "):typeof t=="string"?t:"any",r=Be(e.items);return n==="array"&&r&&typeof r.type=="string"?`array of ${r.type}`:n}var bi=[["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 zr(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 bi)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 Be(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function qt(e){return" ".repeat(e)}var xi=7,Qr=120,$i=864e5,vi={mcp:"connector",local:"custom app",browser:"browser"};async function Zr(e){let t=h(e),n=ki(w(e.flags,"days")),r=w(e.flags,"tool"),o=new Date,s=new Date(o.getTime()-n*$i),i=await d(`${S(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(m(e.flags,"json")){process.stdout.write(JSON.stringify({days:n,errors:l,truncated:c},null,2)+`
195
195
  `);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)
196
196
  `);return}process.stdout.write(`Tool errors in ${p}, last ${n} days (most frequent first):
197
197
 
198
- `);for(let u of l){let f=ui[u.tool_backend]??u.tool_backend;process.stdout.write(` ${String(u.occurrences).padStart(5)}\xD7 ${u.tool_name} (${f}), last ${u.last_at}
198
+ `);for(let u of l){let f=vi[u.tool_backend]??u.tool_backend;process.stdout.write(` ${String(u.occurrences).padStart(5)}\xD7 ${u.tool_name} (${f}), last ${u.last_at}
199
199
  ${u.error}
200
200
  `)}c&&process.stdout.write(`
201
201
  The rarest errors are left out of this list.
202
- `)}function pi(e){if(e===void 0)return li;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 zr(e){let t=e.positional[0]??"list",n={...e,positional:e.positional.slice(1)};switch(t){case"list":await Hr(n);return;case"add":await Mr(n);return;case"remove":await Gr(n);return;case"enable":await Bt(n,!0);return;case"disable":await Bt(n,!1);return;case"maker":await qr(n);return;case"health":await Vr(n);return;case"tools":await Jr(n);return;case"errors":await Yr(n);return;default:throw new Error(`Unknown connectors subcommand: ${t}. Use \`npx greatstore connectors [add|remove|enable|disable|maker|health|tools|errors]\`.`)}}import*as Zr from"readline";function D(e){return`${b(e)}/knowledge`}async function He(e){return(await d(`${D(e)}/sources`)).sources}function Gt(e,t){let n=e.find(o=>o.id===t);if(n)return n;let r=e.filter(o=>o.displayName===t);if(r.length===1)return r[0];if(r.length>1){let o=r.map(s=>` ${s.id}`).join(`
202
+ `)}function ki(e){if(e===void 0)return xi;let t=Number(e);if(!Number.isInteger(t)||t<1||t>Qr)throw new Error(`--days must be a whole number from 1 to ${Qr}.`);return t}async function eo(e){let t=e.positional[0]??"list",n={...e,positional:e.positional.slice(1)};switch(t){case"list":await Vr(n);return;case"add":await Kr(n);return;case"remove":await Jr(n);return;case"enable":await Mt(n,!0);return;case"disable":await Mt(n,!1);return;case"maker":await Wr(n);return;case"health":await Yr(n);return;case"tools":await Xr(n);return;case"errors":await Zr(n);return;default:throw new Error(`Unknown connectors subcommand: ${t}. Use \`npx greatstore connectors [add|remove|enable|disable|maker|health|tools|errors]\`.`)}}import*as ro from"readline";function B(e){return`${S(e)}/knowledge`}async function Ue(e){return(await d(`${B(e)}/sources`)).sources}function Gt(e,t){let n=e.find(o=>o.id===t);if(n)return n;let r=e.filter(o=>o.displayName===t);if(r.length===1)return r[0];if(r.length>1){let o=r.map(s=>` ${s.id}`).join(`
203
203
  `);throw new Error(`${r.length} sources are named "${t}". Use one of their ids:
204
- ${o}`)}throw new Error(`No source with id or name "${t}". Run \`npx greatstore knowledge list\` to see them.`)}async function ge(e,t,n){if(!t)throw new Error(`Usage: ${n}`);return Gt(await He(e),t)}function Ue(e){return e==="ready"||e==="failed"}var di=3e3,fi=10*6e4;async function he(e,t,n={}){let r=n.pollMs??di,o=n.timeoutMs??fi,s=n.now??Date.now,i=n.sleep??(l=>new Promise(c=>setTimeout(c,l))),a=s()+o;for(n.firstPollDelay&&await i(r);;){let l=await He(e),c=t.map(p=>l.find(u=>u.id===p));if(c.every(p=>p!==void 0&&Ue(p.status)))return c;if(s()>=a){let p=t.filter((u,f)=>!c[f]||!Ue(c[f].status)).map(u=>` ${u}`).join(`
204
+ ${o}`)}throw new Error(`No source with id or name "${t}". Run \`npx greatstore knowledge list\` to see them.`)}async function ge(e,t,n){if(!t)throw new Error(`Usage: ${n}`);return Gt(await Ue(e),t)}function Me(e){return e==="ready"||e==="failed"}var Ei=3e3,Pi=10*6e4;async function he(e,t,n={}){let r=n.pollMs??Ei,o=n.timeoutMs??Pi,s=n.now??Date.now,i=n.sleep??(l=>new Promise(c=>setTimeout(c,l))),a=s()+o;for(n.firstPollDelay&&await i(r);;){let l=await Ue(e),c=t.map(p=>l.find(u=>u.id===p));if(c.every(p=>p!==void 0&&Me(p.status)))return c;if(s()>=a){let p=t.filter((u,f)=>!c[f]||!Me(c[f].status)).map(u=>` ${u}`).join(`
205
205
  `);throw new Error(`Still processing after ${Math.round(o/6e4)} minutes:
206
206
  ${p}
207
207
  Check again later with \`npx greatstore knowledge status\`.`)}await i(r)}}function we(e){let t=!1;for(let n of e)n.status==="failed"?(t=!0,process.stdout.write(`\u2717 ${n.displayName} (${n.id}) failed${n.error?`: ${n.error}`:""}
208
208
  `)):process.stdout.write(`\u2713 ${n.displayName} (${n.id}) is ready
209
- `);return t}function Xr(e){return e===null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function X(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function Qr(e,t){let n=e.old,r=e.new;if(typeof n!="string"||n==="")throw new Error(`Missing --old <text>. Usage: ${t}`);if(typeof r!="string")throw new Error(`Missing --new <text> (use --new "" to delete). Usage: ${t}`);return[{oldText:n,newText:r}]}async function eo(e){let t=h(e),n=await He(t);if(m(e.flags,"json")){process.stdout.write(JSON.stringify({sources:n},null,2)+`
209
+ `);return t}function to(e){return e===null?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function X(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function no(e,t){let n=e.old,r=e.new;if(typeof n!="string"||n==="")throw new Error(`Missing --old <text>. Usage: ${t}`);if(typeof r!="string")throw new Error(`Missing --new <text> (use --new "" to delete). Usage: ${t}`);return[{oldText:n,newText:r}]}async function oo(e){let t=h(e),n=await Ue(t);if(m(e.flags,"json")){process.stdout.write(JSON.stringify({sources:n},null,2)+`
210
210
  `);return}if(n.length===0){process.stdout.write(`(no knowledge sources in ${t})
211
- `);return}let r=n.map(i=>({name:i.displayName,kind:i.kind,status:i.status,size:Xr(i.sizeBytes),id:i.id})),o={name:Math.max(4,...r.map(i=>i.name.length)),kind:4,status:Math.max(6,...r.map(i=>i.status.length)),size:Math.max(4,...r.map(i=>i.size.length))};process.stdout.write(`${X("NAME",o.name)} ${X("KIND",o.kind)} ${X("STATUS",o.status)} ${X("SIZE",o.size)} ID
211
+ `);return}let r=n.map(i=>({name:i.displayName,kind:i.kind,status:i.status,size:to(i.sizeBytes),id:i.id})),o={name:Math.max(4,...r.map(i=>i.name.length)),kind:4,status:Math.max(6,...r.map(i=>i.status.length)),size:Math.max(4,...r.map(i=>i.size.length))};process.stdout.write(`${X("NAME",o.name)} ${X("KIND",o.kind)} ${X("STATUS",o.status)} ${X("SIZE",o.size)} ID
212
212
  `);for(let i of r)process.stdout.write(`${X(i.name,o.name)} ${X(i.kind,o.kind)} ${X(i.status,o.status)} ${X(i.size,o.size)} ${i.id}
213
213
  `);let s=n.filter(i=>i.status==="failed");for(let i of s)process.stdout.write(`
214
214
  \u2717 ${i.displayName}: ${i.error??"failed"}`);s.length>0&&process.stdout.write(`
215
- `)}async function to(e){let t=h(e),n=e.positional[0],r=await He(t),o=n?[Gt(r,n)]:r,s=m(e.flags,"json"),i=o;m(e.flags,"wait")&&o.some(l=>!Ue(l.status))&&(s||process.stderr.write(`Waiting for processing to finish\u2026
215
+ `)}async function so(e){let t=h(e),n=e.positional[0],r=await Ue(t),o=n?[Gt(r,n)]:r,s=m(e.flags,"json"),i=o;m(e.flags,"wait")&&o.some(l=>!Me(l.status))&&(s||process.stderr.write(`Waiting for processing to finish\u2026
216
216
  `),i=await he(t,o.map(l=>l.id)));let a=i.some(l=>l.status==="failed");if(s)return process.stdout.write(JSON.stringify({sources:i.map(({id:l,displayName:c,status:p,error:u})=>({id:l,displayName:c,status:p,error:u}))},null,2)+`
217
217
  `),a?1:0;if(i.length===0)return process.stdout.write(`(no knowledge sources in ${t})
218
- `),0;for(let l of i)Ue(l.status)?we([l]):process.stdout.write(`\u2026 ${l.displayName} (${l.id}) is ${l.status}
219
- `);return a?1:0}async function no(e){let t=h(e),n=await ge(t,e.positional[0],"npx greatstore knowledge show <id|name> [--json]"),r=await Le(`${D(t)}/sources/${encodeURIComponent(n.id)}/content`,{headers:{accept:"*/*"}}),o=r.headers.get("x-content-hash"),s=r.headers.get("content-type")??"";if(!s.startsWith("text/"))throw new Error(`"${n.displayName}" is a ${s||"binary"} document and can't be shown as text.`);let i=await r.text();if(m(e.flags,"json")){process.stdout.write(JSON.stringify({source:n,content:i,hash:o},null,2)+`
218
+ `),0;for(let l of i)Me(l.status)?we([l]):process.stdout.write(`\u2026 ${l.displayName} (${l.id}) is ${l.status}
219
+ `);return a?1:0}async function io(e){let t=h(e),n=await ge(t,e.positional[0],"npx greatstore knowledge show <id|name> [--json]"),r=await Ie(`${B(t)}/sources/${encodeURIComponent(n.id)}/content`,{headers:{accept:"*/*"}}),o=r.headers.get("x-content-hash"),s=r.headers.get("content-type")??"";if(!s.startsWith("text/"))throw new Error(`"${n.displayName}" is a ${s||"binary"} document and can't be shown as text.`);let i=await r.text();if(m(e.flags,"json")){process.stdout.write(JSON.stringify({source:n,content:i,hash:o},null,2)+`
220
220
  `);return}process.stdout.write(i.endsWith(`
221
221
  `)?i:`${i}
222
222
  `),o&&process.stderr.write(`hash: ${o}
223
- `)}async function ro(e){let t=h(e),n="npx greatstore knowledge rename <id|name> <new name>",r=await ge(t,e.positional[0],n),o=e.positional[1]??w(e.flags,"name");if(!o?.trim())throw new Error(`Usage: ${n}`);await d(`${D(t)}/sources/${encodeURIComponent(r.id)}`,{method:"PATCH",body:{displayName:o.trim()},validationDetail:!0}),process.stdout.write(`Renamed "${r.displayName}" \u2192 "${o.trim()}"
224
- `)}async function oo(e){let t=h(e),n=await ge(t,e.positional[0],"npx greatstore knowledge remove <id|name> [--yes]");if(!m(e.flags,"yes")&&(await mi(`Remove "${n.displayName}" from the knowledge base of "${t}"? Type "yes" to confirm: `)).trim()!=="yes"){process.stdout.write(`Aborted.
225
- `);return}await d(`${D(t)}/sources/${encodeURIComponent(n.id)}`,{method:"DELETE"}),process.stdout.write(`Removed "${n.displayName}"
226
- `)}async function so(e){let t=h(e),n=await ge(t,e.positional[0],"npx greatstore knowledge reindex <id|name> [--wait]"),r=await d(`${D(t)}/sources/${encodeURIComponent(n.id)}/reindex`,{method:"POST",validationDetail:!0});if(process.stdout.write(`Reprocessing "${n.displayName}"
227
- `),!m(e.flags,"wait"))return 0;let o=await he(t,[r.source.id],{firstPollDelay:!0});return we(o)?1:0}function mi(e){let t=Zr.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{t.question(e,r=>{t.close(),n(r)})})}import*as Q from"fs";import*as Z from"path";var qt=`npx greatstore knowledge add <file> --name <name> --unsafe-upload [--wait]
223
+ `)}async function ao(e){let t=h(e),n="npx greatstore knowledge rename <id|name> <new name>",r=await ge(t,e.positional[0],n),o=e.positional[1]??w(e.flags,"name");if(!o?.trim())throw new Error(`Usage: ${n}`);await d(`${B(t)}/sources/${encodeURIComponent(r.id)}`,{method:"PATCH",body:{displayName:o.trim()},validationDetail:!0}),process.stdout.write(`Renamed "${r.displayName}" \u2192 "${o.trim()}"
224
+ `)}async function lo(e){let t=h(e),n=await ge(t,e.positional[0],"npx greatstore knowledge remove <id|name> [--yes]");if(!m(e.flags,"yes")&&(await Ai(`Remove "${n.displayName}" from the knowledge base of "${t}"? Type "yes" to confirm: `)).trim()!=="yes"){process.stdout.write(`Aborted.
225
+ `);return}await d(`${B(t)}/sources/${encodeURIComponent(n.id)}`,{method:"DELETE"}),process.stdout.write(`Removed "${n.displayName}"
226
+ `)}async function co(e){let t=h(e),n=await ge(t,e.positional[0],"npx greatstore knowledge reindex <id|name> [--wait]"),r=await d(`${B(t)}/sources/${encodeURIComponent(n.id)}/reindex`,{method:"POST",validationDetail:!0});if(process.stdout.write(`Reprocessing "${n.displayName}"
227
+ `),!m(e.flags,"wait"))return 0;let o=await he(t,[r.source.id],{firstPollDelay:!0});return we(o)?1:0}function Ai(e){let t=ro.createInterface({input:process.stdin,output:process.stdout});return new Promise(n=>{t.question(e,r=>{t.close(),n(r)})})}import*as Q from"fs";import*as Z from"path";var Vt=`npx greatstore knowledge add <file> --name <name> --unsafe-upload [--wait]
228
228
  npx greatstore knowledge add <file> <file> \u2026 --unsafe-upload [--wait] (each named after its file)
229
229
  npx greatstore knowledge add --url <url> --name <name> [--wait]
230
230
  npx greatstore knowledge add --text <text> --name <name> [--wait]
231
- npx greatstore knowledge add --text-file <path> --name <name> --unsafe-upload [--wait]`,ao="unsafe-upload";function Me(e,t="knowledge"){if(e[ao]===void 0)throw new Error(t==="instructions"?`This puts a local file's contents into the agent instructions, which the store's assistant follows on every reply.
231
+ npx greatstore knowledge add --text-file <path> --name <name> --unsafe-upload [--wait]`,po="unsafe-upload";function He(e,t="knowledge"){if(e[po]===void 0)throw new Error(t==="instructions"?`This puts a local file's contents into the agent instructions, which the store's assistant follows on every reply.
232
232
  Confirm with the user that this exact file should become the instructions, then re-run with --unsafe-upload.`:`Uploading a local file puts its contents where the store's assistant can share them with shoppers.
233
- Confirm with the user that this exact file belongs in the knowledge base, then re-run with --unsafe-upload.`)}function gi(e){let t=e.flags[ao];return typeof t!="string"||t==="true"?e:{...e,positional:[...e.positional,t]}}var hi={".pdf":"application/pdf",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".txt":"text/plain",".md":"text/markdown",".markdown":"text/markdown",".csv":"text/csv",".html":"text/html",".htm":"text/html"},wi=4*1024*1024,io=120;function yi(e,t){if(e.length>1&&t!==void 0)throw new Error("--name names a single source. With several files, each is named after its file \u2014 add them one at a time to name them yourself.");if(e.length===1&&!t?.trim())throw new Error(`Missing --name for the source.
234
- Usage: ${qt}`);return e.map(n=>{let r=Z.resolve(n);if(!Q.existsSync(r)||!Q.statSync(r).isFile())throw new Error(`File not found: ${n}`);let o=Z.extname(r).toLowerCase(),s=hi[o];if(!s)throw new Error(`${n}: this file type can't be read. Use a PDF, Word (.docx), text, Markdown, CSV or HTML file.`);if(Q.statSync(r).size>wi)throw new Error(`${n} is larger than 4 MB.`);let i=t?.trim()||Z.basename(r,Z.extname(r));if(i.length>io)throw new Error(`${n}: source names can be up to ${io} characters. Rename the file, or add it on its own with a shorter --name.`);return{path:r,mime:s,name:i}})}async function lo(e){let t=gi(e),n=h(t),r=`${D(n)}/sources`,o=w(t.flags,"url"),s=w(t.flags,"text"),i=w(t.flags,"text-file"),a=w(t.flags,"name"),l=t.positional;if([l.length>0,o!==void 0,s!==void 0,i!==void 0].filter(Boolean).length!==1)throw new Error(`Add files, a --url, or a note (--text / --text-file) \u2014 one at a time.
235
- Usage: ${qt}`);(l.length>0||i!==void 0)&&Me(t.flags);let p=[];if(l.length>0){let f=yi(l,a);for(let y of f){let g=new FormData;g.append("file",new Blob([new Uint8Array(Q.readFileSync(y.path))],{type:y.mime}),Z.basename(y.path)),g.append("name",y.name);let L=await d(r,{method:"POST",multipart:g,validationDetail:!0});p.push(L.source),process.stdout.write(`Added "${L.source.displayName}" (${L.source.id})
233
+ Confirm with the user that this exact file belongs in the knowledge base, then re-run with --unsafe-upload.`)}function Ci(e){let t=e.flags[po];return typeof t!="string"||t==="true"?e:{...e,positional:[...e.positional,t]}}var Ti={".pdf":"application/pdf",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".txt":"text/plain",".md":"text/markdown",".markdown":"text/markdown",".csv":"text/csv",".html":"text/html",".htm":"text/html"},Ri=4*1024*1024,uo=120;function _i(e,t){if(e.length>1&&t!==void 0)throw new Error("--name names a single source. With several files, each is named after its file \u2014 add them one at a time to name them yourself.");if(e.length===1&&!t?.trim())throw new Error(`Missing --name for the source.
234
+ Usage: ${Vt}`);return e.map(n=>{let r=Z.resolve(n);if(!Q.existsSync(r)||!Q.statSync(r).isFile())throw new Error(`File not found: ${n}`);let o=Z.extname(r).toLowerCase(),s=Ti[o];if(!s)throw new Error(`${n}: this file type can't be read. Use a PDF, Word (.docx), text, Markdown, CSV or HTML file.`);if(Q.statSync(r).size>Ri)throw new Error(`${n} is larger than 4 MB.`);let i=t?.trim()||Z.basename(r,Z.extname(r));if(i.length>uo)throw new Error(`${n}: source names can be up to ${uo} characters. Rename the file, or add it on its own with a shorter --name.`);return{path:r,mime:s,name:i}})}async function fo(e){let t=Ci(e),n=h(t),r=`${B(n)}/sources`,o=w(t.flags,"url"),s=w(t.flags,"text"),i=w(t.flags,"text-file"),a=w(t.flags,"name"),l=t.positional;if([l.length>0,o!==void 0,s!==void 0,i!==void 0].filter(Boolean).length!==1)throw new Error(`Add files, a --url, or a note (--text / --text-file) \u2014 one at a time.
235
+ Usage: ${Vt}`);(l.length>0||i!==void 0)&&He(t.flags);let p=[];if(l.length>0){let f=_i(l,a);for(let y of f){let g=new FormData;g.append("file",new Blob([new Uint8Array(Q.readFileSync(y.path))],{type:y.mime}),Z.basename(y.path)),g.append("name",y.name);let I=await d(r,{method:"POST",multipart:g,validationDetail:!0});p.push(I.source),process.stdout.write(`Added "${I.source.displayName}" (${I.source.id})
236
236
  `)}}else{if(!a?.trim())throw new Error(`Missing --name for the source.
237
- Usage: ${qt}`);let f,y;if(o!==void 0)f=`${r}/link`,y={url:o,name:a.trim()};else{let L=i!==void 0?Si(i):s;if(!L.trim())throw new Error("The note is empty.");f=`${r}/text`,y={text:L,name:a.trim()}}let g=await d(f,{method:"POST",body:y,validationDetail:!0});p.push(g.source),process.stdout.write(`Added "${g.source.displayName}" (${g.source.id})
237
+ Usage: ${Vt}`);let f,y;if(o!==void 0)f=`${r}/link`,y={url:o,name:a.trim()};else{let I=i!==void 0?ji(i):s;if(!I.trim())throw new Error("The note is empty.");f=`${r}/text`,y={text:I,name:a.trim()}}let g=await d(f,{method:"POST",body:y,validationDetail:!0});p.push(g.source),process.stdout.write(`Added "${g.source.displayName}" (${g.source.id})
238
238
  `)}if(!m(t.flags,"wait"))return process.stdout.write("Processing has started. Check it with `npx greatstore knowledge status`, or pass --wait next time.\n"),0;process.stderr.write(`Waiting for processing to finish\u2026
239
- `);let u=await he(n,p.map(f=>f.id));return we(u)?1:0}function Si(e){let t=Z.resolve(e);if(!Q.existsSync(t))throw new Error(`File not found: ${e}`);return Q.readFileSync(t,"utf8")}import*as St from"fs";import*as uo from"path";var co=`npx greatstore knowledge edit <id|name> --old <text> --new <text> [--wait]
240
- npx greatstore knowledge edit <id|name> --file <path> --expect <hash> --unsafe-upload [--wait]`;function Vt(e,t){let n=w(e,"file");if(n===void 0)return{edits:Qr(e,t)};if(e.old!==void 0||e.new!==void 0)throw new Error(`Use --old/--new or --file, not both.
239
+ `);let u=await he(n,p.map(f=>f.id));return we(u)?1:0}function ji(e){let t=Z.resolve(e);if(!Q.existsSync(t))throw new Error(`File not found: ${e}`);return Q.readFileSync(t,"utf8")}import*as St from"fs";import*as go from"path";var mo=`npx greatstore knowledge edit <id|name> --old <text> --new <text> [--wait]
240
+ npx greatstore knowledge edit <id|name> --file <path> --expect <hash> --unsafe-upload [--wait]`;function Kt(e,t){let n=w(e,"file");if(n===void 0)return{edits:no(e,t)};if(e.old!==void 0||e.new!==void 0)throw new Error(`Use --old/--new or --file, not both.
241
241
  Usage: ${t}`);let r=w(e,"expect");if(!r)throw new Error(`Replacing the whole text needs --expect <hash>: the hash \`show\` printed when you read it.
242
- Usage: ${t}`);let o=uo.resolve(n);if(!St.existsSync(o))throw new Error(`File not found: ${n}`);return{content:St.readFileSync(o,"utf8"),expectedHash:r}}async function po(e){let t=h(e);e.flags.file!==void 0&&Me(e.flags);let n=await ge(t,e.positional[0],co),r=Vt(e.flags,co),o=await d(`${D(t)}/sources/${encodeURIComponent(n.id)}`,{method:"PATCH",body:r,validationDetail:!0});if(process.stdout.write(`Saved "${n.displayName}" \u2014 reprocessing it now
242
+ Usage: ${t}`);let o=go.resolve(n);if(!St.existsSync(o))throw new Error(`File not found: ${n}`);return{content:St.readFileSync(o,"utf8"),expectedHash:r}}async function ho(e){let t=h(e);e.flags.file!==void 0&&He(e.flags);let n=await ge(t,e.positional[0],mo),r=Kt(e.flags,mo),o=await d(`${B(t)}/sources/${encodeURIComponent(n.id)}`,{method:"PATCH",body:r,validationDetail:!0});if(process.stdout.write(`Saved "${n.displayName}" \u2014 reprocessing it now
243
243
  `),!m(e.flags,"wait"))return 0;let s=await he(t,[o.source.id],{firstPollDelay:!0});return we(s)?1:0}var bt=`npx greatstore knowledge instructions [show] [--json]
244
244
  npx greatstore knowledge instructions edit --old <text> --new <text>
245
- npx greatstore knowledge instructions set --file <path> --expect <hash> --unsafe-upload`;async function fo(e){let t=h(e),n=e.positional[0]??"show",r=`${D(t)}/instructions`;switch(n){case"show":{let o=await d(r);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(o,null,2)+`
245
+ npx greatstore knowledge instructions set --file <path> --expect <hash> --unsafe-upload`;async function wo(e){let t=h(e),n=e.positional[0]??"show",r=`${B(t)}/instructions`;switch(n){case"show":{let o=await d(r);if(m(e.flags,"json")){process.stdout.write(JSON.stringify(o,null,2)+`
246
246
  `);return}o.instructions?process.stdout.write(o.instructions.endsWith(`
247
247
  `)?o.instructions:`${o.instructions}
248
248
  `):process.stderr.write(`(no agent instructions in ${t})
249
249
  `),process.stderr.write(`hash: ${o.hash}
250
250
  `);return}case"edit":case"set":{if(n==="edit"&&e.flags.file!==void 0)throw new Error(`To replace the whole text use \`instructions set\`.
251
251
  Usage: ${bt}`);if(n==="set"&&e.flags.file===void 0)throw new Error(`Missing --file <path>.
252
- Usage: ${bt}`);n==="set"&&Me(e.flags,"instructions");let o=await d(r,{method:"PATCH",body:Vt(e.flags,bt),validationDetail:!0});process.stdout.write(o.instructions?`Saved the agent instructions.
252
+ Usage: ${bt}`);n==="set"&&He(e.flags,"instructions");let o=await d(r,{method:"PATCH",body:Kt(e.flags,bt),validationDetail:!0});process.stdout.write(o.instructions?`Saved the agent instructions.
253
253
  `:`Cleared the agent instructions.
254
254
  `),process.stderr.write(`hash: ${o.hash}
255
255
  `);return}default:throw new Error(`Unknown instructions subcommand: ${n}.
256
- Usage: ${bt}`)}}var bi='npx greatstore knowledge ask "<message>" [--conversation <id>] [--json]';function xi(e){let t=e;return!t||typeof t.usedCredits!="number"||typeof t.limitCredits!="number"||typeof t.remainingCredits!="number"||typeof t.windowHours!="number"?null:{usedCredits:t.usedCredits,limitCredits:t.limitCredits,remainingCredits:t.remainingCredits,windowHours:t.windowHours}}function $i(e){let t="",n=null,r=null,o=null,s=new Map;for(let i of e){if(!i.trim())continue;let a;try{a=JSON.parse(i)}catch{continue}switch(a.type){case"text_chunk":typeof a.delta=="string"&&(t+=a.delta);break;case"text_reset":t="";break;case"tool_start":case"tool_done":{let l=String(a.toolCallId??s.size),c=typeof a.toolName=="string"?a.toolName:"unknown",p=s.get(l),u=a.args&&typeof a.args=="object"&&!Array.isArray(a.args)?a.args:null;s.set(l,{name:c,args:u??p?.args??null,success:a.type==="tool_done"?a.success===!0:p?.success??null});break}case"result":{let l=a.data??{};typeof l.reply=="string"&&(n=l.reply),typeof l.conversationId=="string"&&(r=l.conversationId),o=xi(l.testAllowance);break}case"error":throw new Error(typeof a.error=="string"?a.error:"The assistant couldn't reply.")}}return{reply:n??t,conversationId:r,tools:[...s.values()],testAllowance:o}}var ki=300;function vi(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}async function mo(e){let t=h(e),n=e.positional.join(" ").trim();if(!n)throw new Error(`Usage: ${bi}`);let r=w(e.flags,"conversation"),o=await Le(`${b(t)}/chat`,{method:"POST",headers:{accept:"text/x-ndjson"},body:{messages:[{text:n}],...r?{conversationId:r}:{}},validationDetail:!0}),s=$i((await o.text()).split(`
256
+ Usage: ${bt}`)}}var Ii='npx greatstore knowledge ask "<message>" [--conversation <id>] [--json]';function Li(e){let t=e;return!t||typeof t.usedCredits!="number"||typeof t.limitCredits!="number"||typeof t.remainingCredits!="number"||typeof t.windowHours!="number"?null:{usedCredits:t.usedCredits,limitCredits:t.limitCredits,remainingCredits:t.remainingCredits,windowHours:t.windowHours}}function Ni(e){let t="",n=null,r=null,o=null,s=new Map;for(let i of e){if(!i.trim())continue;let a;try{a=JSON.parse(i)}catch{continue}switch(a.type){case"text_chunk":typeof a.delta=="string"&&(t+=a.delta);break;case"text_reset":t="";break;case"tool_start":case"tool_done":{let l=String(a.toolCallId??s.size),c=typeof a.toolName=="string"?a.toolName:"unknown",p=s.get(l),u=a.args&&typeof a.args=="object"&&!Array.isArray(a.args)?a.args:null;s.set(l,{name:c,args:u??p?.args??null,success:a.type==="tool_done"?a.success===!0:p?.success??null});break}case"result":{let l=a.data??{};typeof l.reply=="string"&&(n=l.reply),typeof l.conversationId=="string"&&(r=l.conversationId),o=Li(l.testAllowance);break}case"error":throw new Error(typeof a.error=="string"?a.error:"The assistant couldn't reply.")}}return{reply:n??t,conversationId:r,tools:[...s.values()],testAllowance:o}}var Oi=300;function Fi(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}async function yo(e){let t=h(e),n=e.positional.join(" ").trim();if(!n)throw new Error(`Usage: ${Ii}`);let r=w(e.flags,"conversation"),o=await Ie(`${S(t)}/chat`,{method:"POST",headers:{accept:"text/x-ndjson"},body:{messages:[{text:n}],...r?{conversationId:r}:{}},validationDetail:!0}),s=Ni((await o.text()).split(`
257
257
  `));if(m(e.flags,"json")){process.stdout.write(JSON.stringify(s,null,2)+`
258
258
  `);return}if(process.stdout.write(`${s.reply.trim()}
259
259
  `),s.tools.length>0){process.stdout.write(`
260
260
  Tools used:
261
- `);for(let i of s.tools){let a=i.success===!1?" (failed)":"",l=i.args?` ${vi(JSON.stringify(i.args),ki)}`:"";process.stdout.write(` ${i.name}${a}${l}
261
+ `);for(let i of s.tools){let a=i.success===!1?" (failed)":"",l=i.args?` ${Fi(JSON.stringify(i.args),Oi)}`:"";process.stdout.write(` ${i.name}${a}${l}
262
262
  `)}}if(s.testAllowance){let i=s.testAllowance;process.stdout.write(`
263
263
  Test chats: ${i.usedCredits} of ${i.limitCredits} credits used in the last ${i.windowHours} hours, ${i.remainingCredits} left.
264
264
  `)}s.conversationId&&process.stdout.write(`
265
265
  Continue with: npx greatstore knowledge ask "<message>" --conversation ${s.conversationId}
266
- `)}var go=`npx greatstore knowledge \u2014 manage what the store's assistant knows and follows.
266
+ `)}var So=`npx greatstore knowledge \u2014 manage what the store's assistant knows and follows.
267
267
  Alias: npx greatstore kb
268
268
 
269
269
  Knowledge sources (what the assistant looks things up in):
@@ -311,17 +311,50 @@ add, edit and reindex take --wait to block until processing finishes.
311
311
  Flags:
312
312
  --store <slug> Which store to act on (default: nearest .gsrc).
313
313
  --json Machine-readable output for list, status, show, instructions, ask.
314
- `;async function ho(e){let t=e.positional[0]??"list",n={...e,positional:e.positional.slice(1)};switch(t){case"list":return await eo(n),0;case"status":return to(n);case"add":return lo(n);case"show":return await no(n),0;case"edit":return po(n);case"rename":return await ro(n),0;case"reindex":return so(n);case"remove":return await oo(n),0;case"instructions":return await fo(n),0;case"ask":return await mo(n),0;default:throw new Error(`Unknown knowledge subcommand: ${t}. Run \`npx greatstore knowledge --help\`.`)}}function Kt(e,t=15){if(!e.trim())return"";let n=e.split(`
314
+ `;async function bo(e){let t=e.positional[0]??"list",n={...e,positional:e.positional.slice(1)};switch(t){case"list":return await oo(n),0;case"status":return so(n);case"add":return fo(n);case"show":return await io(n),0;case"edit":return ho(n);case"rename":return await ao(n),0;case"reindex":return co(n);case"remove":return await lo(n),0;case"instructions":return await wo(n),0;case"ask":return await yo(n),0;default:throw new Error(`Unknown knowledge subcommand: ${t}. Run \`npx greatstore knowledge --help\`.`)}}function xo(e,t){return{kind:e,from:t.from,to:t.to,page:t.page,pages:t.pages,total:t.total,days:t.days.map(({day:n,turns:r})=>({day:n,items:r.map(o=>({quote:o.quote,conversationId:o.conversationId,seq:o.seq,time:o.time,...e==="gaps"?{reason:o.reason??null}:{answered:o.answered}}))}))}}function $o(e,t,n){let r=[];for(let o of t){let s=o.updatedAt.slice(0,10),i=r.at(-1);i?.day!==s&&(i={day:s,chats:[]},r.push(i)),i.chats.push(Di(o))}return{from:e.from,to:e.to,...n,days:r}}function Di(e){return{id:e.conversationId,startedAt:e.createdAt,lastActivityAt:e.updatedAt,status:e.terminated?"ended":"active",messageCount:e.messageCount,channel:e.channel,preview:e.lastMessagePreview}}function vo(e){let t=new Map;for(let r of e.messages)r.role==="tool"&&typeof r.success=="boolean"&&t.set(r.toolCallId,r.success);let n=e.messages.flatMap((r,o)=>{if(r.role!=="user"&&r.role!=="assistant")return[];if(r.hidden===!0)return[];let s={seq:e.messageSeqs[o]??null,role:r.role,time:e.messageTimes?.[o]??null,text:r.content};if(r.role==="user")return[{...s,...r.voice?{voice:!0}:{}}];if(!r.content.trim()&&!r.toolCalls?.length)return[];let i=(r.toolCalls??[]).map(a=>({name:a.toolName,input:a.args??{},success:t.get(a.toolCallId)??null}));return[{...s,...i.length?{toolCalls:i}:{}}]});return{id:e.conversationId,startedAt:e.createdAt,lastActivityAt:e.updatedAt,status:e.terminated?"ended":"active",channel:e.channel,messages:n}}var Wt=`npx greatstore analyze \u2014 read the store's shopper traffic, as JSON.
315
+
316
+ analyze gaps Shopper messages the assistant couldn't answer, each
317
+ with the reason.
318
+ analyze searches What shoppers searched for, and whether it was answered.
319
+ analyze questions What shoppers asked, and whether it was answered.
320
+ analyze chats Conversations by the day they were last active.
321
+ analyze chat <id> One conversation in full: every message with its time,
322
+ and the tools the assistant called.
323
+
324
+ Lists are grouped by day, newest first, 50 items a page; the output carries
325
+ page, pages and total. Each gap, search and question names its conversationId
326
+ and seq, the message's position in \`analyze chat <id>\`. Test chats (the
327
+ dashboard preview, app Try it, \`knowledge ask\`) are never included.
328
+
329
+ Flags:
330
+ --from <YYYY-MM-DD> First day, UTC (default: 6 days before --to).
331
+ --to <YYYY-MM-DD> Last day, UTC, inclusive (default: today). At most 90 days.
332
+ --page <n> Which page of a list (default: 1).
333
+ --store <slug> Which store to read (default: nearest .gsrc).
334
+ `,Jt=50,Bi=7,ko=90,Eo=864e5,Mi=/^\d{4}-\d{2}-\d{2}$/,xt=e=>new Date(e).toISOString().slice(0,10);function Po(e,t){if(t===void 0)return;let n=typeof t=="string"&&Mi.test(t)?Date.parse(t):Number.NaN;if(Number.isNaN(n)||xt(n)!==t)throw new Error(`--${e} must be a date as YYYY-MM-DD.`);return n}function Ao(e,t=Date.now()){let n=Po("from",e.from),r=Po("to",e.to)??Date.parse(xt(t)),o=n??r-(Bi-1)*Eo;if(o>r)throw new Error("--from must be on or before --to.");if((r-o)/Eo+1>ko)throw new Error(`The range can cover at most ${ko} days.`);return{from:xt(o),to:xt(r)}}function Co(e){let t=e.page;if(t===void 0)return 1;let n=typeof t=="string"&&/^\d+$/.test(t)?Number(t):Number.NaN;if(!Number.isSafeInteger(n)||n<1)throw new Error("--page must be a whole number from 1.");return n}var Yt=e=>process.stdout.write(`${JSON.stringify(e,null,2)}
335
+ `);async function Ui(e,t){let n=h(t),{from:r,to:o}=Ao(t.flags),s=await d(`${S(n)}/insights/day`,{method:"POST",body:{day:r,to:o,kind:e,page:Co(t.flags)}});Yt(xo(e,s.data))}async function Hi(e){let t=h(e),n=Ao(e.flags),r=Co(e.flags),o=l=>d(`${S(t)}/chats/sessions/report`,{method:"POST",body:{...n,status:"all",limit:Jt,offset:(l-1)*Jt}}).then(c=>c.data),s=await o(r),i=Math.max(1,Math.ceil(s.total/Jt)),a=Math.min(r,i);a!==r&&(s=await o(a)),Yt($o(n,s.sessions,{page:a,pages:i,total:s.total}))}async function qi(e){let t=e.positional[0];if(!t)throw new Error("Usage: npx greatstore analyze chat <id>");let n=h(e),r=new Error(`No chat with id ${t}. Run \`npx greatstore analyze chats\` to list them.`),o;try{o=(await d(`${S(n)}/chats/sessions/view`,{method:"POST",body:{conversationId:t}})).data.session}catch(s){throw s instanceof D&&s.status===404?r:s}if(o.channel==="admin")throw r;Yt(vo(o))}async function To(e){let t=e.positional[0],n={...e,positional:e.positional.slice(1)};switch(t){case void 0:return process.stdout.write(Wt),0;case"gaps":case"searches":case"questions":return await Ui(t,n),0;case"chats":return await Hi(n),0;case"chat":return await qi(n),0;default:throw new Error(`Unknown analyze subcommand: ${t}. Run \`npx greatstore analyze --help\`.`)}}function zt(e,t=15){if(!e.trim())return"";let n=e.split(`
315
336
  `),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(`
316
- `).trimEnd()}function wo(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&&xe(s,t)>0}r&&n.push(o)}return n.join(`
317
- `).trimEnd()}import*as _e from"fs";import*as Jt from"os";import*as bo from"path";var Ei="version-check.json",Pi="0.0.0-dev";function xo(e){return bo.join(pe(e),Ei)}function Wt(e=Jt.homedir()){try{let t=JSON.parse(_e.readFileSync(xo(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 $o(e,t=Jt.homedir()){if(e===Pi)return!1;let n=Wt(t);if(n?.version===e)return!1;let r=n!==null&&xe(e,n.version)>0;try{_e.mkdirSync(pe(t),{recursive:!0,mode:448});let o=n?{version:e,previous:n.version}:{version:e};_e.writeFileSync(xo(t),JSON.stringify(o)+`
318
- `)}catch{return!1}return r}var yo="\x1B[34m",Ai="\x1B[30;42m",So="\x1B[0m";function ko(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}`:""}
319
- `;let o=t?` ${Ai} Updated! ${So}${yo} ${r}`:"";return`${yo}greatstore v${e}${o}${So}
320
- `}var Yt=`# Changelog
337
+ `).trimEnd()}function Ro(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&&xe(s,t)>0}r&&n.push(o)}return n.join(`
338
+ `).trimEnd()}import*as _e from"fs";import*as Xt from"os";import*as Io from"path";var Gi="version-check.json",Vi="0.0.0-dev";function Lo(e){return Io.join(pe(e),Gi)}function Qt(e=Xt.homedir()){try{let t=JSON.parse(_e.readFileSync(Lo(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 No(e,t=Xt.homedir()){if(e===Vi)return!1;let n=Qt(t);if(n?.version===e)return!1;let r=n!==null&&xe(e,n.version)>0;try{_e.mkdirSync(pe(t),{recursive:!0,mode:448});let o=n?{version:e,previous:n.version}:{version:e};_e.writeFileSync(Lo(t),JSON.stringify(o)+`
339
+ `)}catch{return!1}return r}var _o="\x1B[34m",Ki="\x1B[30;42m",jo="\x1B[0m";function Oo(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}`:""}
340
+ `;let o=t?` ${Ki} Updated! ${jo}${_o} ${r}`:"";return`${_o}greatstore v${e}${o}${jo}
341
+ `}var Zt=`# Changelog
321
342
 
322
343
  All notable changes to \`@greatstore/cli\` are recorded here. The format
323
344
  follows [Keep a Changelog](https://keepachangelog.com/).
324
345
 
346
+ ## 0.4.0 \u2014 2026-11-19
347
+
348
+ ### Added
349
+ - \`analyze\` reads the store's real shopper traffic as JSON: \`gaps\` (messages
350
+ the assistant couldn't answer, with why), \`searches\`, \`questions\`, \`chats\`,
351
+ and \`chat <id>\` for one conversation in full. Lists take \`--from\` / \`--to\`
352
+ and \`--page\`, and never include test chats.
353
+ - The skill's knowledge base audit starts from what shoppers really asked:
354
+ its test questions come from \`analyze\`, recurring gaps become proposed
355
+ sources, and missing product details are pointed to the product catalog.
356
+ Fixing an ignored instruction starts from a real chat that shows it.
357
+
325
358
  ## 0.3.1 \u2014 2026-11-13
326
359
 
327
360
  ### Changed
@@ -1044,7 +1077,7 @@ follows [Keep a Changelog](https://keepachangelog.com/).
1044
1077
 
1045
1078
  ### Fixed
1046
1079
  - Sign-in callback parameter handling.
1047
- `,vo=`greatstore \u2014 GreatStore CLI (v${N})
1080
+ `,Fo=`greatstore \u2014 GreatStore CLI (v${N})
1048
1081
 
1049
1082
  Usage:
1050
1083
  npx greatstore <command> [args] [flags]
@@ -1080,6 +1113,9 @@ Store administration:
1080
1113
  rename, reindex, remove, instructions, and ask
1081
1114
  to test the live assistant.
1082
1115
  \`npx greatstore knowledge --help\` lists them.
1116
+ analyze Read shopper traffic as JSON: gaps, searches,
1117
+ questions, chats, and one chat in full.
1118
+ \`npx greatstore analyze --help\` lists them.
1083
1119
  apps <subcommand> Author and ship custom in-chat apps (init, build,
1084
1120
  list, pull, push, publish, unpublish, rename, delete).
1085
1121
  \`npx greatstore apps help\` lists them; all but rename also work
@@ -1112,14 +1148,14 @@ Environment:
1112
1148
  GS_API_BASE Override API base (full URL, no trailing slash).
1113
1149
  GS_DASHBOARD_BASE Override the sign-in/store-picker base URL.
1114
1150
  GS_BROWSER_CMD Override the browser-open command.
1115
- `,Ci=new Set(["init","build","list","pull","push","publish","unpublish","delete"]);async function Ti(){let e=process.argv.slice(2),t=nn(e);if($n(N),m(t.flags,"version")){process.stdout.write(`greatstore v${N}
1151
+ `,Ji=new Set(["init","build","list","pull","push","publish","unpublish","delete"]);async function Wi(){let e=process.argv.slice(2),t=an(e);if(Pn(N),m(t.flags,"version")){process.stdout.write(`greatstore v${N}
1116
1152
 
1117
- `);let n=Kt(Yt);return n&&process.stdout.write(`${n}
1118
- `),0}if(m(t.flags,"help")||t.command==="help"||t.command===null){let n=t.command==="configure"?jn(t.positional[0]):t.command==="knowledge"||t.command==="kb"?go:void 0;return process.stdout.write(n??vo),0}if(m(t.flags,"json")||process.stderr.write(ko(N,$o(N))),t.command!==null&&Ci.has(t.command))return Ft({...t,positional:[t.command,...t.positional]});switch(t.command){case"login":return await vn(t),0;case"logout":return En(),0;case"whoami":return Pn();case"switch":return An(t.positional);case"apps":return Ft(t);case"configure":return await Ur(t),0;case"connectors":return await zr(t),0;case"knowledge":case"kb":return ho(t);case"skill":return Cn(),0;case"whats-new":{let n=Wt()?.previous,r=n?wo(Yt,n):Kt(Yt);return process.stdout.write(`${r||"No release notes in this build."}
1153
+ `);let n=zt(Zt);return n&&process.stdout.write(`${n}
1154
+ `),0}if(m(t.flags,"help")||t.command==="help"||t.command===null){let n=t.command==="configure"?Ln(t.positional[0]):t.command==="knowledge"||t.command==="kb"?So:t.command==="analyze"?Wt:void 0;return process.stdout.write(n??Fo),0}if(!m(t.flags,"json")&&t.command!=="analyze"&&process.stderr.write(Oo(N,No(N))),t.command!==null&&Ji.has(t.command))return Dt({...t,positional:[t.command,...t.positional]});switch(t.command){case"login":return await Cn(t),0;case"logout":return Tn(),0;case"whoami":return Rn();case"switch":return _n(t.positional);case"apps":return Dt(t);case"configure":return await Gr(t),0;case"connectors":return await eo(t),0;case"knowledge":case"kb":return bo(t);case"analyze":return To(t);case"skill":return jn(),0;case"whats-new":{let n=Qt()?.previous,r=n?Ro(Zt,n):zt(Zt);return process.stdout.write(`${r||"No release notes in this build."}
1119
1155
  `),0}default:return process.stderr.write(`Unknown command: ${t.command}
1120
1156
 
1121
- ${vo}`),1}}Ti().then(e=>process.exit(e||Number(process.exitCode??0))).catch(e=>{e instanceof q?process.stderr.write(`${e.message}
1122
- `):e instanceof M?process.stderr.write(`Error: ${e.message}
1157
+ ${Fo}`),1}}Wi().then(e=>process.exit(e||Number(process.exitCode??0))).catch(e=>{e instanceof G?process.stderr.write(`${e.message}
1158
+ `):e instanceof D?process.stderr.write(`Error: ${e.message}
1123
1159
  `):e instanceof ee||e instanceof ue?process.stderr.write(`Error: ${e.message}
1124
1160
  `):e instanceof Error?process.stderr.write(`Error: ${e.message}
1125
1161
  `):process.stderr.write(`Error: ${String(e)}